From 074682647f5744c4043ce397c76f7708ef125d70 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 03:30:35 +0800 Subject: [PATCH 001/161] fix: honor cooperative cancellation in Windows focus waits --- Progress.md | 5 +- architecture_explore.md | 14 +++--- docs/guides/en/usage.md | 2 + docs/guides/zh-CN/usage.md | 2 + docs/guides/zh-TW/usage.md | 2 + .../doc/new_features/v202_features_doc.rst | 10 ++++ docs/updates/2026-11.md | 6 +++ docs/updates/README.md | 3 +- .../accessibility/backends/windows_backend.py | 7 ++- .../accessibility/backends/windows_events.py | 26 ++++++++++ .../test_accessibility_windows_content.py | 50 +++++++++++++++++++ 11 files changed, 113 insertions(+), 14 deletions(-) create mode 100644 je_auto_control/utils/accessibility/backends/windows_events.py diff --git a/Progress.md b/Progress.md index ff62ad5f3..20cb6437e 100644 --- a/Progress.md +++ b/Progress.md @@ -101,12 +101,13 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **Windows UIA 後端的執行緒模型完全沒對真的 COM 驗過**:現在每個呼叫執行緒各有一個自動化物件(`accessibility/backends/windows_automation.py`; 主執行緒 STA、其他執行緒進 MTA),Accessibility 分頁與 A11y Audit 已移出 GUI 執行緒。開發環境沒裝 `comtypes`,CI 也沒有同時有 `comtypes` 與桌面的 job, 測試全是假 COM 物件。未驗證的假設:MTA 工作執行緒上的 UIA 呼叫可用;焦點事件 callback 不需要 message pump; - `import comtypes` 第一次發生在已經是 MTA 的執行緒上會丟 `OSError`(憑記憶,沒處理)。`AC_wait_for_focus_change` 的原生 `Queue.get` 仍不會被 stop 叫醒。 + `import comtypes` 第一次發生在已經是 MTA 的執行緒上會丟 `OSError`(憑記憶,沒處理)。焦點等待的 cooperative cancellation 已有 headless 回歸測試;真實 COM 訂閱/解除與停止行為仍待原生驗收。 - **Script Builder 的一次性值**:一次執行最多保留 200 個(`MAX_ONE_TIME_VALUES`,留前面的);`AC_parallel` 分支裡產生的值不經結果掛鉤回報, 只能從區塊的結果裡取得(標成 `results[0].…`)。結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep、`AC_wait_for_focus_change`; +- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep; + `AC_wait_for_focus_change` 的取消 token 路徑已接合,未綁定 token 的舊 stop 路徑仍待核對。 MCP 自己的輪詢(`ac_wait_for_image`/`ac_wait_for_pixel`)不在可停止的執行裡。非腳本的分頁工作在後端無法取消,只是結果被丟掉。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/architecture_explore.md b/architecture_explore.md index 7dda09cf4..d9dd69e90 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -24,8 +24,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,494 | -| 程式碼總行數 | 228,248 | +| Python 模組總數(含周邊子專案) | 1,495 | +| 程式碼總行數 | 228,273 | | `je_auto_control/utils/` 子套件數 | 311 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -455,12 +455,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,827 行。 +> 16 個套件、約 4,852 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a11y_audit/` | 362 | 以無障礙樹 + OCR 進行無障礙與 i18n 稽核 | -| `utils/accessibility/` | 3,292 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | +| `utils/accessibility/` | 3,317 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | | `utils/ax_text/` | 102 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | @@ -1216,7 +1216,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | 子套件 | 檔案組成 | | --- | --- | -| `accessibility/` | `accessibility_api.py`(公開 API)、`element.py`(dataclass)、`tree.py`(遞迴樹傾印)、`recorder.py`(輪詢式事件錄製)、`backends/`:`base.py` 330 行抽象、`windows_backend.py` 801 行(comtypes UIA)、`windows_reads.py` 142 行(pattern/文字範圍/表頭/元素屬性的純讀取與 `UIA_READ_ERRORS`)、`windows_query.py` 176 行(UIA 搜尋起點、可中斷走訪、快取請求、NULL COM 指標判定與 `UIA_ERRORS`)、`windows_state.py` 98 行(控制項狀態讀取與密碼欄位判定)、`macos_backend.py` 125 行(pyobjc AX)、`null_backend.py` fallback | +| `accessibility/` | `accessibility_api.py`(公開 API)、`element.py`(dataclass)、`tree.py`(遞迴樹傾印)、`recorder.py`(輪詢式事件錄製)、`backends/`:`base.py` 330 行抽象、`windows_backend.py` 801 行(comtypes UIA)、`windows_events.py`(以單一期限及取消 token 等待焦點事件)、`windows_reads.py` 142 行(pattern/文字範圍/表頭/元素屬性的純讀取與 `UIA_READ_ERRORS`)、`windows_query.py` 176 行(UIA 搜尋起點、可中斷走訪、快取請求、NULL COM 指標判定與 `UIA_ERRORS`)、`windows_state.py` 98 行(控制項狀態讀取與密碼欄位判定)、`macos_backend.py` 125 行(pyobjc AX)、`null_backend.py` fallback | | `agent/` | `agent_loop.py`、`computer_use.py`、`backends/`:`anthropic.py`、`anthropic_computer_use.py`(644 行)、`_computer_toolset.py`(141 行,GA `computer_toolset_20260801` 的批次、依高解析度層級上限縮放截圖、座標換算與 `zoom` 裁切)、`openai.py`、`base.py` | | `ocr/` | `ocr_engine.py`(門面)、`structure.py`(版面)、`tesseract_setup.py`(找執行檔、`TESSDATA_PREFIX`、`ocr_status`/`ocr_languages`;`None` 與 `[]` 分開回報)、`backends/`:`tesseract_backend.py`、`easyocr_backend.py`、`paddleocr_backend.py`、`base.py` | | `vision/` | `vlm_api.py`、`frame_capture.py`(記憶體邏輯影像與範圍內原點,保留可注入 bytes 接縫)、`backends/`:`anthropic_backend.py`、`openai_backend.py`、`null_backend.py`、`_parse.py`、`base.py` | @@ -1499,7 +1499,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | -| `utils/accessibility/` | 15 | 3,292 | +| `utils/accessibility/` | 16 | 3,317 | | `wrapper/` | 25 | 5,992 | | `windows/` | 24 | 2,265 | | `utils/rest_api/` | 8 | 2,226 | @@ -1514,7 +1514,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,486 | -| **總計** | **1,482** | **227,503** | +| **總計** | **1,483** | **227,528** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/usage.md b/docs/guides/en/usage.md index 850906a88..a79b37e88 100644 --- a/docs/guides/en/usage.md +++ b/docs/guides/en/usage.md @@ -214,3 +214,5 @@ sets `TEST_PIONEER_ARTIFACT_DIR`, the HTML, JSON and XML reports asked for under a relative name are written below that directory. --- + +Windows focus-event waits honor a bound cooperative cancellation token and release their event subscription on exit. Native COM acceptance remains pending. diff --git a/docs/guides/zh-CN/usage.md b/docs/guides/zh-CN/usage.md index d14178b25..ee8776dea 100644 --- a/docs/guides/zh-CN/usage.md +++ b/docs/guides/zh-CN/usage.md @@ -201,3 +201,5 @@ je_auto_control version `run` 只要有任何动作失败就以 1 退出(仍会跑完整份脚本),CI 步骤会随之失败。旧版 `python -m je_auto_control -e file.json` 入口仍然可用,它的 `-e`、`-d` 与 `--execute_str` 标志也同样在有动作失败时以 1 退出。由 [TestPioneer](https://github.com/Integration-Automation/TestPioneer) 启动时(它会设置 `TEST_PIONEER_ARTIFACT_DIR`),以相对名称要求的 HTML、JSON、XML 报告会写到该目录底下。 --- + +Windows 焦点事件等待支持已绑定的协作取消 token,退出等待时解除事件订阅;真实 COM 验收仍待执行。 diff --git a/docs/guides/zh-TW/usage.md b/docs/guides/zh-TW/usage.md index 9ceb1df77..0b852f1b1 100644 --- a/docs/guides/zh-TW/usage.md +++ b/docs/guides/zh-TW/usage.md @@ -201,3 +201,5 @@ je_auto_control version `run` 只要有任何動作失敗就以 1 結束(仍會跑完整份腳本),CI 步驟會跟著失敗。舊版 `python -m je_auto_control -e file.json` 進入點仍然可用,它的 `-e`、`-d` 與 `--execute_str` 旗標也同樣在有動作失敗時以 1 結束。由 [TestPioneer](https://github.com/Integration-Automation/TestPioneer) 啟動時(它會設定 `TEST_PIONEER_ARTIFACT_DIR`),以相對名稱要求的 HTML、JSON、XML 報告會寫到該目錄底下。 --- + +Windows 焦點事件等待支援已綁定的協作取消 token,離開等待時解除事件訂閱;真實 COM 驗收仍待執行。 diff --git a/docs/source/Eng/doc/new_features/v202_features_doc.rst b/docs/source/Eng/doc/new_features/v202_features_doc.rst index 121406668..12f48bc93 100644 --- a/docs/source/Eng/doc/new_features/v202_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v202_features_doc.rst @@ -35,3 +35,13 @@ Executor commands ``AC_wait_for_focus_change`` (``timeout``) returns ``{changed, element}``. It is exposed as the read-only ``ac_wait_for_focus_change`` MCP tool and as a Script Builder command under **Native UI**. + +Cooperative cancellation +------------------------ + +On Windows, a wait inside a bound cancellation scope checks its token between +bounded queue reads. Cancellation raises ``CancelledError`` and removes the +focus-event subscription in the calling thread. Polling uses the original +monotonic deadline; it does not extend the timeout. Unscoped waits retain their +existing timeout behavior. Native COM acceptance remains pending in +``Progress.md``. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index cc9ca94b7..6583014ec 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -654,3 +654,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **Check.** If the cause is something else, the quality run on #548 will fail again in the same place. It then needs a gc callback that logs long collections, not a wider deadline. - **Open items:** none. + +## U-20261110-01 · 2026-11-10 · Cooperative cancellation for Windows focus waits · #done #accessibility + +- **What:** Windows focus-event queue waits now poll the bound cancellation token with one monotonic deadline and release the subscription through the existing finally block. +- **Evidence:** Regression failed before the fix with `DID NOT RAISE CancelledError`; the focused accessibility, thread and public API suite passed 98 tests with one skip. +- **Open items:** Real COM acceptance and the legacy stop path without a cancellation token remain in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 0f58b8f0e..5e6cdaed6 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-01 | 2026-11-10 | Cooperative cancellation for Windows focus waits | #done #accessibility | [2026-11](2026-11.md) | | U-20261103-01 | 2026-11-03 | Hold the collector off around the presence reader's timed windows | #incident #agent #ci #test | [2026-11](2026-11.md) | | U-20261102-03 | 2026-11-02 | Require Python 3.11; stop supporting 3.10 | #migration #deps #ci | [2026-11](2026-11.md) | | U-20261102-02 | 2026-11-02 | Clear the SonarCloud findings the 1.1.0 release PR reported | #ci #test #quality | [2026-11](2026-11.md) | @@ -608,7 +609,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 21 | +| [2026-11.md](2026-11.md) | 2026-11 | 22 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/utils/accessibility/backends/windows_backend.py b/je_auto_control/utils/accessibility/backends/windows_backend.py index 469d07471..9e30f1d75 100644 --- a/je_auto_control/utils/accessibility/backends/windows_backend.py +++ b/je_auto_control/utils/accessibility/backends/windows_backend.py @@ -545,6 +545,7 @@ def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent( def wait_for_focus_change(self, timeout=5.0) -> Optional[Dict[str, Any]]: import queue + from je_auto_control.utils.accessibility.backends.windows_events import wait_for_event automation = self._ensure_automation() events: "queue.Queue" = queue.Queue() handler = self._make_focus_handler(events) @@ -555,10 +556,8 @@ def wait_for_focus_change(self, timeout=5.0) -> Optional[Dict[str, Any]]: automation.AddFocusChangedEventHandler(None, handler) except _UIA_ERRORS: return None - try: # Queue.get(inf) raises OverflowError on Windows; None waits for good. - return events.get(timeout=None if float(timeout) == float("inf") else float(timeout)) - except queue.Empty: - return None + try: + return wait_for_event(events, float(timeout)) finally: with self._event_lock: try: diff --git a/je_auto_control/utils/accessibility/backends/windows_events.py b/je_auto_control/utils/accessibility/backends/windows_events.py new file mode 100644 index 000000000..6eb26e0ee --- /dev/null +++ b/je_auto_control/utils/accessibility/backends/windows_events.py @@ -0,0 +1,26 @@ +"""Cancellable UIA event queue waits with one monotonic deadline.""" +import queue +import time +from typing import Any, Dict, Optional + +from je_auto_control.utils.exception.cancellation import ( + cancellation_checkpoint, cancellation_timeout, +) + + +def wait_for_event(events: queue.Queue, timeout: float) -> Optional[Dict[str, Any]]: + """Wait for one event while honoring the calling task's cancellation scope.""" + deadline = time.monotonic() + timeout + while True: + cancellation_checkpoint() + remaining = max(0.0, deadline - time.monotonic()) + interval = cancellation_timeout(remaining) + try: + event = events.get(timeout=None if interval == float("inf") else interval) + except queue.Empty: + cancellation_checkpoint() + if time.monotonic() >= deadline: + return None + else: + cancellation_checkpoint() + return event diff --git a/test/unit_test/headless/test_accessibility_windows_content.py b/test/unit_test/headless/test_accessibility_windows_content.py index 8a843d2ef..8e095de6f 100644 --- a/test/unit_test/headless/test_accessibility_windows_content.py +++ b/test/unit_test/headless/test_accessibility_windows_content.py @@ -731,3 +731,53 @@ def test_a_uia_module_without_the_event_interface_has_no_handler(backend, assert backend._make_focus_handler(None) is None + + +def test_focus_wait_cancellation_releases_subscription(backend, monkeypatch): + from concurrent.futures import CancelledError + from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope + import queue + + token = CancellationToken(1) + automation = backend._automation + real_get = queue.Queue.get + + def cancel_during_wait(events, *args, **kwargs): + token.cancel() + return real_get(events, block=False) + + monkeypatch.setattr(backend, "_make_focus_handler", lambda sink: object()) + monkeypatch.setattr(queue.Queue, "get", cancel_during_wait) + with cancellation_scope(token), pytest.raises(CancelledError): + backend.wait_for_focus_change(timeout=float("inf")) + assert automation.focus_handlers == [] + + +def test_scoped_focus_wait_uses_bounded_queue_polls(monkeypatch): + from concurrent.futures import CancelledError + from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope + from je_auto_control.utils.accessibility.backends.windows_events import wait_for_event + import queue + + token = CancellationToken(2) + intervals = [] + + class Events: + def get(self, *, timeout): + intervals.append(timeout) + token.cancel() + raise queue.Empty + + with cancellation_scope(token), pytest.raises(CancelledError): + wait_for_event(Events(), float("inf")) + assert len(intervals) == 1 + assert 0 < intervals[0] <= 0.1 + + +def test_focus_queue_timeout_does_not_restart_deadline(monkeypatch): + from je_auto_control.utils.accessibility.backends import windows_events + import queue + + moments = iter([10.0, 10.0, 11.0]) + monkeypatch.setattr(windows_events.time, "monotonic", lambda: next(moments)) + assert windows_events.wait_for_event(queue.Queue(), 0) is None From 89ff22a47def2f3e4ba547d0ac32132d4076b49e Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:28:28 +0800 Subject: [PATCH 002/161] fix: propagate executor stop into focus-event waits --- Progress.md | 1 - architecture_explore.md | 10 +++---- docs/guides/en/usage.md | 2 +- docs/guides/zh-CN/usage.md | 2 +- docs/guides/zh-TW/usage.md | 2 +- .../doc/new_features/v202_features_doc.rst | 4 +++ docs/updates/2026-11.md | 6 +++++ docs/updates/README.md | 3 ++- .../accessibility/backends/windows_events.py | 7 +++++ .../test_accessibility_windows_content.py | 27 +++++++++++++++++++ 10 files changed, 54 insertions(+), 10 deletions(-) diff --git a/Progress.md b/Progress.md index 20cb6437e..5161bb80b 100644 --- a/Progress.md +++ b/Progress.md @@ -107,7 +107,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 - **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep; - `AC_wait_for_focus_change` 的取消 token 路徑已接合,未綁定 token 的舊 stop 路徑仍待核對。 MCP 自己的輪詢(`ac_wait_for_image`/`ac_wait_for_pixel`)不在可停止的執行裡。非腳本的分頁工作在後端無法取消,只是結果被丟掉。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/architecture_explore.md b/architecture_explore.md index d9dd69e90..eb042fe9f 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,495 | -| 程式碼總行數 | 228,273 | +| 程式碼總行數 | 228,280 | | `je_auto_control/utils/` 子套件數 | 311 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -455,12 +455,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,852 行。 +> 16 個套件、約 4,859 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a11y_audit/` | 362 | 以無障礙樹 + OCR 進行無障礙與 i18n 稽核 | -| `utils/accessibility/` | 3,317 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | +| `utils/accessibility/` | 3,324 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | | `utils/ax_text/` | 102 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | @@ -1499,7 +1499,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | -| `utils/accessibility/` | 16 | 3,317 | +| `utils/accessibility/` | 16 | 3,324 | | `wrapper/` | 25 | 5,992 | | `windows/` | 24 | 2,265 | | `utils/rest_api/` | 8 | 2,226 | @@ -1514,7 +1514,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,486 | -| **總計** | **1,483** | **227,528** | +| **總計** | **1,483** | **227,535** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/usage.md b/docs/guides/en/usage.md index a79b37e88..23da3072c 100644 --- a/docs/guides/en/usage.md +++ b/docs/guides/en/usage.md @@ -215,4 +215,4 @@ under a relative name are written below that directory. --- -Windows focus-event waits honor a bound cooperative cancellation token and release their event subscription on exit. Native COM acceptance remains pending. +Windows focus-event waits honor a bound cooperative cancellation token or an executor stop token and release their event subscription on exit. Native COM acceptance remains pending. diff --git a/docs/guides/zh-CN/usage.md b/docs/guides/zh-CN/usage.md index ee8776dea..a89400394 100644 --- a/docs/guides/zh-CN/usage.md +++ b/docs/guides/zh-CN/usage.md @@ -202,4 +202,4 @@ je_auto_control version --- -Windows 焦点事件等待支持已绑定的协作取消 token,退出等待时解除事件订阅;真实 COM 验收仍待执行。 +Windows 焦点事件等待支持已绑定的协作取消 token 与 executor stop token,退出等待时解除事件订阅;真实 COM 验收仍待执行。 diff --git a/docs/guides/zh-TW/usage.md b/docs/guides/zh-TW/usage.md index 0b852f1b1..65d1da80e 100644 --- a/docs/guides/zh-TW/usage.md +++ b/docs/guides/zh-TW/usage.md @@ -202,4 +202,4 @@ je_auto_control version --- -Windows 焦點事件等待支援已綁定的協作取消 token,離開等待時解除事件訂閱;真實 COM 驗收仍待執行。 +Windows 焦點事件等待支援已綁定的協作取消 token 與 executor stop token,離開等待時解除事件訂閱;真實 COM 驗收仍待執行。 diff --git a/docs/source/Eng/doc/new_features/v202_features_doc.rst b/docs/source/Eng/doc/new_features/v202_features_doc.rst index 12f48bc93..88442103e 100644 --- a/docs/source/Eng/doc/new_features/v202_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v202_features_doc.rst @@ -45,3 +45,7 @@ focus-event subscription in the calling thread. Polling uses the original monotonic deadline; it does not extend the timeout. Unscoped waits retain their existing timeout behavior. Native COM acceptance remains pending in ``Progress.md``. + +Executor stop tokens are checked at the same queue boundaries. A stopped run +raises ``ExecutionStopped``; a shielded cleanup wait ignores the first stop +request and exits on the second, following the executor's cleanup rules. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 6583014ec..07c6a0e59 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -660,3 +660,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Windows focus-event queue waits now poll the bound cancellation token with one monotonic deadline and release the subscription through the existing finally block. - **Evidence:** Regression failed before the fix with `DID NOT RAISE CancelledError`; the focused accessibility, thread and public API suite passed 98 tests with one skip. - **Open items:** Real COM acceptance and the legacy stop path without a cancellation token remain in `Progress.md`. + +## U-20261110-02 · 2026-11-10 · Executor stop reaches focus-event waits · #done #accessibility + +- **What:** Focus-event waits check the existing executor stop token between bounded queue reads. They retain the single deadline, remove their subscription on stop, and honor cleanup shielding until a second stop request. +- **Evidence:** Both new stop regressions failed with `focus wait kept polling after stop` before the fix. Focus and public API tests pass after the fix. +- **Open items:** Native COM acceptance remains in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 5e6cdaed6..3441795a2 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-02 | 2026-11-10 | Executor stop reaches focus-event waits | #done #accessibility | [2026-11](2026-11.md) | | U-20261110-01 | 2026-11-10 | Cooperative cancellation for Windows focus waits | #done #accessibility | [2026-11](2026-11.md) | | U-20261103-01 | 2026-11-03 | Hold the collector off around the presence reader's timed windows | #incident #agent #ci #test | [2026-11](2026-11.md) | | U-20261102-03 | 2026-11-02 | Require Python 3.11; stop supporting 3.10 | #migration #deps #ci | [2026-11](2026-11.md) | @@ -609,7 +610,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 22 | +| [2026-11.md](2026-11.md) | 2026-11 | 23 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/utils/accessibility/backends/windows_events.py b/je_auto_control/utils/accessibility/backends/windows_events.py index 6eb26e0ee..029d7eb44 100644 --- a/je_auto_control/utils/accessibility/backends/windows_events.py +++ b/je_auto_control/utils/accessibility/backends/windows_events.py @@ -7,20 +7,27 @@ cancellation_checkpoint, cancellation_timeout, ) +from je_auto_control.utils.executor.run_control import checkpoint, current_stop_token + def wait_for_event(events: queue.Queue, timeout: float) -> Optional[Dict[str, Any]]: """Wait for one event while honoring the calling task's cancellation scope.""" deadline = time.monotonic() + timeout while True: cancellation_checkpoint() + checkpoint() remaining = max(0.0, deadline - time.monotonic()) interval = cancellation_timeout(remaining) + if current_stop_token() is not None: + interval = min(interval, 0.1) try: event = events.get(timeout=None if interval == float("inf") else interval) except queue.Empty: cancellation_checkpoint() + checkpoint() if time.monotonic() >= deadline: return None else: cancellation_checkpoint() + checkpoint() return event diff --git a/test/unit_test/headless/test_accessibility_windows_content.py b/test/unit_test/headless/test_accessibility_windows_content.py index 8e095de6f..5f4415f8e 100644 --- a/test/unit_test/headless/test_accessibility_windows_content.py +++ b/test/unit_test/headless/test_accessibility_windows_content.py @@ -781,3 +781,30 @@ def test_focus_queue_timeout_does_not_restart_deadline(monkeypatch): moments = iter([10.0, 10.0, 11.0]) monkeypatch.setattr(windows_events.time, "monotonic", lambda: next(moments)) assert windows_events.wait_for_event(queue.Queue(), 0) is None + + +@pytest.mark.parametrize("shield", [False, True]) +def test_focus_wait_observes_stop_and_releases_handler(backend, monkeypatch, shield): + from contextlib import nullcontext + import queue + from je_auto_control.utils.executor.run_control import ( + StopToken, ExecutionStopped, bound_stop_token, shielded, + ) + + token = StopToken("focus-wait") + polls = [] + + def stop_during_wait(events, *, timeout): + polls.append(timeout) + assert len(polls) <= 2, "focus wait kept polling after stop" + token.stop("stop focus wait") + raise queue.Empty + + monkeypatch.setattr(backend, "_make_focus_handler", lambda sink: object()) + monkeypatch.setattr(queue.Queue, "get", stop_during_wait) + with bound_stop_token(token), shielded() if shield else nullcontext(): + with pytest.raises(ExecutionStopped, match="stop focus wait"): + backend.wait_for_focus_change(timeout=float("inf")) + assert len(polls) == (2 if shield else 1) + assert all(interval is not None and 0 < interval <= 0.1 for interval in polls) + assert backend._automation.focus_handlers == [] From 8fea89d107e8d5319bb1420571a186c93d8106e0 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:36:46 +0800 Subject: [PATCH 003/161] fix: connect GUI task cancellation to headless operations --- Progress.md | 4 +- architecture_explore.md | 6 +- docs/guides/en/usage.md | 2 + docs/guides/zh-CN/usage.md | 2 + docs/guides/zh-TW/usage.md | 2 + docs/updates/2026-11.md | 6 + docs/updates/README.md | 3 +- je_auto_control/gui/_tab_task.py | 17 ++- .../accessibility/backends/windows_events.py | 2 +- pyproject.toml | 1 + .../test_tab_task_headless_cancellation.py | 110 ++++++++++++++++++ 11 files changed, 143 insertions(+), 12 deletions(-) create mode 100644 test/unit_test/headless/test_tab_task_headless_cancellation.py diff --git a/Progress.md b/Progress.md index 5161bb80b..880644ca1 100644 --- a/Progress.md +++ b/Progress.md @@ -79,7 +79,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD - Android:`input draganddrop` 是否存在、`monkey` 啟動輸出、`pidof`/`pm path` 的結束碼、`dumpsys activity activities` 的格式、`pkill -INT screenrecord` 能否收尾 MP4。 ADBKeyBoard 的送達無法由裝置確認,是從 IME 被選取推定的。 - 已知限制:iOS 捏合忽略 `x`/`y`/`span`;iOS `app_state` 不會回 `not_installed`;iOS 的安裝/檔案/錄影沒有 adapter(只有 `MobileExtension` 協定與註冊點); - Mobile 分頁的 probe/run 會卡住 GUI 執行緒到裝置回應或逾時。`AC_android_shell` 刻意不做成 MCP 工具,**請維護者確認**。 + Mobile 分頁的 probe/run 已由 TabTask 在背景執行;真實 SDK 的逾時、取消與裝置回應仍待實機驗收。`AC_android_shell` 刻意不做成 MCP 工具,**請維護者確認**。 - 沒有 `examples/` 的實機腳本以外的 smoke;Xcode/WDA 的建置與簽章只寫成前置條件。 --- @@ -107,7 +107,7 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 - **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep; - MCP 自己的輪詢(`ac_wait_for_image`/`ac_wait_for_pixel`)不在可停止的執行裡。非腳本的分頁工作在後端無法取消,只是結果被丟掉。 + MCP 自己的輪詢(`ac_wait_for_image`/`ac_wait_for_pixel`)不在可停止的執行裡。非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 - **WebRTC**:`StatsPoller.start()` 會在 GUI 執行緒上最多等 2 秒(`future.result(timeout=2.0)`,是啟動路徑,沒動)。LAN 廣播的註冊與取消已移出 GUI 執行緒, diff --git a/architecture_explore.md b/architecture_explore.md index eb042fe9f..5b5341686 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,495 | -| 程式碼總行數 | 228,280 | +| 程式碼總行數 | 228,287 | | `je_auto_control/utils/` 子套件數 | 311 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1493,7 +1493,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,844 | +| `gui/` | 144 | 39,851 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,243 | | `utils/executor/` | 11 | 10,702 | @@ -1514,7 +1514,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,486 | -| **總計** | **1,483** | **227,535** | +| **總計** | **1,483** | **227,542** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/usage.md b/docs/guides/en/usage.md index 23da3072c..5c7cf66b9 100644 --- a/docs/guides/en/usage.md +++ b/docs/guides/en/usage.md @@ -216,3 +216,5 @@ under a relative name are written below that directory. --- Windows focus-event waits honor a bound cooperative cancellation token or an executor stop token and release their event subscription on exit. Native COM acceptance remains pending. + +Ordinary GUI tab tasks pass cancellation to cooperative headless operations. Stop, timeout and closing the owner cancel those operations; late results from backends that do not check cancellation are discarded. Script tasks retain executor stop and cleanup-shield rules. diff --git a/docs/guides/zh-CN/usage.md b/docs/guides/zh-CN/usage.md index a89400394..e8e0ea736 100644 --- a/docs/guides/zh-CN/usage.md +++ b/docs/guides/zh-CN/usage.md @@ -203,3 +203,5 @@ je_auto_control version --- Windows 焦点事件等待支持已绑定的协作取消 token 与 executor stop token,退出等待时解除事件订阅;真实 COM 验收仍待执行。 + +普通 GUI 标签页任务会把取消信号传给支持协作取消的核心操作。停止、超时或关闭所属窗口会取消操作;未检查取消信号的后端,其迟到结果会被丢弃。脚本任务仍使用 executor 的停止与清理保护规则。 diff --git a/docs/guides/zh-TW/usage.md b/docs/guides/zh-TW/usage.md index 65d1da80e..7aff9fc7a 100644 --- a/docs/guides/zh-TW/usage.md +++ b/docs/guides/zh-TW/usage.md @@ -203,3 +203,5 @@ je_auto_control version --- Windows 焦點事件等待支援已綁定的協作取消 token 與 executor stop token,離開等待時解除事件訂閱;真實 COM 驗收仍待執行。 + +一般 GUI 分頁工作會把取消訊號傳給支援協作取消的核心操作。停止、逾時或關閉擁有者會取消操作;未檢查取消訊號的後端,其晚到結果會被丟棄。腳本工作仍使用 executor 的停止與清理保護規則。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 07c6a0e59..f9e8227c5 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -666,3 +666,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Focus-event waits check the existing executor stop token between bounded queue reads. They retain the single deadline, remove their subscription on stop, and honor cleanup shielding until a second stop request. - **Evidence:** Both new stop regressions failed with `focus wait kept polling after stop` before the fix. Focus and public API tests pass after the fix. - **Open items:** Native COM acceptance remains in `Progress.md`. + +## U-20261110-03 · 2026-11-10 · GUI task cancellation reaches headless waits · #done #gui + +- **What:** Ordinary TabTask work binds a core cancellation scope linked to the GUI token. Stop, timeout and owner destruction reach cooperative waits; pre-cancelled work does not start, and completed work releases the scope. Script stop shielding stays unchanged. +- **Evidence:** Five new regressions failed before the fix and passed afterward; delegate controller/executor suite: 43 passed; new tests plus GUI scripts: 22 passed. Mobile surface tests: 13 passed, confirming probe/run already execute asynchronously. +- **Open items:** Noncooperative backend calls and native/device acceptance remain in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 3441795a2..72a2a2827 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-03 | 2026-11-10 | GUI task cancellation reaches headless waits | #done #gui | [2026-11](2026-11.md) | | U-20261110-02 | 2026-11-10 | Executor stop reaches focus-event waits | #done #accessibility | [2026-11](2026-11.md) | | U-20261110-01 | 2026-11-10 | Cooperative cancellation for Windows focus waits | #done #accessibility | [2026-11](2026-11.md) | | U-20261103-01 | 2026-11-03 | Hold the collector off around the presence reader's timed windows | #incident #agent #ci #test | [2026-11](2026-11.md) | @@ -610,7 +611,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 23 | +| [2026-11.md](2026-11.md) | 2026-11 | 24 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/gui/_tab_task.py b/je_auto_control/gui/_tab_task.py index 74efcb538..a43252336 100644 --- a/je_auto_control/gui/_tab_task.py +++ b/je_auto_control/gui/_tab_task.py @@ -16,8 +16,8 @@ it never waits for the worker, so a script that drives this GUI cannot deadlock it -- and the run's end arrives as an ``ExecutionStopped`` error once the worker has really unwound, which is when the tab is free again. - Other work is cancelled through its handle: it runs to its end unobserved - and its result is dropped. + Other work binds a headless cancellation scope. Cooperative backends stop + at their next checkpoint; late results from noncooperative work are dropped. The object keeps no reference to its tab beyond Qt parentage, and the work it is given must not hold a widget (the controller refuses it): read what the @@ -29,6 +29,9 @@ from PySide6.QtCore import QObject, Signal from je_auto_control.gui.tab_task_controller import CancellationToken, TaskHandle, task_controller +from je_auto_control.utils.exception.cancellation import ( + CancellationToken as CoreCancellationToken, cancellation_scope, +) from je_auto_control.utils.executor.run_control import ( ExecutionStopped, StopToken, stop_execution, stoppable_run, ) @@ -104,9 +107,13 @@ def _on_finished(self) -> None: self.finished.emit() -def _call_plain(work: Callable[[], Any], _token: CancellationToken) -> Any: - """Worker thread: work that takes neither a timeout nor a cancel signal.""" - return work() +def _call_plain(work: Callable[[], Any], token: CancellationToken) -> Any: + """Worker thread: bind handle cancellation for cooperative headless work.""" + core_token = CoreCancellationToken(task_id=id(token)) + token.on_cancel(core_token.cancel) + with cancellation_scope(core_token): + core_token.checkpoint() + return work() def _call_stoppable(stop: StopToken, work: Callable[[], Any], token: CancellationToken) -> Any: diff --git a/je_auto_control/utils/accessibility/backends/windows_events.py b/je_auto_control/utils/accessibility/backends/windows_events.py index 029d7eb44..b67a12ba2 100644 --- a/je_auto_control/utils/accessibility/backends/windows_events.py +++ b/je_auto_control/utils/accessibility/backends/windows_events.py @@ -10,7 +10,7 @@ from je_auto_control.utils.executor.run_control import checkpoint, current_stop_token -def wait_for_event(events: queue.Queue, timeout: float) -> Optional[Dict[str, Any]]: +def wait_for_event(events: queue.Queue[Dict[str, Any]], timeout: float) -> Optional[Dict[str, Any]]: """Wait for one event while honoring the calling task's cancellation scope.""" deadline = time.monotonic() + timeout while True: diff --git a/pyproject.toml b/pyproject.toml index ac2ee761c..dc81b8bef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -441,6 +441,7 @@ module = [ "je_auto_control.gui._weak_call", "je_auto_control.gui._qt_typed", "je_auto_control.utils.accessibility.backends.windows_automation", + "je_auto_control.utils.accessibility.backends.windows_events", "je_auto_control.utils.remote_desktop.input_send_queue", "je_auto_control_pytest", ] diff --git a/test/unit_test/headless/test_tab_task_headless_cancellation.py b/test/unit_test/headless/test_tab_task_headless_cancellation.py new file mode 100644 index 000000000..8847c7d6c --- /dev/null +++ b/test/unit_test/headless/test_tab_task_headless_cancellation.py @@ -0,0 +1,110 @@ +"""Tab cancellation reaches cooperative headless work without native UI operations.""" +import os +import queue +import threading +import time +import weakref +from concurrent.futures import CancelledError + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +from PySide6.QtCore import QEvent # noqa: E402 +from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 +from je_auto_control.gui._tab_task import TabTask, _call_plain # noqa: E402 +from je_auto_control.gui.tab_task_controller import CancellationToken, TaskTimeout # noqa: E402 +from je_auto_control.utils.accessibility.backends.windows_events import wait_for_event # noqa: E402 +from je_auto_control.utils.exception.cancellation import current_cancellation_token # noqa: E402 + + +def _pump(app, predicate): + deadline = time.monotonic() + 3 + while not predicate() and time.monotonic() < deadline: + app.processEvents() + time.sleep(0.005) + return predicate() + + +def _destroy(app, owner): + owner.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + app.processEvents() + + +@pytest.mark.parametrize("reason", ["stop", "timeout", "owner_destroyed"]) +def test_tab_cancellation_ends_headless_wait(reason): + app = QApplication.instance() or QApplication([]) + owner = QWidget() + tab = TabTask(owner) + entered, exited = threading.Event(), threading.Event() + events = queue.Queue() + cancelled, results, errors = [], [], [] + + def work(): + entered.set() + try: + return wait_for_event(events, 10) + except CancelledError: + cancelled.append(True) + raise + finally: + exited.set() + + tab.result.connect(results.append) + tab.error.connect(errors.append) + assert tab.start(work, timeout_s=0.5 if reason == "timeout" else None) + try: + assert _pump(app, entered.is_set) + if reason == "stop": + assert tab.stop() + elif reason == "owner_destroyed": + _destroy(app, owner) + assert _pump(app, exited.is_set), "cancel did not reach the headless wait" + assert cancelled == [True] + assert results == [] + if reason == "timeout": + assert len(errors) == 1 and isinstance(errors[0], TaskTimeout) + else: + assert errors == [] + finally: + events.put({"cleanup": True}) + assert _pump(app, exited.is_set) + if reason != "owner_destroyed": + _destroy(app, owner) + + +def test_precancelled_tab_work_never_starts_and_scope_is_restored(): + token = CancellationToken() + token.cancel() + called = [] + with pytest.raises(CancelledError): + _call_plain(lambda: called.append(True), token) + assert called == [] + assert current_cancellation_token() is None + + +def test_tab_work_delivers_normal_result_with_scope(): + app = QApplication.instance() or QApplication([]) + owner = QWidget() + tab = TabTask(owner) + results, scopes = [], [] + + def work(): + token = current_cancellation_token() + assert token is not None + scopes.append(weakref.ref(token)) + events = queue.Queue() + events.put({"name": "ready"}) + return wait_for_event(events, 1) + + tab.result.connect(results.append) + try: + assert tab.start(work) + assert _pump(app, lambda: not tab.running) + assert results == [{"name": "ready"}] + assert current_cancellation_token() is None + assert _pump(app, lambda: scopes[0]() is None), "completed work retained its cancellation scope" + finally: + _destroy(app, owner) From a44828f23f6b1936a85af6370a5e93e042322525 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:38:48 +0800 Subject: [PATCH 004/161] docs: reconcile verified USB progress with current implementation --- Progress.md | 5 ++--- docs/updates/2026-11.md | 6 ++++++ docs/updates/README.md | 3 ++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Progress.md b/Progress.md index 880644ca1..f18ab9634 100644 --- a/Progress.md +++ b/Progress.md @@ -142,9 +142,8 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` `ac_handle_file_dialog` 的 `path`、自由格式物件裡的路徑(`ac_run_suite` 的 `spec`、`ac_run_dag` 的 `definition`、`ac_assert_all` 的 `specs`)、沒標註的外掛工具。 檔案 symlink 的跳脫在這台機器上建不出來(只跑了目錄 junction);POSIX 的 `:` 分隔與 `~` 沒在 Linux/macOS 跑。 `roots/list` 來的根目錄要另外開 `JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT` 才算數——這是實作時定的,請維護者確認。 -- **USB passthrough**:client 仍在 `reply_timeout_s`(10 秒)放棄,即使呼叫端要的 `timeout_ms` 更長(host 接受到 60 秒); - 對新 host 逾時已經無害,對舊 host 正常使用就會進入「需重連」。通道層的 ERROR(passthrough 關閉、bad frame、host 沒有 session)在 session 之前送出、不帶請求編號, - 呼叫仍是等到逾時。沒對真的舊版 host、真的 WebRTC 通道或真的 USB 裝置跑過。 +- **USB passthrough 實機驗收**:仍須對真的舊版 host、WebRTC 通道與 USB 裝置驗證長時間 transfer、 + 裝置逾時、通道 ERROR、晚到回覆與重新連線。現有 fake channel/backend 測試不能代替這項驗收。 - **變數範圍**:free-threaded 原生執行緒繼承與同時存取範圍的行為尚未實測。 - **遠端桌面的擁有者模型**:Quick Connect 沒有狀態列,它的連線被取代時視窗只是關掉;主機的 Stop 會停任何擁有者開的 host(刻意的); 只用假的 viewer/host 測過,真的 viewer 被擠掉時會不會觸發 `on_error` 而多跳一個警告框,沒看過。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index f9e8227c5..07acaa282 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -672,3 +672,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Ordinary TabTask work binds a core cancellation scope linked to the GUI token. Stop, timeout and owner destruction reach cooperative waits; pre-cancelled work does not start, and completed work releases the scope. Script stop shielding stays unchanged. - **Evidence:** Five new regressions failed before the fix and passed afterward; delegate controller/executor suite: 43 passed; new tests plus GUI scripts: 22 passed. Mobile surface tests: 13 passed, confirming probe/run already execute asynchronously. - **Open items:** Noncooperative backend calls and native/device acceptance remain in `Progress.md`. + +## U-20261110-04 · 2026-11-10 · Reconcile USB wait and channel-error progress · #done #usb + +- **What:** Verified the existing viewer adds the bounded device timeout to its reply budget and channel-level errors reach their matching request. Removed the stale implementation gaps from Progress, retaining actual device/WebRTC/legacy-host acceptance. +- **Evidence:** `test_usb_client_wait_and_channel_errors.py`: 31 passed. Source: `viewer_client._round_trip`, `_client_requests.device_timeout_s`, and channel host/client adapters. +- **Open items:** Real USB, WebRTC and legacy-host acceptance remain in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 72a2a2827..5c810deaf 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-04 | 2026-11-10 | Reconcile USB wait and channel-error progress | #done #usb | [2026-11](2026-11.md) | | U-20261110-03 | 2026-11-10 | GUI task cancellation reaches headless waits | #done #gui | [2026-11](2026-11.md) | | U-20261110-02 | 2026-11-10 | Executor stop reaches focus-event waits | #done #accessibility | [2026-11](2026-11.md) | | U-20261110-01 | 2026-11-10 | Cooperative cancellation for Windows focus waits | #done #accessibility | [2026-11](2026-11.md) | @@ -611,7 +612,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 24 | +| [2026-11.md](2026-11.md) | 2026-11 | 25 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | From 418e0eedebddaaa256347586099e94a3249f1848 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:40:28 +0800 Subject: [PATCH 005/161] docs: close verified RBAC administration delivery gap --- Progress.md | 1 - docs/updates/2026-11.md | 6 ++++++ docs/updates/README.md | 3 ++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Progress.md b/Progress.md index f18ab9634..56e7e97ea 100644 --- a/Progress.md +++ b/Progress.md @@ -134,7 +134,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 私鑰是未加密的 PEM(0600,Windows 上沒驗權限位元),沒有通行碼選項;遷移模式開著時 HMAC 簽章會被接受。 強制簽章經 socket/REST/MCP 的端到端沒有跑過,覆蓋的是共用的 `read_executable_action_json` 與指令本身。 - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - - 使用者只能用 Python 管(`UserStore.add_user/set_role/rotate_token/remove_user`),沒有 `AC_*`、CLI 或 GUI;`Capability.MANAGE_USERS` 因此沒有任何路由或工具對應。 - viewer 的其餘影像檔案型、mobile 與外掛唯讀工具仍需全面盤點 capability;自製工具仍依提示採預設分類。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;SSE、無狀態與 `subscriptions/listen` 路徑、TLS 加 RBAC 沒有測試。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉)管不到的參數:執行動作清單的工具、 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 07acaa282..11043e4e5 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -678,3 +678,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Verified the existing viewer adds the bounded device timeout to its reply budget and channel-level errors reach their matching request. Removed the stale implementation gaps from Progress, retaining actual device/WebRTC/legacy-host acceptance. - **Evidence:** `test_usb_client_wait_and_channel_errors.py`: 31 passed. Source: `viewer_client._round_trip`, `_client_requests.device_timeout_s`, and channel host/client adapters. - **Open items:** Real USB, WebRTC and legacy-host acceptance remain in `Progress.md`. + +## U-20261110-05 · 2026-11-10 · Verify existing RBAC administration delivery · #done #rbac + +- **What:** Confirmed user administration already shares `rbac.admin` across AC commands, MCP, REST, CLI and the GUI panel. Removed the obsolete Python-only delivery gap from Progress. +- **Evidence:** `test_rbac_user_admin.py` and `test_rbac_users_gui.py`: 34 passed. Tests cover admin-only requests, first-admin CLI bootstrap, last-admin protection, token disclosure/audit behavior and offscreen GUI actions. +- **Open items:** Actual clients, TLS combinations and remaining capability coverage stay in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 5c810deaf..9df63ac6c 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-05 | 2026-11-10 | Verify existing RBAC administration delivery | #done #rbac | [2026-11](2026-11.md) | | U-20261110-04 | 2026-11-10 | Reconcile USB wait and channel-error progress | #done #usb | [2026-11](2026-11.md) | | U-20261110-03 | 2026-11-10 | GUI task cancellation reaches headless waits | #done #gui | [2026-11](2026-11.md) | | U-20261110-02 | 2026-11-10 | Executor stop reaches focus-event waits | #done #accessibility | [2026-11](2026-11.md) | @@ -612,7 +613,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 25 | +| [2026-11.md](2026-11.md) | 2026-11 | 26 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | From ca25c88d43f7bfa7705c68c196445c41ed6efc9a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:43:45 +0800 Subject: [PATCH 006/161] refactor: give Report its own lazy widget lifecycle --- Progress.md | 4 +- architecture_explore.md | 12 +- docs/guides/en/setup.md | 2 + docs/guides/zh-CN/setup.md | 2 + docs/guides/zh-TW/setup.md | 2 + docs/updates/2026-11.md | 6 + docs/updates/README.md | 3 +- je_auto_control/gui/_report_tab.py | 46 ++++---- je_auto_control/gui/main_widget.py | 10 +- je_auto_control/gui/tab_registry.py | 2 +- .../headless/test_gui_lazy_registry.py | 2 +- .../headless/test_r3_gui_slot_exceptions.py | 31 +++--- .../headless/test_report_tab_lifecycle.py | 103 ++++++++++++++++++ 13 files changed, 169 insertions(+), 56 deletions(-) create mode 100644 test/unit_test/headless/test_report_tab_lifecycle.py diff --git a/Progress.md b/Progress.md index 56e7e97ea..3cb543432 100644 --- a/Progress.md +++ b/Progress.md @@ -517,9 +517,9 @@ D2 仍缺 helper 隔離與半開交握資源回收;D3 的錄製/全域停止 計畫 E(Android/iOS)、H(型別深化與總驗收)尚未開始。F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 -- **F1 的遺留面板釋放**:擁有者直接建立的核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 +- **F1 的遺留面板釋放**:Auto Click、Screenshot、Image Detection、Record、Script 五個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 -- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 +- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。Report 已完成獨立生命週期,報表產生仍須移出 GUI 執行緒並拒絕關閉後的晚到結果。 - **F4**(啟動/記憶體基準、mixed-DPI、功能對等測試)尚未開始。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/architecture_explore.md b/architecture_explore.md index 5b5341686..874e97cc2 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,495 | -| 程式碼總行數 | 228,287 | +| 程式碼總行數 | 228,285 | | `je_auto_control/utils/` 子套件數 | 311 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1262,7 +1262,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | | `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | -| `main_widget.py` | 394 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | +| `main_widget.py` | 386 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | | `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與既有表單;不匯入 Qt。 | | `navigation.py` | 200 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | @@ -1276,7 +1276,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `_image_detect_tab.py` | 117 | 影像偵測分頁 mixin。 | | `_script_tab.py` | 158 | 腳本執行分頁 mixin。 | | `_record_tab.py` | 144 | 錄製/回放分頁 mixin。 | -| `_report_tab.py` | 88 | 報表分頁 mixin。 | +| `_report_tab.py` | 94 | 報表分頁 mixin。 | | `_i18n_helpers.py` | 79 | 需要即時語言切換的分頁共用的翻譯註冊 mixin。 | | `_validators.py` | 29 | `int_validator()`/`double_validator()`:以 C locale 驗證的數字輸入框 validator,接受的正是 `int()`/`float()` 讀得懂的寫法(預設 locale 在法文、德文下只收小數逗號)。所有數字 `QLineEdit` 都用它。 | | `_screen_geometry.py` | 55 | Qt 邏輯座標與截圖用的原生像素互轉:`native_region()`、`screen_at_native()`、`logical_point()`(每個螢幕的左上角在兩者相同,螢幕內依 device pixel ratio 縮放)。區域選取與主機端標註覆蓋層都用它。 | @@ -1351,7 +1351,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | usb_browser | `usb_browser_tab.py` | 290 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | | diagnostics | `diagnostics_tab.py` | 221 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | -| report | `_report_tab.py` | 88 | 產生 HTML/JSON/XML 報表。 | +| report | `_report_tab.py` | 94 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1493,7 +1493,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,851 | +| `gui/` | 144 | 39,849 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,243 | | `utils/executor/` | 11 | 10,702 | @@ -1514,7 +1514,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,486 | -| **總計** | **1,483** | **227,542** | +| **總計** | **1,483** | **227,540** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/setup.md b/docs/guides/en/setup.md index 334ab0130..059000a93 100644 --- a/docs/guides/en/setup.md +++ b/docs/guides/en/setup.md @@ -353,3 +353,5 @@ Every environment variable AutoControl reads. Nothing here is required: with no | `JE_AUTOCONTROL_PYTEST_ARTIFACTS` | `./autocontrol_screenshots` | Directory the pytest plugin writes failure screenshots to when a test did not request the `autocontrol_screenshot_dir` fixture. | --- + +The Report page is created when first opened. Closing it releases its controls and local result view; reopening creates a fresh page and reads the current recording status. Closing the page does not disable the shared recorder. diff --git a/docs/guides/zh-CN/setup.md b/docs/guides/zh-CN/setup.md index 043ec72bc..34760744a 100644 --- a/docs/guides/zh-CN/setup.md +++ b/docs/guides/zh-CN/setup.md @@ -292,3 +292,5 @@ AutoControl 读取的每一个环境变量。这里没有任何一项是必填 | `JE_AUTOCONTROL_PYTEST_ARTIFACTS` | `./autocontrol_screenshots` | 测试没有使用 `autocontrol_screenshot_dir` fixture 时,pytest 插件写入失败截图的目录。 | --- + +Report 标签页在首次打开时创建。关闭会释放控件和本地结果视图;重新打开会创建新页面并读取当前录制状态。关闭标签页不会禁用共享 recorder。 diff --git a/docs/guides/zh-TW/setup.md b/docs/guides/zh-TW/setup.md index be799a002..2639cbcb1 100644 --- a/docs/guides/zh-TW/setup.md +++ b/docs/guides/zh-TW/setup.md @@ -292,3 +292,5 @@ AutoControl 讀取的每一個環境變數。這裡沒有任何一項是必填 | `JE_AUTOCONTROL_PYTEST_ARTIFACTS` | `./autocontrol_screenshots` | 測試沒有使用 `autocontrol_screenshot_dir` fixture 時,pytest 外掛寫入失敗截圖的目錄。 | --- + +Report 分頁在首次開啟時建立。關閉會釋放控制項與本機結果畫面;重新開啟會建立新頁面並讀取目前錄製狀態。關閉分頁不會停用共用 recorder。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 11043e4e5..8ee18fbcc 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -684,3 +684,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Confirmed user administration already shares `rbac.admin` across AC commands, MCP, REST, CLI and the GUI panel. Removed the obsolete Python-only delivery gap from Progress. - **Evidence:** `test_rbac_user_admin.py` and `test_rbac_users_gui.py`: 34 passed. Tests cover admin-only requests, first-admin CLI bootstrap, last-admin protection, token disclosure/audit behavior and offscreen GUI actions. - **Open items:** Actual clients, TLS combinations and remaining capability coverage stay in `Progress.md`. + +## U-20261110-06 · 2026-11-10 · Give the Report page independent ownership · #done #gui + +- **What:** Migrated Report from a main-window mixin to a lazily created widget with its own controls, translations and Actions. Close releases local state; reopen creates a new page. Construction/show reads actual recorder status; closing does not disable shared recording. +- **Evidence:** Delegate report/registry/exception/actions tests: 77 passed with offscreen Qt. All repository control callers migrated; old mixin path removed. +- **Open items:** Remaining owner-built panels and report-generation responsiveness are tracked under GUI F1/F3 in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 9df63ac6c..950b1a94c 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-06 | 2026-11-10 | Give the Report page independent ownership | #done #gui | [2026-11](2026-11.md) | | U-20261110-05 | 2026-11-10 | Verify existing RBAC administration delivery | #done #rbac | [2026-11](2026-11.md) | | U-20261110-04 | 2026-11-10 | Reconcile USB wait and channel-error progress | #done #usb | [2026-11](2026-11.md) | | U-20261110-03 | 2026-11-10 | GUI task cancellation reaches headless waits | #done #gui | [2026-11](2026-11.md) | @@ -613,7 +614,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 26 | +| [2026-11.md](2026-11.md) | 2026-11 | 27 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/gui/_report_tab.py b/je_auto_control/gui/_report_tab.py index a0ff52941..111d6fac5 100644 --- a/je_auto_control/gui/_report_tab.py +++ b/je_auto_control/gui/_report_tab.py @@ -1,11 +1,11 @@ -"""Report-generation tab builder (extracted mixin).""" -from typing import TYPE_CHECKING, Any, Callable +"""Report-generation panel with independently owned controls and actions.""" from PySide6.QtWidgets import ( QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QWidget, ) +from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.generate_report.generate_html_report import generate_html_report from je_auto_control.utils.generate_report.generate_json_report import generate_json_report @@ -13,22 +13,13 @@ from je_auto_control.utils.test_record.record_test_class import test_record_instance -class ReportTabMixin: - """Provides the report-generation tab builder/handlers. +class ReportTab(TranslatableMixin, QWidget): + """Own report inputs and reflect the process-wide recorder without owning it.""" - Host widget must expose the TranslatableMixin API (``self._tr(...)``) - so every label/button registers for live language switching. - """ - - if TYPE_CHECKING: - # Declared, never defined: the widget this mixin is mixed into owns - # every one of these. The block is stripped at runtime, so nothing - # here can shadow what the host actually binds. - _tr: Callable[..., Any] - - def _build_report_tab(self) -> QWidget: - tab = QWidget() - layout = QVBoxLayout() + def __init__(self, parent=None): + super().__init__(parent) + self._tr_init() + layout = QVBoxLayout(self) # Enable/disable recording and report generation run from the # Actions menu; the tab keeps only status, name input, and result. @@ -50,12 +41,27 @@ def _build_report_tab(self) -> QWidget: self.report_result_text.setReadOnly(True) layout.addWidget(self.report_result_text) layout.addStretch() - tab.setLayout(layout) - return tab + self.sync_with_engine() + + def menu_actions(self): + return [ + ("enable_test_record", self._enable_test_record), + ("disable_test_record", self._disable_test_record), + ("generate_html_report", self._gen_html), + ("generate_json_report", self._gen_json), + ("generate_xml_report", self._gen_xml), + ] + + def sync_with_engine(self): + self.tr_status_label.setText("ON" if test_record_instance.init_record else "OFF") + + def showEvent(self, event): # noqa: N802 # reason: Qt virtual method + self.sync_with_engine() + super().showEvent(event) def _set_test_record(self, enable: bool): test_record_instance.set_record_enable(enable) - self.tr_status_label.setText("ON" if enable else "OFF") + self.sync_with_engine() def _enable_test_record(self): self._set_test_record(True) diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index 8c44acc35..51ab3a2cb 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -12,7 +12,6 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._image_detect_tab import ImageDetectTabMixin from je_auto_control.gui._record_tab import RecordTabMixin -from je_auto_control.gui._report_tab import ReportTabMixin from je_auto_control.gui._screenshot_tab import ScreenshotTabMixin from je_auto_control.gui._script_tab import ScriptTabMixin from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper @@ -37,7 +36,7 @@ class _WorkerSignals(QObject): # ============================================================================= class AutoControlGUIWidget( TranslatableMixin, AutoClickTabMixin, ScreenshotTabMixin, - ImageDetectTabMixin, RecordTabMixin, ScriptTabMixin, ReportTabMixin, + ImageDetectTabMixin, RecordTabMixin, ScriptTabMixin, QWidget, ): """Owns the QTabWidget and exposes show/hide/list APIs for the menu bar.""" @@ -131,13 +130,6 @@ def _own_tab_builders(self) -> Dict[str, Any]: ("task_stop", self._stop_script), )), "remote_desktop": (self._build_remote_desktop_tab, ()), - "report": (self._build_report_tab(), ( - ("enable_test_record", self._enable_test_record), - ("disable_test_record", self._disable_test_record), - ("generate_html_report", self._gen_html), - ("generate_json_report", self._gen_json), - ("generate_xml_report", self._gen_xml), - )), } @staticmethod diff --git a/je_auto_control/gui/tab_registry.py b/je_auto_control/gui/tab_registry.py index 27d3ec004..c78a50d46 100644 --- a/je_auto_control/gui/tab_registry.py +++ b/je_auto_control/gui/tab_registry.py @@ -194,5 +194,5 @@ def close(self, key: str) -> None: TabSpec("usb_share", "tab_usb_share", "system", f"{_GUI}.usb_passthrough_panel", "UsbPassthroughPanel"), TabSpec("diagnostics", "tab_diagnostics", "system", f"{_GUI}.diagnostics_tab", "DiagnosticsTab"), TabSpec("config_sync", "tab_config_sync", "system", f"{_GUI}.config_sync_tab", "ConfigSyncTab"), - TabSpec("report", "tab_report", "system"), + TabSpec("report", "tab_report", "system", f"{_GUI}._report_tab", "ReportTab"), ) diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index 8d299506e..8be8c987a 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -17,7 +17,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[3] # Built by the main widget itself: its mixin tabs, and Remote Desktop's placeholder fallback. -OWN_TABS = {"auto_click", "screenshot", "image_detect", "record", "script", "remote_desktop", "report"} +OWN_TABS = {"auto_click", "screenshot", "image_detect", "record", "script", "remote_desktop"} OPEN_AT_START = ["record", "script_builder", "remote_desktop"] diff --git a/test/unit_test/headless/test_r3_gui_slot_exceptions.py b/test/unit_test/headless/test_r3_gui_slot_exceptions.py index 22c20adf1..c43da0da3 100644 --- a/test/unit_test/headless/test_r3_gui_slot_exceptions.py +++ b/test/unit_test/headless/test_r3_gui_slot_exceptions.py @@ -102,22 +102,21 @@ def test_execute_script_slot_surfaces_autocontrol_exception(monkeypatch): # --- Finding 6: report tab, zero records ----------------------------------- -def test_report_gen_html_slot_surfaces_autocontrol_exception(): - from je_auto_control.gui._report_tab import ReportTabMixin - from je_auto_control.utils.test_record.record_test_class import ( - test_record_instance, - ) - test_record_instance.test_record_list.clear() # zero records -> raises - captured = {} - stub = types.SimpleNamespace( - report_name_input=types.SimpleNamespace(text=lambda: "rpt"), - report_result_text=types.SimpleNamespace( - setText=lambda s: captured.__setitem__("t", s), - ), - ) - - ReportTabMixin._gen_html(stub) # must not raise AutoControlHTMLException - assert captured.get("t", "").startswith("Error") +def test_report_gen_html_slot_surfaces_autocontrol_exception(monkeypatch): + from PySide6.QtWidgets import QApplication + from je_auto_control.gui._report_tab import ReportTab + from je_auto_control.utils.test_record.record_test_class import test_record_instance + + app = QApplication.instance() or QApplication([]) + monkeypatch.setattr(test_record_instance, "test_record_list", []) + tab = ReportTab() + tab.report_name_input.setText("rpt") + try: + tab._gen_html() + assert tab.report_result_text.toPlainText().startswith("Error") + finally: + tab.deleteLater() + app.processEvents() def test_report_generate_html_report_really_raises_on_zero_records(): diff --git a/test/unit_test/headless/test_report_tab_lifecycle.py b/test/unit_test/headless/test_report_tab_lifecycle.py new file mode 100644 index 000000000..949be7200 --- /dev/null +++ b/test/unit_test/headless/test_report_tab_lifecycle.py @@ -0,0 +1,103 @@ +"""Report panels own their controls and release them on registry close.""" +import os + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +from PySide6.QtCore import QEvent # noqa: E402 +from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 +from shiboken6 import isValid # noqa: E402 +from je_auto_control.gui import _report_tab # noqa: E402 +from je_auto_control.gui.tab_registry import TAB_SPECS, TabEntry, TabRegistry, lazy_factory # noqa: E402 +from je_auto_control.utils.test_record.record_test_class import TestRecord as Recorder # noqa: E402 + + +@pytest.fixture +def app(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def recorder(monkeypatch): + record = Recorder(init_record=True) + monkeypatch.setattr(_report_tab, "test_record_instance", record) + return record + + +def _delete(app, widget): + widget.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +def test_report_registry_releases_and_rebuilds_local_state(app, recorder): + spec = next(spec for spec in TAB_SPECS if spec.key == "report") + owner = QWidget() + entry = TabEntry(spec.key, spec.title_key, lazy_factory(spec.module, spec.class_name), + on_build=lambda page: page.setParent(owner)) + registry = TabRegistry([entry]) + assert not entry.built + page = registry.open("report") + page.report_name_input.setText("temporary-name") + page.report_result_text.setText("old result") + assert page.tr_status_label.text() == "ON" + page.hide() + assert registry.open("report") is page + assert page.report_name_input.text() == "temporary-name" + registry.close("report") + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + assert not entry.built + assert not isValid(page) + assert recorder.init_record + replacement = registry.open("report") + assert replacement is not page + assert replacement.report_name_input.text() == "autocontrol_report" + assert replacement.report_result_text.toPlainText() == "" + assert replacement.tr_status_label.text() == "ON" + assert not hasattr(owner, "report_name_input") + replacement.retranslate() + _delete(app, owner) + + +def test_report_refreshes_process_state_when_shown(app, recorder): + page = _report_tab.ReportTab() + try: + assert page.tr_status_label.text() == "ON" + page.show() + page.hide() + recorder.init_record = False + page.show() + assert page.tr_status_label.text() == "OFF" + finally: + _delete(app, page) + + +def test_record_actions_use_actual_recorder(app, recorder): + page = _report_tab.ReportTab() + try: + actions = dict(page.menu_actions()) + assert list(actions) == ["enable_test_record", "disable_test_record", "generate_html_report", + "generate_json_report", "generate_xml_report"] + actions["disable_test_record"]() + assert not recorder.init_record + assert page.tr_status_label.text() == "OFF" + actions["enable_test_record"]() + assert recorder.init_record + assert page.tr_status_label.text() == "ON" + finally: + _delete(app, page) + + +@pytest.mark.parametrize("format_name", ["html", "json", "xml"]) +def test_report_actions_generate_named_outputs(app, recorder, monkeypatch, format_name): + calls = [] + monkeypatch.setattr(_report_tab, "generate_" + format_name + "_report", calls.append) + page = _report_tab.ReportTab() + try: + page.report_name_input.setText("chosen-name") + dict(page.menu_actions())["generate_" + format_name + "_report"]() + assert calls == ["chosen-name"] + assert page.report_result_text.toPlainText() == format_name.upper() + " report generated: chosen-name" + finally: + _delete(app, page) From 171270fea5341e1bd2c158d8581173ccd759184c Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:47:15 +0800 Subject: [PATCH 007/161] fix: bind owned Linux presence endpoints through private helpers --- Progress.md | 7 +- architecture_explore.md | 24 +- docs/guides/en/integrations.md | 2 + docs/guides/zh-CN/integrations.md | 2 + docs/guides/zh-TW/integrations.md | 2 + docs/updates/2026-11.md | 6 + docs/updates/README.md | 3 +- .../utils/agent_runtime/native_target.py | 3 + .../utils/agent_runtime/native_worker.py | 14 +- .../utils/agent_runtime/presence_broker.py | 10 +- .../utils/agent_runtime/presence_host.py | 17 +- .../utils/agent_runtime/presence_pool.py | 25 +- .../utils/agent_runtime/presence_reader.py | 20 +- .../test_agent_presence_endpoint_flow.py | 226 ++++++++++++++++++ .../test_agent_presence_service_linux.py | 42 ++++ 15 files changed, 377 insertions(+), 26 deletions(-) create mode 100644 test/unit_test/headless/test_agent_presence_endpoint_flow.py diff --git a/Progress.md b/Progress.md index 3cb543432..3149dfa79 100644 --- a/Progress.md +++ b/Progress.md @@ -331,8 +331,11 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev 5 類呼叫者已改經 `owned_channel` 取得 channel: Linux 若有主機安裝的 root 擁有綁定檔,只能經服務啟動清單中完全相符的 argv,不退回本機程序。 已決定(2026-10-29):Linux 無綁定時繼續以本機 channel 執行 helper,runtime status 回報 - not_configured。presence broker 目前只有 Windows 版本,nested grant 待 Linux presence 來源 - 存在後接合。parent_watch、輸入 journal/lease 與本機 pipe 執行緒退場仍須接合。 + not_configured。Linux presence 已有私有 socket 傳輸及 owned-launch endpoint 經 broker/pool/host + 傳入 helper 的路徑;標準桌面准入仍限 Windows,Linux seat/真人活動與 nested grant 的完整接合仍待完成。 + Linux-only socket 端到端測試尚未本機執行:既有 WSL validation distro 的 ext4.vhdx 遺失, + 啟動回報 Wsl/Service/CreateInstance/MountDisk/HCS/ERROR_PATH_NOT_FOUND;不以 Windows IPC 或 mock 通過代替。 + parent_watch、輸入 journal/lease 與本機 pipe 執行緒退場仍須接合。 owner 服務原始碼依 2026-10-29 決定已進入 `native/owner_service/`(src、manifest 範本、build.sh、 tests 與兩個驗收執行器,不進 wheel),每個 client 帳號的 lease 配額已實作。 現況:經四十一輪獨立審查(處理紀錄見 docs/updates/2026-10-e.md,U-20261029-23 起),第二十三輪 diff --git a/architecture_explore.md b/architecture_explore.md index 874e97cc2..c3bf1591b 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,495 | -| 程式碼總行數 | 228,285 | +| 程式碼總行數 | 228,352 | | `je_auto_control/utils/` 子套件數 | 311 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -508,13 +508,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,131 行。 +> 14 個套件、約 52,198 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,253 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,891 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 25,958 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -1011,7 +1011,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,891 行/182 檔) +#### `utils/agent_runtime/`(25,958 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1083,8 +1083,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `native_job.py` | 170 | Own a Windows helper process tree through a kill-on-close Job Object. | | `native_recovery.py` | 36 | Host-only input recovery checks never replay persisted keys or signal persisted PIDs. | | `native_scope.py` | 111 | Scope native window and control targets before their existing backend performs an action. | -| `native_target.py` | 304 | Native desktop proxy with private IPC, host input ledger and cross-database ownership. | -| `native_worker.py` | 339 | Private native helper entry point; stdout is a bounded owner-only JSON protocol. | +| `native_target.py` | 307 | Native desktop proxy with private IPC, host input ledger and cross-database ownership. | +| `native_worker.py` | 349 | Private native helper entry point; stdout is a bounded owner-only JSON protocol. | | `observation_refs.py` | 151 | Resolve observation-local elements and thumbnail points into host-checked native coordinates. | | `ollama.py` | 82 | Local-only Ollama decisions over bounded HTTP, without an SDK or remote fallback. | | `origin_policy.py` | 193 | Live origin path ceilings remain restrictive across accepted tasks, workers and service processes. | @@ -1100,18 +1100,18 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence_channel_linux.py` | 434 | Own authenticated Linux packet channels, bounded leases and protected listeners. | | `presence_endpoint_linux.py` | 226 | Own protected Linux socket paths without stale-path reuse or recursive cleanup. | | `presence_frames.py` | 137 | Closed finite JSON byte frames and exact presence request/result validation. | -| `presence_broker.py` | 170 | Private broker with internally selected source ownership and normal busy/lease-lost results. | +| `presence_broker.py` | 176 | Private broker with internally selected source ownership and normal busy/lease-lost results. | | `presence_handshake.py` | 77 | Fresh byte challenges bound to native peer identity, birth and process-object liveness. | -| `presence_host.py` | 100 | Lazy host-owned source lifetimes and fixed per-helper capabilities, never task-selected authority. | +| `presence_host.py` | 115 | Lazy host-owned source lifetimes and fixed per-helper capabilities, never task-selected authority. | | `presence_messages_linux.py` | 102 | Authenticate each Linux packet and retire every received descriptor before delivery. | | `presence_native_types.py` | 16 | Resource-free native structure size and pointer views for presence components. | | `presence_owner.py` | 38 | Closed bounded owner-only line envelopes for private presence helpers. | | `presence_peer_linux.py` | 218 | Retain Linux connected-process evidence only; no desktop session or input authority. | | `presence_pipe_linux.py` | 211 | Linux presence transport behind the Windows pipe's interface; its endpoint arrives only through the owned launch. | | `presence_pipe_windows.py` | 209 | Secured local byte pipes for owned helpers; no desktop observation or runtime binding. | -| `presence_pool.py` | 381 | Host-only shared presence ownership; task cancellation never cancels another runtime's source. | +| `presence_pool.py` | 404 | Host-only shared presence ownership; task cancellation never cancels another runtime's source. | | `presence_protocol.py` | 74 | Per-connection sequences and issued-token ownership; shared source lifetime remains separate. | -| `presence_reader.py` | 219 | Fresh presence checks inside owned input helpers, with bounded callers and an independent watchdog. | +| `presence_reader.py` | 229 | Fresh presence checks inside owned input helpers, with bounded callers and an independent watchdog. | | `presence_security_windows.py` | 220 | Query-only endpoint identity and noninheritable current-user/System security descriptors. | | `presence_session_windows.py` | 83 | Query-only current physical-console support checks; remote or unknown sessions fail closed. | | `presence_server.py` | 182 | One reserved session source with sixteen authenticated connections and token-only cleanup. | @@ -1513,8 +1513,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 981 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,486 | -| **總計** | **1,483** | **227,540** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,553 | +| **總計** | **1,483** | **227,607** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/integrations.md b/docs/guides/en/integrations.md index a41c30cec..22804a36e 100644 --- a/docs/guides/en/integrations.md +++ b/docs/guides/en/integrations.md @@ -128,3 +128,5 @@ RemoteDesktopHost(token="tok", ip_allowlist=["10.0.0.0/8", "192.168.1.100"]) ``` --- + +The internal presence transport can carry an owned Linux source endpoint through the private host/helper configuration. Lease and endpoint are pinned together; public task options cannot choose that endpoint. Standard desktop admission remains Windows-only. Linux socket execution and native desktop acceptance remain unverified. diff --git a/docs/guides/zh-CN/integrations.md b/docs/guides/zh-CN/integrations.md index 3f4a6ab33..48753e451 100644 --- a/docs/guides/zh-CN/integrations.md +++ b/docs/guides/zh-CN/integrations.md @@ -123,3 +123,5 @@ RemoteDesktopHost(token="tok", ip_allowlist=["10.0.0.0/8", "192.168.1.100"]) ``` --- + +内部 presence 传输可通过主机与 helper 的私有配置传递受管 Linux 来源端点。租约与端点一并固定,公开任务选项不能指定该端点。标准桌面准入仍限 Windows;Linux socket 实跑及原生桌面验收仍未完成。 diff --git a/docs/guides/zh-TW/integrations.md b/docs/guides/zh-TW/integrations.md index a1dd132bf..21d0bd46e 100644 --- a/docs/guides/zh-TW/integrations.md +++ b/docs/guides/zh-TW/integrations.md @@ -124,3 +124,5 @@ RemoteDesktopHost(token="tok", ip_allowlist=["10.0.0.0/8", "192.168.1.100"]) ``` --- + +內部 presence 傳輸可透過主機與 helper 的私有設定傳遞受管 Linux 來源端點。租約與端點一併固定,公開任務選項不能指定該端點。標準桌面准入仍限 Windows;Linux socket 實跑及原生桌面驗收仍未完成。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 8ee18fbcc..c042c1231 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -690,3 +690,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Migrated Report from a main-window mixin to a lazily created widget with its own controls, translations and Actions. Close releases local state; reopen creates a new page. Construction/show reads actual recorder status; closing does not disable shared recording. - **Evidence:** Delegate report/registry/exception/actions tests: 77 passed with offscreen Qt. All repository control callers migrated; old mixin path removed. - **Open items:** Remaining owner-built panels and report-generation responsiveness are tracked under GUI F1/F3 in `Progress.md`. + +## U-20261110-07 · 2026-11-10 · Carry owned Linux presence endpoints into helpers · #done #agent + +- **What:** Broker/pool retain a validated endpoint from their owned source launch. An exact live-reference grant supplies a fresh snapshot; host/channel/spec and worker configuration pin it. Reader uses the platform transport and refuses Linux startup without the trusted endpoint. Source lease wire fields and Windows desktop admission remain unchanged. +- **Evidence:** Delegate focused suites: 78 passed; endpoint/Windows synthetic IPC: 33 passed, 3 Linux-only skipped; endpoint/runtime/worker binding: 34 passed. Mypy passed for the six modified production modules. Added Linux-only real-socket synthetic-source end-to-end coverage. +- **Open items:** Linux socket execution is unverified because the existing WSL validation distro cannot mount its missing ext4.vhdx; native authority integration and acceptance remain in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 950b1a94c..95be623ed 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-07 | 2026-11-10 | Carry owned Linux presence endpoints into helpers | #done #agent | [2026-11](2026-11.md) | | U-20261110-06 | 2026-11-10 | Give the Report page independent ownership | #done #gui | [2026-11](2026-11.md) | | U-20261110-05 | 2026-11-10 | Verify existing RBAC administration delivery | #done #rbac | [2026-11](2026-11.md) | | U-20261110-04 | 2026-11-10 | Reconcile USB wait and channel-error progress | #done #usb | [2026-11](2026-11.md) | @@ -614,7 +615,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 27 | +| [2026-11.md](2026-11.md) | 2026-11 | 28 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/utils/agent_runtime/native_target.py b/je_auto_control/utils/agent_runtime/native_target.py index d1b2731e0..db6402032 100644 --- a/je_auto_control/utils/agent_runtime/native_target.py +++ b/je_auto_control/utils/agent_runtime/native_target.py @@ -209,6 +209,9 @@ def ready(self, spec: AgentTaskSpec) -> tuple[bool, str]: channel = self._ensure() deadline = time.monotonic() + spec.budget.action_seconds payload['presence'] = self._presence.bind(context, channel, spec.budget.action_seconds) + endpoint = self._presence.endpoint() + if endpoint is not None: + payload['presence_endpoint'] = endpoint result = self._request("configure", payload, deadline=deadline) return bool(result["ready"]), str(result.get("reason", "")) diff --git a/je_auto_control/utils/agent_runtime/native_worker.py b/je_auto_control/utils/agent_runtime/native_worker.py index dba5f6318..f589a5071 100644 --- a/je_auto_control/utils/agent_runtime/native_worker.py +++ b/je_auto_control/utils/agent_runtime/native_worker.py @@ -22,6 +22,7 @@ from je_auto_control.utils.agent_runtime.context import TaskOperation, operation_scope from je_auto_control.utils.agent_runtime.presence_frames import presence_body from je_auto_control.utils.agent_runtime.presence_reader import PresenceReader +from je_auto_control.utils.agent_runtime.presence_pipe_linux import endpoint_from_wire, endpoint_to_wire _LIMIT = 1_100_000 @@ -42,6 +43,7 @@ def __init__(self, source: Any, sink: Any, *, target: Any = None) -> None: self._control_event = threading.Event() self._sink_lock = threading.Lock() self._presence_binding: dict | None = None + self._presence_endpoint: Any = None self._notice_stop = threading.Event() self._notice_thread: threading.Thread | None = None @@ -203,7 +205,10 @@ def _configure_scope(self, payload: dict) -> None: def _check_presence_pin(self, spec: AgentTaskSpec, owner: AuthorizationContext | None, payload: dict) -> None: if self._presence_binding is not None and (spec != self._spec or owner != self._owner - or payload.get('presence') != self._presence_binding): + or payload.get('presence') != self._presence_binding + or payload.get('presence_endpoint') != ( + endpoint_to_wire(self._presence_endpoint) + if self._presence_endpoint is not None else None)): raise AgentTaskError('configured desktop presence cannot change capability or owner scope') def _configure_presence(self, payload: dict) -> None: @@ -211,7 +216,10 @@ def _configure_presence(self, payload: dict) -> None: binding = payload.get('presence') if not isinstance(binding, dict): raise AgentTaskError('standard desktop worker requires a host presence binding') + endpoint = (endpoint_from_wire(payload['presence_endpoint']) + if 'presence_endpoint' in payload else None) self._presence_binding = presence_body('check', binding) + self._presence_endpoint = endpoint def _requires_presence(self) -> bool: return (not self._custom_target and self._spec is not None and self._spec.target != 'local-files' @@ -264,7 +272,9 @@ def _ready_activity(self) -> None: if self._activity is None: if self._presence_binding is None: raise AgentTaskError('standard desktop worker has no host presence binding') - self._activity = PresenceReader(self._presence_binding, self._control_event.set) + options = ({'endpoint': endpoint_to_wire(self._presence_endpoint)} + if self._presence_endpoint is not None else {}) + self._activity = PresenceReader(self._presence_binding, self._control_event.set, **options) self._notice_thread = threading.Thread(target=self._physical_takeover, name='AgentPresenceNotice', daemon=True) try: diff --git a/je_auto_control/utils/agent_runtime/presence_broker.py b/je_auto_control/utils/agent_runtime/presence_broker.py index 39649c410..b786645d9 100644 --- a/je_auto_control/utils/agent_runtime/presence_broker.py +++ b/je_auto_control/utils/agent_runtime/presence_broker.py @@ -18,6 +18,7 @@ ) from je_auto_control.utils.agent_runtime.presence_worker import SourceProcess from je_auto_control.utils.agent_runtime.parent_watch import start_parent_watch +from je_auto_control.utils.agent_runtime.presence_pipe_linux import endpoint_from_wire, endpoint_to_wire @dataclass @@ -27,6 +28,7 @@ class _Binding: owner: Any = None generation: str | None = None expected: str | None = None + endpoint: Any = None sequence: int = 1 closed: bool = False @@ -74,7 +76,8 @@ def _discover(self) -> Any: self._binding.expected = _ready(started) if self._binding.expected is not None and 'endpoint' in started: # Only this owned launch may name the endpoint; the channel then pins its listener. - self._pipe.use(started['endpoint']) + self._binding.endpoint = endpoint_from_wire(started['endpoint']) + self._pipe.use(endpoint_to_wire(self._binding.endpoint)) if self._binding.expected is None: self._binding.owner.close() self._binding.owner = None @@ -94,7 +97,10 @@ def bootstrap(self) -> dict: self._binding.generation = generation if not _available(self.request('inspect', {})): return {'ready': False, 'status': 'busy'} - return {'ready': True, 'generation': self._binding.generation} + result: dict[str, Any] = {'ready': True, 'generation': self._binding.generation} + if self._binding.endpoint is not None: + result['endpoint'] = endpoint_to_wire(self._binding.endpoint) + return result except AgentControlBusy: return {'ready': False, 'status': 'busy'} except BaseException: diff --git a/je_auto_control/utils/agent_runtime/presence_host.py b/je_auto_control/utils/agent_runtime/presence_host.py index 78a0e0575..2fc886377 100644 --- a/je_auto_control/utils/agent_runtime/presence_host.py +++ b/je_auto_control/utils/agent_runtime/presence_host.py @@ -7,6 +7,7 @@ from je_auto_control.utils.agent_runtime.errors import AgentControlBusy, AgentTaskError from je_auto_control.utils.agent_runtime.presence_pool import PresenceReference, shared_reference +from je_auto_control.utils.agent_runtime.presence_pipe_linux import endpoint_from_wire, endpoint_to_wire def require_windows() -> None: @@ -52,12 +53,13 @@ def status(self) -> dict: return self._reference.status() -@dataclass +@dataclass(frozen=True) class _Grant: reference: PresenceReference binding: dict channel: Any spec: Any + endpoint: Any = None class TargetPresence: @@ -76,6 +78,9 @@ def bind(self, operation: Any, channel: Any, timeout: float) -> dict: if self._grant is not None: if channel is not self._grant.channel or operation.spec != self._grant.spec: raise AgentTaskError('presence binding requires prior input/helper retirement') + endpoint = self._grant.reference.endpoint(self._grant.binding) + if endpoint != self.endpoint(): + raise AgentTaskError('presence helper endpoint cannot change') return dict(self._grant.binding) provider = operation.presence if provider is None: @@ -83,8 +88,18 @@ def bind(self, operation: Any, channel: Any, timeout: float) -> dict: reference = provider() binding = reference.acquire(operation.checkpoint, timeout) self._grant = _Grant(reference, dict(binding), channel, operation.spec) + endpoint = reference.endpoint(binding) + self._grant = _Grant(reference, dict(binding), channel, operation.spec, + endpoint_from_wire(endpoint) if endpoint is not None else None) return dict(binding) + def endpoint(self) -> dict | None: + """Copy only the endpoint pinned with the current helper's host-owned grant.""" + if self._grant is None: + raise AgentTaskError('presence endpoint requires a bound helper') + endpoint = self._grant.endpoint + return endpoint_to_wire(endpoint) if endpoint is not None else None + def release(self) -> None: """Schedule owned token release only after proven input/helper cleanup, never certify input.""" if self._grant is not None: diff --git a/je_auto_control/utils/agent_runtime/presence_pool.py b/je_auto_control/utils/agent_runtime/presence_pool.py index 8680b12cf..9a0f4a130 100644 --- a/je_auto_control/utils/agent_runtime/presence_pool.py +++ b/je_auto_control/utils/agent_runtime/presence_pool.py @@ -15,6 +15,7 @@ from je_auto_control.utils.agent_runtime.presence_frames import ( identifier, presence_body, unsigned, validate_response, ) +from je_auto_control.utils.agent_runtime.presence_pipe_linux import endpoint_from_wire, endpoint_to_wire @dataclass(eq=False) @@ -43,6 +44,7 @@ class _Grant: class _Owner: channel: Any = None generation: str | None = None + endpoint: Any = None thread: threading.Thread | None = None stop: threading.Event = field(default_factory=threading.Event) retired: threading.Event = field(default_factory=threading.Event) @@ -82,6 +84,10 @@ def acquire(self, check: Callable[[], None], timeout: float) -> dict: """Wait within this caller's budget; cancellation abandons only this caller's grant.""" return self._pool.acquire_reference(self._owner, check, timeout) + def endpoint(self, binding: dict) -> dict | None: + """Snapshot launch metadata for this reference's exact live grant, without discovery.""" + return self._pool.endpoint_reference(self._owner, binding) + def release(self, binding: dict) -> None: """Schedule negative-only retirement of a token issued to this exact reference.""" self._pool.release_reference(self._owner, binding) @@ -198,6 +204,19 @@ def _wait(self, ticket: _Ticket, check: Callable[[], None]) -> dict: ticket.accepted.set() return dict(value.binding) + def endpoint_reference(self, owner: _Reference, binding: dict) -> dict | None: + """Check ownership and copy the pinned endpoint atomically with reference/grant retirement.""" + binding = presence_body('check', binding) + with self._mutex: + self._check_owner() + grant = owner.tokens.get(binding['lease_id']) + if (owner not in self._references or owner.closed.is_set() or grant is None + or grant.binding != binding or grant.released.is_set() + or not grant.ticket.accepted.is_set()): + raise AgentTaskError('presence endpoint requires this reference live grant') + endpoint = self._owner.endpoint + return endpoint_to_wire(endpoint) if endpoint is not None else None + def release_reference(self, owner: _Reference, binding: dict) -> None: """Mark only a recorded owned grant; the I/O owner performs its negative release.""" binding = presence_body('release', binding) @@ -248,9 +267,13 @@ def _ensure(self) -> None: value = self._owner.channel.request('bootstrap', {}, timeout=15, check=self._check_owner) if value == {'ready': False, 'status': 'busy'} and value['ready'] is False: raise AgentControlBusy('shared presence source is not ready') - if not isinstance(value, dict) or set(value) != {'ready', 'generation'} or value['ready'] is not True: + if (not isinstance(value, dict) + or set(value) not in ({'ready', 'generation'}, {'ready', 'generation', 'endpoint'}) + or value['ready'] is not True): raise AgentTaskError('shared presence bootstrap is invalid') + endpoint = endpoint_from_wire(value['endpoint']) if 'endpoint' in value else None self._owner.generation = identifier(value['generation']) + self._owner.endpoint = endpoint def _rpc(self, operation: str, body: dict) -> dict: self._check_owner() diff --git a/je_auto_control/utils/agent_runtime/presence_reader.py b/je_auto_control/utils/agent_runtime/presence_reader.py index 000791743..0c689d849 100644 --- a/je_auto_control/utils/agent_runtime/presence_reader.py +++ b/je_auto_control/utils/agent_runtime/presence_reader.py @@ -3,6 +3,7 @@ from dataclasses import dataclass, field import queue +import sys import threading import time from typing import Any, Callable @@ -12,8 +13,8 @@ decode_frame, encode_frame, presence_body, validate_response, ) from je_auto_control.utils.agent_runtime.presence_handshake import client_handshake -from je_auto_control.utils.agent_runtime.presence_pipe_windows import WindowsPresencePipe -from je_auto_control.utils.agent_runtime.presence_security_windows import WindowsPresenceSecurity +from je_auto_control.utils.agent_runtime.presence_platform import default_presence_pipe, default_presence_security +from je_auto_control.utils.agent_runtime.presence_pipe_linux import endpoint_from_wire, endpoint_to_wire @dataclass @@ -48,11 +49,20 @@ class PresenceReader: """One permanent lease binding; only its private I/O owner touches blocking native resources.""" def __init__(self, binding: dict, takeover: Callable[[], None], *, pipe: Any = None, - security: Any = None) -> None: + security: Any = None, endpoint: dict | None = None) -> None: self._binding = presence_body('check', binding) self._takeover = takeover - security = security if security is not None else WindowsPresenceSecurity() - self._wire = _Transport(pipe if pipe is not None else WindowsPresencePipe(security), security) + if pipe is None: + if sys.platform.startswith('linux'): + if endpoint is None: + raise AgentTaskError('Linux presence reader requires an owned launch endpoint') + elif sys.platform != 'win32' or endpoint is not None: + raise AgentTaskError('presence reader transport is unsupported on this platform') + pipe = default_presence_pipe() + if endpoint is not None: + pipe.use(endpoint_to_wire(endpoint_from_wire(endpoint))) + security = security if security is not None else default_presence_security() + self._wire = _Transport(pipe, security) self._state = _Lifetime() self._state.retired.set() self._mutex = threading.RLock() diff --git a/test/unit_test/headless/test_agent_presence_endpoint_flow.py b/test/unit_test/headless/test_agent_presence_endpoint_flow.py new file mode 100644 index 000000000..826be310b --- /dev/null +++ b/test/unit_test/headless/test_agent_presence_endpoint_flow.py @@ -0,0 +1,226 @@ +"""Owned endpoint metadata survives private host transport without widening source leases.""" +from copy import deepcopy +from types import SimpleNamespace + +import pytest + +from je_auto_control.utils.agent_runtime.errors import AgentTaskError +from je_auto_control.utils.agent_runtime.presence_host import TargetPresence +from .test_agent_presence_pool import Channel, noop, pool +from .test_agent_presence_broker import setup, Child + + +@pytest.fixture +def endpoint(tmp_path): + return {'directory': str(tmp_path), 'socket_name': 'source.sock', + 'directory_identity': {'device': 1, 'inode': 2, 'owner': 3, 'mode': 448}, + 'socket_identity': {'device': 1, 'inode': 4, 'owner': 3, 'mode': 384}, + 'listener_process': {'pid': 5, 'uid': 3, 'gid': 3, 'birth': 6, + 'user_namespace': 'user:[7]', 'pid_namespace': 'pid:[8]'}} + + +class EndpointChannel(Channel): + def __init__(self, endpoint): + super().__init__() + self.endpoint = endpoint + + def request(self, operation, body, **kwargs): + result = super().request(operation, body, **kwargs) + if operation == 'bootstrap': + result['endpoint'] = self.endpoint + return result + + +def test_pool_snapshots_endpoint_for_only_exact_live_owned_lease(endpoint): + original = deepcopy(endpoint) + channel = EndpointChannel(endpoint) + instance = pool(lambda argv: channel) + first, other = instance.reference(), instance.reference() + try: + binding = first.acquire(noop, 2) + endpoint['listener_process']['pid'] = 999 + assert first.endpoint(binding) == original + result = first.endpoint(binding) + result['socket_identity']['inode'] = 999 + assert first.endpoint(binding) == original + with pytest.raises(AgentTaskError): + other.endpoint(binding) + with pytest.raises(AgentTaskError): + first.endpoint({**binding, 'generation': 'wrong'}) + first.release(binding) + with pytest.raises(AgentTaskError): + first.endpoint(binding) + assert all('endpoint' not in body for operation, body in channel.calls) + finally: + first.close() + other.close() + with pytest.raises(AgentTaskError): + first.endpoint(binding) + + +def test_target_pins_owned_endpoint_and_returns_copies(endpoint): + instance = pool(lambda argv: EndpointChannel(endpoint)) + reference = instance.reference() + operation = SimpleNamespace(presence=lambda: reference, checkpoint=noop, spec=object()) + channel = object() + target = TargetPresence() + try: + binding = target.bind(operation, channel, 2) + result = target.endpoint() + result['listener_process']['pid'] = 900 + assert target.endpoint() == endpoint + assert target.bind(operation, channel, 2) == binding + with pytest.raises(AgentTaskError): + target.bind(operation, object(), 2) + reference.release(binding) + with pytest.raises(AgentTaskError): + target.bind(operation, channel, 2) + finally: + reference.close() + target.release() + + +def test_broker_publishes_only_owned_validated_endpoint_after_handshake(endpoint, monkeypatch): + create, source, pipe, children = setup(monkeypatch) + real_start = Child.start + def start(child): + result = real_start(child) + result['endpoint'] = endpoint + return result + monkeypatch.setattr(Child, 'start', start) + pipe.use = lambda value: None + broker = create() + try: + result = broker.bootstrap() + assert result['endpoint'] == endpoint + original = deepcopy(endpoint) + endpoint['listener_process']['pid'] = 100 + result['endpoint']['socket_identity']['inode'] = 100 + assert broker.bootstrap()['endpoint'] == original + finally: + broker.close() + + +@pytest.mark.parametrize('replacement', [None, {}, {'ready': True}]) +def test_pool_rejects_malformed_owned_endpoint(replacement): + instance = pool(lambda argv: EndpointChannel(replacement)) + reference = instance.reference() + try: + with pytest.raises(AgentTaskError): + reference.acquire(noop, 2) + finally: + reference.close() + + +def test_worker_rejects_changed_removed_or_added_endpoint(endpoint, monkeypatch): + from je_auto_control.utils.agent_runtime.native_worker import NativeWorker + worker = NativeWorker(None, None, target=object()) + monkeypatch.setattr(worker, '_requires_presence', lambda: True) + channel = EndpointChannel(endpoint) + binding = channel.protocol.request({'request_id': 1, 'operation': 'acquire', 'body': {}})['result'] + try: + worker._configure_presence({'presence': binding, 'presence_endpoint': endpoint}) + worker._check_presence_pin(None, None, {'presence': binding, 'presence_endpoint': deepcopy(endpoint)}) + for changed in [None, {}, {**endpoint, 'socket_name': 'other.sock'}]: + with pytest.raises(AgentTaskError): + worker._check_presence_pin(None, None, {'presence': binding, 'presence_endpoint': changed}) + worker._presence_endpoint = None + with pytest.raises(AgentTaskError): + worker._check_presence_pin(None, None, {'presence': binding, 'presence_endpoint': endpoint}) + finally: + channel.close() + + +def test_reader_uses_private_endpoint_before_connect_and_keeps_windows_gate(endpoint, monkeypatch): + from je_auto_control.utils.agent_runtime import presence_reader + from je_auto_control.utils.agent_runtime.presence_pipe_linux import LinuxPresencePipe + channel = EndpointChannel(endpoint) + binding = channel.protocol.request({'request_id': 1, 'operation': 'acquire', 'body': {}})['result'] + try: + monkeypatch.setattr(presence_reader.sys, 'platform', 'linux') + reader = presence_reader.PresenceReader(binding, noop) + except AgentTaskError as error: + assert 'owned launch endpoint' in str(error) + else: + pytest.fail('Linux reader accepted missing endpoint') + try: + reader = presence_reader.PresenceReader(binding, noop, endpoint=endpoint) + assert isinstance(reader._wire.pipe, LinuxPresencePipe) + assert reader._wire.pipe._endpoint.socket_name == endpoint['socket_name'] + endpoint['socket_name'] = 'changed.sock' + assert reader._wire.pipe._endpoint.socket_name == 'source.sock' + reader.close() + monkeypatch.setattr(presence_reader.sys, 'platform', 'win32') + with pytest.raises(AgentTaskError, match='unsupported'): + presence_reader.PresenceReader(binding, noop, endpoint=endpoint) + finally: + channel.close() + + +@pytest.mark.parametrize('bad_endpoint', [False, True]) +def test_broker_does_not_publish_unverified_owned_endpoint(endpoint, monkeypatch, bad_endpoint): + from je_auto_control.utils.agent_runtime import presence_broker + create, source, pipe, children = setup(monkeypatch) + real_start = Child.start + def start(child): + result = real_start(child) + result['endpoint'] = {} if bad_endpoint else endpoint + return result + monkeypatch.setattr(Child, 'start', start) + if not bad_endpoint: + monkeypatch.setattr(presence_broker, 'client_handshake', + lambda conn, security: ('wrong-generation', SimpleNamespace(close=noop))) + pipe.use = lambda value: None + broker = create() + with pytest.raises(AgentTaskError): + broker.bootstrap() + assert children[0].closed + assert broker._binding.closed + + +def test_windows_bootstrap_and_reference_do_not_add_endpoint(monkeypatch): + instance = pool(lambda argv: Channel()) + reference = instance.reference() + try: + binding = reference.acquire(noop, 2) + assert reference.endpoint(binding) is None + finally: + reference.close() + + + +def test_runtime_configure_carries_only_host_endpoint_to_worker(endpoint, tmp_path, monkeypatch): + import io + from .test_agent_presence_runtime import Fixture, spec + from .test_agent_presence_binding import Target, Gate + from je_auto_control.utils.agent_runtime import native_worker + fixture = Fixture(monkeypatch, tmp_path) + fixture.source = EndpointChannel(endpoint) + captured = [] + + class Reader(Gate): + def __init__(self, binding, takeover, *, endpoint): + super().__init__(binding, takeover) + captured.append(deepcopy(endpoint)) + + monkeypatch.setattr(native_worker, 'DesktopTarget', Target) + monkeypatch.setattr(native_worker, 'PresenceReader', Reader) + runtime = fixture.runtime('endpoint') + worker = native_worker.NativeWorker(io.BytesIO(), io.BytesIO()) + try: + request = spec() + request['options'] = {'presence_endpoint': {'untrusted': True}} + task = runtime.submit(request) + runtime.observe(task.task_id) + payload = next(payload for operation, payload, timeout in fixture.helpers[0].calls + if operation == 'configure') + assert payload['presence_endpoint'] == endpoint + assert worker._dispatch('configure', payload)['ready'] + assert captured == [endpoint] + changed = deepcopy(payload) + changed['presence_endpoint']['socket_name'] = 'different.sock' + with pytest.raises(AgentTaskError): + worker._dispatch('configure', changed) + finally: + worker.close() + runtime.close() diff --git a/test/unit_test/headless/test_agent_presence_service_linux.py b/test/unit_test/headless/test_agent_presence_service_linux.py index 800864db2..3815b63c3 100644 --- a/test/unit_test/headless/test_agent_presence_service_linux.py +++ b/test/unit_test/headless/test_agent_presence_service_linux.py @@ -132,3 +132,45 @@ def test_an_owned_worker_hands_its_endpoint_to_the_broker_and_serves_presence(tm finally: broker.close() assert broker.retired + + +@linux +def test_owned_endpoint_reaches_host_grant_and_actual_reader(tmp_path, monkeypatch): + import threading + from types import SimpleNamespace + from je_auto_control.utils.agent_runtime.native_channel import OwnedChannel + from je_auto_control.utils.agent_runtime.presence_pool import PresencePool + from je_auto_control.utils.agent_runtime.presence_host import TargetPresence + from je_auto_control.utils.agent_runtime.presence_reader import PresenceReader + + runtime = tmp_path / 'runtime' + runtime.mkdir(mode=0o700) + os.chmod(runtime, 0o700) + monkeypatch.setenv('XDG_RUNTIME_DIR', str(runtime)) + clock = tmp_path / 'clock.txt' + clock.write_text('0', encoding='utf-8') + broker = OwnedChannel([sys.executable, '-u', '-c', _broker_script(clock)]) + owner = PresencePool(channel_factory=lambda argv: broker) + reference = owner.reference() + target = TargetPresence() + reader = None + notice = threading.Event() + try: + assert broker.request('bootstrap', {}, timeout=15)['ready'] is True + clock.write_text('60', encoding='utf-8') + operation = SimpleNamespace(presence=lambda: reference, checkpoint=lambda: None, spec=object()) + binding = target.bind(operation, object(), 3) + endpoint = target.endpoint() + reader = PresenceReader(binding, notice.set, endpoint=endpoint) + reader.ready() + reader.check() + assert not notice.is_set() + reference.release(binding) + assert notice.wait(2), 'source revocation must fence the independently connected reader' + finally: + if reader is not None: + reader.close() + reference.close() + target.release() + assert reader.retired + assert owner.retired From 4ce4b52ff95e2c52dcb5e2ac7ef360ab815b286a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:50:47 +0800 Subject: [PATCH 008/161] fix: generate reports asynchronously with owned task feedback --- Progress.md | 2 +- architecture_explore.md | 10 +-- docs/guides/en/setup.md | 2 + docs/guides/zh-CN/setup.md | 2 + docs/guides/zh-TW/setup.md | 2 + docs/updates/2026-11.md | 6 ++ docs/updates/README.md | 3 +- je_auto_control/gui/_report_tab.py | 74 +++++++++++-------- .../headless/test_r3_gui_slot_exceptions.py | 1 + .../headless/test_report_tab_lifecycle.py | 66 ++++++++++++++++- 10 files changed, 129 insertions(+), 39 deletions(-) diff --git a/Progress.md b/Progress.md index 3149dfa79..83df2fb1c 100644 --- a/Progress.md +++ b/Progress.md @@ -522,7 +522,7 @@ D2 仍缺 helper 隔離與半開交握資源回收;D3 的錄製/全域停止 - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 - **F1 的遺留面板釋放**:Auto Click、Screenshot、Image Detection、Record、Script 五個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 -- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。Report 已完成獨立生命週期,報表產生仍須移出 GUI 執行緒並拒絕關閉後的晚到結果。 +- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 - **F4**(啟動/記憶體基準、mixed-DPI、功能對等測試)尚未開始。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/architecture_explore.md b/architecture_explore.md index c3bf1591b..717e24638 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,495 | -| 程式碼總行數 | 228,352 | +| 程式碼總行數 | 228,364 | | `je_auto_control/utils/` 子套件數 | 311 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1276,7 +1276,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `_image_detect_tab.py` | 117 | 影像偵測分頁 mixin。 | | `_script_tab.py` | 158 | 腳本執行分頁 mixin。 | | `_record_tab.py` | 144 | 錄製/回放分頁 mixin。 | -| `_report_tab.py` | 94 | 報表分頁 mixin。 | +| `_report_tab.py` | 106 | 報表分頁 mixin。 | | `_i18n_helpers.py` | 79 | 需要即時語言切換的分頁共用的翻譯註冊 mixin。 | | `_validators.py` | 29 | `int_validator()`/`double_validator()`:以 C locale 驗證的數字輸入框 validator,接受的正是 `int()`/`float()` 讀得懂的寫法(預設 locale 在法文、德文下只收小數逗號)。所有數字 `QLineEdit` 都用它。 | | `_screen_geometry.py` | 55 | Qt 邏輯座標與截圖用的原生像素互轉:`native_region()`、`screen_at_native()`、`logical_point()`(每個螢幕的左上角在兩者相同,螢幕內依 device pixel ratio 縮放)。區域選取與主機端標註覆蓋層都用它。 | @@ -1351,7 +1351,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | usb_browser | `usb_browser_tab.py` | 290 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | | diagnostics | `diagnostics_tab.py` | 221 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | -| report | `_report_tab.py` | 94 | 產生 HTML/JSON/XML 報表。 | +| report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1493,7 +1493,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,849 | +| `gui/` | 144 | 39,861 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,243 | | `utils/executor/` | 11 | 10,702 | @@ -1514,7 +1514,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,553 | -| **總計** | **1,483** | **227,607** | +| **總計** | **1,483** | **227,619** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/setup.md b/docs/guides/en/setup.md index 059000a93..4212c9ed2 100644 --- a/docs/guides/en/setup.md +++ b/docs/guides/en/setup.md @@ -355,3 +355,5 @@ Every environment variable AutoControl reads. Nothing here is required: with no --- The Report page is created when first opened. Closing it releases its controls and local result view; reopening creates a fresh page and reads the current recording status. Closing the page does not disable the shared recorder. + +Report generation runs in the background and shows a running status. A page accepts one generation at a time and captures the name when you start it. Closing drops late results; an already-running file write may still finish. diff --git a/docs/guides/zh-CN/setup.md b/docs/guides/zh-CN/setup.md index 34760744a..786976de6 100644 --- a/docs/guides/zh-CN/setup.md +++ b/docs/guides/zh-CN/setup.md @@ -294,3 +294,5 @@ AutoControl 读取的每一个环境变量。这里没有任何一项是必填 --- Report 标签页在首次打开时创建。关闭会释放控件和本地结果视图;重新打开会创建新页面并读取当前录制状态。关闭标签页不会禁用共享 recorder。 + +报表在后台生成并显示运行状态。每个标签页一次接受一个生成任务,使用开始时输入的名称。关闭会丢弃迟到结果;已开始的文件写入仍可能完成。 diff --git a/docs/guides/zh-TW/setup.md b/docs/guides/zh-TW/setup.md index 2639cbcb1..e00477d0d 100644 --- a/docs/guides/zh-TW/setup.md +++ b/docs/guides/zh-TW/setup.md @@ -294,3 +294,5 @@ AutoControl 讀取的每一個環境變數。這裡沒有任何一項是必填 --- Report 分頁在首次開啟時建立。關閉會釋放控制項與本機結果畫面;重新開啟會建立新頁面並讀取目前錄製狀態。關閉分頁不會停用共用 recorder。 + +報表在背景產生並顯示執行中狀態。每個分頁一次接受一個產生工作,使用開始時輸入的名稱。關閉會丟棄晚到結果;已開始的檔案寫入仍可能完成。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index c042c1231..7fb04f60e 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -696,3 +696,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Broker/pool retain a validated endpoint from their owned source launch. An exact live-reference grant supplies a fresh snapshot; host/channel/spec and worker configuration pin it. Reader uses the platform transport and refuses Linux startup without the trusted endpoint. Source lease wire fields and Windows desktop admission remain unchanged. - **Evidence:** Delegate focused suites: 78 passed; endpoint/Windows synthetic IPC: 33 passed, 3 Linux-only skipped; endpoint/runtime/worker binding: 34 passed. Mypy passed for the six modified production modules. Added Linux-only real-socket synthetic-source end-to-end coverage. - **Open items:** Linux socket execution is unverified because the existing WSL validation distro cannot mount its missing ext4.vhdx; native authority integration and acceptance remain in `Progress.md`. + +## U-20261110-08 · 2026-11-10 · Generate reports without blocking the GUI · #done #gui + +- **What:** Report generation now captures plain name/format inputs and runs through TabTask. It shows localized running status, refuses duplicate starts, and discards late results after close without touching a reopened page. Already-running writes may finish. +- **Evidence:** Delegate report/registry/actions suite: 79 passed; running-feedback regression suite: 8 passed. Tests hold a fake writer blocked while a Qt timer ticks and verify name snapshots and close/reopen isolation. Mypy and Ruff passed. +- **Open items:** Other GUI task/lifecycle gaps remain in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 95be623ed..002376d80 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-08 | 2026-11-10 | Generate reports without blocking the GUI | #done #gui | [2026-11](2026-11.md) | | U-20261110-07 | 2026-11-10 | Carry owned Linux presence endpoints into helpers | #done #agent | [2026-11](2026-11.md) | | U-20261110-06 | 2026-11-10 | Give the Report page independent ownership | #done #gui | [2026-11](2026-11.md) | | U-20261110-05 | 2026-11-10 | Verify existing RBAC administration delivery | #done #rbac | [2026-11](2026-11.md) | @@ -615,7 +616,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 28 | +| [2026-11.md](2026-11.md) | 2026-11 | 29 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/gui/_report_tab.py b/je_auto_control/gui/_report_tab.py index 111d6fac5..d3ffd3697 100644 --- a/je_auto_control/gui/_report_tab.py +++ b/je_auto_control/gui/_report_tab.py @@ -1,12 +1,16 @@ """Report-generation panel with independently owned controls and actions.""" +from functools import partial +from typing import Callable, Optional +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.utils.exception.exceptions import AutoControlException +from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.generate_report.generate_html_report import generate_html_report from je_auto_control.utils.generate_report.generate_json_report import generate_json_report from je_auto_control.utils.generate_report.generate_xml_report import generate_xml_report @@ -16,7 +20,7 @@ class ReportTab(TranslatableMixin, QWidget): """Own report inputs and reflect the process-wide recorder without owning it.""" - def __init__(self, parent=None): + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() layout = QVBoxLayout(self) @@ -41,9 +45,12 @@ def __init__(self, parent=None): self.report_result_text.setReadOnly(True) layout.addWidget(self.report_result_text) layout.addStretch() + self._task = TabTask(self) + self._task.result.connect(self._on_report_result) + self._task.error.connect(self._on_report_error) self.sync_with_engine() - def menu_actions(self): + def menu_actions(self) -> list[tuple[str, Callable[[], object]]]: return [ ("enable_test_record", self._enable_test_record), ("disable_test_record", self._disable_test_record), @@ -52,43 +59,48 @@ def menu_actions(self): ("generate_xml_report", self._gen_xml), ] - def sync_with_engine(self): + def sync_with_engine(self) -> None: self.tr_status_label.setText("ON" if test_record_instance.init_record else "OFF") - def showEvent(self, event): # noqa: N802 # reason: Qt virtual method + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt virtual method self.sync_with_engine() super().showEvent(event) - def _set_test_record(self, enable: bool): + def _set_test_record(self, enable: bool) -> None: test_record_instance.set_record_enable(enable) self.sync_with_engine() - def _enable_test_record(self): + def _enable_test_record(self) -> None: self._set_test_record(True) - def _disable_test_record(self): + def _disable_test_record(self) -> None: self._set_test_record(False) - def _gen_html(self): - try: - name = self.report_name_input.text() or "autocontrol_report" - generate_html_report(name) - self.report_result_text.setText(f"HTML report generated: {name}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.report_result_text.setText(f"Error: {error}") - - def _gen_json(self): - try: - name = self.report_name_input.text() or "autocontrol_report" - generate_json_report(name) - self.report_result_text.setText(f"JSON report generated: {name}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.report_result_text.setText(f"Error: {error}") - - def _gen_xml(self): - try: - name = self.report_name_input.text() or "autocontrol_report" - generate_xml_report(name) - self.report_result_text.setText(f"XML report generated: {name}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.report_result_text.setText(f"Error: {error}") + def _start_report(self, generator: Callable[[str], None], format_name: str) -> None: + name = self.report_name_input.text() or "autocontrol_report" + if self._task.start(partial(_write_report, generator, name, format_name)): + self.report_result_text.setText(language_wrapper.translate("task_running", "task_running")) + + def _gen_html(self) -> None: + self._start_report(generate_html_report, "HTML") + + def _gen_json(self) -> None: + self._start_report(generate_json_report, "JSON") + + def _gen_xml(self) -> None: + self._start_report(generate_xml_report, "XML") + + def _on_report_result(self, result: str) -> None: + self.report_result_text.setText(result) + + def _on_report_error(self, error: object) -> None: + self.report_result_text.setText(f"Error: {error}") + + def dispose(self) -> None: + """Drop late results; an already-running report write may still finish.""" + self._task.stop() + + +def _write_report(generator: Callable[[str], None], name: str, format_name: str) -> str: + generator(name) + return f"{format_name} report generated: {name}" diff --git a/test/unit_test/headless/test_r3_gui_slot_exceptions.py b/test/unit_test/headless/test_r3_gui_slot_exceptions.py index c43da0da3..b747a377b 100644 --- a/test/unit_test/headless/test_r3_gui_slot_exceptions.py +++ b/test/unit_test/headless/test_r3_gui_slot_exceptions.py @@ -113,6 +113,7 @@ def test_report_gen_html_slot_surfaces_autocontrol_exception(monkeypatch): tab.report_name_input.setText("rpt") try: tab._gen_html() + assert settle(tab._task, "task") assert tab.report_result_text.toPlainText().startswith("Error") finally: tab.deleteLater() diff --git a/test/unit_test/headless/test_report_tab_lifecycle.py b/test/unit_test/headless/test_report_tab_lifecycle.py index 949be7200..00f24ebb8 100644 --- a/test/unit_test/headless/test_report_tab_lifecycle.py +++ b/test/unit_test/headless/test_report_tab_lifecycle.py @@ -1,14 +1,16 @@ """Report panels own their controls and release them on registry close.""" import os +import threading import pytest os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) -from PySide6.QtCore import QEvent # noqa: E402 +from PySide6.QtCore import QEvent, QTimer # noqa: E402 from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 from shiboken6 import isValid # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 from je_auto_control.gui import _report_tab # noqa: E402 from je_auto_control.gui.tab_registry import TAB_SPECS, TabEntry, TabRegistry, lazy_factory # noqa: E402 from je_auto_control.utils.test_record.record_test_class import TestRecord as Recorder # noqa: E402 @@ -97,7 +99,69 @@ def test_report_actions_generate_named_outputs(app, recorder, monkeypatch, forma try: page.report_name_input.setText("chosen-name") dict(page.menu_actions())["generate_" + format_name + "_report"]() + assert pump_until(lambda: not page._task.running) assert calls == ["chosen-name"] assert page.report_result_text.toPlainText() == format_name.upper() + " report generated: chosen-name" finally: _delete(app, page) + + +def test_report_generation_runs_off_gui_thread(app, recorder, monkeypatch): + threads = [] + monkeypatch.setattr(_report_tab, "generate_html_report", lambda name: threads.append(threading.get_ident())) + page = _report_tab.ReportTab() + try: + page._gen_html() + assert pump_until(lambda: not page._task.running) + assert len(threads) == 1 and threads[0] != threading.get_ident() + finally: + _delete(app, page) + + +def test_close_while_generating_keeps_new_page_free_of_late_results(app, recorder, monkeypatch): + entered, release, exited = threading.Event(), threading.Event(), threading.Event() + names, ticks = [], [] + + def generate(name): + names.append(name) + entered.set() + try: + assert release.wait(5), "test did not release fake generator" + finally: + exited.set() + + monkeypatch.setattr(_report_tab, "generate_html_report", generate) + owner = QWidget() + entry = TabEntry("report", "tab_report", _report_tab.ReportTab, + on_build=lambda page: page.setParent(owner)) + registry = TabRegistry([entry]) + page = registry.open("report") + timer = QTimer(owner) + timer.setInterval(1) + timer.timeout.connect(lambda: ticks.append(True)) + timer.start() + try: + page.report_name_input.setText("original") + monkeypatch.setattr(_report_tab.language_wrapper, "translate", + lambda key, fallback: "localized running" if key == "task_running" else fallback) + page.report_result_text.setText("previous result") + page._gen_html() + assert page.report_result_text.toPlainText() == "localized running" + page.report_result_text.setText("retained status") + page.report_name_input.setText("changed") + page._gen_html() # one in-flight write per page + assert page.report_result_text.toPlainText() == "retained status" + assert pump_until(lambda: entered.is_set() and bool(ticks)) + assert names == ["original"] + registry.close("report") + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + assert not isValid(page) + replacement = registry.open("report") + release.set() + assert pump_until(exited.is_set) + assert replacement.report_result_text.toPlainText() == "" + assert recorder.init_record + finally: + release.set() + assert pump_until(exited.is_set) + _delete(app, owner) From 4630d80e889b6c0254d881dfc18775063cd1e11c Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 10 Nov 2026 04:57:08 +0800 Subject: [PATCH 009/161] Add bounded internal process-memory observations --- CLAUDE.md | 6 +- Progress.md | 15 + architecture_explore.md | 19 +- docs/README.md | 1 + docs/process_memory_contract.md | 130 +++++ docs/updates/2026-11.md | 6 + docs/updates/README.md | 3 +- .../utils/process_memory/__init__.py | 1 + .../utils/process_memory/models.py | 177 ++++++ .../utils/process_memory/reader.py | 244 ++++++++ pyproject.toml | 2 + .../headless/test_process_memory_reader.py | 526 ++++++++++++++++++ 12 files changed, 1117 insertions(+), 13 deletions(-) create mode 100644 docs/process_memory_contract.md create mode 100644 je_auto_control/utils/process_memory/__init__.py create mode 100644 je_auto_control/utils/process_memory/models.py create mode 100644 je_auto_control/utils/process_memory/reader.py create mode 100644 test/unit_test/headless/test_process_memory_reader.py diff --git a/CLAUDE.md b/CLAUDE.md index c125f5d80..f1770f99f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ AutoControl (`je_auto_control`) is a cross-platform GUI automation framework: mouse and keyboard control, image recognition, OCR, accessibility-tree and VLM element location, action scripting, and report generation behind one API. Backends: Windows (Win32 ctypes), macOS (pyobjc/Quartz), Linux X11 (python-Xlib), Linux Wayland (libei / ydotool), Android (adb), iOS (WebDriverAgent). - **Package**: `je_auto_control` · **Python** ≥ 3.11 · **License**: MIT · **Author**: JE-Chen -- **[architecture_explore.md](architecture_explore.md)** is the per-module map — read it before changing structure; it lists all 312 `utils/` subpackages, every GUI tab, and file-level tables for the large subsystems. +- **[architecture_explore.md](architecture_explore.md)** is the per-module map — read it before changing structure; it lists all 313 `utils/` subpackages, every GUI tab, and file-level tables for the large subsystems. ## Architecture @@ -18,7 +18,7 @@ AutoControl (`je_auto_control`) is a cross-platform GUI automation framework: mo | Template Method | `utils/generate_report/` | HTML / JSON / XML share collect → format → write. | | Backend seam | `backends/` under `accessibility`, `ocr`, `vision`, `llm`, `agent`, `hotkey`, `usb`, `usbip` | Abstract base + concrete impls + null fallback, so dependency-free environments still import. | -Layering: entry points (`cli.py`, `gui/`, socket / REST / MCP servers) → executor → `utils/` (312 headless subpackages) → `wrapper/` → per-OS backend. +Layering: entry points (`cli.py`, `gui/`, socket / REST / MCP servers) → executor → `utils/` (313 headless subpackages) → `wrapper/` → per-OS backend. ## Development Commands @@ -94,7 +94,7 @@ The map is only useful while it matches the tree, so **update it in the same cha Never adjust one by hand: the counts are `len(text.splitlines())` (what `wc -l` reports), and hand-editing is how the document ended up quoting the same subsystem at two sizes at once — most tables had been counting a phantom trailing line per file while §1 and §8 counted correctly. -- A new `utils/` subpackage needs a row in **exactly one** §5.4 theme table — the tables partition all 312 subpackages; appearing twice or not at all is a defect. +- A new `utils/` subpackage needs a row in **exactly one** §5.4 theme table — the tables partition all 313 subpackages; appearing twice or not at all is a defect. - A new subsystem over ~1,000 lines also needs a file-level table in §5.4.17. - Keep the header's scan date, version, and branch current. - `README.md` and both translations under `README/` cite the same figures (command / subpackage / tab / MCP-tool / example counts) — update all three alongside the map. diff --git a/Progress.md b/Progress.md index 83df2fb1c..e61faf037 100644 --- a/Progress.md +++ b/Progress.md @@ -18,6 +18,15 @@ ## 輸入、視窗與擷取修正:還沒在真的桌面與 Jeffrey_RPA 上驗過 +### 行程記憶體自有 fixture 原生驗收 + +`TODO` — 原生執行仍暫緩。須先完成 Windows provider、自有 fixture 與受管權限整合, +再驗證 ASLR、32/64 位配置、跨區段/guard/不可讀頁、程序退出、PID 重用、權限拒絕、 +取消及 handle 回收。以 fixture 的已知狀態比對語意結果,獨立觀測前景、焦點、滑鼠與輸入事件。 +目前 injected-provider 測試不算原生通過;設計見 [記憶體觀察契約](docs/process_memory_contract.md)。 + +### 桌面行為驗收 + `TODO` — 原生桌面與正式批次升級前的行為驗收暫緩。 - **正式批次升級前的桌面行為驗收**:需核對 `_gui_control.py` 對下列行為的實際依賴: @@ -616,6 +625,12 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 ### 實作順序與各階段完成條件 +`WIP` — 內部 `utils/process_memory/` 已有不可變身分/probe、區段與位元組預算、 +序號一致性檢查、語意欄位白名單及失敗 handle 保留重試。契約與 fixture 協定見 +[process_memory_contract.md](docs/process_memory_contract.md)。M0/M1 尚未完成, +仍缺 typed Windows provider、可信 ASLR resolver、自有 fixture 程序、runtime grant/helper +生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 + 1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 讀取來源、執行介面、權限、是否全背景、支援版本、驗證方式與不支援原因。 第一個目標採自有 fixture 程序,之後選一個提供正式背景介面的應用;不能先承諾任意軟體。 diff --git a/architecture_explore.md b/architecture_explore.md index 717e24638..6607c2e6c 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -11,7 +11,7 @@ CI 以 `python scripts/generate_facade_exports.py --check` 檢查一致性。六 > 擷取每個模組的 docstring 與頂層公開名稱;統計數字取自實際檔案,非估算。 > 指令數與公開 API 數以 `executor.known_commands()` 與 `je_auto_control.__all__` 在工作樹上實測取得。 > -> **掃描時間**:2026-10-29 **版本**:`pyproject.toml` version `0.0.228` **分支**:`feat/agent-task-runtime` +> **掃描時間**:2026-11-10 **版本**:`pyproject.toml` version `1.2.0` **分支**:`dev` --- @@ -24,9 +24,9 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,495 | -| 程式碼總行數 | 228,364 | -| `je_auto_control/utils/` 子套件數 | 311 | +| Python 模組總數(含周邊子專案) | 1,498 | +| 程式碼總行數 | 228,786 | +| `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | | GUI 分頁數(`main_widget` 註冊) | 51 | @@ -60,7 +60,7 @@ USB/IP 協定、Prometheus 指標),以維持這條輕相依基線。 └───────────────────────────────┬──────────────────────────────────────────┘ │ ┌───────────────────────────────▼──────────────────────────────────────────┐ -│ 能力層 utils/(311 個子套件,全部無 Qt 相依) │ +│ 能力層 utils/(313 個子套件,全部無 Qt 相依) │ │ 影像辨識 │ OCR │ 無障礙樹 │ 定位自癒 │ AI/Agent │ 遠端桌面 │ USB │ │ 報表觀測 │ 資料 │ 安全 │ 韌性 │ 系統整合 │ 排程觸發 │ 網路協定 │ └───────────────────────────────┬──────────────────────────────────────────┘ @@ -278,7 +278,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `ios/input.py` | 83 | iOS 觸控與按鍵原語。 | | `ios/screen.py` | 85 | iOS 裝置螢幕擷取與尺寸。 | -### 5.4 能力層 `utils/`(312 個子套件) +### 5.4 能力層 `utils/`(313 個子套件) 以下依主題分組。每個子套件都是獨立可匯入的無頭模組,不含任何 Qt 相依。 @@ -317,7 +317,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 14 個套件、約 3,796 行。 +> 15 個套件、約 4,218 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -333,6 +333,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 193 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | +| `utils/process_memory/` | 422 | 內部受審 probe 的有界語意觀察、身分重驗與失敗 handle 回收;原生 provider 與 runtime 整合待完成 | | `utils/shell_process/` | 279 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -1513,8 +1514,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 981 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 997 | 101,553 | -| **總計** | **1,483** | **227,619** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,000 | 101,975 | +| **總計** | **1,486** | **228,041** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/README.md b/docs/README.md index 17d11f00d..762020320 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,3 +17,4 @@ Start with the [project README](../README.md) for installation and a first Pytho - [Examples](../examples/README.md) - [Development updates](updates/README.md) - [Current progress](../Progress.md) +- [Internal process-memory observation contract](process_memory_contract.md) diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md new file mode 100644 index 000000000..83c7acf5e --- /dev/null +++ b/docs/process_memory_contract.md @@ -0,0 +1,130 @@ +# Reviewed process-memory observations + +This is the internal M0/M1 foundation for the background-operation plan in +[Progress.md](../Progress.md). It supplies a testable semantic observation path. +It does not supply a Windows native provider, runtime authorization wiring, a +public memory command, an application adapter or completed native acceptance. + +## Ownership and scope + +An application adapter owns a `ProcessMemoryReader` inside its existing managed +helper. The runtime remains the owner of tasks, cancellation and action authority. +A separate observer service was rejected because it would require another +authentication and lifecycle boundary before an observation could be used. + +The host reviews a `ReviewedProbe` with exact application versions, architectures, +semantic field names, decoder and resolver. A query only chooses a subset of those +fields. It cannot provide addresses, offsets, expressions, process enumeration or +new permissions. A probe is executable trusted adapter code, not serialized user +configuration. The package is intentionally absent from the facade, executor, +MCP, REST and GUI registries until those boundaries have real policy integration. + +The runtime adapter must pass its live `TaskOperation.checkpoint` into `observe`. +The default checkpoint only checks cooperative cancellation; it is not an +authorization check. Calling the internal reader does not authorize reading a +process. Existing desktop foreground and input-presence gates are unchanged. + +## Windows capability matrix + +| Operation | Source and scope | Background requirement | Evidence and present state | +|---|---|---|---| +| Process/session identity | OS process handle, creation time, executable identity and architecture | Read/query rights only; no privilege escalation | Provider contract defined; native implementation and acceptance pending | +| UI state | UIA read-only element properties for an explicitly selected application | No Invoke, SetValue or focus change | Existing UIA implementation; new background adapter integration pending | +| Browser state | Existing WebRunner managed DOM session and reviewed origins | Dedicated managed browser; no desktop input fallback | Existing browser path; this reader adds no browser access | +| Fixture semantic state | Reviewed schema resolved for the retained fixture process identity | Bounded `VirtualQueryEx` / `ReadProcessMemory` provider; no writes | Injected-provider semantic and failure tests implemented; native provider pending | +| Application command | Each application's official API, CLI or IPC with scoped resources | Must independently prove no foreground/focus/mouse/input interference | Application selection and command adapter pending | +| OS service operation | Specific approved service's management interface | Explicit service scope and independent status readback | Adapter and policy integration pending | +| Completed background task | Fresh state or artifact verification under current runtime authority | Observation does not grant execution rights or replace a completion receipt | End-to-end M4/M5 integration pending | + +## Retained identity and private reads + +`ProcessIdentity` includes host/session identifiers, PID, process birth, executable +identity and version, architecture and pointer width. A retained provider handle +must report the actual process identity, including after reads. Reused PIDs and +changed identity invalidate the whole observation. + +The reviewed resolver runs anew for each observation. It supplies one private +payload range and optionally an eight-byte sequence range. A native adapter must +resolve its current module/fixture location from the retained target relationship; +it cannot cache an absolute address across launches or trust a path string as +executable identity. That native resolution remains unimplemented. + +The reader visits only intersecting regions. Each region must be committed, +readable and unguarded. Addresses, lengths and pointer-width arithmetic are +validated before reading. The provider must return exact immutable bytes. +Region metadata and process identity are checked again after every chunk. +Short reads, changed mappings and inaccessible pages produce no partial values. + +The byte budget includes sequence reads. Region visits are charged per chunk, +including repeated sequence visits. One monotonic deadline covers opening, +resolution, reads, decoding and successful return after cleanup. Every provider +call and decoder invocation has checkpoints before/after the operation. These +checks detect overruns but cannot preempt a blocking native call or decoder; +the future owned helper must supply hard process retirement and provider time +bounds. This package does not claim a hard real-time timeout. + +## Semantic output and consistency + +The decoder returns exactly the requested fields as bounded strings, signed +64-bit integers, booleans or null. The reader copies them to an immutable tuple. +The result includes the adapter's target ID and a digest of the checked process +identity, so a changed process birth cannot reuse an earlier observation's identity. +No mapping, raw byte buffer, handle, PID or address is returned. Sensitive process +identity and semantic values are omitted from object representations. Reviewed +schemas must exclude secrets; an allowlisted semantic value is intentionally +visible to its authorized caller. + +For a target with a sequence protocol, the reader requires an even sequence before +the payload and the same sequence afterward. The target must increment to an odd +value before changing the payload and publish the next even value afterward. +The result says `sequence_checked`; it does not imply a snapshot if the target +does not implement that protocol. A target without it returns `best_effort`. +Repeated equal bytes alone never imply atomicity. This increment performs one +attempt; an inconsistent observation fails instead of retrying with a fresh budget. + +Failures have closed reasons for unsupported probes, denied scope/access, changed +targets, unreadable regions, partial reads, inconsistent snapshots, exhausted +budgets/deadlines, decoding and cleanup. Provider adapters should use +`MemoryObservationError`, `PermissionError` or other `OSError` subclasses for +expected native failures. The reader normalizes other ordinary provider exceptions +to a safe failure too; resolver and decoder exceptions never expose their original +messages. Provider adapters must not log captured data or addresses themselves. +Cancellation, executor stop and hard interruption signals propagate after cleanup +instead of becoming ordinary failures. Live checkpoint authority errors also +propagate unchanged; only failures raised inside provider/resolver/decoder calls +are normalized, not the surrounding runtime authority checks. + +## Cleanup ownership + +Each observation opens and closes its own handle. A failed close remains owned +by the reader; `pending_cleanup` stays true and `close_pending()` explicitly retries +only retained failed handles. A close failure cannot return a successful observation +or claim retirement. If cancellation and failed close coincide, cancellation still +propagates and the reader retains cleanup ownership. The future runtime adapter +must retain the reader/helper while this flag is true; dropping the reader is not +proof that the process handle retired. + +## Native fixture protocol and acceptance design + +The headless fixture in `test_process_memory_reader.py` uses schema version 1: +little-endian `uint32 document_id`, followed by a 12-byte zero-padded ASCII +`job_status`. States are exactly `ready`, `busy` or `done`. An optional independent +eight-byte little-endian sequence counter follows the even/odd contract above. + +The future native fixture must be a repository-owned child process. Its owned +bootstrap channel reports its birth identity, executable/version digest and the +current payload/sequence locations. The parent must measure and match these facts +against its retained read-only process handle before constructing a reviewed probe. +The fixture exposes a separate test-control channel for changing state and fault +injection; memory writes are performed by the fixture itself, never by the reader. + +Native acceptance must cover 32/64-bit layout, ASLR across restarts, guard/no-access +pages, cross-region payloads, changed protection, short reads, process exit, PID +reuse, permission denial, cancellation and failed handle retirement. Compare exact +semantic values to fixture-owned expected values. Independently observe foreground +window, focus, mouse and desktop-input events to establish noninterference. + +No native acceptance command is supplied or executed by this increment. Native +execution stays paused under `Progress.md`; the fixture, typed Win32 provider, +host probe configuration, runtime lifecycle/policy integration and application +coverage must be implemented and reviewed before M1/M3 can be marked complete. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 7fb04f60e..e64735920 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -702,3 +702,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Report generation now captures plain name/format inputs and runs through TabTask. It shows localized running status, refuses duplicate starts, and discards late results after close without touching a reopened page. Already-running writes may finish. - **Evidence:** Delegate report/registry/actions suite: 79 passed; running-feedback regression suite: 8 passed. Tests hold a fake writer blocked while a Qt timer ticks and verify name snapshots and close/reopen isolation. Mypy and Ruff passed. - **Open items:** Other GUI task/lifecycle gaps remain in `Progress.md`. + +## U-20261110-09 · 2026-11-10 · Bound internal semantic process-memory observations · #snapshot #agent + +- **What:** Added internal immutable identities and reviewed probes, bounded region reads, versioned semantic decoding, sequence checks and retained failed-handle cleanup. Provider failures are sanitized while checkpoint authority errors and interruption signals propagate. +- **Evidence:** Injected-provider suite: 84 passed. Delegate strict mypy, Ruff and exception-policy tests passed. No native process memory was read. +- **Open items:** Windows provider, trusted resolver, owned fixture, runtime grants/lifecycle, public surfaces and native acceptance remain in Progress.md; M0/M1 are incomplete. diff --git a/docs/updates/README.md b/docs/updates/README.md index 002376d80..3ce8b11f9 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-09 | 2026-11-10 | Bound internal semantic process-memory observations | #snapshot #agent | [2026-11](2026-11.md) | | U-20261110-08 | 2026-11-10 | Generate reports without blocking the GUI | #done #gui | [2026-11](2026-11.md) | | U-20261110-07 | 2026-11-10 | Carry owned Linux presence endpoints into helpers | #done #agent | [2026-11](2026-11.md) | | U-20261110-06 | 2026-11-10 | Give the Report page independent ownership | #done #gui | [2026-11](2026-11.md) | @@ -616,7 +617,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 29 | +| [2026-11.md](2026-11.md) | 2026-11 | 30 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/utils/process_memory/__init__.py b/je_auto_control/utils/process_memory/__init__.py new file mode 100644 index 000000000..87d7685a5 --- /dev/null +++ b/je_auto_control/utils/process_memory/__init__.py @@ -0,0 +1 @@ +"""Internal reviewed process observations; no native provider or public command registration.""" diff --git a/je_auto_control/utils/process_memory/models.py b/je_auto_control/utils/process_memory/models.py new file mode 100644 index 000000000..2d0f6a497 --- /dev/null +++ b/je_auto_control/utils/process_memory/models.py @@ -0,0 +1,177 @@ +"""Closed identities, reviewed probes and safe semantic observation results.""" +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import Enum +import hashlib +import json +import math +import re +from typing import Callable, Literal, Mapping, Protocol, TypeAlias + +from je_auto_control.utils.exception.exceptions import AutoControlException + +Scalar: TypeAlias = str | int | bool | None + + +class FailureReason(str, Enum): + UNSUPPORTED = "unsupported" + SCOPE_DENIED = "scope_denied" + ACCESS_DENIED = "access_denied" + TARGET_CHANGED = "target_changed" + UNREADABLE_REGION = "unreadable_region" + PARTIAL_READ = "partial_read" + INCONSISTENT_SNAPSHOT = "inconsistent_snapshot" + DEADLINE_EXCEEDED = "deadline_exceeded" + BUDGET_EXCEEDED = "budget_exceeded" + DECODE_FAILED = "decode_failed" + CLEANUP_FAILED = "cleanup_failed" + + +class MemoryObservationError(AutoControlException): + """A fixed reason; provider details and memory contents never enter its message.""" + + def __init__(self, reason: FailureReason) -> None: + self.reason = reason + super().__init__(reason.value) + + +def _identifier(value: str) -> None: + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", value): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + + +def _positive(value: int, ceiling: int) -> None: + if type(value) is not int or not 0 < value <= ceiling: + raise MemoryObservationError(FailureReason.UNSUPPORTED) + + +@dataclass(frozen=True) +class ProcessIdentity: + """Identity measured from the retained process, not from a reusable PID alone.""" + + host: str = field(repr=False) + session: str = field(repr=False) + pid: int = field(repr=False) + birth: int = field(repr=False) + executable: str = field(repr=False) + version: str = field(repr=False) + architecture: str + pointer_bits: int + + def __post_init__(self) -> None: + for value in (self.host, self.session, self.executable, self.version): + _identifier(value) + _positive(self.pid, (1 << 32) - 1) + _positive(self.birth, (1 << 64) - 1) + if (type(self.pointer_bits) is not int + or (self.architecture, self.pointer_bits) not in {("x86", 32), ("x64", 64), ("arm64", 64)}): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + + @property + def digest(self) -> str: + """Bind observations to the measured identity without returning its private fields.""" + value = (self.host, self.session, self.pid, self.birth, self.executable, + self.version, self.architecture, self.pointer_bits) + return hashlib.sha256(json.dumps(value, separators=(",", ":")).encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class MemoryRegion: + """Private mapping evidence returned by the provider for an intersecting range.""" + + base: int = field(repr=False) + size: int = field(repr=False) + allocation: int = field(repr=False) + protection: int = field(repr=False) + committed: bool + readable: bool + guard: bool + + +@dataclass(frozen=True) +class ReadPlan: + """Private locations freshly resolved by a host-reviewed application adapter.""" + + address: int = field(repr=False) + size: int = field(repr=False) + sequence_address: int | None = field(default=None, repr=False) + + +@dataclass(frozen=True) +class ReviewedProbe: + """Immutable host-owned ceiling and trusted version-specific resolver/decoder.""" + + probe_id: str + schema_version: str + executable: str = field(repr=False) + versions: tuple[str, ...] + architectures: tuple[str, ...] + fields: tuple[str, ...] + max_bytes: int + max_regions: int + timeout: float + max_value_bytes: int + resolve: Callable[[ProcessIdentity], ReadPlan] = field(repr=False, compare=False) + decode: Callable[[bytes, tuple[str, ...]], Mapping[str, Scalar]] = field(repr=False, compare=False) + + def __post_init__(self) -> None: + for value in (self.probe_id, self.schema_version, self.executable): + _identifier(value) + for name in ("versions", "architectures", "fields"): + values = tuple(getattr(self, name)) + if not values or len(values) > 64 or len(set(values)) != len(values): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + for value in values: + _identifier(value) + object.__setattr__(self, name, values) + _positive(self.max_bytes, 1 << 20) + _positive(self.max_regions, 1024) + _positive(self.max_value_bytes, 65536) + if (isinstance(self.timeout, bool) or not isinstance(self.timeout, (float, int)) + or not math.isfinite(self.timeout) or not 0 < self.timeout <= 60): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + + +class ProcessHandle(Protocol): + """One retained read-only process handle; close failure leaves ownership with the reader.""" + + def identity(self) -> ProcessIdentity: ... + + def query_region(self, address: int) -> MemoryRegion: ... + + def read(self, address: int, size: int) -> bytes: ... + + def close(self) -> None: ... + + +class ProcessProvider(Protocol): + """Open only the specified process with read/query rights; no escalation or discovery.""" + + def open_readonly(self, identity: ProcessIdentity) -> ProcessHandle: ... + + +@dataclass(frozen=True) +class Observation: + observation_id: str + target_id: str + identity_digest: str + probe_id: str + schema_version: str + started: float + finished: float + fields: tuple[tuple[str, Scalar], ...] = field(repr=False) + consistency: Literal["sequence_checked", "best_effort"] + bytes_read: int + regions_read: int + source: str = field(default="process_memory", init=False) + complete: bool = field(default=True, init=False) + + +@dataclass(frozen=True) +class ObservationFailure: + reason: FailureReason + retired: bool = True + + +ObservationResult: TypeAlias = Observation | ObservationFailure diff --git a/je_auto_control/utils/process_memory/reader.py b/je_auto_control/utils/process_memory/reader.py new file mode 100644 index 000000000..868dc562b --- /dev/null +++ b/je_auto_control/utils/process_memory/reader.py @@ -0,0 +1,244 @@ +"""Adapter-owned semantic observations with bounded reads and retained cleanup ownership.""" +from __future__ import annotations + +from dataclasses import dataclass +import threading +import time +from typing import Callable, Mapping, TypeVar +from uuid import uuid4 + +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint +from je_auto_control.utils.exception.control_signals import raise_if_run_interrupted +from je_auto_control.utils.executor.run_control import ExecutionStopped +from je_auto_control.utils.process_memory.models import ( + FailureReason, MemoryObservationError, MemoryRegion, Observation, ObservationFailure, + ObservationResult, ProcessHandle, ProcessIdentity, ProcessProvider, ReadPlan, ReviewedProbe, Scalar, + _identifier, +) + +_T = TypeVar("_T") + + +class _ObservationFailed(MemoryObservationError): + """Only reader-owned failures are converted to results; authority callbacks are not.""" + + +def _preserve_interruption(error: BaseException) -> None: + if isinstance(error, ExecutionStopped): + raise error + raise_if_run_interrupted(error) + + +def _provider_call(call: Callable[[], _T]) -> _T: + try: + return call() + except Exception as error: # reason: sanitize provider detail, preserving interruption signals + _preserve_interruption(error) + reason = FailureReason.TARGET_CHANGED + if isinstance(error, PermissionError): + reason = FailureReason.ACCESS_DENIED + elif isinstance(error, MemoryObservationError) and isinstance(error.reason, FailureReason): + reason = error.reason + raise _ObservationFailed(reason) from None + + +def _fail(reason: FailureReason) -> None: + raise _ObservationFailed(reason) + + +def _range(address: int, size: int, bits: int) -> None: + if (type(address) is not int or type(size) is not int or address < 0 or size <= 0 + or address >= 1 << bits or size > (1 << bits) - address): + _fail(FailureReason.UNREADABLE_REGION) + + +@dataclass +class _Operation: + expected: ProcessIdentity + probe: ReviewedProbe + checkpoint: Callable[[], None] + clock: Callable[[], float] + deadline: float + bytes_read: int = 0 + regions_read: int = 0 + + def check(self) -> None: + self.checkpoint() + if self.clock() >= self.deadline: + _fail(FailureReason.DEADLINE_EXCEEDED) + + def identity(self, handle: ProcessHandle) -> None: + self.check() + if _provider_call(handle.identity) != self.expected: + _fail(FailureReason.TARGET_CHANGED) + self.check() + + def region(self, handle: ProcessHandle, address: int) -> MemoryRegion: + self.check() + value = _provider_call(lambda: handle.query_region(address)) + self.check() + if not isinstance(value, MemoryRegion): + _fail(FailureReason.UNREADABLE_REGION) + _range(value.base, value.size, self.expected.pointer_bits) + if (any(type(flag) is not bool for flag in (value.committed, value.readable, value.guard)) + or type(value.allocation) is not int or not 0 <= value.allocation < 1 << self.expected.pointer_bits + or type(value.protection) is not int or not 0 <= value.protection < 1 << 32 + or not value.base <= address < value.base + value.size or not value.committed + or not value.readable or value.guard): + _fail(FailureReason.UNREADABLE_REGION) + return value + + def read(self, handle: ProcessHandle, address: int, size: int) -> bytes: + _range(address, size, self.expected.pointer_bits) + if size > self.probe.max_bytes - self.bytes_read: + _fail(FailureReason.BUDGET_EXCEEDED) + collected = bytearray() + while len(collected) < size: + self.identity(handle) + if self.regions_read >= self.probe.max_regions: + _fail(FailureReason.BUDGET_EXCEEDED) + current = address + len(collected) + region = self.region(handle, current) + count = min(size - len(collected), region.base + region.size - current) + self.bytes_read += count + self.regions_read += 1 + chunk = _provider_call(lambda: handle.read(current, count)) + self.check() + if type(chunk) is not bytes or len(chunk) != count: + _fail(FailureReason.PARTIAL_READ) + if self.region(handle, current) != region: + _fail(FailureReason.TARGET_CHANGED) + self.identity(handle) + collected.extend(chunk) + return bytes(collected) + + +def _values(decoded: Mapping[str, Scalar], fields: tuple[str, ...], limit: int) -> tuple[tuple[str, Scalar], ...]: + if set(decoded) != set(fields): + _fail(FailureReason.DECODE_FAILED) + values: list[tuple[str, Scalar]] = [] + for name in fields: + value = decoded[name] + if type(value) is str: + if len(value.encode("utf-8")) > limit: + _fail(FailureReason.DECODE_FAILED) + elif type(value) is int: + if not -(1 << 63) <= value < 1 << 63: + _fail(FailureReason.DECODE_FAILED) + elif value is not None and type(value) is not bool: + _fail(FailureReason.DECODE_FAILED) + values.append((name, value)) + return tuple(values) + + +class ProcessMemoryReader: + """Run reviewed queries; failed closes remain owned until an explicit cleanup retry.""" + + def __init__(self, provider: ProcessProvider, *, clock: Callable[[], float] = time.monotonic) -> None: + self._provider = provider + self._clock = clock + self._pending: list[ProcessHandle] = [] + self._cleanup_inflight = 0 + self._cleanup_lock = threading.Lock() + + @property + def pending_cleanup(self) -> bool: + with self._cleanup_lock: + return bool(self._pending or self._cleanup_inflight) + + def _close(self, handle: ProcessHandle) -> bool: + try: + handle.close() + except BaseException as error: # reason: retain failed ownership even when cleanup is interrupted + with self._cleanup_lock: + self._pending.append(handle) + _preserve_interruption(error) + if not isinstance(error, Exception): + raise + return False + return True + + def close_pending(self) -> bool: + """Retry only retained failed handles; simultaneous readers keep their own live handles.""" + with self._cleanup_lock: + pending, self._pending = self._pending, [] + self._cleanup_inflight += len(pending) + success = True + try: + for index, handle in enumerate(pending): + try: + success = self._close(handle) and success + except BaseException: # reason: retain remaining handles before propagating interruption + with self._cleanup_lock: + self._pending.extend(pending[index + 1:]) + raise + finally: + with self._cleanup_lock: + self._cleanup_inflight -= len(pending) + return success and not self.pending_cleanup + + def observe(self, expected: ProcessIdentity, probe: ReviewedProbe, fields: tuple[str, ...], *, + target_id: str, checkpoint: Callable[[], None] = cancellation_checkpoint) -> ObservationResult: + """Query semantic fields under a host-reviewed probe and the runtime's live checkpoint.""" + selected = tuple(fields) + if not selected or len(set(selected)) != len(selected) or not set(selected) <= set(probe.fields): + return ObservationFailure(FailureReason.SCOPE_DENIED) + _identifier(target_id) + if (expected.executable != probe.executable or expected.version not in probe.versions + or expected.architecture not in probe.architectures): + return ObservationFailure(FailureReason.UNSUPPORTED) + started = self._clock() + operation = _Operation(expected, probe, checkpoint, self._clock, started + probe.timeout) + handle: ProcessHandle | None = None + retired = True + result: ObservationResult + try: + operation.check() + handle = _provider_call(lambda: self._provider.open_readonly(expected)) + result = self._collect(handle, operation, selected, target_id, started) + except _ObservationFailed as error: + result = ObservationFailure(error.reason) + finally: + if handle is not None: + retired = self._close(handle) + if not retired: + return ObservationFailure(FailureReason.CLEANUP_FAILED, retired=False) + if isinstance(result, Observation): + try: + operation.check() + except _ObservationFailed as error: + return ObservationFailure(error.reason) + return result + + def _collect(self, handle: ProcessHandle, operation: _Operation, fields: tuple[str, ...], + target_id: str, started: float) -> Observation: + operation.identity(handle) + probe = operation.probe + try: + plan = probe.resolve(operation.expected) + except Exception as error: # reason: resolver failures must not disclose private addresses + _preserve_interruption(error) + raise _ObservationFailed(FailureReason.UNSUPPORTED) from None + if not isinstance(plan, ReadPlan): + _fail(FailureReason.UNSUPPORTED) + operation.check() + before: bytes | None = None + if plan.sequence_address is not None: + before = operation.read(handle, plan.sequence_address, 8) + if int.from_bytes(before, "little") % 2: + _fail(FailureReason.INCONSISTENT_SNAPSHOT) + raw = operation.read(handle, plan.address, plan.size) + if plan.sequence_address is not None: + if operation.read(handle, plan.sequence_address, 8) != before: + _fail(FailureReason.INCONSISTENT_SNAPSHOT) + try: + values = _values(probe.decode(raw, fields), fields, probe.max_value_bytes) + except Exception as error: # reason: decoder failures must not disclose captured bytes + _preserve_interruption(error) + raise _ObservationFailed(FailureReason.DECODE_FAILED) from None + operation.check() + operation.identity(handle) + return Observation(uuid4().hex, target_id, operation.expected.digest, probe.probe_id, probe.schema_version, + started, operation.clock(), values, + "sequence_checked" if before is not None else "best_effort", + operation.bytes_read, operation.regions_read) diff --git a/pyproject.toml b/pyproject.toml index dc81b8bef..73b7f4cb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -411,6 +411,8 @@ module = [ "je_auto_control.utils.mcp_server.disclosure", "je_auto_control.utils.mcp_server.discovery", "je_auto_control.utils.monitor_layout.macos_frame", + "je_auto_control.utils.process_memory", + "je_auto_control.utils.process_memory.*", "je_auto_control.utils.ocr.tesseract_setup", "je_auto_control.utils.path_guard.policy", "je_auto_control.utils.rbac.__main__", diff --git a/test/unit_test/headless/test_process_memory_reader.py b/test/unit_test/headless/test_process_memory_reader.py new file mode 100644 index 000000000..2bd306a53 --- /dev/null +++ b/test/unit_test/headless/test_process_memory_reader.py @@ -0,0 +1,526 @@ +"""Reviewed semantic memory observations against an owned synthetic process provider.""" +from concurrent.futures import CancelledError +from asyncio import CancelledError as AsyncCancelledError +from dataclasses import replace +import struct +import threading + +import pytest + +from je_auto_control.utils.exception.control_signals import OperationCancelledError +from je_auto_control.utils.executor.run_control import ExecutionStopped +from je_auto_control.utils.process_memory.models import ( + FailureReason, MemoryObservationError, MemoryRegion, Observation, ObservationFailure, + ProcessIdentity, ReadPlan, ReviewedProbe, +) +from je_auto_control.utils.process_memory.reader import ProcessMemoryReader + + +IDENTITY = ProcessIdentity("host-1", "session-1", 42, 900, "fixture-sha256", "1", "x64", 64) +ADDRESS = 4096 +SCHEMA = struct.Struct(" Date: Tue, 10 Nov 2026 04:57:55 +0800 Subject: [PATCH 010/161] Forward nested owner grants to presence sources --- Progress.md | 6 +- architecture_explore.md | 14 +- docs/updates/2026-11.md | 6 + docs/updates/README.md | 3 +- .../utils/agent_runtime/presence_broker.py | 8 +- .../headless/test_agent_presence_nested.py | 193 ++++++++++++++++++ 6 files changed, 219 insertions(+), 11 deletions(-) create mode 100644 test/unit_test/headless/test_agent_presence_nested.py diff --git a/Progress.md b/Progress.md index e61faf037..72ba38387 100644 --- a/Progress.md +++ b/Progress.md @@ -280,7 +280,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev - macOS、X11:真人活動來源已實作(`presence_quartz.py`、`presence_x11.py`,U-20261101-06), 由 `presence_platform.py` 依平台選用並由既有來源迴圈與 60 秒閒置狀態機執行;仍缺: macOS 的 presence transport(Linux 的 worker/broker/server 已改經 `presence_pipe_linux.py`, - U-20261101-13;presence_reader 仍只有 Windows pipe)、觀察目標身分、 + U-20261101-13;reader 已接可信 Linux endpoint,原生執行未驗證)、觀察目標身分、 視窗範圍輸入、自有 helper 隔離與非 Windows 對話框/未儲存 gate,以及以真實實體輸入 驗證「實體/注入」判定的原生驗收(CI 只能證明注入事件不被誤計)。 Wayland:一般 client 看不到全域輸入,也無法區分 libei/uinput 注入與真人,目前沒有可信來源; @@ -299,7 +299,9 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev 正式繫結仍須核實取消發生於 native spawn 期間的所有權、失敗清理、群組與逸出後代退場, 並補受支援版本/架構驗證;隔離原型與直接子程序驗收不等於正式 helper 已接合,安裝前仍須比對。 不得把原始逾時改稱 registry 死鎖,也不得放寬原始 10 秒期限或改動跳過政策。 - presence_worker 仍須接合 Linux source/pipe/security,處理真正登入、seat、鎖定與活動來源; + presence_worker 已接平台 source/pipe/security;broker 已把 inherited nested grant + 傳給每個 source 的 owned channel。仍須建立可信登入/seat 權限與來源環境, + 並驗證真正登入、鎖定與實體活動來源;服務的空白環境不提供 DISPLAY/XDG_SESSION_ID。 已安裝固定模組的未支援回覆及正常 EOF 退場不能證明實體來源或完整後代退場。 不得替換空白 initializer 或偽裝 Wayland session 取代完整應用驗證。 獨立 owner 核心仍須完成每筆記錄的啟動、取消、句柄發布、執行緒回收與服務端持續所有權; diff --git a/architecture_explore.md b/architecture_explore.md index 6607c2e6c..3b145ac20 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,498 | -| 程式碼總行數 | 228,786 | +| 程式碼總行數 | 228,792 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -509,13 +509,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,198 行。 +> 14 個套件、約 52,204 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,253 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,958 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 25,964 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -1012,7 +1012,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,958 行/182 檔) +#### `utils/agent_runtime/`(25,964 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1101,7 +1101,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence_channel_linux.py` | 434 | Own authenticated Linux packet channels, bounded leases and protected listeners. | | `presence_endpoint_linux.py` | 226 | Own protected Linux socket paths without stale-path reuse or recursive cleanup. | | `presence_frames.py` | 137 | Closed finite JSON byte frames and exact presence request/result validation. | -| `presence_broker.py` | 176 | Private broker with internally selected source ownership and normal busy/lease-lost results. | +| `presence_broker.py` | 182 | Private broker with internally selected source ownership and normal busy/lease-lost results. | | `presence_handshake.py` | 77 | Fresh byte challenges bound to native peer identity, birth and process-object liveness. | | `presence_host.py` | 115 | Lazy host-owned source lifetimes and fixed per-helper capabilities, never task-selected authority. | | `presence_messages_linux.py` | 102 | Authenticate each Linux packet and retire every received descriptor before delivery. | @@ -1514,8 +1514,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 981 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,000 | 101,975 | -| **總計** | **1,486** | **228,041** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,000 | 101,981 | +| **總計** | **1,486** | **228,047** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index e64735920..99a6ea7b9 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -708,3 +708,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Added internal immutable identities and reviewed probes, bounded region reads, versioned semantic decoding, sequence checks and retained failed-handle cleanup. Provider failures are sanitized while checkpoint authority errors and interruption signals propagate. - **Evidence:** Injected-provider suite: 84 passed. Delegate strict mypy, Ruff and exception-policy tests passed. No native process memory was read. - **Open items:** Windows provider, trusted resolver, owned fixture, runtime grants/lifecycle, public surfaces and native acceptance remain in Progress.md; M0/M1 are incomplete. + +## U-20261110-10 · 2026-11-10 · Forward nested owner grants to presence sources · #done #agent + +- **What:** Linux broker reads inherited bootstrap once after parent-watch startup and passes the immutable grant through its private source launcher; each source owns a separate lease. +- **Evidence:** Delegate suites: 95 passed, 2 skipped; final entry/factory file: 7 passed. Malformed grants and missing service/policy fail closed. Ruff and broker mypy passed. +- **Open items:** Trusted Linux login/seat authority, live owner-service integration and native acceptance remain in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index 3ce8b11f9..97396893e 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-10 | 2026-11-10 | Forward nested owner grants to presence sources | #done #agent | [2026-11](2026-11.md) | | U-20261110-09 | 2026-11-10 | Bound internal semantic process-memory observations | #snapshot #agent | [2026-11](2026-11.md) | | U-20261110-08 | 2026-11-10 | Generate reports without blocking the GUI | #done #gui | [2026-11](2026-11.md) | | U-20261110-07 | 2026-11-10 | Carry owned Linux presence endpoints into helpers | #done #agent | [2026-11](2026-11.md) | @@ -617,7 +618,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 30 | +| [2026-11.md](2026-11.md) | 2026-11 | 31 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/utils/agent_runtime/presence_broker.py b/je_auto_control/utils/agent_runtime/presence_broker.py index b786645d9..e45751d97 100644 --- a/je_auto_control/utils/agent_runtime/presence_broker.py +++ b/je_auto_control/utils/agent_runtime/presence_broker.py @@ -3,11 +3,14 @@ from contextlib import ExitStack from dataclasses import dataclass +from functools import partial import sys import threading from typing import Any, Callable from je_auto_control.utils.agent_runtime.errors import AgentControlBusy, AgentTaskError +from je_auto_control.utils.agent_runtime import owner_service_nested +from je_auto_control.utils.agent_runtime.owned_channel_factory import owned_channel from je_auto_control.utils.agent_runtime.presence_frames import ( decode_frame, encode_frame, identifier, presence_body, validate_response, ) @@ -169,7 +172,10 @@ def run(source: Any, sink: Any, broker: PresenceBroker | None = None) -> None: def main() -> None: """Run only as the fixed hidden helper of a host-owned presence pool.""" start_parent_watch() - run(sys.stdin.buffer, sys.stdout.buffer) + grant = owner_service_nested.read_nested_bootstrap() if sys.platform.startswith('linux') else None + # Only the inherited, immutable grant may authorize source child leases. + launch = partial(SourceProcess, channel_factory=partial(owned_channel, nested=grant)) + run(sys.stdin.buffer, sys.stdout.buffer, PresenceBroker(launch=launch)) if __name__ == '__main__': diff --git a/test/unit_test/headless/test_agent_presence_nested.py b/test/unit_test/headless/test_agent_presence_nested.py new file mode 100644 index 000000000..6cb7ca686 --- /dev/null +++ b/test/unit_test/headless/test_agent_presence_nested.py @@ -0,0 +1,193 @@ +"""Broker entry consumes owned nested bootstrap and keeps source child leases isolated.""" +import os +import struct + +import pytest + +from je_auto_control.utils.agent_runtime import presence_broker, owner_service_nested as nested +from je_auto_control.utils.agent_runtime import owned_channel_factory as factory, helper_owner_linux +from je_auto_control.utils.agent_runtime import native_channel, owner_service_wire as wire +from je_auto_control.utils.agent_runtime.errors import AgentTaskError +from .test_agent_helper_owner_linux import FakeService + + +def configure(monkeypatch, data=None, *, platform='linux', binding=True): + service = FakeService() + if data is None: + data = nested._FRAME.pack(nested.BOOTSTRAP_MAGIC, nested.BOOTSTRAP_VERSION, + struct.pack(' Date: Tue, 10 Nov 2026 04:59:09 +0800 Subject: [PATCH 011/161] Give Screenshot independent lifecycle and background tasks --- Progress.md | 2 +- architecture_explore.md | 12 +- docs/guides/en/setup.md | 2 + docs/guides/zh-CN/setup.md | 2 + docs/guides/zh-TW/setup.md | 2 + docs/updates/2026-11.md | 6 + docs/updates/README.md | 3 +- je_auto_control/gui/_screenshot_tab.py | 163 +++++++----- je_auto_control/gui/main_widget.py | 12 +- je_auto_control/gui/tab_registry.py | 2 +- .../headless/test_gui_lazy_registry.py | 2 +- .../headless/test_gui_tab_lifecycle_audit.py | 17 +- .../headless/test_screenshot_tab_lifecycle.py | 233 ++++++++++++++++++ 13 files changed, 373 insertions(+), 85 deletions(-) create mode 100644 test/unit_test/headless/test_screenshot_tab_lifecycle.py diff --git a/Progress.md b/Progress.md index 72ba38387..c0ac3db2a 100644 --- a/Progress.md +++ b/Progress.md @@ -531,7 +531,7 @@ D2 仍缺 helper 隔離與半開交握資源回收;D3 的錄製/全域停止 計畫 E(Android/iOS)、H(型別深化與總驗收)尚未開始。F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 -- **F1 的遺留面板釋放**:Auto Click、Screenshot、Image Detection、Record、Script 五個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 +- **F1 的遺留面板釋放**:Auto Click、Image Detection、Record、Script 四個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 - **F4**(啟動/記憶體基準、mixed-DPI、功能對等測試)尚未開始。 diff --git a/architecture_explore.md b/architecture_explore.md index 3b145ac20..c77667aef 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -25,7 +25,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,498 | -| 程式碼總行數 | 228,792 | +| 程式碼總行數 | 228,825 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1263,7 +1263,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | | `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | -| `main_widget.py` | 386 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | +| `main_widget.py` | 378 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | | `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與既有表單;不匯入 Qt。 | | `navigation.py` | 200 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | @@ -1273,7 +1273,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `config_sync_worker.py` | 131 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | | `config_sync_tab.py` | 413 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | | `_auto_click_tab.py` | 295 | 自動點擊分頁的 mixin 建構器。 | -| `_screenshot_tab.py` | 138 | 截圖/取像素分頁 mixin。 | +| `_screenshot_tab.py` | 179 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | | `_image_detect_tab.py` | 117 | 影像偵測分頁 mixin。 | | `_script_tab.py` | 158 | 腳本執行分頁 mixin。 | | `_record_tab.py` | 144 | 錄製/回放分頁 mixin。 | @@ -1304,7 +1304,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | 分頁 | 模組 | 行數 | 職責 | | --- | --- | ---: | --- | | auto_click | `_auto_click_tab.py` | 295 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | -| screenshot | `_screenshot_tab.py` | 138 | 截圖、選區、螢幕尺寸、取像素色。 | +| screenshot | `_screenshot_tab.py` | 179 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 117 | 樣板裁切、定位、定位全部、定位並點擊。 | | record | `_record_tab.py` | 144 | 錄製/停止/回放/存檔/載入。 | | script_builder | `script_builder/` | 6,902 | **視覺化腳本編輯器**:`command_schema.py`(5,549 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | @@ -1494,7 +1494,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,861 | +| `gui/` | 144 | 39,894 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,243 | | `utils/executor/` | 11 | 10,702 | @@ -1515,7 +1515,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,000 | 101,981 | -| **總計** | **1,486** | **228,047** | +| **總計** | **1,486** | **228,080** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/setup.md b/docs/guides/en/setup.md index 4212c9ed2..d07f836c2 100644 --- a/docs/guides/en/setup.md +++ b/docs/guides/en/setup.md @@ -357,3 +357,5 @@ Every environment variable AutoControl reads. Nothing here is required: with no The Report page is created when first opened. Closing it releases its controls and local result view; reopening creates a fresh page and reads the current recording status. Closing the page does not disable the shared recorder. Report generation runs in the background and shows a running status. A page accepts one generation at a time and captures the name when you start it. Closing drops late results; an already-running file write may still finish. + +The Screenshot page is also created on first open and released on close. Screen-size queries, captures and pixel reads run in the background with a running status and one operation at a time. Inputs are captured when the operation starts. Closing discards late results; a capture already in progress may still write its file. Hiding preserves the page. Region picking and file browsing remain explicit interactive actions. diff --git a/docs/guides/zh-CN/setup.md b/docs/guides/zh-CN/setup.md index 786976de6..4bdad58d0 100644 --- a/docs/guides/zh-CN/setup.md +++ b/docs/guides/zh-CN/setup.md @@ -295,4 +295,6 @@ AutoControl 读取的每一个环境变量。这里没有任何一项是必填 Report 标签页在首次打开时创建。关闭会释放控件和本地结果视图;重新打开会创建新页面并读取当前录制状态。关闭标签页不会禁用共享 recorder。 +Screenshot 标签页同样在首次打开时创建,关闭时释放。屏幕尺寸查询、截图和像素读取在后台执行,显示运行状态,每次接受一项任务,并使用启动时的输入值。关闭后丢弃迟到结果;已开始的截图仍可能写入文件。隐藏会保留页面。选区和浏览文件仍须由用户明确操作。 + 报表在后台生成并显示运行状态。每个标签页一次接受一个生成任务,使用开始时输入的名称。关闭会丢弃迟到结果;已开始的文件写入仍可能完成。 diff --git a/docs/guides/zh-TW/setup.md b/docs/guides/zh-TW/setup.md index e00477d0d..c1ce11d85 100644 --- a/docs/guides/zh-TW/setup.md +++ b/docs/guides/zh-TW/setup.md @@ -295,4 +295,6 @@ AutoControl 讀取的每一個環境變數。這裡沒有任何一項是必填 Report 分頁在首次開啟時建立。關閉會釋放控制項與本機結果畫面;重新開啟會建立新頁面並讀取目前錄製狀態。關閉分頁不會停用共用 recorder。 +Screenshot 分頁同樣在首次開啟時建立,關閉時釋放。螢幕尺寸查詢、截圖與像素讀取會在背景執行,顯示執行中狀態,每次接受一項工作,並使用啟動時的輸入值。關閉後丟棄晚到結果;已開始的截圖仍可能寫入檔案。隱藏會保留頁面。選區與瀏覽檔案仍須由使用者明確操作。 + 報表在背景產生並顯示執行中狀態。每個分頁一次接受一個產生工作,使用開始時輸入的名稱。關閉會丟棄晚到結果;已開始的檔案寫入仍可能完成。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 99a6ea7b9..057929c8b 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -714,3 +714,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Linux broker reads inherited bootstrap once after parent-watch startup and passes the immutable grant through its private source launcher; each source owns a separate lease. - **Evidence:** Delegate suites: 95 passed, 2 skipped; final entry/factory file: 7 passed. Malformed grants and missing service/policy fail closed. Ruff and broker mypy passed. - **Open items:** Trusted Linux login/seat authority, live owner-service integration and native acceptance remain in Progress.md. + +## U-20261110-11 · 2026-11-10 · Own Screenshot lifecycle and run reads asynchronously · #done #agent + +- **What:** Screenshot is an independent lazy widget. Capture, pixel and size operations use TabTask with input snapshots, running status and close-discard; pixel errors survive retranslation. +- **Evidence:** Delegate related suite: 90 passed; Ruff and targeted mypy passed. All native operations, dialogs and pickers were mocked before construction. +- **Open items:** Remaining GUI panels and native acceptance stay in Progress.md. Already-entered capture writes may finish after close. diff --git a/docs/updates/README.md b/docs/updates/README.md index 97396893e..6203fa1da 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261110-11 | 2026-11-10 | Own Screenshot lifecycle and run reads asynchronously | #done #agent | [2026-11](2026-11.md) | | U-20261110-10 | 2026-11-10 | Forward nested owner grants to presence sources | #done #agent | [2026-11](2026-11.md) | | U-20261110-09 | 2026-11-10 | Bound internal semantic process-memory observations | #snapshot #agent | [2026-11](2026-11.md) | | U-20261110-08 | 2026-11-10 | Generate reports without blocking the GUI | #done #gui | [2026-11](2026-11.md) | @@ -618,7 +619,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 31 | +| [2026-11.md](2026-11.md) | 2026-11 | 32 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/gui/_screenshot_tab.py b/je_auto_control/gui/_screenshot_tab.py index 4f8896448..2276843e0 100644 --- a/je_auto_control/gui/_screenshot_tab.py +++ b/je_auto_control/gui/_screenshot_tab.py @@ -1,16 +1,17 @@ -"""Screenshot / pixel-probe tab builder (extracted mixin).""" -from typing import TYPE_CHECKING, Any, Callable +"""Screenshot and pixel-probe panel with independently owned controls.""" +from functools import partial +from typing import Callable, Literal, Optional from PySide6.QtWidgets import ( QFileDialog, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, - QMessageBox, QTextEdit, QVBoxLayout, QWidget, + QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._validators import int_validator -from je_auto_control.gui._qt_typed import as_widget +from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.selector import open_region_selector -from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.wrapper.auto_control_screen import screen_size, screenshot, get_pixel @@ -19,24 +20,13 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -class ScreenshotTabMixin: - """Provides the screenshot tab builder/handlers. +class ScreenshotTab(TranslatableMixin, QWidget): + """Own screenshot inputs and pixel-result state independently of the workspace.""" - Host widget must expose the ``TranslatableMixin`` API (``self._tr(...)``, - ``self._translate(...)``) so every label registers for live language - switching. - """ - - if TYPE_CHECKING: - # Declared, never defined: the widget this mixin is mixed into owns - # every one of these. The block is stripped at runtime, so nothing - # here can shadow what the host actually binds. - _tr: Callable[..., Any] - _translate: Callable[[str], str] - - def _build_screenshot_tab(self) -> QWidget: - tab = QWidget() - layout = QVBoxLayout() + def __init__(self, parent: Optional[QWidget] = None) -> None: + super().__init__(parent) + self._tr_init() + layout = QVBoxLayout(self) # Screen size (read via Actions menu -> Get Screen Size) size_group = self._tr(QGroupBox(), "screen_size_label") @@ -72,10 +62,8 @@ def _build_screenshot_tab(self) -> QWidget: self.pixel_y_input.setValidator(int_validator()) px_grid.addWidget(self.pixel_y_input, 0, 3) self.pixel_result_label = QLabel() - self._pixel_result_suffix = " --" - self.pixel_result_label.setText( - self._translate("pixel_result") + self._pixel_result_suffix, - ) + self._pixel_result: tuple[Literal["value", "error", "running"], str] = ("value", "--") + self._render_pixel_result() px_grid.addWidget(self.pixel_result_label, 1, 0, 1, 4) px_group.setLayout(px_grid) layout.addWidget(px_group) @@ -85,54 +73,107 @@ def _build_screenshot_tab(self) -> QWidget: self.ss_result_text.setMaximumHeight(100) layout.addWidget(self.ss_result_text) layout.addStretch() - tab.setLayout(layout) - return tab - - def _get_screen_size(self): - try: - w, h = screen_size() - self.screen_size_label.setText(f"{w} x {h}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) - - def _browse_ss_path(self): - path, _ = QFileDialog.getSaveFileName(as_widget(self), _t("save_screenshot"), "", "PNG (*.png);;All (*)") + self._task = TabTask(self) + self._task.result.connect(self._on_result) + self._task.error.connect(self._on_error) + + def menu_actions(self) -> list[tuple[str, Callable[[], object]]]: + return [ + ("take_screenshot", self._take_screenshot), + ("browse", self._browse_ss_path), + ("pick_region", self._pick_ss_region), + ("get_screen_size", self._get_screen_size), + ("get_pixel_label", self._get_pixel_color), + ] + + def _get_screen_size(self) -> None: + if self._task.start(_read_screen_size, tag="size"): + self.screen_size_label.setText(_t("task_running")) + + def _browse_ss_path(self) -> None: + path, _ = QFileDialog.getSaveFileName(self, _t("save_screenshot"), "", "PNG (*.png);;All (*)") if path: self.ss_path_input.setText(path) - def _pick_ss_region(self): - region = open_region_selector(as_widget(self)) + def _pick_ss_region(self) -> None: + region = open_region_selector(self) if region is None: return x, y, w, h = region self.ss_region_input.setText(f"{x}, {y}, {x + w}, {y + h}") - def _take_screenshot(self): + def _take_screenshot(self) -> None: + if self._task.running: + return try: path = self.ss_path_input.text() or None region_text = self.ss_region_input.text().strip() - region = None - if region_text: - region = [int(x.strip()) for x in region_text.split(",")] - screenshot(file_path=path, screen_region=region) - self.ss_result_text.setText(f"Screenshot saved: {path or '(not saved)'}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: + region = tuple(int(x.strip()) for x in region_text.split(",")) if region_text else None + except (ValueError, TypeError) as error: self.ss_result_text.setText(f"Error: {error}") + return + if self._task.start(partial(_capture, path, region), tag="screenshot"): + self.ss_result_text.setText(_t("task_running")) - def _get_pixel_color(self): + def _get_pixel_color(self) -> None: + if self._task.running: + return try: x = int(self.pixel_x_input.text()) y = int(self.pixel_y_input.text()) - color = get_pixel(x, y) - self._pixel_result_suffix = f" {color}" - self.pixel_result_label.setText( - self._translate("pixel_result") + self._pixel_result_suffix, - ) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.pixel_result_label.setText(f"Error: {error}") - - def _screenshot_retranslate(self) -> None: - if hasattr(self, "pixel_result_label"): - self.pixel_result_label.setText( - self._translate("pixel_result") + self._pixel_result_suffix, - ) + except (ValueError, TypeError) as error: + self._pixel_result = ("error", str(error)) + self._render_pixel_result() + return + if self._task.start(partial(_read_pixel, x, y), tag="pixel"): + self._pixel_result = ("running", "") + self._render_pixel_result() + + def _on_result(self, result: str) -> None: + if self._task.tag == "size": + self.screen_size_label.setText(result) + elif self._task.tag == "pixel": + self._pixel_result = ("value", result) + self._render_pixel_result() + else: + self.ss_result_text.setText(result) + + def _on_error(self, error: object) -> None: + if self._task.tag == "size": + self.screen_size_label.setText(f"Error: {error}") + elif self._task.tag == "pixel": + self._pixel_result = ("error", str(error)) + self._render_pixel_result() + else: + self.ss_result_text.setText(f"Error: {error}") + + def _render_pixel_result(self) -> None: + kind, text = self._pixel_result + if kind == "running": + self.pixel_result_label.setText(_t("task_running")) + elif kind == "error": + self.pixel_result_label.setText(f"Error: {text}") + else: + self.pixel_result_label.setText(f"{_t('pixel_result')} {text}") + + def retranslate(self) -> None: + super().retranslate() + self._render_pixel_result() + + def dispose(self) -> None: + """Discard late results; an already-entered native operation may still finish.""" + self._task.stop() + + +def _read_screen_size() -> str: + width, height = screen_size() + return f"{width} x {height}" + + +def _capture(path: Optional[str], region: Optional[tuple[int, ...]]) -> str: + screenshot(file_path=path, screen_region=list(region) if region is not None else None) + return f"Screenshot saved: {path or '(not saved)'}" + + +def _read_pixel(x: int, y: int) -> str: + return str(get_pixel(x, y)) diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index 51ab3a2cb..616669e25 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -12,7 +12,6 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._image_detect_tab import ImageDetectTabMixin from je_auto_control.gui._record_tab import RecordTabMixin -from je_auto_control.gui._screenshot_tab import ScreenshotTabMixin from je_auto_control.gui._script_tab import ScriptTabMixin from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.tab_registry import ( @@ -35,7 +34,7 @@ class _WorkerSignals(QObject): # Main Widget # ============================================================================= class AutoControlGUIWidget( - TranslatableMixin, AutoClickTabMixin, ScreenshotTabMixin, + TranslatableMixin, AutoClickTabMixin, ImageDetectTabMixin, RecordTabMixin, ScriptTabMixin, QWidget, ): @@ -99,13 +98,6 @@ def _own_tab_builders(self) -> Dict[str, Any]: ("write_send", self._send_write), ("scroll_send", self._send_scroll), )), - "screenshot": (self._build_screenshot_tab(), ( - ("take_screenshot", self._take_screenshot), - ("browse", self._browse_ss_path), - ("pick_region", self._pick_ss_region), - ("get_screen_size", self._get_screen_size), - ("get_pixel_label", self._get_pixel_color), - )), "image_detect": (self._build_image_detect_tab(), ( ("browse", self._browse_img), ("crop_template", self._crop_template), @@ -357,7 +349,7 @@ def _retranslate_core_tabs(self) -> None: capture = getattr(self, "script_history_controls", None) if capture is not None: capture.retranslate() - for name in ("_auto_click_retranslate", "_screenshot_retranslate", "_record_retranslate"): + for name in ("_auto_click_retranslate", "_record_retranslate"): if hasattr(self, name): getattr(self, name)() diff --git a/je_auto_control/gui/tab_registry.py b/je_auto_control/gui/tab_registry.py index c78a50d46..b2f9c7e9c 100644 --- a/je_auto_control/gui/tab_registry.py +++ b/je_auto_control/gui/tab_registry.py @@ -142,7 +142,7 @@ def close(self, key: str) -> None: # Desktop, which needs an optional extra and falls back to a placeholder). TAB_SPECS: Tuple[TabSpec, ...] = ( TabSpec("auto_click", "tab_auto_click", "core"), - TabSpec("screenshot", "tab_screenshot", "core"), + TabSpec("screenshot", "tab_screenshot", "core", f"{_GUI}._screenshot_tab", "ScreenshotTab"), TabSpec("image_detect", "tab_image_detect", "core"), TabSpec("record", "tab_record", "core", default_visible=True), TabSpec("script_builder", "tab_script_builder", "core", diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index 8be8c987a..24b77a751 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -17,7 +17,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[3] # Built by the main widget itself: its mixin tabs, and Remote Desktop's placeholder fallback. -OWN_TABS = {"auto_click", "screenshot", "image_detect", "record", "script", "remote_desktop"} +OWN_TABS = {"auto_click", "image_detect", "record", "script", "remote_desktop"} OPEN_AT_START = ["record", "script_builder", "remote_desktop"] diff --git a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py index 37ee1d582..e464fc578 100644 --- a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py +++ b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py @@ -109,10 +109,19 @@ def bad_region(**kwargs): raise AutoControlScreenException("bad region") monkeypatch.setattr(tab, "screenshot", bad_region) - fake = types.SimpleNamespace(ss_path_input=QLineEdit(), ss_region_input=QLineEdit("100,100,50,50"), - ss_result_text=QTextEdit()) - tab.ScreenshotTabMixin._take_screenshot(fake) - assert "bad region" in fake.ss_result_text.toPlainText() + monkeypatch.setattr(tab, "screen_size", lambda: (800, 600)) + monkeypatch.setattr(tab, "get_pixel", lambda x, y: (0, 0, 0)) + monkeypatch.setattr(tab, "open_region_selector", lambda parent: None) + monkeypatch.setattr(tab.QFileDialog, "getSaveFileName", lambda *args: ("", "")) + page = tab.ScreenshotTab() + page.ss_region_input.setText("100,100,50,50") + try: + page._take_screenshot() + from headless._qt_settle import pump_until + assert pump_until(lambda: not page._task.running) + assert "bad region" in page.ss_result_text.toPlainText() + finally: + page.deleteLater() def test_the_manual_script_shows_an_unknown_command(qapp): diff --git a/test/unit_test/headless/test_screenshot_tab_lifecycle.py b/test/unit_test/headless/test_screenshot_tab_lifecycle.py new file mode 100644 index 000000000..5d287e823 --- /dev/null +++ b/test/unit_test/headless/test_screenshot_tab_lifecycle.py @@ -0,0 +1,233 @@ +"""Screenshot panel lifecycle and state with every native operation replaced.""" +import os +import threading +from types import SimpleNamespace + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +from PySide6.QtCore import QEvent, QTimer # noqa: E402 +from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 +from shiboken6 import isValid # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 +from je_auto_control.gui import _screenshot_tab as module # noqa: E402 +from je_auto_control.gui.tab_registry import TAB_SPECS, TabEntry, TabRegistry, lazy_factory # noqa: E402 + + +@pytest.fixture +def app(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture(autouse=True) +def fakes(monkeypatch): + calls = SimpleNamespace(captures=[], pixels=[], dialogs=[], warnings=[], sizes=[], selections=[]) + monkeypatch.setattr(module, "screen_size", lambda: (calls.sizes.append(True) or (800, 600))) + monkeypatch.setattr(module, "screenshot", lambda **kw: calls.captures.append(kw)) + monkeypatch.setattr(module, "get_pixel", lambda x, y: (calls.pixels.append((x, y)) or (1, 2, 3))) + monkeypatch.setattr(module, "open_region_selector", + lambda parent: (calls.selections.append(True) or (10, 20, 30, 40))) + monkeypatch.setattr(module.QFileDialog, "getSaveFileName", + lambda *args: (calls.dialogs.append(True) or ("chosen.png", "PNG"))) + return calls + + +def _delete(app, widget): + widget.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +def test_screenshot_tab_is_lazy_and_close_rebuilds_owned_state(app, fakes): + spec = next(spec for spec in TAB_SPECS if spec.key == "screenshot") + owner = QWidget() + entry = TabEntry(spec.key, spec.title_key, lazy_factory(spec.module, spec.class_name), + on_build=lambda page: page.setParent(owner)) + registry = TabRegistry([entry]) + assert not entry.built + page = registry.open("screenshot") + assert not any(vars(fakes).values()), "construction performed native or dialog work" + page.ss_path_input.setText("old.png") + page.ss_result_text.setText("old result") + page.hide() + assert registry.open("screenshot") is page + assert page.ss_path_input.text() == "old.png" + registry.close("screenshot") + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + assert not isValid(page) + assert not entry.built + replacement = registry.open("screenshot") + assert replacement is not page + assert replacement.ss_path_input.text() == "" + assert replacement.ss_result_text.toPlainText() == "" + assert not hasattr(owner, "ss_path_input") + _delete(app, owner) + + +def test_screenshot_actions_preserve_picker_region_convention(app, fakes): + page = module.ScreenshotTab() + try: + actions = dict(page.menu_actions()) + assert list(actions) == ["take_screenshot", "browse", "pick_region", "get_screen_size", "get_pixel_label"] + actions["browse"]() + assert page.ss_path_input.text() == "chosen.png" + actions["pick_region"]() + assert page.ss_region_input.text() == "10, 20, 40, 60" + actions["take_screenshot"]() + assert pump_until(lambda: not page._task.running) + assert fakes.captures == [{"file_path": "chosen.png", "screen_region": [10, 20, 40, 60]}] + assert "chosen.png" in page.ss_result_text.toPlainText() + actions["get_screen_size"]() + assert pump_until(lambda: not page._task.running) + assert page.screen_size_label.text() == "800 x 600" + page.pixel_x_input.setText("7") + page.pixel_y_input.setText("8") + actions["get_pixel_label"]() + assert pump_until(lambda: not page._task.running) + assert fakes.pixels == [(7, 8)] + assert "(1, 2, 3)" in page.pixel_result_label.text() + finally: + _delete(app, page) + + +def test_pixel_error_survives_retranslation_after_success(app, monkeypatch): + page = module.ScreenshotTab() + try: + page._get_pixel_color() + assert pump_until(lambda: not page._task.running) + assert "(1, 2, 3)" in page.pixel_result_label.text() + + def fail(x, y): + raise RuntimeError("pixel unavailable") + + monkeypatch.setattr(module, "get_pixel", fail) + page._get_pixel_color() + assert pump_until(lambda: not page._task.running) + page.retranslate() + assert page.pixel_result_label.text() == "Error: pixel unavailable" + monkeypatch.setattr(module, "get_pixel", lambda x, y: (4, 5, 6)) + page._get_pixel_color() + assert pump_until(lambda: not page._task.running) + page.retranslate() + assert "(4, 5, 6)" in page.pixel_result_label.text() + assert "Error" not in page.pixel_result_label.text() + finally: + _delete(app, page) + + +def test_invalid_inputs_do_not_call_native_backends(app, fakes): + page = module.ScreenshotTab() + try: + page.ss_region_input.setText("invalid") + page._take_screenshot() + assert page.ss_result_text.toPlainText().startswith("Error") + page.pixel_x_input.setText("invalid") + page._get_pixel_color() + assert pump_until(lambda: not page._task.running) + assert page.pixel_result_label.text().startswith("Error") + assert fakes.captures == [] and fakes.pixels == [] + finally: + _delete(app, page) + + +def test_cancelled_dialogs_keep_current_inputs(app, monkeypatch): + monkeypatch.setattr(module, "open_region_selector", lambda parent: None) + monkeypatch.setattr(module.QFileDialog, "getSaveFileName", lambda *args: ("", "")) + page = module.ScreenshotTab() + try: + page.ss_path_input.setText("keep.png") + page.ss_region_input.setText("1, 2, 3, 4") + page._browse_ss_path() + page._pick_ss_region() + assert page.ss_path_input.text() == "keep.png" + assert page.ss_region_input.text() == "1, 2, 3, 4" + finally: + _delete(app, page) + +@pytest.mark.parametrize("operation,backend", [ + ("_get_screen_size", "screen_size"), + ("_take_screenshot", "screenshot"), + ("_get_pixel_color", "get_pixel"), +]) +def test_capture_operations_run_off_gui_thread(app, monkeypatch, operation, backend): + threads = [] + + def call(*args, **kwargs): + threads.append(threading.get_ident()) + return (800, 600) if backend == "screen_size" else (1, 2, 3) + + monkeypatch.setattr(module, backend, call) + page = module.ScreenshotTab() + try: + getattr(page, operation)() + assert pump_until(lambda: not page._task.running) + assert len(threads) == 1 and threads[0] != threading.get_ident() + finally: + _delete(app, page) + + +@pytest.mark.parametrize("fail", [False, True]) +def test_capture_close_reopen_discards_late_outcome(app, monkeypatch, fail): + entered, release, exited = threading.Event(), threading.Event(), threading.Event() + calls, ticks = [], [] + + def capture(**kwargs): + calls.append(kwargs) + entered.set() + try: + assert release.wait(5), "test did not release fake capture" + if fail: + raise RuntimeError("late capture error") + finally: + exited.set() + + monkeypatch.setattr(module, "screenshot", capture) + monkeypatch.setattr(module.language_wrapper, "translate", + lambda key, fallback: "localized running" if key == "task_running" else fallback) + owner = QWidget() + entry = TabEntry("screenshot", "tab_screenshot", module.ScreenshotTab, + on_build=lambda page: page.setParent(owner)) + registry = TabRegistry([entry]) + page = registry.open("screenshot") + timer = QTimer(owner) + timer.setInterval(1) + timer.timeout.connect(lambda: ticks.append(True)) + timer.start() + try: + page.ss_path_input.setText("original.png") + page.ss_region_input.setText("1, 2, 3, 4") + page._take_screenshot() + assert page.ss_result_text.toPlainText() == "localized running" + page.ss_result_text.setText("retained status") + page.ss_path_input.setText("changed.png") + page.ss_region_input.setText("invalid") + page._take_screenshot() + assert page.ss_result_text.toPlainText() == "retained status" + assert pump_until(lambda: entered.is_set() and bool(ticks)) + assert calls == [{"file_path": "original.png", "screen_region": [1, 2, 3, 4]}] + registry.close("screenshot") + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + assert not isValid(page) + replacement = registry.open("screenshot") + release.set() + assert pump_until(exited.is_set) + assert replacement.ss_result_text.toPlainText() == "" + finally: + release.set() + assert pump_until(exited.is_set) + _delete(app, owner) + + +def test_size_failure_is_displayed_inline(app, monkeypatch): + def fail(): + raise RuntimeError("size unavailable") + + monkeypatch.setattr(module, "screen_size", fail) + page = module.ScreenshotTab() + try: + page._get_screen_size() + assert pump_until(lambda: not page._task.running) + assert page.screen_size_label.text() == "Error: size unavailable" + finally: + _delete(app, page) From 7cb7fde2d19bb067ac738ff7b9a2f6e33f82af18 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:07:20 +0800 Subject: [PATCH 012/161] Prepare owned process-memory fixture for provider validation --- Progress.md | 4 +- architecture.md | 5 + architecture_explore.md | 7 +- docs/process_memory_contract.md | 27 +++- docs/updates/2026-11.md | 8 + docs/updates/README.md | 1 + test/fixtures/process_memory_fixture.py | 124 +++++++++++++++ .../headless/test_process_memory_fixture.py | 147 ++++++++++++++++++ 8 files changed, 317 insertions(+), 6 deletions(-) create mode 100644 test/fixtures/process_memory_fixture.py create mode 100644 test/unit_test/headless/test_process_memory_fixture.py diff --git a/Progress.md b/Progress.md index c0ac3db2a..ad0c6afe9 100644 --- a/Progress.md +++ b/Progress.md @@ -630,7 +630,9 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 `WIP` — 內部 `utils/process_memory/` 已有不可變身分/probe、區段與位元組預算、 序號一致性檢查、語意欄位白名單及失敗 handle 保留重試。契約與 fixture 協定見 [process_memory_contract.md](docs/process_memory_contract.md)。M0/M1 尚未完成, -仍缺 typed Windows provider、可信 ASLR resolver、自有 fixture 程序、runtime grant/helper +已有自有 fixture 的固定緩衝區與有界管線控制協定,測試僅驗證本機資料配置及背景子程序通訊。 +bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報資訊,不能充當 OS 出生身分或可信 resolver。 +仍缺 typed Windows provider、可信 ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 diff --git a/architecture.md b/architecture.md index e30b10cd7..2a139eed4 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,10 @@ # AutoControl Architecture +The process-memory test fixture owns fixed payload and sequence buffers in a hidden +child process. Bounded inherited pipes expose expected state and validated fixture +updates. Bootstrap facts remain unverified until a native provider independently +matches the retained process identity. This tooling adds no public memory API. + The package facade resolves each public export from its existing source module. Concrete typing declarations generate runtime binding tables, checked by `python scripts/generate_facade_exports.py --check` in CI. Resolution obtains the real object diff --git a/architecture_explore.md b/architecture_explore.md index c77667aef..0692f5bb1 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -11,12 +11,15 @@ CI 以 `python scripts/generate_facade_exports.py --check` 檢查一致性。六 > 擷取每個模組的 docstring 與頂層公開名稱;統計數字取自實際檔案,非估算。 > 指令數與公開 API 數以 `executor.known_commands()` 與 `je_auto_control.__all__` 在工作樹上實測取得。 > -> **掃描時間**:2026-11-10 **版本**:`pyproject.toml` version `1.2.0` **分支**:`dev` +> **掃描時間**:2026-11-11 **版本**:`pyproject.toml` version `1.2.0` **分支**:`dev` --- ## 1. 專案定位與規模 +`test/fixtures/process_memory_fixture.py` 由子程序持有固定 payload 與 sequence 緩衝區, +以有界管線提供已知語意狀態及更新。bootstrap 僅自報資訊,原生身分核對與記憶體讀回仍待實作。 + `je_auto_control` 是一套跨平台 GUI 自動化框架,涵蓋 Windows(Win32 API)、macOS(pyobjc/Quartz)、 Linux X11(python-Xlib)與 Linux Wayland(libei / ydotool),並延伸到 Android(ADB / uiautomator2)與 iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、螢幕擷取、動作腳本化與報表產生; @@ -1403,7 +1406,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 846 個 `test_*.py`/8,825 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,168 個 `test_*.py`/11,354 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index 83c7acf5e..d7e882991 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -124,7 +124,28 @@ reuse, permission denial, cancellation and failed handle retirement. Compare exa semantic values to fixture-owned expected values. Independently observe foreground window, focus, mouse and desktop-input events to establish noninterference. +### Owned fixture preparation + +`test/fixtures/process_memory_fixture.py` owns fixed payload and sequence buffers +for its process lifetime. Its bounded JSON-lines protocol uses inherited stdin and +stdout pipes. Bootstrap and control replies have distinct message kinds on the +same transport. This is not yet the separate native acceptance control channel. +Only the fixture changes its buffers. The parent can request expected semantic +state, a validated state change or shutdown; it cannot request arbitrary memory +reads or writes. + +Bootstrap reports PID, pointer width, buffer locations, fixture source digest and +a fresh launch nonce as unverified self-reports. The nonce is not OS process birth, +and the source digest is not measured executable identity. No reviewed probe may +trust these records without the future provider's independent identity checks. + +Headless tests exercise exact local buffer layout and real hidden child-process +communication, invalid requests, EOF and shutdown. These checks do not establish +cross-process memory readback, ASLR resolution, native publication guarantees or +desktop noninterference. Shared-memory mappings were rejected because parent-side +mapping reads would bypass the future process-memory provider. + No native acceptance command is supplied or executed by this increment. Native -execution stays paused under `Progress.md`; the fixture, typed Win32 provider, -host probe configuration, runtime lifecycle/policy integration and application -coverage must be implemented and reviewed before M1/M3 can be marked complete. +execution stays paused under `Progress.md`; typed Win32 calls, trusted bootstrap +matching, page-protection fault injection, host probe configuration, runtime +lifecycle/policy integration and application coverage remain required for M1/M3. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 057929c8b..f6658a0ba 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -720,3 +720,11 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Screenshot is an independent lazy widget. Capture, pixel and size operations use TabTask with input snapshots, running status and close-discard; pixel errors survive retranslation. - **Evidence:** Delegate related suite: 90 passed; Ruff and targeted mypy passed. All native operations, dialogs and pickers were mocked before construction. - **Open items:** Remaining GUI panels and native acceptance stay in Progress.md. Already-entered capture writes may finish after close. + +## U-20261111-01 · 2026-11-11 · Prepare owned memory fixture buffers and bounded control · #snapshot #agent + +- **What:** Added a standalone child fixture with fixed payload and sequence buffers, strictly bounded JSON-lines control, validated state changes and clean EOF/stop. Bootstrap records explicitly contain self-reported identity. The nonce is stable for one fixture lifetime. +- **Evidence:** Main-worktree fixture tests passed 25 cases, including hidden child communication, malformed input, exact frame limit and sequence exhaustion. Reader and documentation checks passed 119 cases. Ruff and package Bandit passed. Independent source review found no blocking issues. +- **Files:** `test/fixtures/process_memory_fixture.py`, `test/unit_test/headless/test_process_memory_fixture.py`, `docs/process_memory_contract.md`. +- **Check limits:** Fixture Pylint error checks passed. Whole-package Pylint reported existing findings and was stopped before completion. Package Radon reported five existing C-grade blocks; production package code was unchanged. +- **Open items:** Native identity matching, provider, resolver, protection faults, runtime integration and native acceptance remain in `Progress.md`. No native cross-process reads or desktop operations ran. diff --git a/docs/updates/README.md b/docs/updates/README.md index 6203fa1da..acedbf620 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-01 | 2026-11-11 | Prepare owned memory fixture buffers and bounded control | #snapshot #agent | [2026-11](2026-11.md) | | U-20261110-11 | 2026-11-10 | Own Screenshot lifecycle and run reads asynchronously | #done #agent | [2026-11](2026-11.md) | | U-20261110-10 | 2026-11-10 | Forward nested owner grants to presence sources | #done #agent | [2026-11](2026-11.md) | | U-20261110-09 | 2026-11-10 | Bound internal semantic process-memory observations | #snapshot #agent | [2026-11](2026-11.md) | diff --git a/test/fixtures/process_memory_fixture.py b/test/fixtures/process_memory_fixture.py new file mode 100644 index 000000000..64c9ec10c --- /dev/null +++ b/test/fixtures/process_memory_fixture.py @@ -0,0 +1,124 @@ +"""Own fixed memory buffers and a bounded test-control pipe, without native inspection.""" +from __future__ import annotations + +import ctypes +import hashlib +import json +import os +from pathlib import Path +import secrets +import struct +import sys +from typing import BinaryIO + + +PAYLOAD = struct.Struct(" None: + self.payload = ctypes.create_string_buffer(PAYLOAD.size) + self.sequence = ctypes.create_string_buffer(SEQUENCE.size) + self._generation = 0 + self._document_id = 17 + self._job_status = "ready" + self._launch_nonce = secrets.token_hex(16) + self.payload.raw = PAYLOAD.pack(self._document_id, b"ready") + + def bootstrap(self) -> dict[str, object]: + """Describe self-reported locations, without asserting an OS-verified identity.""" + return { + "kind": "bootstrap", "protocol_version": 1, "schema_version": 1, + "identity": "self_reported", "pid": os.getpid(), + "pointer_bits": ctypes.sizeof(ctypes.c_void_p) * 8, + "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "launch_nonce": self._launch_nonce, + "payload_address": ctypes.addressof(self.payload), "payload_size": PAYLOAD.size, + "sequence_address": ctypes.addressof(self.sequence), "sequence_size": SEQUENCE.size, + } + + def snapshot(self) -> dict[str, object]: + """Return expected values independently of any cross-process memory reader.""" + return {"kind": "snapshot", "document_id": self._document_id, + "job_status": self._job_status, "sequence": self._generation} + + def set_state(self, document_id: object, job_status: object) -> dict[str, object]: + """Validate the complete change before publishing an odd/even sequence update.""" + if type(document_id) is not int or not 0 <= document_id <= 0xFFFFFFFF: + return _error("invalid_state") + if not isinstance(job_status, str) or job_status not in STATES: + return _error("invalid_state") + if self._generation > 0xFFFFFFFFFFFFFFFD: + return _error("sequence_exhausted") + encoded = PAYLOAD.pack(document_id, job_status.encode("ascii")) + self.sequence.raw = SEQUENCE.pack(self._generation + 1) + self.payload.raw = encoded + self._document_id, self._job_status = document_id, job_status + self._generation += 2 + self.sequence.raw = SEQUENCE.pack(self._generation) + return self.snapshot() + + +def _error(code: str) -> dict[str, object]: + return {"kind": "error", "code": code} + + +def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate key") + result[key] = value + return result + + +def _dispatch(state: FixtureState, request: object) -> dict[str, object]: + if not isinstance(request, dict): + return _error("invalid_request") + command = request.get("command") + if command == "snapshot" and set(request) == {"command"}: + return state.snapshot() + if command == "stop" and set(request) == {"command"}: + return {"kind": "stopped"} + if command == "set" and set(request) == {"command", "document_id", "job_status"}: + return state.set_state(request["document_id"], request["job_status"]) + return _error("invalid_request") + + +def _emit(output: BinaryIO, record: dict[str, object]) -> None: + output.write(json.dumps(record, separators=(",", ":")).encode("ascii") + b"\n") + output.flush() + + +def serve(source: BinaryIO, output: BinaryIO) -> int: + """Serve inherited pipes until stop, EOF or an oversized frame.""" + state = FixtureState() + _emit(output, state.bootstrap()) + while True: + line = source.readline(MAX_REQUEST_BYTES + 1) + if not line: + return 0 + if len(line) > MAX_REQUEST_BYTES: + _emit(output, _error("request_too_large")) + return 2 + if not line.endswith(b"\n"): + _emit(output, _error("incomplete_request")) + return 2 + try: + request = json.loads(line.decode("utf-8"), object_pairs_hook=_unique_object) + except (ValueError, RecursionError): + _emit(output, _error("invalid_json")) + continue + response = _dispatch(state, request) + _emit(output, response) + if response["kind"] == "stopped": + return 0 + + +if __name__ == "__main__": + raise SystemExit(serve(sys.stdin.buffer, sys.stdout.buffer)) diff --git a/test/unit_test/headless/test_process_memory_fixture.py b/test/unit_test/headless/test_process_memory_fixture.py new file mode 100644 index 000000000..4999f8006 --- /dev/null +++ b/test/unit_test/headless/test_process_memory_fixture.py @@ -0,0 +1,147 @@ +"""Check owned fixture buffers and hidden child control without native memory reads.""" +import ctypes +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import struct +import subprocess +import sys + +import pytest + + +FIXTURE_PATH = Path(__file__).resolve().parents[2] / "fixtures" / "process_memory_fixture.py" +SPEC = importlib.util.spec_from_file_location("process_memory_fixture", FIXTURE_PATH) +fixture_module = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(fixture_module) + + +def _run_child(requests: bytes) -> tuple[int, list[dict], bytes]: + flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0 + child = subprocess.Popen( + [sys.executable, "-I", "-u", str(FIXTURE_PATH)], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + creationflags=flags, + ) + try: + output, errors = child.communicate(requests, timeout=5) + return child.returncode, [json.loads(line) for line in output.splitlines()], errors + finally: + if child.poll() is None: + child.kill() + child.communicate(timeout=5) + + +def test_buffers_have_exact_layout_and_retain_addresses_after_changes(): + state = fixture_module.FixtureState() + payload_address = ctypes.addressof(state.payload) + sequence_address = ctypes.addressof(state.sequence) + assert state.payload.raw == struct.pack(" 0 and bootstrap["pid"] != os.getpid() + assert bootstrap["pointer_bits"] == struct.calcsize("P") * 8 + assert bootstrap["source_sha256"] == hashlib.sha256(FIXTURE_PATH.read_bytes()).hexdigest() + assert bootstrap["payload_size"] == 16 and bootstrap["sequence_size"] == 8 + assert bootstrap["payload_address"] > 0 and bootstrap["sequence_address"] > 0 + assert records[1] == {"kind": "snapshot", "document_id": 17, "job_status": "ready", "sequence": 0} + assert records[2] == records[3] == { + "kind": "snapshot", "document_id": 42, "job_status": "busy", "sequence": 2, + } + assert records[4:] == [{"kind": "stopped"}] + + +@pytest.mark.parametrize("frame,reason", [ + (b'[]\n', "invalid_request"), + (b'{"command":"read","address":1}\n', "invalid_request"), + (b'{"command":"stop","extra":1}\n', "invalid_request"), + (b'{"command":[]}\n', "invalid_request"), + (b'{"command":"set","document_id":true,"job_status":"done"}\n', "invalid_state"), + (b'{"command":"snapshot","command":"stop"}\n', "invalid_json"), + (b'PRIVATE-MALFORMED-DATA\n', "invalid_json"), + (b'\xff\n', "invalid_json"), +]) +def test_child_rejects_bad_requests_without_mutation_or_echo(frame, reason): + code, records, errors = _run_child(frame + b'{"command":"snapshot"}\n') + assert code == 0 and errors == b"" + assert records[1] == {"kind": "error", "code": reason} + assert records[2:] == [{"kind": "snapshot", "document_id": 17, "job_status": "ready", "sequence": 0}] + + +@pytest.mark.parametrize("frame,reason", [ + (b"x" * 1025, "request_too_large"), + (b"x" * 1024 + b"\n", "request_too_large"), + (b'{"command":"snapshot"}', "incomplete_request"), +]) +def test_child_terminates_invalid_framing(frame, reason): + code, records, errors = _run_child(frame) + assert code == 2 and errors == b"" + assert records[1:] == [{"kind": "error", "code": reason}] + + +def test_clean_eof_and_fresh_launch_identity(): + first_code, first, first_errors = _run_child(b"") + second_code, second, second_errors = _run_child(b"") + assert first_code == second_code == 0 and first_errors == second_errors == b"" + assert len(first) == len(second) == 1 + assert first[0]["launch_nonce"] != second[0]["launch_nonce"] + assert first[0]["source_sha256"] == second[0]["source_sha256"] From 88829cebfba71080c1b9b908d81674747cb2c940 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:21:48 +0800 Subject: [PATCH 013/161] Bound Windows memory reads behind reviewed identity attestation --- Progress.md | 6 +- architecture.md | 4 + architecture_explore.md | 14 +- docs/process_memory_contract.md | 56 +++- docs/updates/2026-11.md | 7 + docs/updates/README.md | 1 + .../utils/process_memory/models.py | 16 +- .../utils/process_memory/reader.py | 21 +- .../utils/process_memory/windows.py | 197 +++++++++++ .../utils/process_memory/windows_native.py | 89 +++++ .../headless/test_process_memory_windows.py | 305 ++++++++++++++++++ 11 files changed, 688 insertions(+), 28 deletions(-) create mode 100644 je_auto_control/utils/process_memory/windows.py create mode 100644 je_auto_control/utils/process_memory/windows_native.py create mode 100644 test/unit_test/headless/test_process_memory_windows.py diff --git a/Progress.md b/Progress.md index ad0c6afe9..ec39b3eb9 100644 --- a/Progress.md +++ b/Progress.md @@ -20,7 +20,7 @@ ### 行程記憶體自有 fixture 原生驗收 -`TODO` — 原生執行仍暫緩。須先完成 Windows provider、自有 fixture 與受管權限整合, +`TODO` — 原生執行仍暫緩。須先完成 Windows provider 的可信應用身分核對、自有 fixture 與受管權限整合, 再驗證 ASLR、32/64 位配置、跨區段/guard/不可讀頁、程序退出、PID 重用、權限拒絕、 取消及 handle 回收。以 fixture 的已知狀態比對語意結果,獨立觀測前景、焦點、滑鼠與輸入事件。 目前 injected-provider 測試不算原生通過;設計見 [記憶體觀察契約](docs/process_memory_contract.md)。 @@ -632,7 +632,9 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 [process_memory_contract.md](docs/process_memory_contract.md)。M0/M1 尚未完成, 已有自有 fixture 的固定緩衝區與有界管線控制協定,測試僅驗證本機資料配置及背景子程序通訊。 bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報資訊,不能充當 OS 出生身分或可信 resolver。 -仍缺 typed Windows provider、可信 ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime grant/helper +typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 handle 的注入測試; +應用身分仍須由明確受審的 attestor 提供,沒有預設信任或由期望身分反填的實作。 +仍缺可信 executable/version attestor、ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 diff --git a/architecture.md b/architecture.md index 2a139eed4..5c188769b 100644 --- a/architecture.md +++ b/architecture.md @@ -4,6 +4,10 @@ The process-memory test fixture owns fixed payload and sequence buffers in a hid child process. Bounded inherited pipes expose expected state and validated fixture updates. Bootstrap facts remain unverified until a native provider independently matches the retained process identity. This tooling adds no public memory API. +The internal Windows provider owns read/query handles and measures native process +facts before asking an explicit reviewed attestor for application identity. Its +bindings are tested through injected calls; trusted attestation and native acceptance +remain separate requirements. The package facade resolves each public export from its existing source module. Concrete typing declarations generate runtime binding tables, checked by diff --git a/architecture_explore.md b/architecture_explore.md index 0692f5bb1..225f270a8 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,498 | -| 程式碼總行數 | 228,825 | +| Python 模組總數(含周邊子專案) | 1,500 | +| 程式碼總行數 | 229,124 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -320,7 +320,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,218 行。 +> 15 個套件、約 4,517 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -336,7 +336,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 193 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | -| `utils/process_memory/` | 422 | 內部受審 probe 的有界語意觀察、身分重驗與失敗 handle 回收;原生 provider 與 runtime 整合待完成 | +| `utils/process_memory/` | 721 | 內部受審 probe 的有界語意觀察、typed Windows provider 與失敗 handle 回收;可信應用身分與 runtime 整合待完成 | | `utils/shell_process/` | 279 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -1406,7 +1406,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,168 個 `test_*.py`/11,354 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,169 個 `test_*.py`/11,371 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1517,8 +1517,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 981 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,000 | 101,981 | -| **總計** | **1,486** | **228,080** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,280 | +| **總計** | **1,488** | **228,379** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index d7e882991..6170902fd 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -1,9 +1,10 @@ # Reviewed process-memory observations This is the internal M0/M1 foundation for the background-operation plan in -[Progress.md](../Progress.md). It supplies a testable semantic observation path. -It does not supply a Windows native provider, runtime authorization wiring, a -public memory command, an application adapter or completed native acceptance. +[Progress.md](../Progress.md). It supplies a semantic reader and typed Windows +read/query calls tested through injected native functions. It does not supply +trusted executable attestation, runtime authorization wiring, a public memory +command, an application adapter or completed native acceptance. ## Ownership and scope @@ -28,10 +29,10 @@ process. Existing desktop foreground and input-presence gates are unchanged. | Operation | Source and scope | Background requirement | Evidence and present state | |---|---|---|---| -| Process/session identity | OS process handle, creation time, executable identity and architecture | Read/query rights only; no privilege escalation | Provider contract defined; native implementation and acceptance pending | +| Process/session identity | Retained OS handle, creation time, session and architecture; reviewed application attestor | Read/query/synchronize rights only; no privilege escalation | Typed calls and injected tests implemented; executable attestation and native acceptance pending | | UI state | UIA read-only element properties for an explicitly selected application | No Invoke, SetValue or focus change | Existing UIA implementation; new background adapter integration pending | | Browser state | Existing WebRunner managed DOM session and reviewed origins | Dedicated managed browser; no desktop input fallback | Existing browser path; this reader adds no browser access | -| Fixture semantic state | Reviewed schema resolved for the retained fixture process identity | Bounded `VirtualQueryEx` / `ReadProcessMemory` provider; no writes | Injected-provider semantic and failure tests implemented; native provider pending | +| Fixture semantic state | Reviewed schema resolved for the retained fixture process identity | Bounded `VirtualQueryEx` / `ReadProcessMemory` provider; no writes | Typed provider and injected-call tests implemented; trusted resolver and native acceptance pending | | Application command | Each application's official API, CLI or IPC with scoped resources | Must independently prove no foreground/focus/mouse/input interference | Application selection and command adapter pending | | OS service operation | Specific approved service's management interface | Explicit service scope and independent status readback | Adapter and policy integration pending | | Completed background task | Fresh state or artifact verification under current runtime authority | Observation does not grant execution rights or replace a completion receipt | End-to-end M4/M5 integration pending | @@ -43,6 +44,47 @@ identity and version, architecture and pointer width. A retained provider handle must report the actual process identity, including after reads. Reused PIDs and changed identity invalidate the whole observation. +### Windows provider and attestation boundary + +`windows.py` owns each process handle and serializes identity, query, read and close. +It opens only `PROCESS_QUERY_INFORMATION`, `PROCESS_VM_READ` and `SYNCHRONIZE`. +The last right permits a zero-time process-liveness check. It never requests write, +terminate, all-access or privilege-adjustment rights. Failed close keeps ownership +with the existing reader cleanup queue. + +`windows_native.py` binds DWORD and BOOL with fixed widths and address/length +arguments with pointer-sized ctypes. `VirtualQueryEx` uses the caller's 28-byte +or 48-byte layout, including when a 64-bit caller observes a 32-bit WOW64 target. +A 32-bit caller refuses a 64-bit target. `IsWow64Process2` must be available; +unknown architectures are unsupported rather than guessed. + +The provider measures PID, process creation time, Windows session ID, architecture +and liveness from the retained process relationship. A required host-reviewed +attestor receives those immutable `NativeProcessFacts` and returns a `ProcessIdentity`. +It must independently bind host/session, executable identity and application version +to those facts and the owned launch. The provider supplies no default attestor, +passes no expected identity to the callback, rejects replaced native identity fields, +and measures facts again after attestation. A path string, fixture nonce, self-reported +digest or a callback that merely echoes an expected identity is not an attestation. +The production attestor and trusted fixture bootstrap matching remain unimplemented. + +Each native read is limited to 1 MiB and one committed, readable, unguarded region. +The semantic reader splits reviewed ranges at region boundaries under its smaller +per-probe budget. Failed or short reads publish no bytes; post-read region and native +identity changes fail the observation. These checks and cooperative checkpoints do +not interrupt a blocked syscall. Owned helper retirement remains M3 work. + +Two provider shapes were considered: exposing raw handles to application adapters, +or retaining handle lifetime and native checks behind `ProcessHandle`. The latter +keeps cleanup and read bounds in one owner. The attestation callback receives facts, +not a raw native handle, and must use separately reviewed launch evidence. + +ABI references are Microsoft's [memory information layouts](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information), +[VirtualQueryEx](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualqueryex), +[ReadProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory), +[IsWow64Process2](https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process2) +and [process access rights](https://learn.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights). + The reviewed resolver runs anew for each observation. It supplies one private payload range and optionally an eight-byte sequence range. A native adapter must resolve its current module/fixture location from the retained target relationship; @@ -146,6 +188,6 @@ desktop noninterference. Shared-memory mappings were rejected because parent-sid mapping reads would bypass the future process-memory provider. No native acceptance command is supplied or executed by this increment. Native -execution stays paused under `Progress.md`; typed Win32 calls, trusted bootstrap -matching, page-protection fault injection, host probe configuration, runtime +execution stays paused under `Progress.md`; native verification of the typed calls, +trusted bootstrap matching, page-protection fault injection, host probe configuration, runtime lifecycle/policy integration and application coverage remain required for M1/M3. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index f6658a0ba..995f5d756 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -728,3 +728,10 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **Files:** `test/fixtures/process_memory_fixture.py`, `test/unit_test/headless/test_process_memory_fixture.py`, `docs/process_memory_contract.md`. - **Check limits:** Fixture Pylint error checks passed. Whole-package Pylint reported existing findings and was stopped before completion. Package Radon reported five existing C-grade blocks; production package code was unchanged. - **Open items:** Native identity matching, provider, resolver, protection faults, runtime integration and native acceptance remain in `Progress.md`. No native cross-process reads or desktop operations ran. + +## U-20261111-02 · 2026-11-11 · Bound Windows memory reads behind reviewed attestation · #snapshot #agent + +- **What:** Added typed Win32 read/query bindings and owned handles with native process facts, bounded region reads, short-read rejection and failed-close retention. Application identity requires an explicit reviewed attestor. Decomposed existing memory validation and observation logic to meet the complexity limit. +- **Evidence:** Independent review reran 147 reader, fixture and injected Win32 cases. Integration with document and file-budget checks passed 186 cases. Scoped three-target mypy, Ruff and Bandit passed; memory subsystem has no C-grade complexity blocks. +- **Files:** `utils/process_memory/windows.py`, `windows_native.py`, `models.py`, `reader.py`, `test_process_memory_windows.py`, `docs/process_memory_contract.md`. +- **Open items:** Trusted application attestation, fixture bootstrap matching, resolver, runtime wiring and native acceptance remain in `Progress.md`. Injected functions do not prove native Windows execution. diff --git a/docs/updates/README.md b/docs/updates/README.md index acedbf620..94a0ad1b5 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-02 | 2026-11-11 | Bound Windows memory reads behind reviewed attestation | #snapshot #agent | [2026-11](2026-11.md) | | U-20261111-01 | 2026-11-11 | Prepare owned memory fixture buffers and bounded control | #snapshot #agent | [2026-11](2026-11.md) | | U-20261110-11 | 2026-11-10 | Own Screenshot lifecycle and run reads asynchronously | #done #agent | [2026-11](2026-11.md) | | U-20261110-10 | 2026-11-10 | Forward nested owner grants to presence sources | #done #agent | [2026-11](2026-11.md) | diff --git a/je_auto_control/utils/process_memory/models.py b/je_auto_control/utils/process_memory/models.py index 2d0f6a497..db7cd55b8 100644 --- a/je_auto_control/utils/process_memory/models.py +++ b/je_auto_control/utils/process_memory/models.py @@ -46,6 +46,15 @@ def _positive(value: int, ceiling: int) -> None: raise MemoryObservationError(FailureReason.UNSUPPORTED) +def _identifiers(values: tuple[str, ...]) -> tuple[str, ...]: + values = tuple(values) + if not values or len(values) > 64 or len(set(values)) != len(values): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + for value in values: + _identifier(value) + return values + + @dataclass(frozen=True) class ProcessIdentity: """Identity measured from the retained process, not from a reusable PID alone.""" @@ -119,12 +128,7 @@ def __post_init__(self) -> None: for value in (self.probe_id, self.schema_version, self.executable): _identifier(value) for name in ("versions", "architectures", "fields"): - values = tuple(getattr(self, name)) - if not values or len(values) > 64 or len(set(values)) != len(values): - raise MemoryObservationError(FailureReason.UNSUPPORTED) - for value in values: - _identifier(value) - object.__setattr__(self, name, values) + object.__setattr__(self, name, _identifiers(getattr(self, name))) _positive(self.max_bytes, 1 << 20) _positive(self.max_regions, 1024) _positive(self.max_value_bytes, 65536) diff --git a/je_auto_control/utils/process_memory/reader.py b/je_auto_control/utils/process_memory/reader.py index 868dc562b..18059084e 100644 --- a/je_auto_control/utils/process_memory/reader.py +++ b/je_auto_control/utils/process_memory/reader.py @@ -52,6 +52,18 @@ def _range(address: int, size: int, bits: int) -> None: _fail(FailureReason.UNREADABLE_REGION) +def _region_metadata(value: MemoryRegion, bits: int) -> None: + _range(value.base, value.size, bits) + if (any(type(flag) is not bool for flag in (value.committed, value.readable, value.guard)) + or type(value.allocation) is not int or not 0 <= value.allocation < 1 << bits + or type(value.protection) is not int or not 0 <= value.protection < 1 << 32): + _fail(FailureReason.UNREADABLE_REGION) + + +def _allows_fields(selected: tuple[str, ...], allowed: tuple[str, ...]) -> bool: + return bool(selected) and len(set(selected)) == len(selected) and set(selected) <= set(allowed) + + @dataclass class _Operation: expected: ProcessIdentity @@ -79,11 +91,8 @@ def region(self, handle: ProcessHandle, address: int) -> MemoryRegion: self.check() if not isinstance(value, MemoryRegion): _fail(FailureReason.UNREADABLE_REGION) - _range(value.base, value.size, self.expected.pointer_bits) - if (any(type(flag) is not bool for flag in (value.committed, value.readable, value.guard)) - or type(value.allocation) is not int or not 0 <= value.allocation < 1 << self.expected.pointer_bits - or type(value.protection) is not int or not 0 <= value.protection < 1 << 32 - or not value.base <= address < value.base + value.size or not value.committed + _region_metadata(value, self.expected.pointer_bits) + if (not value.base <= address < value.base + value.size or not value.committed or not value.readable or value.guard): _fail(FailureReason.UNREADABLE_REGION) return value @@ -181,7 +190,7 @@ def observe(self, expected: ProcessIdentity, probe: ReviewedProbe, fields: tuple target_id: str, checkpoint: Callable[[], None] = cancellation_checkpoint) -> ObservationResult: """Query semantic fields under a host-reviewed probe and the runtime's live checkpoint.""" selected = tuple(fields) - if not selected or len(set(selected)) != len(selected) or not set(selected) <= set(probe.fields): + if not _allows_fields(selected, probe.fields): return ObservationFailure(FailureReason.SCOPE_DENIED) _identifier(target_id) if (expected.executable != probe.executable or expected.version not in probe.versions diff --git a/je_auto_control/utils/process_memory/windows.py b/je_auto_control/utils/process_memory/windows.py new file mode 100644 index 000000000..3823a9f6e --- /dev/null +++ b/je_auto_control/utils/process_memory/windows.py @@ -0,0 +1,197 @@ +"""Owned Windows read handles with measured native facts and reviewed application attestation.""" +from __future__ import annotations + +import ctypes +from dataclasses import dataclass, field +import threading +from typing import Callable, NoReturn + +from .models import FailureReason, MemoryObservationError, MemoryRegion, ProcessIdentity +from .windows_native import FileTime, Kernel, MemoryInfo32, MemoryInfo64, SIZE, U16, U32, bind, load + +_ACCESS = 0x00100000 | 0x0400 | 0x0010 +_ARCHITECTURES = {0x014C: ("x86", 32), 0x8664: ("x64", 64), 0xAA64: ("arm64", 64)} +_READABLE = frozenset({0x02, 0x04, 0x08, 0x20, 0x40, 0x80}) +_MAX_READ = 1 << 20 + + +@dataclass(frozen=True) +class NativeProcessFacts: + """Measured retained-process facts for a host-reviewed application attestor.""" + + pid: int = field(repr=False) + birth: int = field(repr=False) + session_id: int = field(repr=False) + architecture: str + pointer_bits: int + + +Attestor = Callable[[NativeProcessFacts], ProcessIdentity] + + +def _fail(reason: FailureReason) -> NoReturn: + raise MemoryObservationError(reason) + + +def _range(address: int, size: int, bits: int) -> None: + if (type(address) is not int or type(size) is not int or address < 0 or size <= 0 + or address >= 1 << bits or size > (1 << bits) - address): + _fail(FailureReason.UNREADABLE_REGION) + + +class WindowsProcessHandle: + """Serialize read/query/close; an unsuccessful close keeps its native handle owned.""" + + def __init__(self, kernel: Kernel, attestor: Attestor, + last_error: Callable[[], int], caller_bits: int) -> None: + self._kernel = kernel + self._handle: int | None = None + self._attestor = attestor + self._last_error = last_error + self._caller_bits = caller_bits + self._lock = threading.RLock() + + def _owned(self) -> int: + if self._handle is None: + _fail(FailureReason.TARGET_CHANGED) + return self._handle + + def _error(self, fallback: FailureReason) -> NoReturn: + code = self._last_error() + _fail(FailureReason.ACCESS_DENIED if code == 5 else fallback) + + def _alive(self, handle: int) -> None: + if self._kernel.WaitForSingleObject(handle, 0) != 258: + _fail(FailureReason.TARGET_CHANGED) + + def _architecture(self, handle: int) -> tuple[str, int]: + process_machine, native_machine = U16(), U16() + if not self._kernel.IsWow64Process2(handle, ctypes.byref(process_machine), ctypes.byref(native_machine)): + self._error(FailureReason.UNSUPPORTED) + architecture = _ARCHITECTURES.get(process_machine.value or native_machine.value) + if architecture is None or architecture[1] > self._caller_bits: + _fail(FailureReason.UNSUPPORTED) + return architecture + + def _facts(self) -> NativeProcessFacts: + handle = self._owned() + self._alive(handle) + pid = self._kernel.GetProcessId(handle) + times = [FileTime() for _ in range(4)] + if not pid or not self._kernel.GetProcessTimes(handle, *[ctypes.byref(item) for item in times]): + self._error(FailureReason.TARGET_CHANGED) + session = U32() + if not self._kernel.ProcessIdToSessionId(pid, ctypes.byref(session)): + self._error(FailureReason.TARGET_CHANGED) + architecture = self._architecture(handle) + birth = times[0].low | (times[0].high << 32) + if not birth: + _fail(FailureReason.TARGET_CHANGED) + self._alive(handle) + return NativeProcessFacts(pid, birth, session.value, *architecture) + + def identity(self) -> ProcessIdentity: + """Measure native facts, then ask the reviewed owner to attest application identity.""" + with self._lock: + before = self._facts() + identity = self._attestor(before) + if not isinstance(identity, ProcessIdentity): + _fail(FailureReason.UNSUPPORTED) + if ((identity.pid, identity.birth, identity.architecture, identity.pointer_bits) + != (before.pid, before.birth, before.architecture, before.pointer_bits) + or self._facts() != before): + _fail(FailureReason.TARGET_CHANGED) + return identity + + def _region(self, address: int, bits: int) -> MemoryRegion: + _range(address, 1, bits) + info = MemoryInfo64() if self._caller_bits == 64 else MemoryInfo32() + size = ctypes.sizeof(info) + returned = self._kernel.VirtualQueryEx(self._owned(), address, ctypes.byref(info), size) + if not returned: + self._error(FailureReason.UNREADABLE_REGION) + if returned != size: + _fail(FailureReason.UNREADABLE_REGION) + _range(info.base, info.size, bits) + if not info.base <= address < info.base + info.size: + _fail(FailureReason.UNREADABLE_REGION) + committed = info.state == 0x1000 + protection = info.protection if committed else 0 + allocation = info.allocation if info.state != 0x10000 else 0 + return MemoryRegion(info.base, info.size, allocation, protection, committed, + committed and (protection & 0xFF) in _READABLE, bool(protection & 0x100)) + + def query_region(self, address: int) -> MemoryRegion: + """Query the intersecting region using the caller ABI, even for a WOW64 target.""" + with self._lock: + facts = self._facts() + region = self._region(address, facts.pointer_bits) + if self._facts() != facts: + _fail(FailureReason.TARGET_CHANGED) + return region + + def _read_chunk(self, address: int, size: int) -> bytes: + buffer, count = ctypes.create_string_buffer(size), SIZE() + if not self._kernel.ReadProcessMemory(self._owned(), address, buffer, size, ctypes.byref(count)): + code = self._last_error() + self._alive(self._owned()) + reason = FailureReason.PARTIAL_READ if code == 299 else FailureReason.UNREADABLE_REGION + _fail(FailureReason.ACCESS_DENIED if code == 5 else reason) + if count.value != size: + _fail(FailureReason.PARTIAL_READ) + return buffer.raw + + def read(self, address: int, size: int) -> bytes: + """Read one bounded committed readable region; never return partial bytes.""" + with self._lock: + facts = self._facts() + _range(address, size, facts.pointer_bits) + if size > _MAX_READ: + _fail(FailureReason.BUDGET_EXCEEDED) + region = self._region(address, facts.pointer_bits) + if (not region.committed or not region.readable or region.guard + or size > region.base + region.size - address): + _fail(FailureReason.UNREADABLE_REGION) + raw = self._read_chunk(address, size) + if self._facts() != facts or self._region(address, facts.pointer_bits) != region: + _fail(FailureReason.TARGET_CHANGED) + return raw + + def close(self) -> None: + """Retain ownership on failure; successful repeated closes are harmless.""" + with self._lock: + if self._handle is not None: + if not self._kernel.CloseHandle(self._handle): + _fail(FailureReason.CLEANUP_FAILED) + self._handle = None + + +class WindowsProcessProvider: + """Open query/read handles; application identity requires an explicit reviewed attestor.""" + + def __init__(self, attestor: Attestor, *, kernel: Kernel | None = None, + last_error: Callable[[], int] | None = None, caller_bits: int | None = None) -> None: + bits = ctypes.sizeof(ctypes.c_void_p) * 8 if caller_bits is None else caller_bits + if type(bits) is not int or bits not in (32, 64) or not callable(attestor): + _fail(FailureReason.UNSUPPORTED) + if kernel is None: + if bits != ctypes.sizeof(ctypes.c_void_p) * 8: + _fail(FailureReason.UNSUPPORTED) + kernel, last_error = load() + else: + if last_error is None: + _fail(FailureReason.UNSUPPORTED) + bind(kernel) + self._kernel, self._last_error = kernel, last_error + self._attestor, self._caller_bits = attestor, bits + + def open_readonly(self, identity: ProcessIdentity) -> WindowsProcessHandle: + """Transfer ownership immediately; all fallible identity work happens on the returned handle.""" + if identity.pointer_bits > self._caller_bits: + _fail(FailureReason.UNSUPPORTED) + owned = WindowsProcessHandle(self._kernel, self._attestor, self._last_error, self._caller_bits) + handle = self._kernel.OpenProcess(_ACCESS, False, identity.pid) + if not handle: + _fail(FailureReason.ACCESS_DENIED if self._last_error() == 5 else FailureReason.TARGET_CHANGED) + owned._handle = handle + return owned diff --git a/je_auto_control/utils/process_memory/windows_native.py b/je_auto_control/utils/process_memory/windows_native.py new file mode 100644 index 000000000..68fad6a30 --- /dev/null +++ b/je_auto_control/utils/process_memory/windows_native.py @@ -0,0 +1,89 @@ +"""Typed Win32 query/read bindings and caller-sized memory information layouts.""" +from __future__ import annotations + +import ctypes +import sys +from typing import Callable, Protocol, cast + +from .models import FailureReason, MemoryObservationError + +U16 = ctypes.c_uint16 +U32 = ctypes.c_uint32 +U64 = ctypes.c_uint64 +PTR = ctypes.c_void_p +SIZE = ctypes.c_size_t +BOOL = ctypes.c_int32 + + +class FileTime(ctypes.Structure): + """Windows FILETIME has two DWORD fields on every caller architecture.""" + + _fields_ = [("low", U32), ("high", U32)] + + +class MemoryInfo32(ctypes.Structure): + """The 28-byte 32-bit MEMORY_BASIC_INFORMATION layout.""" + + _fields_ = [("base", U32), ("allocation", U32), ("allocation_protection", U32), + ("size", U32), ("state", U32), ("protection", U32), ("kind", U32)] + + +class MemoryInfo64(ctypes.Structure): + """The 48-byte 64-bit layout, including both alignment fields.""" + + _fields_ = [("base", U64), ("allocation", U64), ("allocation_protection", U32), + ("alignment1", U32), ("size", U64), ("state", U32), + ("protection", U32), ("kind", U32), ("alignment2", U32)] + + +class NativeFunction(Protocol): + """A ctypes function with an explicitly installed native signature.""" + + argtypes: list[object] + restype: object + + def __call__(self, *arguments: object) -> int: ... + + +class Kernel(Protocol): + """Only process identity, liveness, memory queries and handle release are exposed.""" + + OpenProcess: NativeFunction + CloseHandle: NativeFunction + GetProcessId: NativeFunction + GetProcessTimes: NativeFunction + ProcessIdToSessionId: NativeFunction + IsWow64Process2: NativeFunction + WaitForSingleObject: NativeFunction + VirtualQueryEx: NativeFunction + ReadProcessMemory: NativeFunction + + +def bind(kernel: Kernel) -> None: + """Install fixed-width DWORD/BOOL and pointer-sized address/length signatures.""" + signatures: tuple[tuple[NativeFunction, list[object], object], ...] = ( + (kernel.OpenProcess, [U32, BOOL, U32], PTR), + (kernel.CloseHandle, [PTR], BOOL), + (kernel.GetProcessId, [PTR], U32), + (kernel.GetProcessTimes, [PTR, *[ctypes.POINTER(FileTime)] * 4], BOOL), + (kernel.ProcessIdToSessionId, [U32, ctypes.POINTER(U32)], BOOL), + (kernel.IsWow64Process2, [PTR, ctypes.POINTER(U16), ctypes.POINTER(U16)], BOOL), + (kernel.WaitForSingleObject, [PTR, U32], U32), + (kernel.VirtualQueryEx, [PTR, PTR, PTR, SIZE], SIZE), + (kernel.ReadProcessMemory, [PTR, PTR, PTR, SIZE, ctypes.POINTER(SIZE)], BOOL), + ) + for function, arguments, result in signatures: + function.argtypes = arguments + function.restype = result + + +def load() -> tuple[Kernel, Callable[[], int]]: + """Load on explicit provider construction; imports never touch native resources.""" + if sys.platform != "win32": + raise MemoryObservationError(FailureReason.UNSUPPORTED) + try: + kernel = cast(Kernel, ctypes.WinDLL("kernel32", use_last_error=True)) + bind(kernel) + except (OSError, AttributeError): + raise MemoryObservationError(FailureReason.UNSUPPORTED) from None + return kernel, ctypes.get_last_error diff --git a/test/unit_test/headless/test_process_memory_windows.py b/test/unit_test/headless/test_process_memory_windows.py new file mode 100644 index 000000000..70e4c641c --- /dev/null +++ b/test/unit_test/headless/test_process_memory_windows.py @@ -0,0 +1,305 @@ +"""Exercise injected Win32 calls and ownership without touching native process memory.""" +import ctypes +from dataclasses import replace +import struct + +import pytest + +from je_auto_control.utils.process_memory.models import ( + FailureReason, MemoryObservationError, Observation, ObservationFailure, + ProcessIdentity, ReadPlan, ReviewedProbe, +) +from je_auto_control.utils.process_memory.reader import ProcessMemoryReader +from je_auto_control.utils.process_memory.windows import WindowsProcessProvider +from je_auto_control.utils.process_memory.windows_native import FileTime, MemoryInfo32, MemoryInfo64, PTR, SIZE, U32 + + +IDENTITY = ProcessIdentity("owned-host", "owned-session", 42, 0x100000002, "reviewed-image", "1", "x64", 64) + + +class Function: + def __init__(self, implementation): + self.implementation = implementation + self.argtypes = [] + self.restype = None + self.calls = [] + + def __call__(self, *arguments): + self.calls.append(arguments) + return self.implementation(*arguments) + + +class Kernel: + def __init__(self): + self.pid, self.birth, self.session = IDENTITY.pid, IDENTITY.birth, 7 + self.machine, self.native = 0, 0x8664 + self.wait, self.error, self.close_ok, self.open_value = 258, 0, True, 91 + self.protection, self.state, self.query_short = 4, 0x1000, False + self.read_ok, self.read_count = True, None + self.after_read = lambda: None + self.regions = [(0x1000, 8), (0x1008, 8)] + self.payload = struct.pack("> 32 + return True + + def session_id(self, pid, target): + target._obj.value = self.session + return True + + def architecture(self, handle, process, native): + process._obj.value, native._obj.value = self.machine, self.native + return True + + def query(self, handle, address, target, size): + for base, length in self.regions: + if base <= address < base + length: + info = target._obj + info.base, info.size, info.allocation = base, length, 0x1000 + info.protection, info.state = self.protection, self.state + return size - 1 if self.query_short else size + return 0 + + def read(self, handle, address, buffer, size, count): + buffer.raw = self.payload[address - 0x1000:address - 0x1000 + size] + count._obj.value = size if self.read_count is None else self.read_count + self.after_read() + return self.read_ok + + +def attestor(facts): + assert facts.session_id == 7 + return replace(IDENTITY, pid=facts.pid, birth=facts.birth, + architecture=facts.architecture, pointer_bits=facts.pointer_bits) + + +def provider(kernel, **options): + return WindowsProcessProvider(attestor, kernel=kernel, last_error=lambda: kernel.error, **options) + + +def probe(): + return ReviewedProbe("fixture", "1", IDENTITY.executable, ("1",), ("x64", "x86"), + ("document_id",), 64, 8, 1, 32, + lambda identity: ReadPlan(0x1000, 16), + lambda raw, fields: {"document_id": struct.unpack(" Date: Wed, 11 Nov 2026 16:25:29 +0800 Subject: [PATCH 014/161] Release Image Detection state and cancel pending click work --- Progress.md | 2 +- README.md | 4 + README/README_zh-CN.md | 4 + README/README_zh-TW.md | 4 + architecture.md | 6 + architecture_explore.md | 18 +- .../doc/new_features/v223_features_doc.rst | 16 +- .../Zh/doc/new_features/v223_features_doc.rst | 12 +- docs/updates/2026-11.md | 7 + docs/updates/README.md | 1 + je_auto_control/gui/_image_detect_tab.py | 190 +++++++++------ je_auto_control/gui/main_widget.py | 10 +- je_auto_control/gui/tab_registry.py | 2 +- je_auto_control/wrapper/auto_control_image.py | 6 +- .../headless/test_gui_lazy_registry.py | 4 +- .../headless/test_gui_tab_lifecycle_audit.py | 17 +- .../headless/test_image_click_cancellation.py | 32 +++ .../test_image_detection_tab_lifecycle.py | 217 ++++++++++++++++++ 18 files changed, 444 insertions(+), 108 deletions(-) create mode 100644 test/unit_test/headless/test_image_click_cancellation.py create mode 100644 test/unit_test/headless/test_image_detection_tab_lifecycle.py diff --git a/Progress.md b/Progress.md index ec39b3eb9..b726bc8e9 100644 --- a/Progress.md +++ b/Progress.md @@ -531,7 +531,7 @@ D2 仍缺 helper 隔離與半開交握資源回收;D3 的錄製/全域停止 計畫 E(Android/iOS)、H(型別深化與總驗收)尚未開始。F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 -- **F1 的遺留面板釋放**:Auto Click、Image Detection、Record、Script 四個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 +- **F1 的遺留面板釋放**:Auto Click、Record、Script 三個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 - **F4**(啟動/記憶體基準、mixed-DPI、功能對等測試)尚未開始。 diff --git a/README.md b/README.md index 4b90b365e..e146994da 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,10 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" - Connect AI clients through MCP, or integrate through REST and Python. - Use recording, scheduling and remote-desktop tools through the optional GUI. +The Image Detection page runs matching in the background and owns its mouse-button selection. +Its Actions menu can stop a pending search; closing the page discards late results and reopening resets its inputs. +Cancellation prevents later move/click steps, but cannot interrupt a native call already in progress. + Windows, macOS, X11 and Wayland use different backends. Available features depend on system permissions and optional dependencies; Windows ARM64 has additional limitations. See the installation guide before choosing a deployment target. Managed agent tasks and cross-host transfers include experimental features. See the implementation notes and project progress before relying on them in production. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 1710ace94..4d5f9d137 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -35,6 +35,10 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" - 通过 MCP 连接 AI 客户端,或通过 REST 与 Python 整合。 - 在可选 GUI 中使用录制、调度与远程桌面工具。 +图像检测分页在后台执行匹配,并有自己的鼠标按键选择。 +Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果,重新打开会重置输入字段。 +取消可阻止后续移动与点击步骤,但无法中断已进入的原生调用。 + Windows、macOS、X11 与 Wayland 使用不同后端,实际功能取决于系统权限与可选依赖。Windows ARM64 另有限制,部署前请先阅读安装文件。 受管理的 Agent 任务与跨主机传输包含实验性功能;采用前请查看实现记录与项目进度中的验收状态。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index bab0a7129..62604f943 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -35,6 +35,10 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" - 透過 MCP 連接 AI 用戶端,或透過 REST 與 Python 整合。 - 在選配 GUI 中使用錄製、排程與遠端桌面工具。 +影像偵測分頁在背景執行比對,並有自己的滑鼠按鍵選擇。 +Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果,重新開啟會重設輸入欄位。 +取消可阻止後續移動與點擊步驟,但無法中斷已進入的原生呼叫。 + Windows、macOS、X11 與 Wayland 使用不同後端,實際功能取決於系統權限與選配依賴。Windows ARM64 另有限制,部署前請先閱讀安裝文件。 受管理的 Agent 任務與跨主機傳輸包含實驗性功能;採用前請查看實作紀錄與專案進度中的驗收狀態。 diff --git a/architecture.md b/architecture.md index 5c188769b..81e127c6b 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,11 @@ # AutoControl Architecture +Image Detection is a lazy independent widget. It owns its inputs and mouse-button +selection, captures immutable worker arguments and runs matching through TabTask. +Close cancels work and discards late results; reopen creates fresh controls. +The shared locate-and-click path checks cancellation before detection and before +moving or clicking. Calls already inside a native backend may still finish. + The process-memory test fixture owns fixed payload and sequence buffers in a hidden child process. Bounded inherited pipes expose expected state and validated fixture updates. Bootstrap facts remain unverified until a native provider independently diff --git a/architecture_explore.md b/architecture_explore.md index 225f270a8..01879a97d 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,500 | -| 程式碼總行數 | 229,124 | +| 程式碼總行數 | 229,162 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -195,7 +195,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `wrapper/auto_control_mouse.py` | 600 | 滑鼠 API:位置讀寫、按下/放開/點擊、捲動、座標前處理、送訊息給指定視窗。 | | `wrapper/auto_control_keyboard.py` | 566 | 鍵盤 API:鍵表查詢、`keyboard_key_name` 反查標準鍵名(不回別名)、按下/放開/敲擊、`write` 字串、`hotkey` 組合鍵、按鍵狀態偵測。**`type_keyboard` 與 `hotkey` 的放開走 `finally`**(見下)。 | | `wrapper/auto_control_screen.py` | 111 | 螢幕 API:`screen_size`、`screenshot`(可指定區域)、`get_pixel`。 | -| `wrapper/auto_control_image.py` | 85 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | +| `wrapper/auto_control_image.py` | 89 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | | `wrapper/auto_control_record.py` | 124 | 錄製 API:`record`/`stop_record`/`record_to_json`(支援 stop event 與逾時)。 | | `wrapper/auto_control_window.py` | 332 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | | `wrapper/window_backends/` | 1,114 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | @@ -1266,7 +1266,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | | `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | -| `main_widget.py` | 378 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | +| `main_widget.py` | 370 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | | `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與既有表單;不匯入 Qt。 | | `navigation.py` | 200 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | @@ -1277,7 +1277,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `config_sync_tab.py` | 413 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | | `_auto_click_tab.py` | 295 | 自動點擊分頁的 mixin 建構器。 | | `_screenshot_tab.py` | 179 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | -| `_image_detect_tab.py` | 117 | 影像偵測分頁 mixin。 | +| `_image_detect_tab.py` | 159 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | | `_script_tab.py` | 158 | 腳本執行分頁 mixin。 | | `_record_tab.py` | 144 | 錄製/回放分頁 mixin。 | | `_report_tab.py` | 106 | 報表分頁 mixin。 | @@ -1308,7 +1308,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | --- | ---: | --- | | auto_click | `_auto_click_tab.py` | 295 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | | screenshot | `_screenshot_tab.py` | 179 | 截圖、選區、螢幕尺寸、取像素色。 | -| image_detect | `_image_detect_tab.py` | 117 | 樣板裁切、定位、定位全部、定位並點擊。 | +| image_detect | `_image_detect_tab.py` | 159 | 樣板裁切、定位、定位全部、定位並點擊。 | | record | `_record_tab.py` | 144 | 錄製/停止/回放/存檔/載入。 | | script_builder | `script_builder/` | 6,902 | **視覺化腳本編輯器**:`command_schema.py`(5,549 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | | flow_editor | `flow_editor/` | 490 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | @@ -1406,7 +1406,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,169 個 `test_*.py`/11,371 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,171 個 `test_*.py`/11,378 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1497,14 +1497,14 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,894 | +| `gui/` | 144 | 39,928 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,243 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,324 | -| `wrapper/` | 25 | 5,992 | +| `wrapper/` | 25 | 5,996 | | `windows/` | 24 | 2,265 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | @@ -1518,7 +1518,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,280 | -| **總計** | **1,488** | **228,379** | +| **總計** | **1,488** | **228,417** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 92ac6288e..6ab0ad576 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -11,10 +11,11 @@ The Actions menu Two ways a tab surfaces its commands: -* **Registry actions** — core tabs (Auto Click, Screenshot, Image Detection, - Record, Script Executor, Report) declare ``(label_key, handler)`` pairs when +* **Registry actions** — legacy core tabs (Auto Click, Record and Script Executor) + declare ``(label_key, handler)`` pairs when they are registered in ``gui/main_widget.py``. -* **The** ``menu_actions()`` **hook** — feature tabs expose a +* **The** ``menu_actions()`` **hook** — independent tabs, including Screenshot, + Image Detection and Report, expose a ``menu_actions()`` method returning the same ``[(label_key, handler), ...]`` shape; the menu bar queries the active tab and renders whatever it returns. @@ -28,6 +29,15 @@ checkboxes. The navigation panel -------------------- +Image Detection is built only when opened and owns its template, threshold, +draw option and mouse-button selection. Matching runs through ``TabTask`` with +an input snapshot. **Actions > Stop run** cancels pending work. Closing the page +discards late results; reopening creates fresh inputs. Hiding the page preserves +them. Cancellation is checked before detection and before each move/click step +in ``locate_and_click``. An entered native call may still finish. Cropping remains +interactive, and the draw option retains the backend's visualization behavior. + + Every registered tab is listed on the left of the window, grouped by the same five categories, whether it is open or not; open tabs are shown in bold. Click a feature to open it (or bring it to the front). The search box filters diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index b1d421bdc..5008d93b4 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -10,9 +10,9 @@ Actions 選單 分頁有兩種方式呈現其指令: -* **註冊時宣告**——核心分頁(自動點擊、截圖、影像偵測、錄製、腳本執行器、 - 報告)在 ``gui/main_widget.py`` 註冊時宣告 ``(label_key, handler)`` 配對。 -* ``menu_actions()`` **掛鉤**——功能分頁提供 ``menu_actions()`` 方法, +* **註冊時宣告**——舊式核心分頁(自動點擊、錄製、腳本執行器)在 + ``gui/main_widget.py`` 註冊時宣告 ``(label_key, handler)`` 配對。 +* ``menu_actions()`` **掛鉤**——獨立分頁,包括截圖、影像偵測與報告,提供 ``menu_actions()`` 方法, 回傳相同的 ``[(label_key, handler), ...]`` 形狀;選單列查詢當前分頁並 渲染其回傳內容。 @@ -164,3 +164,9 @@ GUI 執行緒執行,原本接在阻塞呼叫後面的程式碼就放在這裡。 這是 GUI 內部 API(會 import ``PySide6``),套件 facade 不會重新匯出;分頁所呼叫的 無頭函式不需要它也能使用。 + +影像偵測分頁在開啟時才建立,獨立持有樣板、門檻、繪圖選項與滑鼠按鍵選擇。 +比對使用輸入快照,透過 ``TabTask`` 在背景執行。**Actions > Stop run** 可取消待完成工作。 +關閉分頁會丟棄晚到結果,重新開啟會重設輸入;隱藏則保留輸入。 +``locate_and_click`` 在開始偵測以及移動、點擊前檢查取消,但已進入的原生呼叫仍可能完成。 +裁切仍為互動操作,繪圖選項沿用後端的視覺化行為。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 995f5d756..b956fa667 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -735,3 +735,10 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **Evidence:** Independent review reran 147 reader, fixture and injected Win32 cases. Integration with document and file-budget checks passed 186 cases. Scoped three-target mypy, Ruff and Bandit passed; memory subsystem has no C-grade complexity blocks. - **Files:** `utils/process_memory/windows.py`, `windows_native.py`, `models.py`, `reader.py`, `test_process_memory_windows.py`, `docs/process_memory_contract.md`. - **Open items:** Trusted application attestation, fixture bootstrap matching, resolver, runtime wiring and native acceptance remain in `Progress.md`. Injected functions do not prove native Windows execution. + +## U-20261111-03 · 2026-11-11 · Release Image Detection and cancel pending click work · #done #gui + +- **What:** Replaced the retained workspace mixin with a lazy Image Detection widget that owns its inputs, mouse selection, translations and background task. Stop and close cancel pending work; close discards late results and reopen creates fresh state. The headless locate-and-click path checks cancellation before detection, movement and clicking. +- **Evidence:** Implementation suite passed 219 cases, independent offscreen review passed 95, and integration with document checks passed 50. Scoped three-platform mypy, real Qt type checks, Ruff and Bandit passed. All desktop and dialog backends were faked. +- **Files:** `gui/_image_detect_tab.py`, `main_widget.py`, `tab_registry.py`, `wrapper/auto_control_image.py`, lifecycle/cancellation tests, three READMEs and English/Chinese Sphinx guidance. +- **Open items:** Remaining retained panels and backend/native acceptance are in `Progress.md`. Entered native calls cannot be preempted; cropping remains interactive. diff --git a/docs/updates/README.md b/docs/updates/README.md index 94a0ad1b5..d009de3a4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-03 | 2026-11-11 | Release Image Detection and cancel pending click work | #done #gui | [2026-11](2026-11.md) | | U-20261111-02 | 2026-11-11 | Bound Windows memory reads behind reviewed attestation | #snapshot #agent | [2026-11](2026-11.md) | | U-20261111-01 | 2026-11-11 | Prepare owned memory fixture buffers and bounded control | #snapshot #agent | [2026-11](2026-11.md) | | U-20261110-11 | 2026-11-10 | Own Screenshot lifecycle and run reads asynchronously | #done #agent | [2026-11](2026-11.md) | diff --git a/je_auto_control/gui/_image_detect_tab.py b/je_auto_control/gui/_image_detect_tab.py index ffd0226bf..935d46405 100644 --- a/je_auto_control/gui/_image_detect_tab.py +++ b/je_auto_control/gui/_image_detect_tab.py @@ -1,117 +1,159 @@ -"""Image-detection tab builder (extracted mixin).""" -from typing import TYPE_CHECKING, Any, Callable +"""Independent image-detection panel with owned inputs and cancellable background work.""" +from dataclasses import dataclass +from functools import partial +import math +from typing import Callable, Literal from PySide6.QtWidgets import ( - QCheckBox, QFileDialog, QGridLayout, QLabel, QLineEdit, QMessageBox, + QCheckBox, QComboBox, QFileDialog, QGridLayout, QLabel, QLineEdit, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) +from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui._validators import double_validator -from je_auto_control.gui._qt_typed import as_widget from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.selector import crop_template_to_file from je_auto_control.utils.exception.exceptions import AutoControlException -from je_auto_control.wrapper.auto_control_image import ( - locate_all_image, locate_image_center, locate_and_click, -) +from je_auto_control.wrapper.auto_control_image import locate_all_image, locate_image_center, locate_and_click +from je_auto_control.wrapper.auto_control_mouse import mouse_keys_table def _t(key: str) -> str: - """language_wrapper shorthand""" return language_wrapper.translate(key, key) -class ImageDetectTabMixin: - """Provides the image-detection tab builder/handlers. +@dataclass(frozen=True) +class _Detection: + operation: Literal["center", "all", "click"] + path: str + threshold: float + draw: bool + button: str + - Host widget must expose the ``TranslatableMixin`` API (``self._tr(...)``). - ``_locate_click`` reuses the auto-click tab's ``mouse_button_combo`` when - the host also mixes in :class:`AutoClickTabMixin`, falling back to the - left button otherwise. - """ +def _detect(request: _Detection) -> str: + if request.operation == "center": + return f"Center: {locate_image_center(request.path, request.threshold, request.draw)}" + if request.operation == "all": + matches = locate_all_image(request.path, request.threshold, request.draw) + return f"Found {len(matches)} matches:\n{matches}" + point = locate_and_click(request.path, request.button, request.threshold, request.draw) + return f"Clicked at: {point}" - if TYPE_CHECKING: - # Declared, never defined: the widget this mixin is mixed into owns - # every one of these. The block is stripped at runtime, so nothing - # here can shadow what the host actually binds. - _tr: Callable[..., Any] - def _build_image_detect_tab(self) -> QWidget: - tab = QWidget() - layout = QVBoxLayout() +class ImageDetectionTab(TranslatableMixin, QWidget): + """Own image-detection inputs, result state and worker lifetime.""" - # Detection inputs; locate/crop commands run from the Actions menu. + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._tr_init() + layout = QVBoxLayout(self) grid = QGridLayout() grid.addWidget(self._tr(QLabel(), "template_image"), 0, 0) self.img_path_input = QLineEdit() grid.addWidget(self.img_path_input, 0, 1) - grid.addWidget(self._tr(QLabel(), "threshold_label"), 1, 0) self.threshold_input = QLineEdit("0.8") self.threshold_input.setValidator(double_validator(0.0, 1.0, 2)) grid.addWidget(self.threshold_input, 1, 1) self.draw_check = self._tr(QCheckBox(), "draw_image_check") grid.addWidget(self.draw_check, 1, 2) - + grid.addWidget(self._tr(QLabel(), "mouse_button"), 2, 0) + self.mouse_button_combo = QComboBox() + self.mouse_button_combo.addItems(list(mouse_keys_table)) + self.mouse_button_combo.setCurrentText("mouse_left") + grid.addWidget(self.mouse_button_combo, 2, 1) layout.addLayout(grid) - layout.addWidget(self._tr(QLabel(), "detection_result")) self.detect_result_text = QTextEdit() self.detect_result_text.setReadOnly(True) layout.addWidget(self.detect_result_text) - tab.setLayout(layout) - return tab - - def _browse_img(self): - path, _ = QFileDialog.getOpenFileName( - as_widget(self), _t("template_image"), "", "Images (*.png *.jpg *.bmp);;All (*)") + self._status_key = "" + self._task = TabTask(self) + self._task.result.connect(self._on_result) + self._task.error.connect(self._on_error) + self._task.finished.connect(self._on_finished) + + def menu_actions(self) -> list[tuple[str, Callable[[], object]]]: + """Expose file selection, detection and cancellation through Actions.""" + return [ + ("browse", self._browse_img), ("crop_template", self._crop_template), + ("locate_image", self._locate_image), ("locate_all", self._locate_all), + ("locate_click", self._locate_click), ("task_stop", self._stop), + ] + + def _browse_img(self) -> None: + path, _ = QFileDialog.getOpenFileName(self, _t("template_image"), "", "Images (*.png *.jpg *.bmp);;All (*)") if path: self.img_path_input.setText(path) - def _crop_template(self): - save_path, _ = QFileDialog.getSaveFileName( - as_widget(self), _t("crop_template"), "", "PNG (*.png)" - ) + def _crop_template(self) -> None: + if self._task.running: + return + save_path, _ = QFileDialog.getSaveFileName(self, _t("crop_template"), "", "PNG (*.png)") if not save_path: return try: - region = crop_template_to_file(save_path, as_widget(self)) - if region is None: - return - self.img_path_input.setText(save_path) - self.detect_result_text.setText(f"Template saved: {save_path} region={region}") + region = crop_template_to_file(save_path, self) + if region is not None: + self.img_path_input.setText(save_path) + self._on_result(f"Template saved: {save_path} region={region}") except (AutoControlException, OSError, ValueError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + QMessageBox.warning(self, "Error", str(error)) - def _get_detect_params(self): - path = self.img_path_input.text() - if not path: - raise ValueError("Template image path is empty") - threshold = float(self.threshold_input.text() or "0.8") - draw = self.draw_check.isChecked() - return path, threshold, draw - - def _locate_image(self): - try: - path, th, draw = self._get_detect_params() - result = locate_image_center(path, th, draw) - self.detect_result_text.setText(f"Center: {result}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.detect_result_text.setText(f"Error: {error}") - - def _locate_all(self): - try: - path, th, draw = self._get_detect_params() - result = locate_all_image(path, th, draw) - self.detect_result_text.setText(f"Found {len(result)} matches:\n{result}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.detect_result_text.setText(f"Error: {error}") - - def _locate_click(self): + def _start(self, operation: Literal["center", "all", "click"]) -> None: + if self._task.running: + return try: - path, th, draw = self._get_detect_params() - btn = self.mouse_button_combo.currentText() if hasattr(self, "mouse_button_combo") else "mouse_left" - result = locate_and_click(path, btn, th, draw) - self.detect_result_text.setText(f"Clicked at: {result}") - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.detect_result_text.setText(f"Error: {error}") + path = self.img_path_input.text() + if not path: + raise ValueError("Template image path is empty") + threshold = float(self.threshold_input.text() or "0.8") + if not math.isfinite(threshold) or not 0 <= threshold <= 1: + raise ValueError("Threshold must be between 0 and 1") + request = _Detection(operation, path, threshold, self.draw_check.isChecked(), + self.mouse_button_combo.currentText()) + except (ValueError, TypeError) as error: + self._on_error(error) + return + if self._task.start(partial(_detect, request)): + self._status_key = "task_running" + self.detect_result_text.setText(_t(self._status_key)) + + def _locate_image(self) -> None: + self._start("center") + + def _locate_all(self) -> None: + self._start("all") + + def _locate_click(self) -> None: + self._start("click") + + def _stop(self) -> None: + if self._task.running: + self._status_key = "task_stopping" + self.detect_result_text.setText(_t(self._status_key)) + self._task.stop() + + def _on_result(self, result: str) -> None: + self._status_key = "" + self.detect_result_text.setText(result) + + def _on_error(self, error: object) -> None: + self._on_result(f"Error: {error}") + + def _on_finished(self) -> None: + if self._status_key in {"task_running", "task_stopping"}: + self._status_key = "task_stopped" + self.detect_result_text.setText(_t(self._status_key)) + + def retranslate(self) -> None: + """Refresh labels and transient status without discarding the last result.""" + super().retranslate() + if self._status_key: + self.detect_result_text.setText(_t(self._status_key)) + + def dispose(self) -> None: + """Cancel pending work and drop late outcomes; entered native calls may finish.""" + self._task.stop() diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index 616669e25..608ab8572 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -10,7 +10,6 @@ from je_auto_control.gui._auto_click_tab import AutoClickTabMixin from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._image_detect_tab import ImageDetectTabMixin from je_auto_control.gui._record_tab import RecordTabMixin from je_auto_control.gui._script_tab import ScriptTabMixin from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper @@ -35,7 +34,7 @@ class _WorkerSignals(QObject): # ============================================================================= class AutoControlGUIWidget( TranslatableMixin, AutoClickTabMixin, - ImageDetectTabMixin, RecordTabMixin, ScriptTabMixin, + RecordTabMixin, ScriptTabMixin, QWidget, ): """Owns the QTabWidget and exposes show/hide/list APIs for the menu bar.""" @@ -98,13 +97,6 @@ def _own_tab_builders(self) -> Dict[str, Any]: ("write_send", self._send_write), ("scroll_send", self._send_scroll), )), - "image_detect": (self._build_image_detect_tab(), ( - ("browse", self._browse_img), - ("crop_template", self._crop_template), - ("locate_image", self._locate_image), - ("locate_all", self._locate_all), - ("locate_click", self._locate_click), - )), "record": (self._build_record_tab(), ( ("start_record", self._start_record), ("stop_record", self._stop_record), diff --git a/je_auto_control/gui/tab_registry.py b/je_auto_control/gui/tab_registry.py index b2f9c7e9c..ca4e48929 100644 --- a/je_auto_control/gui/tab_registry.py +++ b/je_auto_control/gui/tab_registry.py @@ -143,7 +143,7 @@ def close(self, key: str) -> None: TAB_SPECS: Tuple[TabSpec, ...] = ( TabSpec("auto_click", "tab_auto_click", "core"), TabSpec("screenshot", "tab_screenshot", "core", f"{_GUI}._screenshot_tab", "ScreenshotTab"), - TabSpec("image_detect", "tab_image_detect", "core"), + TabSpec("image_detect", "tab_image_detect", "core", f"{_GUI}._image_detect_tab", "ImageDetectionTab"), TabSpec("record", "tab_record", "core", default_visible=True), TabSpec("script_builder", "tab_script_builder", "core", f"{_GUI}.script_builder", "ScriptBuilderTab", default_visible=True), diff --git a/je_auto_control/wrapper/auto_control_image.py b/je_auto_control/wrapper/auto_control_image.py index 4e1c77fed..23ccc5087 100644 --- a/je_auto_control/wrapper/auto_control_image.py +++ b/je_auto_control/wrapper/auto_control_image.py @@ -1,6 +1,7 @@ from typing import List, Tuple from je_auto_control.utils.cv2_utils import template_detection +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.exception.exception_tags import cant_find_image_error_message from je_auto_control.utils.exception.exceptions import ImageNotFoundException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -67,6 +68,7 @@ def locate_and_click(image, mouse_keycode: int | str, :return: (center_x, center_y) """ + cancellation_checkpoint() autocontrol_logger.info(f"Locate and click {image}, keycode={mouse_keycode}, threshold={detect_threshold}") try: image_data_array = template_detection.find_image(image, detect_threshold, draw_image) @@ -74,7 +76,9 @@ def locate_and_click(image, mouse_keycode: int | str, x1, y1, x2, y2 = image_data_array[1] center_x = int((x1 + x2) // 2) center_y = int((y1 + y2) // 2) + cancellation_checkpoint() set_mouse_position(center_x, center_y) + cancellation_checkpoint() click_mouse(mouse_keycode) record_action_to_list("locate_and_click", {"image": image, "threshold": detect_threshold}) return center_x, center_y @@ -82,4 +86,4 @@ def locate_and_click(image, mouse_keycode: int | str, except (OSError, RuntimeError, AttributeError, TypeError, ValueError, ImageNotFoundException) as error: record_action_to_list("locate_and_click", {"image": image}, repr(error)) autocontrol_logger.error(f"locate_and_click failed: {repr(error)}") - raise \ No newline at end of file + raise diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index 24b77a751..0eae0060b 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -17,7 +17,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[3] # Built by the main widget itself: its mixin tabs, and Remote Desktop's placeholder fallback. -OWN_TABS = {"auto_click", "image_detect", "record", "script", "remote_desktop"} +OWN_TABS = {"auto_click", "record", "script", "remote_desktop"} OPEN_AT_START = ["record", "script_builder", "remote_desktop"] @@ -90,6 +90,7 @@ def test_a_lazy_factory_imports_at_call_time(): "open_at_start": [row["key"] for row in widget.list_registered_tabs() if row["visible"]], "variables_imported_at_start": "je_auto_control.gui.variables_tab" in sys.modules, "presence_imported_at_start": "je_auto_control.gui.presence_tab" in sys.modules, + "image_detect_imported_at_start": "je_auto_control.gui._image_detect_tab" in sys.modules, } widget.list_registered_tabs() widget.retranslate() @@ -138,6 +139,7 @@ def test_only_the_start_tabs_and_the_widgets_own_forms_are_built(report): assert report["open_at_start"] == OPEN_AT_START assert not report["variables_imported_at_start"] assert not report["presence_imported_at_start"] + assert not report["image_detect_imported_at_start"] def test_listing_translating_and_hiding_build_nothing(report): diff --git a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py index e464fc578..2e01d194f 100644 --- a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py +++ b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py @@ -94,12 +94,17 @@ def not_found(*args, **kwargs): for name in ("locate_image_center", "locate_all_image", "locate_and_click"): monkeypatch.setattr(tab, name, not_found) - fake = types.SimpleNamespace(_get_detect_params=lambda: ("t.png", 0.8, False), - detect_result_text=QTextEdit(), mouse_button_combo=QComboBox()) - for slot in ("_locate_image", "_locate_all", "_locate_click"): - fake.detect_result_text.clear() - getattr(tab.ImageDetectTabMixin, slot)(fake) - assert "not on screen" in fake.detect_result_text.toPlainText() + from headless._qt_settle import pump_until + page = tab.ImageDetectionTab() + page.img_path_input.setText("t.png") + try: + for slot in ("_locate_image", "_locate_all", "_locate_click"): + page.detect_result_text.clear() + getattr(page, slot)() + assert pump_until(lambda: not page._task.running) + assert "not on screen" in page.detect_result_text.toPlainText() + finally: + page.deleteLater() def test_screenshot_shows_a_bad_region(qapp, monkeypatch): diff --git a/test/unit_test/headless/test_image_click_cancellation.py b/test/unit_test/headless/test_image_click_cancellation.py new file mode 100644 index 000000000..0d9db2a34 --- /dev/null +++ b/test/unit_test/headless/test_image_click_cancellation.py @@ -0,0 +1,32 @@ +"""Image clicks observe scoped cancellation before each native input boundary.""" +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.wrapper import auto_control_image as module + + +@pytest.mark.parametrize("cancel_at", ["before", "detection", "move"]) +def test_cancellation_prevents_next_input_without_replay(monkeypatch, cancel_at): + token = CancellationToken(1) + events = [] + + def detect(*args): + events.append("detect") + if cancel_at == "detection": + token.cancel() + return [True, [0, 0, 8, 8]] + + def move(*args): + events.append("move") + token.cancel() + + monkeypatch.setattr(module.template_detection, "find_image", detect) + monkeypatch.setattr(module, "set_mouse_position", move) + monkeypatch.setattr(module, "click_mouse", lambda *args: events.append("click")) + if cancel_at == "before": + token.cancel() + with cancellation_scope(token), pytest.raises(CancelledError): + module.locate_and_click("template.png", "mouse_left") + assert events == {"before": [], "detection": ["detect"], "move": ["detect", "move"]}[cancel_at] diff --git a/test/unit_test/headless/test_image_detection_tab_lifecycle.py b/test/unit_test/headless/test_image_detection_tab_lifecycle.py new file mode 100644 index 000000000..85b7485bb --- /dev/null +++ b/test/unit_test/headless/test_image_detection_tab_lifecycle.py @@ -0,0 +1,217 @@ +"""Owned image-detection tasks with fake capture, dialogs and desktop input.""" +import os +import threading +from types import SimpleNamespace + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +from PySide6.QtCore import QEvent, QTimer # noqa: E402 # reason: optional Qt +from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 # reason: optional Qt +from shiboken6 import isValid # noqa: E402 # reason: optional Qt +from headless._qt_settle import pump_until # noqa: E402 # reason: optional Qt +from je_auto_control.gui import _image_detect_tab as module # noqa: E402 # reason: optional Qt +from je_auto_control.gui.tab_registry import ( # noqa: E402 # reason: optional Qt + TAB_SPECS, TabEntry, TabRegistry, lazy_factory, +) +from je_auto_control.wrapper import auto_control_image as backend # noqa: E402 # reason: optional Qt + + +@pytest.fixture +def app(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture(autouse=True) +def fakes(monkeypatch): + calls = SimpleNamespace(center=[], all=[], click=[], crop=[], dialogs=[], warnings=[]) + monkeypatch.setattr(module, "locate_image_center", lambda *args: (calls.center.append(args) or (3, 4))) + monkeypatch.setattr(module, "locate_all_image", lambda *args: (calls.all.append(args) or [[1, 2, 5, 6]])) + monkeypatch.setattr(module, "locate_and_click", lambda *args: (calls.click.append(args) or (3, 4))) + monkeypatch.setattr(module, "crop_template_to_file", lambda *args: (calls.crop.append(args) or (1, 2, 3, 4))) + monkeypatch.setattr(module.QFileDialog, "getOpenFileName", + lambda *args: (calls.dialogs.append(True) or ("chosen.png", "PNG"))) + monkeypatch.setattr(module.QFileDialog, "getSaveFileName", + lambda *args: (calls.dialogs.append(True) or ("crop.png", "PNG"))) + monkeypatch.setattr(module.QMessageBox, "warning", lambda *args: calls.warnings.append(args)) + return calls + + +def _delete(app, widget): + widget.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +def test_lazy_panel_owns_controls_and_rebuilds_after_close(app, fakes): + spec = next(spec for spec in TAB_SPECS if spec.key == "image_detect") + owner = QWidget() + entry = TabEntry(spec.key, spec.title_key, lazy_factory(spec.module, spec.class_name), + on_build=lambda page: page.setParent(owner)) + registry = TabRegistry([entry]) + assert not entry.built + page = registry.open("image_detect") + assert not any(vars(fakes).values()) + page.img_path_input.setText("old.png") + page.mouse_button_combo.setCurrentText("mouse_right") + page.hide() + assert registry.open("image_detect") is page + assert not hasattr(owner, "img_path_input") + registry.close("image_detect") + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + assert not isValid(page) and not entry.built + replacement = registry.open("image_detect") + assert replacement.img_path_input.text() == "" + assert replacement.mouse_button_combo.currentText() == "mouse_left" + assert replacement.detect_result_text.toPlainText() == "" + _delete(app, owner) + + +def test_actions_keep_detection_and_click_separate_with_local_button(app, fakes): + page = module.ImageDetectionTab() + try: + actions = dict(page.menu_actions()) + assert list(actions) == ["browse", "crop_template", "locate_image", "locate_all", "locate_click", "task_stop"] + actions["browse"]() + assert page.img_path_input.text() == "chosen.png" + actions["crop_template"]() + assert page.img_path_input.text() == "crop.png" + page.threshold_input.setText("0.65") + page.draw_check.setChecked(True) + page.mouse_button_combo.setCurrentText("mouse_right") + actions["locate_image"]() + assert pump_until(lambda: not page._task.running) + assert fakes.center == [("crop.png", 0.65, True)] and fakes.click == [] + actions["locate_all"]() + assert pump_until(lambda: not page._task.running) + assert fakes.all == [("crop.png", 0.65, True)] and fakes.click == [] + assert "Found 1 matches" in page.detect_result_text.toPlainText() + actions["locate_click"]() + assert pump_until(lambda: not page._task.running) + assert fakes.click == [("crop.png", "mouse_right", 0.65, True)] + assert "Clicked at: (3, 4)" == page.detect_result_text.toPlainText() + finally: + _delete(app, page) + + +@pytest.mark.parametrize("threshold", ["nan", "inf", "-0.1", "1.1", "bad"]) +def test_invalid_threshold_is_rejected_without_backend_call(app, fakes, threshold): + page = module.ImageDetectionTab() + try: + page.img_path_input.setText("template.png") + page.threshold_input.setText(threshold) + page._locate_click() + assert page.detect_result_text.toPlainText().startswith("Error:") + assert fakes.click == [] and not page._task.running + finally: + _delete(app, page) + + +def test_dialog_cancellation_and_retranslation_preserve_state(app, fakes, monkeypatch): + monkeypatch.setattr(module.QFileDialog, "getOpenFileName", lambda *args: ("", "")) + monkeypatch.setattr(module.QFileDialog, "getSaveFileName", lambda *args: ("", "")) + page = module.ImageDetectionTab() + try: + page.img_path_input.setText("keep.png") + page._browse_img() + page._crop_template() + assert page.img_path_input.text() == "keep.png" and fakes.crop == [] + page._on_error(RuntimeError("keep error")) + page.retranslate() + assert page.detect_result_text.toPlainText() == "Error: keep error" + finally: + _delete(app, page) + + +@pytest.mark.parametrize("fail", [False, True]) +def test_worker_snapshots_inputs_keeps_ui_live_and_discards_after_close(app, monkeypatch, fail): + entered, release, exited = threading.Event(), threading.Event(), threading.Event() + calls, ticks = [], [] + + def detect(*args): + calls.append((args, threading.get_ident())) + entered.set() + try: + assert release.wait(5) + if fail: + raise RuntimeError("late detection error") + return (3, 4) + finally: + exited.set() + + monkeypatch.setattr(module, "locate_image_center", detect) + monkeypatch.setattr(module.language_wrapper, "translate", lambda key, fallback: "running" if key == "task_running" + else fallback) + owner = QWidget() + entry = TabEntry("image_detect", "tab_image_detect", module.ImageDetectionTab, + on_build=lambda page: page.setParent(owner)) + registry = TabRegistry([entry]) + page = registry.open("image_detect") + timer = QTimer(owner) + timer.timeout.connect(lambda: ticks.append(True)) + timer.start(1) + try: + page.img_path_input.setText("original.png") + page._locate_image() + assert page.detect_result_text.toPlainText() == "running" + page.img_path_input.setText("changed.png") + page.threshold_input.setText("bad") + page._locate_click() + assert pump_until(lambda: entered.is_set() and bool(ticks)) + assert calls == [(("original.png", 0.8, False), calls[0][1])] + assert calls[0][1] != threading.get_ident() + registry.close("image_detect") + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + assert not isValid(page) + replacement = registry.open("image_detect") + release.set() + assert pump_until(exited.is_set) + assert replacement.detect_result_text.toPlainText() == "" + finally: + release.set() + assert pump_until(exited.is_set) + _delete(app, owner) + + +@pytest.mark.parametrize("close", [False, True]) +def test_cancel_during_detection_prevents_late_mouse_input(app, monkeypatch, close): + entered, release, exited = threading.Event(), threading.Event(), threading.Event() + inputs = [] + + def find(*args): + entered.set() + assert release.wait(5) + return [True, [1, 2, 5, 6]] + + def locate(*args): + try: + return backend.locate_and_click(*args) + finally: + exited.set() + + monkeypatch.setattr(backend.template_detection, "find_image", find) + monkeypatch.setattr(backend, "set_mouse_position", lambda *args: inputs.append(args)) + monkeypatch.setattr(backend, "click_mouse", lambda *args: inputs.append(args)) + monkeypatch.setattr(module, "locate_and_click", locate) + page = module.ImageDetectionTab() + try: + page.img_path_input.setText("template.png") + page._locate_click() + assert pump_until(entered.is_set) + if close: + page.dispose() + _delete(app, page) + else: + page._stop() + release.set() + assert pump_until(exited.is_set) + assert inputs == [] + if not close: + assert pump_until(lambda: not page._task.running) + assert page.detect_result_text.toPlainText() == module._t("task_stopped") + finally: + release.set() + assert pump_until(exited.is_set) + if isValid(page): + _delete(app, page) From a602d0faef1d31598d90cd2999de86439294a355 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:30:50 +0800 Subject: [PATCH 015/161] Validate media contracts and restore package complexity checks --- Progress.md | 4 +- architecture.md | 4 + architecture_explore.md | 28 +++--- docs/updates/2026-11.md | 7 ++ docs/updates/README.md | 1 + .../utils/agent_runtime/native_target.py | 7 +- .../utils/remote_desktop/hw_codec.py | 37 ++++---- .../utils/remote_desktop/session_recorder.py | 16 +++- .../utils/remote_desktop/webrtc_audio.py | 4 +- .../utils/remote_desktop/webrtc_transport.py | 6 +- .../headless/test_parsers_and_codecs_audit.py | 1 + .../headless/test_webrtc_media_audit.py | 4 +- .../headless/test_webrtc_media_types.py | 93 +++++++++++++++++++ test/verify/typing_extras_exempt.txt | 6 +- 14 files changed, 166 insertions(+), 52 deletions(-) create mode 100644 test/unit_test/headless/test_webrtc_media_types.py diff --git a/Progress.md b/Progress.md index b726bc8e9..e466dcfec 100644 --- a/Progress.md +++ b/Progress.md @@ -125,8 +125,8 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 系統匣路徑在 offscreen 下沒有 tray,`_on_tray_open` 是直接呼叫測的。基準(`benchmarks/gui_*.py`)CI 仍不設門檻。 - **把 Python 建的 widget 放進分頁列在結束時崩潰**:已查明觸發條件——分頁列按鈕上接了 Python callable、又有排隊中的 `deleteLater()`、而行程經 `os._exit` 離開; 先把 deferred delete 沖掉就不會。機制(Qt 在行程結束時釋放那個 slot)是推論,沒有 C 堆疊可看。`_tab_close_icon.py` 沒有改回自訂按鈕。 -- **對真實 Qt 型別的型別檢查**:`test/verify/typing_extras_exempt.txt` 從 70 個模組降到 18 個(11 個 WebRTC 面板 mixin、`navigation`、`step_form_view`、 - `triggers_tab`,與 4 個對 aiortc/av 型別的 `utils/remote_desktop` 模組),只准變少。`QImage.fromData(x, "JPEG")` 的 5 處保留 `# type: ignore[arg-type]`: +- **對真實 Qt 型別的型別檢查**:`test/verify/typing_extras_exempt.txt` 從 70 個模組降到 14 個(11 個 WebRTC 面板 mixin、`navigation`、`step_form_view`、 + `triggers_tab`),只准變少。`QImage.fromData(x, "JPEG")` 的 5 處保留 `# type: ignore[arg-type]`: stub 要 bytes,實際的 binding 對 bytes 丟 `ValueError`。 - 遠端桌面的輸入改成佇列送出後,`AC_remote_send_input` 回的 `{"sent": True}` 意思是「已排入」;`SO_SNDTIMEO` 的 POSIX 包法與經 TLS socket 的行為沒在這台機器上驗過。 - 沒在 macOS/Linux 上看過新的關閉鈕、捲動與重設樣式;沒在真的多螢幕桌面試過視窗位置還原;PyBreeze 沒有對這一版跑過;各語系新增的字串(日文、簡體中文)沒有母語者看過。 diff --git a/architecture.md b/architecture.md index 81e127c6b..b83198783 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,9 @@ # AutoControl Architecture +Remote media adapters validate PyAV video contexts and streams before assigning +video properties, and close failed recording containers. ScreenVideoTrack uses a +separate frame-clock helper so aiortc can retain its integer timestamp field. + Image Detection is a lazy independent widget. It owns its inputs and mouse-button selection, captures immutable worker arguments and runs matching through TabTask. Close cancels work and discards late results; reopen creates fresh controls. diff --git a/architecture_explore.md b/architecture_explore.md index 01879a97d..77af0dfb1 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,500 | -| 程式碼總行數 | 229,162 | +| 程式碼總行數 | 229,174 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -512,13 +512,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,204 行。 +> 14 個套件、約 52,207 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,253 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,964 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 25,967 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -533,14 +533,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 30,477 行。 +> 6 個套件、約 30,486 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 15,243 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 15,252 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -792,7 +792,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(15,243 行/72 檔) +#### `utils/remote_desktop/`(15,252 行/72 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -832,7 +832,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `lan_discovery.py` | 204 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 197 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | -| `hw_codec.py` | 201 | 硬體 H.264 編碼偵測與啟用。 | +| `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | | `webrtc_stats.py` | 174 | 把 aiortc 的 `RTCStats` 報告輪詢成精簡 dict。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | | `adaptive_bitrate.py` | 148 | 依統計調整主機擷取 FPS。 | @@ -840,7 +840,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `trust_list.py` | 139 | 自動接受的檢視端信任清單。 | | `webrtc_inspector.py` | 138 | 行程級的 `StatsSnapshot` 滾動視窗。 | | `input_dispatch.py` | 161 | 在主機端套用輸入訊息。 | -| `session_recorder.py` | 139 | 以 PyAV 把 WebRTC 影格錄成 mp4。 | +| `session_recorder.py` | 145 | 以 PyAV 把 WebRTC 影格錄成 mp4。 | | `totp.py` | 159 | RFC 6238 TOTP(零外部相依)。 | | `file_receipts.py` | 29 | Immutable local publication receipts keep received bytes distinct from later edits to their target path. | | `clipboard_delivery.py` | 62 | Deliver clipboard data under its captured local authority and concrete connection owner. Once-bound ClipboardReceiver weakly pins the origin; queued deliveries keep the concrete peer alive without a registration self-cycle. | @@ -1015,7 +1015,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,964 行/182 檔) +#### `utils/agent_runtime/`(25,967 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1087,7 +1087,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `native_job.py` | 170 | Own a Windows helper process tree through a kill-on-close Job Object. | | `native_recovery.py` | 36 | Host-only input recovery checks never replay persisted keys or signal persisted PIDs. | | `native_scope.py` | 111 | Scope native window and control targets before their existing backend performs an action. | -| `native_target.py` | 307 | Native desktop proxy with private IPC, host input ledger and cross-database ownership. | +| `native_target.py` | 310 | Native desktop proxy with private IPC, host input ledger and cross-database ownership. | | `native_worker.py` | 349 | Private native helper entry point; stdout is a bounded owner-only JSON protocol. | | `observation_refs.py` | 151 | Resolve observation-local elements and thumbnail points into host-checked native coordinates. | | `ollama.py` | 82 | Local-only Ollama decisions over bounded HTTP, without an SDK or remote fallback. | @@ -1406,7 +1406,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,171 個 `test_*.py`/11,378 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,172 個 `test_*.py`/11,383 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1499,7 +1499,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 144 | 39,928 | | `utils/mcp_server/` | 55 | 21,490 | -| `utils/remote_desktop/` | 72 | 15,243 | +| `utils/remote_desktop/` | 72 | 15,252 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1517,8 +1517,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 981 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,280 | -| **總計** | **1,488** | **228,417** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,283 | +| **總計** | **1,488** | **228,429** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index b956fa667..2f47f2822 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -742,3 +742,10 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **Evidence:** Implementation suite passed 219 cases, independent offscreen review passed 95, and integration with document checks passed 50. Scoped three-platform mypy, real Qt type checks, Ruff and Bandit passed. All desktop and dialog backends were faked. - **Files:** `gui/_image_detect_tab.py`, `main_widget.py`, `tab_registry.py`, `wrapper/auto_control_image.py`, lifecycle/cancellation tests, three READMEs and English/Chinese Sphinx guidance. - **Open items:** Remaining retained panels and backend/native acceptance are in `Progress.md`. Entered native calls cannot be preempted; cropping remains interactive. + +## U-20261111-04 · 2026-11-11 · Validate media types and restore package complexity checks · #done #typing + +- **What:** Validate PyAV video contexts and streams, release failed recording containers, type the existing H264 encoder patch, and separate the screen frame-clock helper from aiortc's integer timestamp. Removed four media modules from the measured extras exemptions. Extracted the unchanged native-target presence predicate to restore the remaining complexity limit. +- **Evidence:** Media suite passed 157 cases and independent software-codec checks passed 6 without skips. Native-target suite passed 28 injected cases with independent source review. Integrated media, whole-package complexity and documentation checks passed 69. Integrated three-target typing reported zero ordinary errors and 14 exempt Qt modules on every target. Ruff passed. +- **Files:** `utils/remote_desktop/{hw_codec,session_recorder,webrtc_audio,webrtc_transport}.py`, `utils/agent_runtime/native_target.py`, media tests and `test/verify/typing_extras_exempt.txt`. +- **Open items:** Remaining Qt exemptions, strict typing and full final validation are in `Progress.md`. No desktop, audio hardware or native-target acceptance ran. diff --git a/docs/updates/README.md b/docs/updates/README.md index d009de3a4..8f5c95061 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-04 | 2026-11-11 | Validate media types and restore package complexity checks | #done #typing | [2026-11](2026-11.md) | | U-20261111-03 | 2026-11-11 | Release Image Detection and cancel pending click work | #done #gui | [2026-11](2026-11.md) | | U-20261111-02 | 2026-11-11 | Bound Windows memory reads behind reviewed attestation | #snapshot #agent | [2026-11](2026-11.md) | | U-20261111-01 | 2026-11-11 | Prepare owned memory fixture buffers and bounded control | #snapshot #agent | [2026-11](2026-11.md) | diff --git a/je_auto_control/utils/agent_runtime/native_target.py b/je_auto_control/utils/agent_runtime/native_target.py index db6402032..7b054b19f 100644 --- a/je_auto_control/utils/agent_runtime/native_target.py +++ b/je_auto_control/utils/agent_runtime/native_target.py @@ -203,8 +203,7 @@ def ready(self, spec: AgentTaskSpec) -> tuple[bool, str]: if self._profile is not None: payload["profile"] = self._profile.to_dict() deadline = None - if (self.supports_readonly_completion and spec.target != 'local-files' - and (self._profile is None or self._profile.kind == 'desktop')): + if self._requires_presence(spec): self._presence.check_platform() channel = self._ensure() deadline = time.monotonic() + spec.budget.action_seconds @@ -215,6 +214,10 @@ def ready(self, spec: AgentTaskSpec) -> tuple[bool, str]: result = self._request("configure", payload, deadline=deadline) return bool(result["ready"]), str(result.get("reason", "")) + def _requires_presence(self, spec: AgentTaskSpec) -> bool: + return (self.supports_readonly_completion and spec.target != 'local-files' + and (self._profile is None or self._profile.kind == 'desktop')) + def observe(self) -> dict[str, Any]: """Capture in the helper, enforcing the host's live operation deadline.""" return self._request("observe", {}) diff --git a/je_auto_control/utils/remote_desktop/hw_codec.py b/je_auto_control/utils/remote_desktop/hw_codec.py index 468cda917..10a873a71 100644 --- a/je_auto_control/utils/remote_desktop/hw_codec.py +++ b/je_auto_control/utils/remote_desktop/hw_codec.py @@ -1,14 +1,12 @@ """Detect and (opt-in) enable hardware H.264 encoding for the WebRTC host. -aiortc 1.14 hard-codes ``libx264`` as the encoder in ``H264Encoder``. To -use NVENC / QuickSync / VAAPI we monkey-patch ``av.CodecContext.create`` -so any "libx264" write request gets swapped to the chosen hardware codec. -The original is kept as a fallback if the hardware open fails. +aiortc hard-codes ``libx264`` as the encoder in ``H264Encoder``. To use +hardware encoding we replace ``H264Encoder._encode_frame`` with an encoder +that opens the selected codec and falls back to libx264 if opening fails. -Risk: the swap is process-wide, so every libx264 encode in the process -becomes hardware-backed. For AutoControl that's the WebRTC host only — -no other component encodes H.264 — so it's safe in practice. Still, -``install_hardware_codec`` is opt-in via the GUI and logs a warning. +The replacement affects all aiortc H264Encoder instances in the process. +Other PyAV users, including session recording, keep their own codecs. +``install_hardware_codec`` is opt-in via the GUI. Diagnostic-only path: ``available_hardware_codecs()`` lists which encoders PyAV can actually open without changing global state. @@ -16,10 +14,13 @@ from __future__ import annotations import threading -from typing import List, Optional +from typing import TYPE_CHECKING, Callable, Iterator, List, Optional + +if TYPE_CHECKING: + from aiortc.codecs.h264 import H264Encoder try: - import av # type: ignore + import av except ImportError as exc: # pragma: no cover raise ImportError( "Hardware codec detection requires the 'webrtc' extra (PyAV).", @@ -37,7 +38,7 @@ ] _install_lock = threading.Lock() -_original_encode_frame = None +_original_encode_frame: Callable[[H264Encoder, av.VideoFrame, bool], Iterator[bytes]] | None = None _active_codec: Optional[str] = None @@ -70,10 +71,12 @@ def _can_open(codec_name: str) -> bool: def _open_configured(codec_name: str, width: int, height: int, - bitrate: int, fps: int): + bitrate: int, fps: int) -> av.VideoCodecContext: """Create, configure and open an encoder context (raises when it cannot open).""" from fractions import Fraction ctx = av.CodecContext.create(codec_name, "w") + if not isinstance(ctx, av.VideoCodecContext): + raise ValueError("hardware encoding requires a video codec") ctx.width = width ctx.height = height ctx.bit_rate = bitrate @@ -139,7 +142,7 @@ def install_hardware_codec(codec_name: str) -> bool: ) return False try: - from aiortc.codecs import h264 as aiortc_h264 # type: ignore + from aiortc.codecs import h264 as aiortc_h264 except ImportError as error: autocontrol_logger.warning("aiortc h264 module unavailable: %r", error) return False @@ -149,7 +152,7 @@ def install_hardware_codec(codec_name: str) -> bool: target = codec_name - def patched(self, frame, force_keyframe): + def patched(self: H264Encoder, frame: av.VideoFrame, force_keyframe: bool) -> Iterator[bytes]: # Replicate aiortc's reset-on-shape-change but with hw codec. if _shape_changed(self.codec, frame, self.target_bitrate): self.buffer_data = b"" @@ -170,7 +173,7 @@ def patched(self, frame, force_keyframe): if data_to_send: yield from self._split_bitstream(data_to_send) - aiortc_h264.H264Encoder._encode_frame = patched + setattr(aiortc_h264.H264Encoder, "_encode_frame", patched) _active_codec = codec_name autocontrol_logger.info( "install_hardware_codec: aiortc libx264 -> %s", codec_name, @@ -185,10 +188,10 @@ def uninstall_hardware_codec() -> None: if _original_encode_frame is None: return try: - from aiortc.codecs import h264 as aiortc_h264 # type: ignore + from aiortc.codecs import h264 as aiortc_h264 except ImportError: return - aiortc_h264.H264Encoder._encode_frame = _original_encode_frame + setattr(aiortc_h264.H264Encoder, "_encode_frame", _original_encode_frame) _active_codec = None autocontrol_logger.info("uninstall_hardware_codec: restored libx264 path") diff --git a/je_auto_control/utils/remote_desktop/session_recorder.py b/je_auto_control/utils/remote_desktop/session_recorder.py index 1fcce645e..33ea117e4 100644 --- a/je_auto_control/utils/remote_desktop/session_recorder.py +++ b/je_auto_control/utils/remote_desktop/session_recorder.py @@ -12,7 +12,7 @@ from typing import Optional, Tuple try: - import av # type: ignore + import av except ImportError as exc: # pragma: no cover - 'webrtc' extra raise ImportError( "Session recording requires the 'webrtc' extra (PyAV).", @@ -63,10 +63,16 @@ def _open(self, frame) -> Tuple[ return self._container, self._stream self._path.parent.mkdir(parents=True, exist_ok=True) container = av.open(str(self._path), mode="w") - stream = container.add_stream(self._codec, rate=self._fps) - stream.width = frame.width - stream.height = frame.height - stream.pix_fmt = self._pixel_format + try: + stream = container.add_stream(self._codec, rate=self._fps) + if not isinstance(stream, av.video.stream.VideoStream): + raise ValueError("session recording requires a video codec") + stream.width = frame.width + stream.height = frame.height + stream.pix_fmt = self._pixel_format + except (ValueError, OSError, RuntimeError): + container.close() + raise self._container = container self._stream = stream self._started = True diff --git a/je_auto_control/utils/remote_desktop/webrtc_audio.py b/je_auto_control/utils/remote_desktop/webrtc_audio.py index b4220bcff..739ff4dc1 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_audio.py +++ b/je_auto_control/utils/remote_desktop/webrtc_audio.py @@ -21,7 +21,7 @@ from typing import Any, Optional try: - import av # type: ignore + import av import numpy as np from aiortc import MediaStreamTrack except ImportError as exc: # pragma: no cover - optional dep @@ -61,7 +61,7 @@ def __init__(self, sample_rate: int = _DEFAULT_SAMPLE_RATE, self._channels = channels self._device = device self._queue: asyncio.Queue = asyncio.Queue(maxsize=50) - self._loop = asyncio.get_running_loop() + self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() self._timestamp = 0 self._capture: Optional[AudioCapture] = None self._lock = threading.Lock() diff --git a/je_auto_control/utils/remote_desktop/webrtc_transport.py b/je_auto_control/utils/remote_desktop/webrtc_transport.py index 6015e645d..71baadb9b 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_transport.py +++ b/je_auto_control/utils/remote_desktop/webrtc_transport.py @@ -19,7 +19,7 @@ from je_auto_control.utils.logging.logging_instance import autocontrol_logger try: - import av # type: ignore + import av import numpy as np from aiortc import ( RTCConfiguration, RTCIceServer, RTCPeerConnection, @@ -333,7 +333,7 @@ def _resolve(self) -> dict: self._origin = (int(self._monitor.get("left", 0)), int(self._monitor.get("top", 0))) return self._monitor - def _timestamp(self) -> Tuple[int, fractions.Fraction]: + def _frame_timestamp(self) -> Tuple[int, fractions.Fraction]: """A 90 kHz timestamp from the wall clock. aiortc's ``next_timestamp()`` adds 1/30 s per frame and paces to 30 @@ -358,7 +358,7 @@ async def recv(self): if sleep_for > 0: await asyncio.sleep(sleep_for) self._last_emit = time.monotonic() - pts, time_base = self._timestamp() + pts, time_base = self._frame_timestamp() loop = asyncio.get_running_loop() monitor = self._resolve() frame_array = await loop.run_in_executor( diff --git a/test/unit_test/headless/test_parsers_and_codecs_audit.py b/test/unit_test/headless/test_parsers_and_codecs_audit.py index 849b231b5..636eca4a3 100644 --- a/test/unit_test/headless/test_parsers_and_codecs_audit.py +++ b/test/unit_test/headless/test_parsers_and_codecs_audit.py @@ -81,6 +81,7 @@ def create(name, _mode): # CodecContext is an immutable extension type, so the module is swapped. fake_av = types.SimpleNamespace(CodecContext=types.SimpleNamespace(create=create), + VideoCodecContext=_FakeContext, FFmpegError=hw_codec.av.FFmpegError) monkeypatch.setattr(hw_codec, "av", fake_av) return created diff --git a/test/unit_test/headless/test_webrtc_media_audit.py b/test/unit_test/headless/test_webrtc_media_audit.py index 87b8abca4..fd119ee09 100644 --- a/test/unit_test/headless/test_webrtc_media_audit.py +++ b/test/unit_test/headless/test_webrtc_media_audit.py @@ -89,9 +89,9 @@ def test_the_screen_track_stamps_frames_at_the_real_rate(monkeypatch): clock = [100.0] monkeypatch.setattr(webrtc_transport.time, "monotonic", lambda: clock[0]) track = webrtc_transport.ScreenVideoTrack(fps=10) - first, time_base = track._timestamp() + first, time_base = track._frame_timestamp() clock[0] += 0.1 - second, _ = track._timestamp() + second, _ = track._frame_timestamp() assert (second - first) * time_base == pytest.approx(0.1) diff --git a/test/unit_test/headless/test_webrtc_media_types.py b/test/unit_test/headless/test_webrtc_media_types.py new file mode 100644 index 000000000..4f67b1438 --- /dev/null +++ b/test/unit_test/headless/test_webrtc_media_types.py @@ -0,0 +1,93 @@ +"""Exercise PyAV media boundaries and aiortc subclass contracts without devices.""" +import asyncio +from types import SimpleNamespace + +import pytest + +av = pytest.importorskip("av") +pytest.importorskip("aiortc") + +from aiortc.codecs.h264 import H264Encoder # noqa: E402 # reason: optional media dependencies +from je_auto_control.utils.remote_desktop import ( # noqa: E402 # reason: optional media dependencies + hw_codec, session_recorder, +) +from je_auto_control.utils.remote_desktop.webrtc_transport import ( # noqa: E402 # reason: optional media dependencies + ScreenVideoTrack, +) + + +def test_nonvideo_hardware_codec_is_not_configured(monkeypatch): + context = SimpleNamespace() + fake_av = SimpleNamespace( + CodecContext=SimpleNamespace(create=lambda *args: context), + VideoCodecContext=av.VideoCodecContext, + ) + monkeypatch.setattr(hw_codec, "av", fake_av) + with pytest.raises(ValueError, match="requires a video codec"): + hw_codec._open_configured("audio-codec", 64, 64, 1_000_000, 30) + assert vars(context) == {} + + +@pytest.mark.parametrize("fail_add", [False, True]) +def test_recording_releases_container_when_video_stream_cannot_be_created(monkeypatch, tmp_path, fail_add): + closed = [] + + def add_stream(*args, **kwargs): + if fail_add: + raise ValueError("unsupported codec") + return object() + + container = SimpleNamespace(add_stream=add_stream, close=lambda: closed.append(True)) + monkeypatch.setattr(session_recorder.av, "open", lambda *args, **kwargs: container) + recorder = session_recorder.SessionRecorder(str(tmp_path / "recording.mp4")) + recorder.write_frame(av.VideoFrame(64, 64)) + assert closed == [True] + assert not recorder.is_active and not recorder.has_output + recorder.stop() + assert closed == [True] + + +def test_h264_patch_encodes_and_restores_the_original_method(monkeypatch): + original = H264Encoder._encode_frame + monkeypatch.setattr(hw_codec, "_original_encode_frame", None) + monkeypatch.setattr(hw_codec, "_active_codec", None) + monkeypatch.setattr(hw_codec, "_can_open", lambda name: True) + try: + assert hw_codec.install_hardware_codec("libx264") + frame = av.VideoFrame(64, 64, "yuv420p") + for plane in frame.planes: + plane.update(bytes(plane.buffer_size)) + encoded = list(H264Encoder()._encode_frame(frame, True)) + assert encoded and all(isinstance(packet, bytes) and packet for packet in encoded) + finally: + hw_codec.uninstall_hardware_codec() + assert H264Encoder._encode_frame is original + + +def test_recording_keeps_video_frames_readable_after_flush(tmp_path): + path = tmp_path / "recording.mp4" + recorder = session_recorder.SessionRecorder(str(path)) + for _ in range(2): + frame = av.VideoFrame(64, 64, "yuv420p") + for plane in frame.planes: + plane.update(bytes(plane.buffer_size)) + recorder.write_frame(frame) + assert recorder.is_active + recorder.stop() + with av.open(str(path)) as saved: + frames = list(saved.decode(video=0)) + assert len(frames) == 2 + assert {(frame.width, frame.height) for frame in frames} == {(64, 64)} + + +def test_screen_track_own_clock_does_not_replace_inherited_timestamp_storage(): + track = ScreenVideoTrack(show_cursor=False) + try: + own_pts, own_base = track._frame_timestamp() + base_pts, base_time = asyncio.run(track.next_timestamp()) + assert own_pts == base_pts == 0 + assert own_base == base_time + next_pts, _ = track._frame_timestamp() + assert next_pts > own_pts + finally: + track.stop() diff --git a/test/verify/typing_extras_exempt.txt b/test/verify/typing_extras_exempt.txt index 7bb148c1f..a45212f21 100644 --- a/test/verify/typing_extras_exempt.txt +++ b/test/verify/typing_extras_exempt.txt @@ -12,7 +12,7 @@ # Measure with the versions the `typing-extras` job of `quality.yml` pins. # # Targets: win32, linux, darwin -# Measured entries: 18 +# Measured entries: 14 je_auto_control.gui.navigation je_auto_control.gui.remote_desktop.webrtc_host_connection @@ -28,7 +28,3 @@ je_auto_control.gui.remote_desktop.webrtc_viewer_media je_auto_control.gui.remote_desktop.webrtc_viewer_ui je_auto_control.gui.script_builder.step_form_view je_auto_control.gui.triggers_tab -je_auto_control.utils.remote_desktop.hw_codec -je_auto_control.utils.remote_desktop.session_recorder -je_auto_control.utils.remote_desktop.webrtc_audio -je_auto_control.utils.remote_desktop.webrtc_transport From 9100177d0ce785eb743d4e7dff74c03b4b022c3f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:35:24 +0800 Subject: [PATCH 016/161] Reconcile modernization progress with current implementation evidence --- Progress.md | 7 +++++-- docs/updates/2026-11.md | 6 ++++++ docs/updates/README.md | 1 + 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Progress.md b/Progress.md index e466dcfec..808176937 100644 --- a/Progress.md +++ b/Progress.md @@ -528,13 +528,16 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev 計畫 D1 仍缺 portal session 關閉/恢復、compositor 重啟的狀態與原生驗收、 擷取結果與擁有者 context 的接合,以及原生 session 的重試/取消/停止控制。 D2 仍缺 helper 隔離與半開交握資源回收;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 -計畫 E(Android/iOS)、H(型別深化與總驗收)尚未開始。F 還缺: +計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; +仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 +H 已有三平台型別 gate 與縮減中的真實相依型別豁免;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 +F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 - **F1 的遺留面板釋放**:Auto Click、Record、Script 三個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 -- **F4**(啟動/記憶體基準、mixed-DPI、功能對等測試)尚未開始。 +- **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 **只記未完成的事。** 完成的工作記在 [docs/updates/](docs/updates/README.md)(每月一個批次檔, diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 2f47f2822..e49829af2 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -749,3 +749,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **Evidence:** Media suite passed 157 cases and independent software-codec checks passed 6 without skips. Native-target suite passed 28 injected cases with independent source review. Integrated media, whole-package complexity and documentation checks passed 69. Integrated three-target typing reported zero ordinary errors and 14 exempt Qt modules on every target. Ruff passed. - **Files:** `utils/remote_desktop/{hw_codec,session_recorder,webrtc_audio,webrtc_transport}.py`, `utils/agent_runtime/native_target.py`, media tests and `test/verify/typing_extras_exempt.txt`. - **Open items:** Remaining Qt exemptions, strict typing and full final validation are in `Progress.md`. No desktop, audio hardware or native-target acceptance ran. + +## U-20261111-05 · 2026-11-11 · Reconcile mobile and modernization progress with current evidence · #snapshot #progress + +- **What:** Replaced stale blanket statements that E/H/F4 had not started with their actual remaining requirements. Existing device contexts, mobile operations, shared commands, typing gates and benchmark scripts are present; their presence does not prove complete delivery. +- **Evidence:** Current mobile context, input/capture, application lifecycle and shared-entry tests passed 58 cases against fake ADB/WDA backends. The integrated typing results are recorded in U-20261111-04. Benchmark scripts were inspected, not rerun as a performance claim. +- **Open items:** Actual SDK contracts, iOS extensions, native device checks, strict typing, complete documentation, comparable GUI benchmarks and final acceptance remain in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 8f5c95061..f88a8a45e 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-05 | 2026-11-11 | Reconcile mobile and modernization progress with current evidence | #snapshot #progress | [2026-11](2026-11.md) | | U-20261111-04 | 2026-11-11 | Validate media types and restore package complexity checks | #done #typing | [2026-11](2026-11.md) | | U-20261111-03 | 2026-11-11 | Release Image Detection and cancel pending click work | #done #gui | [2026-11](2026-11.md) | | U-20261111-02 | 2026-11-11 | Bound Windows memory reads behind reviewed attestation | #snapshot #agent | [2026-11](2026-11.md) | From e2e5dce7d77f7d9e876e6bea91585fd8b0af00a1 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:40:36 +0800 Subject: [PATCH 017/161] Check navigation and editor widgets against real Qt contracts --- Progress.md | 4 +- architecture.md | 4 ++ architecture_explore.md | 14 ++--- docs/updates/2026-11.md | 7 +++ docs/updates/README.md | 1 + je_auto_control/gui/navigation.py | 17 +++--- .../gui/script_builder/step_form_view.py | 53 +++++++++++-------- je_auto_control/gui/triggers_tab.py | 24 ++++++--- .../test_script_builder_param_preservation.py | 36 +++++++++++++ .../headless/test_triggers_tab_combine.py | 23 ++++++++ test/verify/typing_extras_exempt.txt | 5 +- 11 files changed, 137 insertions(+), 51 deletions(-) diff --git a/Progress.md b/Progress.md index 808176937..e8dd5a11e 100644 --- a/Progress.md +++ b/Progress.md @@ -125,8 +125,8 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 系統匣路徑在 offscreen 下沒有 tray,`_on_tray_open` 是直接呼叫測的。基準(`benchmarks/gui_*.py`)CI 仍不設門檻。 - **把 Python 建的 widget 放進分頁列在結束時崩潰**:已查明觸發條件——分頁列按鈕上接了 Python callable、又有排隊中的 `deleteLater()`、而行程經 `os._exit` 離開; 先把 deferred delete 沖掉就不會。機制(Qt 在行程結束時釋放那個 slot)是推論,沒有 C 堆疊可看。`_tab_close_icon.py` 沒有改回自訂按鈕。 -- **對真實 Qt 型別的型別檢查**:`test/verify/typing_extras_exempt.txt` 從 70 個模組降到 14 個(11 個 WebRTC 面板 mixin、`navigation`、`step_form_view`、 - `triggers_tab`),只准變少。`QImage.fromData(x, "JPEG")` 的 5 處保留 `# type: ignore[arg-type]`: +- **對真實 Qt 型別的型別檢查**:`test/verify/typing_extras_exempt.txt` 從 70 個模組降到 11 個 WebRTC 面板 mixin, + 只准變少。`QImage.fromData(x, "JPEG")` 的 5 處保留 `# type: ignore[arg-type]`: stub 要 bytes,實際的 binding 對 bytes 丟 `ValueError`。 - 遠端桌面的輸入改成佇列送出後,`AC_remote_send_input` 回的 `{"sent": True}` 意思是「已排入」;`SO_SNDTIMEO` 的 POSIX 包法與經 TLS socket 的行為沒在這台機器上驗過。 - 沒在 macOS/Linux 上看過新的關閉鈕、捲動與重設樣式;沒在真的多螢幕桌面試過視窗位置還原;PyBreeze 沒有對這一版跑過;各語系新增的字串(日文、簡體中文)沒有母語者看過。 diff --git a/architecture.md b/architecture.md index b83198783..9144d495f 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,9 @@ # AutoControl Architecture +Navigation handles optional Qt tree items through one iterator. Script fields are +read and written through their concrete editor types, and trigger actions retain +typed common arguments while checking missing table cells before use. + Remote media adapters validate PyAV video contexts and streams before assigning video properties, and close failed recording containers. ScreenVideoTrack uses a separate frame-clock helper so aiortc can retain its integer timestamp field. diff --git a/architecture_explore.md b/architecture_explore.md index 77af0dfb1..f110c2540 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,500 | -| 程式碼總行數 | 229,174 | +| 程式碼總行數 | 229,192 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1268,7 +1268,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | | `main_widget.py` | 370 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | | `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與既有表單;不匯入 Qt。 | -| `navigation.py` | 200 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | +| `navigation.py` | 203 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | | `workspace.py` | 121 | 可捲動的分頁容器:保留 `widget/currentWidget/indexOf/setCurrentWidget` 的原始頁面身分、移除時保留頁面所有權,並直接繪製隨 palette 變色的向量關閉鈕。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | @@ -1310,7 +1310,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | screenshot | `_screenshot_tab.py` | 179 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 159 | 樣板裁切、定位、定位全部、定位並點擊。 | | record | `_record_tab.py` | 144 | 錄製/停止/回放/存檔/載入。 | -| script_builder | `script_builder/` | 6,902 | **視覺化腳本編輯器**:`command_schema.py`(5,549 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | +| script_builder | `script_builder/` | 6,909 | **視覺化腳本編輯器**:`command_schema.py`(5,549 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | | flow_editor | `flow_editor/` | 490 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | | script | `_script_tab.py` | 158 | 載入/執行單檔或整個目錄、內建編輯器執行。 | | recording_editor | `recording_editor_tab.py` | 262 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | @@ -1326,7 +1326,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | agent_tasks | `agent_tasks_tab.py` | 609 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | | scheduler | `scheduler_tab.py` | 173 | 註冊間隔式 action JSON 執行。 | | hotkeys | `hotkeys_tab.py` | 165 | 將全域熱鍵綁到 action 檔。 | -| triggers | `triggers_tab.py` | 374 | 影像/視窗/像素/檔案事件監看。 | +| triggers | `triggers_tab.py` | 382 | 影像/視窗/像素/檔案事件監看。 | | webhooks | `webhooks_tab.py` | 229 | 將 HTTP 請求綁到 action 腳本。 | | email_triggers | `email_triggers_tab.py` | 257 | 將 IMAP 信箱綁到 action 腳本。 | | test_suite | `test_suite_tab.py` | 197 | 執行 QA 套件規格並管理易碎隔離區。 | @@ -1406,7 +1406,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,172 個 `test_*.py`/11,383 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,172 個 `test_*.py`/11,385 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1497,7 +1497,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,928 | +| `gui/` | 144 | 39,946 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,252 | | `utils/executor/` | 11 | 10,702 | @@ -1518,7 +1518,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,283 | -| **總計** | **1,488** | **228,429** | +| **總計** | **1,488** | **228,447** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index e49829af2..20f464017 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -755,3 +755,10 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Replaced stale blanket statements that E/H/F4 had not started with their actual remaining requirements. Existing device contexts, mobile operations, shared commands, typing gates and benchmark scripts are present; their presence does not prove complete delivery. - **Evidence:** Current mobile context, input/capture, application lifecycle and shared-entry tests passed 58 cases against fake ADB/WDA backends. The integrated typing results are recorded in U-20261111-04. Benchmark scripts were inspected, not rerun as a performance claim. - **Open items:** Actual SDK contracts, iOS extensions, native device checks, strict typing, complete documentation, comparable GUI benchmarks and final acceptance remain in `Progress.md`. + +## U-20261111-06 · 2026-11-11 · Check navigation and editor widgets against real Qt types · #done #typing + +- **What:** Handle optional navigation items consistently, read/write script fields through concrete Qt editor types, and preserve typed trigger arguments with single-read optional table cells. Removed three measured extras exemptions without new casts or ignores. +- **Evidence:** Implementation suite passed 108 offscreen cases. Independent review passed 21 editor/trigger cases and 8 selected navigation cases without skips. Integration with document/type-contract checks passed 63. Full extras measurement reported the same 11 remaining WebRTC modules for win32, Linux and Darwin; scoped ordinary and real Qt mypy, Ruff and Radon passed. +- **Files:** `gui/navigation.py`, `gui/script_builder/step_form_view.py`, `gui/triggers_tab.py`, editor/trigger tests and `test/verify/typing_extras_exempt.txt`. +- **Open items:** Remaining WebRTC typing debt and native GUI acceptance remain in `Progress.md`. Tests used offscreen Qt and fake trigger engines. diff --git a/docs/updates/README.md b/docs/updates/README.md index f88a8a45e..fcba6380a 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-06 | 2026-11-11 | Check navigation and editor widgets against real Qt types | #done #typing | [2026-11](2026-11.md) | | U-20261111-05 | 2026-11-11 | Reconcile mobile and modernization progress with current evidence | #snapshot #progress | [2026-11](2026-11.md) | | U-20261111-04 | 2026-11-11 | Validate media types and restore package complexity checks | #done #typing | [2026-11](2026-11.md) | | U-20261111-03 | 2026-11-11 | Release Image Detection and cancel pending click work | #done #gui | [2026-11](2026-11.md) | diff --git a/je_auto_control/gui/navigation.py b/je_auto_control/gui/navigation.py index 4cc143aef..74df47c17 100644 --- a/je_auto_control/gui/navigation.py +++ b/je_auto_control/gui/navigation.py @@ -5,7 +5,7 @@ The panel only reports which key was chosen; opening the tab stays with the window that owns the tab registry. """ -from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple +from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple from PySide6.QtCore import Qt, Signal from PySide6.QtGui import QFont, QKeyEvent @@ -131,11 +131,16 @@ def _rebuild(self) -> None: # --- search -------------------------------------------------------------- + def _groups(self) -> Iterator[QTreeWidgetItem]: + for index in range(self.tree.topLevelItemCount()): + group = self.tree.topLevelItem(index) + if group is not None: + yield group + def apply_filter(self, text: str = "") -> int: """Hide what ``text`` does not match; return how many features remain.""" shown = 0 - for index in range(self.tree.topLevelItemCount()): - group = self.tree.topLevelItem(index) + for group in self._groups(): in_group = 0 for row in range(group.childCount()): item = group.child(row) @@ -152,8 +157,7 @@ def apply_filter(self, text: str = "") -> int: def visible_keys(self) -> List[str]: """Keys of the features the current search leaves on screen, top to bottom.""" keys: List[str] = [] - for index in range(self.tree.topLevelItemCount()): - group = self.tree.topLevelItem(index) + for group in self._groups(): for row in range(group.childCount()): item = group.child(row) if not item.isHidden(): @@ -161,8 +165,7 @@ def visible_keys(self) -> List[str]: return keys def _first_match(self) -> Optional[QTreeWidgetItem]: - for index in range(self.tree.topLevelItemCount()): - group = self.tree.topLevelItem(index) + for group in self._groups(): for row in range(group.childCount()): if not group.child(row).isHidden(): return group.child(row) diff --git a/je_auto_control/gui/script_builder/step_form_view.py b/je_auto_control/gui/script_builder/step_form_view.py index 3842d51c6..3eca0b2d2 100644 --- a/je_auto_control/gui/script_builder/step_form_view.py +++ b/je_auto_control/gui/script_builder/step_form_view.py @@ -205,11 +205,11 @@ def _file_edit(editor: QWidget) -> Optional[QLineEdit]: return line if isinstance(line, QLineEdit) else None -def _set_text_value(editor: QWidget, value: Any) -> None: +def _set_text_value(editor: QLineEdit, value: Any) -> None: editor.setText("" if value is None else str(value)) -def _set_rgb_value(editor: QWidget, value: Any) -> None: +def _set_rgb_value(editor: QLineEdit, value: Any) -> None: if isinstance(value, (list, tuple)): try: editor.setText(",".join(str(int(v)) for v in value)) @@ -227,7 +227,7 @@ def _set_file_value(editor: QWidget, value: Any) -> None: _set_text_value(line, value) -def _set_enum_value(editor: QWidget, value: Any) -> None: +def _set_enum_value(editor: QComboBox, value: Any) -> None: """Select ``value``, adding it when it is not one of the choices. ``setCurrentText`` ignores a value the combo does not hold, so the next @@ -240,40 +240,44 @@ def _set_enum_value(editor: QWidget, value: Any) -> None: editor.setCurrentText(text) -_SETTERS = { +_TEXT_SETTERS: Dict[FieldType, Callable[[QLineEdit, Any], None]] = { FieldType.STRING: _set_text_value, FieldType.JSON: lambda editor, value: _set_text_value( editor, json.dumps(value, ensure_ascii=False) if value is not None else None), FieldType.INT: _set_text_value, FieldType.FLOAT: _set_text_value, - FieldType.BOOL: lambda e, v: e.setChecked(bool(v)), - FieldType.ENUM: _set_enum_value, - FieldType.FILE_PATH: _set_file_value, FieldType.RGB: _set_rgb_value, } def _set_editor_value(editor: QWidget, spec: FieldSpec, value: Any) -> None: - setter = _SETTERS.get(spec.field_type) - if setter is not None: - setter(editor, value) - - -def _read_string(editor: QWidget) -> Any: + if isinstance(editor, QLineEdit): + setter = _TEXT_SETTERS.get(spec.field_type) + if setter is not None: + setter(editor, value) + elif isinstance(editor, QCheckBox): + editor.setChecked(bool(value)) + elif isinstance(editor, QComboBox): + _set_enum_value(editor, value) + elif spec.field_type == FieldType.FILE_PATH: + _set_file_value(editor, value) + + +def _read_string(editor: QLineEdit) -> Any: return editor.text() or None -def _read_int(editor: QWidget) -> Any: +def _read_int(editor: QLineEdit) -> Any: text = editor.text().strip() return int(text) if text else None -def _read_json(editor: QWidget) -> Any: +def _read_json(editor: QLineEdit) -> Any: text = _read_string(editor) return json.loads(text) if text is not None else None -def _read_float(editor: QWidget) -> Any: +def _read_float(editor: QLineEdit) -> Any: text = editor.text().strip() return float(text) if text else None @@ -283,7 +287,7 @@ def _read_file(editor: QWidget) -> Any: return (line.text() or None) if line is not None else None -def _read_rgb(editor: QWidget) -> Any: +def _read_rgb(editor: QLineEdit) -> Any: text = editor.text().strip() if not text: return None @@ -291,21 +295,24 @@ def _read_rgb(editor: QWidget) -> Any: return [int(p) for p in parts] -_READERS = { +_TEXT_READERS: Dict[FieldType, Callable[[QLineEdit], Any]] = { FieldType.STRING: _read_string, FieldType.JSON: _read_json, FieldType.INT: _read_int, FieldType.FLOAT: _read_float, - FieldType.BOOL: lambda e: bool(e.isChecked()), - FieldType.ENUM: lambda e: e.currentText() or None, - FieldType.FILE_PATH: _read_file, FieldType.RGB: _read_rgb, } def _read_editor_value(editor: QWidget, spec: FieldSpec) -> Any: - reader = _READERS.get(spec.field_type) - return reader(editor) if reader is not None else None + if isinstance(editor, QLineEdit): + reader = _TEXT_READERS.get(spec.field_type) + return reader(editor) if reader is not None else None + if isinstance(editor, QCheckBox): + return bool(editor.isChecked()) + if isinstance(editor, QComboBox): + return editor.currentText() or None + return _read_file(editor) if spec.field_type == FieldType.FILE_PATH else None def _read_field_value(editor: QWidget, spec: FieldSpec) -> tuple[bool, Any]: diff --git a/je_auto_control/gui/triggers_tab.py b/je_auto_control/gui/triggers_tab.py index 5a1faf379..2954f7253 100644 --- a/je_auto_control/gui/triggers_tab.py +++ b/je_auto_control/gui/triggers_tab.py @@ -1,5 +1,5 @@ """Triggers tab: image / window / pixel / file event watchers.""" -from typing import Any, Dict, Iterable, List, Optional, Sequence +from typing import Any, Dict, Iterable, List, Optional, Sequence, TypedDict from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( @@ -37,6 +37,12 @@ def _t(key: str) -> str: } +class _TriggerOptions(TypedDict): + trigger_id: str + script_path: str + repeat: bool + + def children_to_combine(ids: Sequence[str], triggers: Iterable[Any]) -> List[Any]: """The triggers named by ``ids``, or ``[]`` when fewer than two resolve. @@ -251,8 +257,8 @@ def _on_add(self) -> None: def _build_trigger(self, script: str): idx = self._type_combo.currentIndex() - common = {"trigger_id": "", "script_path": script, - "repeat": self._repeat_check.isChecked()} + common: _TriggerOptions = {"trigger_id": "", "script_path": script, + "repeat": self._repeat_check.isChecked()} if idx == 0: return ImageAppearsTrigger( image_path=self._image_widgets["path"].text().strip(), @@ -285,7 +291,7 @@ def _build_cron_form(self) -> dict: self._stack.addWidget(widget) return {"cron": cron_input} - def _build_pixel_trigger(self, common: dict): + def _build_pixel_trigger(self, common: _TriggerOptions): w = self._pixel_widgets return PixelColorTrigger( x=int(w["x"].text() or "0"), y=int(w["y"].text() or "0"), @@ -300,15 +306,17 @@ def _on_remove(self) -> None: row = self._table.currentRow() if row < 0: return - tid = self._table.item(row, 0).text() - default_trigger_engine.remove(tid) + item = self._table.item(row, 0) + if item is None: + return + default_trigger_engine.remove(item.text()) self._refresh() def _selected_ids(self) -> List[str]: """Trigger ids of the selected rows, in row order, without duplicates.""" rows = sorted({idx.row() for idx in self._table.selectedIndexes()}) - return [self._table.item(row, 0).text() for row in rows - if self._table.item(row, 0) is not None] + return [item.text() for row in rows + if (item := self._table.item(row, 0)) is not None] def _on_combine(self, mode: str) -> None: ids = self._selected_ids() diff --git a/test/unit_test/headless/test_script_builder_param_preservation.py b/test/unit_test/headless/test_script_builder_param_preservation.py index afcf3ebb3..cc7e923ea 100644 --- a/test/unit_test/headless/test_script_builder_param_preservation.py +++ b/test/unit_test/headless/test_script_builder_param_preservation.py @@ -93,3 +93,39 @@ def test_clearing_an_optional_field_drops_the_key(qapp): out = step_to_action(step) assert "x" not in out[1] assert out[1]["y"] == 20 + + +@pytest.mark.parametrize("kind,initial,edited,expected", [ + ("string", "old", "new", "new"), + ("json", {"old": 1}, '{"new": [2]}', {"new": [2]}), + ("int", 3, "42", 42), + ("float", 1.5, "2.75", 2.75), + ("bool", False, True, True), + ("enum", "unlisted", "second", "second"), + ("file_path", "old.json", "new.json", "new.json"), + ("rgb", [1, 2, 3], "10,20,30", [10, 20, 30]), +]) +def test_each_editor_round_trips_and_commits_its_native_value(qapp, monkeypatch, kind, initial, edited, expected): + from je_auto_control.gui.script_builder.command_schema import CommandSpec, FieldSpec, FieldType + from je_auto_control.gui.script_builder import step_form_view + + field_type = FieldType(kind) + spec = CommandSpec("AC_test_form", "Test", "Test", fields=( + FieldSpec("value", field_type, choices=("first", "second")), + )) + monkeypatch.setitem(step_form_view.COMMAND_SPECS, spec.command, spec) + step = action_to_step([spec.command, {"value": initial, "extra": "preserved"}]) + view = StepFormView() + view.load_step(step) + assert step.params == {"value": initial, "extra": "preserved"} + editor = view._editors["value"] + if field_type is FieldType.BOOL: + editor.setChecked(edited) + elif field_type is FieldType.ENUM: + assert editor.currentText() == initial + editor.setCurrentText(edited) + elif field_type is FieldType.FILE_PATH: + editor.property("line_edit").setText(edited) + else: + editor.setText(edited) + assert step_to_action(step) == [spec.command, {"value": expected, "extra": "preserved"}] diff --git a/test/unit_test/headless/test_triggers_tab_combine.py b/test/unit_test/headless/test_triggers_tab_combine.py index 790b916ce..5e85f7909 100644 --- a/test/unit_test/headless/test_triggers_tab_combine.py +++ b/test/unit_test/headless/test_triggers_tab_combine.py @@ -46,3 +46,26 @@ def test_every_button_mode_maps_to_its_composite(): assert COMPOSITE_BY_MODE == { "all": AllOfTrigger, "any": AnyOfTrigger, "sequence": SequenceTrigger, } + + +def test_empty_trigger_table_cell_does_not_remove_an_engine_entry(monkeypatch): + from types import SimpleNamespace + from PySide6.QtWidgets import QApplication + from je_auto_control.gui import triggers_tab + + app = QApplication.instance() or QApplication([]) + removed = [] + engine = SimpleNamespace(is_running=False, list_triggers=lambda: [], remove=removed.append) + monkeypatch.setattr(triggers_tab, "default_trigger_engine", engine) + tab = triggers_tab.TriggersTab() + try: + tab._table.setRowCount(1) + tab._table.setCurrentCell(0, 0) + assert tab._table.currentRow() == 0 + assert tab._selected_ids() == [] + tab._on_remove() + assert removed == [] + finally: + tab.dispose() + tab.deleteLater() + app.processEvents() diff --git a/test/verify/typing_extras_exempt.txt b/test/verify/typing_extras_exempt.txt index a45212f21..0d53ff6c9 100644 --- a/test/verify/typing_extras_exempt.txt +++ b/test/verify/typing_extras_exempt.txt @@ -12,9 +12,8 @@ # Measure with the versions the `typing-extras` job of `quality.yml` pins. # # Targets: win32, linux, darwin -# Measured entries: 14 +# Measured entries: 11 -je_auto_control.gui.navigation je_auto_control.gui.remote_desktop.webrtc_host_connection je_auto_control.gui.remote_desktop.webrtc_host_media je_auto_control.gui.remote_desktop.webrtc_host_sessions @@ -26,5 +25,3 @@ je_auto_control.gui.remote_desktop.webrtc_viewer_connection je_auto_control.gui.remote_desktop.webrtc_viewer_files je_auto_control.gui.remote_desktop.webrtc_viewer_media je_auto_control.gui.remote_desktop.webrtc_viewer_ui -je_auto_control.gui.script_builder.step_form_view -je_auto_control.gui.triggers_tab From 124657ee22044cc4022afb7aed91c9133d4381ac Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:51:43 +0800 Subject: [PATCH 018/161] Release core panel views while preserving recorder ownership --- Progress.md | 10 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture.md | 5 + architecture_explore.md | 52 ++--- .../doc/new_features/v223_features_doc.rst | 28 ++- .../Zh/doc/new_features/v223_features_doc.rst | 22 +- docs/updates/2026-11.md | 10 + docs/updates/README.md | 2 + je_auto_control/gui/_auto_click_tab.py | 213 ++++++++++-------- je_auto_control/gui/_record_tab.py | 120 +++++----- je_auto_control/gui/_script_tab.py | 95 +++++--- .../gui/language_wrapper/english.py | 1 + .../gui/language_wrapper/japanese.py | 1 + .../language_wrapper/simplified_chinese.py | 1 + .../language_wrapper/traditional_chinese.py | 1 + je_auto_control/gui/main_widget.py | 87 ++----- je_auto_control/gui/tab_registry.py | 10 +- .../listener/x11_linux_listener.py | 7 + .../linux_with_x11/record/x11_linux_record.py | 6 + je_auto_control/osx/listener/osx_listener.py | 7 + .../utils/input_macro/recorder_base.py | 8 + .../windows/record/win32_input_hook.py | 5 + test/unit_test/headless/_tab_hosts.py | 33 +-- .../headless/test_actions_menu_gui.py | 5 +- .../headless/test_core_panel_ownership.py | 131 +++++++++++ .../headless/test_gui_lazy_registry.py | 8 +- .../headless/test_gui_script_runs.py | 8 +- .../headless/test_gui_slots_menu_audit.py | 11 +- .../headless/test_gui_tab_lifecycle_audit.py | 17 +- .../headless/test_input_hook_timeline.py | 14 ++ .../headless/test_manual_history_gui.py | 8 +- .../headless/test_r3_gui_slot_exceptions.py | 25 +- .../test_recorder_status_snapshots.py | 50 ++++ .../headless/test_x11_lazy_startup.py | 26 +++ 36 files changed, 671 insertions(+), 362 deletions(-) create mode 100644 test/unit_test/headless/test_core_panel_ownership.py create mode 100644 test/unit_test/headless/test_recorder_status_snapshots.py diff --git a/Progress.md b/Progress.md index e8dd5a11e..abb224a12 100644 --- a/Progress.md +++ b/Progress.md @@ -145,9 +145,11 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - viewer 的其餘影像檔案型、mobile 與外掛唯讀工具仍需全面盤點 capability;自製工具仍依提示採預設分類。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;SSE、無狀態與 `subscriptions/listen` 路徑、TLS 加 RBAC 沒有測試。 -- **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉)管不到的參數:執行動作清單的工具、 - 有時才是路徑的參數(`ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target`,`ac_launch_process`/`ac_shell` 的 `argv`/`command`)、 - `ac_handle_file_dialog` 的 `path`、自由格式物件裡的路徑(`ac_run_suite` 的 `spec`、`ac_run_dag` 的 `definition`、`ac_assert_all` 的 `specs`)、沒標註的外掛工具。 +- **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 + `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, + 限於可辨識的絕對路徑、已存在的相對路徑及 `file:` URL;保留原字串,不代表能限制應用程式自行解讀的路徑或尚不存在的相對路徑。 + 仍管不到執行動作清單的工具、`ac_launch_process`/`ac_shell` 的 `argv`/`command`、 + 自由格式物件裡的路徑(`ac_run_suite` 的 `spec`、`ac_run_dag` 的 `definition`、`ac_assert_all` 的 `specs`)與沒標註的外掛工具。 檔案 symlink 的跳脫在這台機器上建不出來(只跑了目錄 junction);POSIX 的 `:` 分隔與 `~` 沒在 Linux/macOS 跑。 `roots/list` 來的根目錄要另外開 `JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT` 才算數——這是實作時定的,請維護者確認。 - **USB passthrough 實機驗收**:仍須對真的舊版 host、WebRTC 通道與 USB 裝置驗證長時間 transfer、 @@ -534,7 +536,7 @@ H 已有三平台型別 gate 與縮減中的真實相依型別豁免;仍缺嚴 F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 -- **F1 的遺留面板釋放**:Auto Click、Record、Script 三個核心表單與 Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 +- **F1 的遺留面板釋放**:Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 diff --git a/README.md b/README.md index e146994da..6b3c5752b 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,8 @@ The Image Detection page runs matching in the background and owns its mouse-butt Its Actions menu can stop a pending search; closing the page discards late results and reopening resets its inputs. Cancellation prevents later move/click steps, but cannot interrupt a native call already in progress. +Auto Click, Record and Script Executor own their controls and background tasks. Closing them stops local work; reopening creates fresh inputs. The shared recorder continues after its page closes, and a reopened page reads backend status (unknown when unsupported). This status does not verify native hook health. Ctrl+4 still stops scripts and auto-clicking. + Windows, macOS, X11 and Wayland use different backends. Available features depend on system permissions and optional dependencies; Windows ARM64 has additional limitations. See the installation guide before choosing a deployment target. Managed agent tasks and cross-host transfers include experimental features. See the implementation notes and project progress before relying on them in production. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 4d5f9d137..301f26e63 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -39,6 +39,8 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果,重新打开会重置输入字段。 取消可阻止后续移动与点击步骤,但无法中断已进入的原生调用。 +自动点击、录制与脚本执行分页各自持有控件与后台任务;关闭会停止本页任务,重新打开会建立新的输入框。共享录制器不随分页关闭,重新打开后会读取后端状态,不支持查询时显示未知;此状态不代表原生钩子健康检查。Ctrl+4 仍可停止脚本与自动点击。 + Windows、macOS、X11 与 Wayland 使用不同后端,实际功能取决于系统权限与可选依赖。Windows ARM64 另有限制,部署前请先阅读安装文件。 受管理的 Agent 任务与跨主机传输包含实验性功能;采用前请查看实现记录与项目进度中的验收状态。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 62604f943..931511f58 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -39,6 +39,8 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果,重新開啟會重設輸入欄位。 取消可阻止後續移動與點擊步驟,但無法中斷已進入的原生呼叫。 +自動點擊、錄製與腳本執行分頁各自持有控制項與背景工作;關閉會停止本頁工作,重開會建立新的輸入欄位。共用錄製器不隨分頁關閉,重開後會讀取後端狀態,不支援查詢時顯示未知;此狀態不代表原生掛鉤健康檢查。Ctrl+4 仍可停止腳本與自動點擊。 + Windows、macOS、X11 與 Wayland 使用不同後端,實際功能取決於系統權限與選配依賴。Windows ARM64 另有限制,部署前請先閱讀安裝文件。 受管理的 Agent 任務與跨主機傳輸包含實驗性功能;採用前請查看實作紀錄與專案進度中的驗收狀態。 diff --git a/architecture.md b/architecture.md index 9144d495f..bfd9838bd 100644 --- a/architecture.md +++ b/architecture.md @@ -8,6 +8,11 @@ Remote media adapters validate PyAV video contexts and streams before assigning video properties, and close failed recording containers. ScreenVideoTrack uses a separate frame-clock helper so aiortc can retain its integer timestamp field. +Auto Click, Record and Script are lazy independent widgets owning their background +tasks and menu actions. Closing cancels page work and releases controls; the shared +recorder survives the Record view. Reopening reads retained recorder state without +probing native hook health. Ctrl+4 still delegates to the global stop path. + Image Detection is a lazy independent widget. It owns its inputs and mouse-button selection, captures immutable worker arguments and runs matching through TabTask. Close cancels work and discards late results; reopen creates fresh controls. diff --git a/architecture_explore.md b/architecture_explore.md index f110c2540..ab0757f01 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,500 | -| 程式碼總行數 | 229,192 | +| 程式碼總行數 | 229,250 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -202,7 +202,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.3 平台後端 -#### Windows(`windows/`,24 檔/2,265 行) +#### Windows(`windows/`,24 檔/2,270 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -211,7 +211,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `core/utils/win32_keypress_check.py` | 21 | `GetAsyncKeyState` 按鍵狀態查詢。 | | `mouse/win32_ctype_mouse_control.py` | 220 | 滑鼠事件產生(含多螢幕絕對座標換算)。 | | `keyboard/win32_ctype_keyboard_control.py` | 98 | 鍵盤事件產生。 | -| `record/win32_input_hook.py` | 253 | 單一一組低階鍵鼠 hook(`WH_KEYBOARD_LL`/`WH_MOUSE_LL`)+訊息迴圈,產生帶時間戳的事件時間軸;停止時以 `PostThreadMessageW(WM_QUIT)` 收掉執行緒,不會每錄一次就漏一條。 | +| `record/win32_input_hook.py` | 258 | 單一一組低階鍵鼠 hook(`WH_KEYBOARD_LL`/`WH_MOUSE_LL`)+訊息迴圈,產生帶時間戳的事件時間軸;停止時以 `PostThreadMessageW(WM_QUIT)` 收掉執行緒,不會每錄一次就漏一條。 | | `record/win32_record.py` | 41 | 把 `win32_input_hook` 的時間軸轉成 action list(含按鍵放開、滾輪與間隔);整形本體與 macOS 共用 `utils/input_macro/recorder_base.py`。 | | `screen/win32_screen.py` | 171 | 螢幕尺寸與像素讀取。**每支 Win32 函式都明寫 argtypes/restype**(HDC 是指標寬度,走預設的 c_int 會截斷,錯誤會沉默地擴散到 GetPixel/ReleaseDC),並持有自己的 user32/gdi32 handle。import 時呼叫 `SetProcessDPIAware()`——**行程層級且不可還原**,實體↔邏輯座標換算請走 `utils/monitor_layout`。 | | `window/windows_window_manage.py` | 473 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | @@ -220,7 +220,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `interception/keyboard.py` | 70 | 經 Interception 驅動的鍵盤輸入(繞過部分反自動化偵測)。 | | `interception/mouse.py` | 160 | 經 Interception 驅動的滑鼠輸入。 | -#### macOS(`osx/`,17 檔/981 行) +#### macOS(`osx/`,17 檔/988 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -228,12 +228,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse/osx_mouse.py` | 193 | Quartz `CGEvent` 滑鼠事件。 | | `keyboard/osx_keyboard.py` | 144 | Quartz 鍵盤事件。 | | `keyboard/osx_keyboard_check.py` | 24 | 按鍵狀態查詢。 | -| `listener/osx_listener.py` | 261 | 專屬執行緒上的 listen-only `CGEventTap`+自己的 `CFRunLoopRunInMode` 切片;不在 import 時建 `NSApplication`,也不用會卡住呼叫緒的 `AppHelper.runEventLoop()`。修飾鍵由 `flagsChanged` 的旗標還原成 press/release,座標取 `CGEventGetLocation`(左上原點,與重播送出的座標同一空間)。 | +| `listener/osx_listener.py` | 268 | 專屬執行緒上的 listen-only `CGEventTap`+自己的 `CFRunLoopRunInMode` 切片;不在 import 時建 `NSApplication`,也不用會卡住呼叫緒的 `AppHelper.runEventLoop()`。修飾鍵由 `flagsChanged` 的旗標還原成 press/release,座標取 `CGEventGetLocation`(左上原點,與重播送出的座標同一空間)。 | | `record/osx_record.py` | 41 | 錄製。捕捉後的整形(舊版按下事件 Queue、時間軸、只錄滑鼠/只錄鍵盤)走共用的 `utils/input_macro/recorder_base.py`。 | | `screen/osx_screen.py` | 143 | 螢幕擷取與尺寸(含 Retina 座標處理)。 | | `pid/pid_control.py` | 53 | 以 PID 操作應用程式。 | -#### Linux X11(`linux_with_x11/`,19 檔/1,369 行) +#### Linux X11(`linux_with_x11/`,19 檔/1,382 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -241,8 +241,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `core/utils/x11_linux_vk.py` | 231 | Resolve X11 key symbols on explicit table or legacy constant access. | | `mouse/x11_linux_mouse_control.py` | 163 | XTest 滑鼠事件。 | | `keyboard/x11_linux_keyboard_control.py` | 101 | XTest 鍵盤事件。 | -| `listener/x11_linux_listener.py` | 243 | Acquire and own an independent X11 RECORD connection on first observation. | -| `record/x11_linux_record.py` | 78 | 錄製。 | +| `listener/x11_linux_listener.py` | 250 | Acquire and own an independent X11 RECORD connection on first observation. | +| `record/x11_linux_record.py` | 84 | 錄製。 | | `screen/x11_linux_screen.py` | 67 | 螢幕尺寸與擷取。 | | `uinput/_device.py` | 246 | `/dev/uinput` 封裝(核心層輸入,選用)。 | | `uinput/keyboard.py` | 44 | uinput 鍵盤後端,介面與 X11 版一致。 | @@ -288,7 +288,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,488 行。 +> 25 個套件、約 19,496 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -302,7 +302,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | | `utils/executor/` | 10,702 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | -| `utils/input_macro/` | 469 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | +| `utils/input_macro/` | 477 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | | `utils/json_store/` | 281 | JSON 字典檔持久化的共用小工具(內部管線) | | `utils/loop_guard/` | 158 | 機械式卡死迴圈偵測(agent loop 用) | @@ -1266,7 +1266,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | | `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | -| `main_widget.py` | 370 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與自己的 mixin 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | +| `main_widget.py` | 317 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與保留的 Remote Desktop 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | | `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與既有表單;不匯入 Qt。 | | `navigation.py` | 203 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | @@ -1275,11 +1275,11 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `agent_transfer_view.py` | 166 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 131 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | | `config_sync_tab.py` | 413 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | -| `_auto_click_tab.py` | 295 | 自動點擊分頁的 mixin 建構器。 | +| `_auto_click_tab.py` | 326 | 獨立自動點擊分頁;快照工作參數,以 TabTask 執行與取消。 | | `_screenshot_tab.py` | 179 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | | `_image_detect_tab.py` | 159 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | -| `_script_tab.py` | 158 | 腳本執行分頁 mixin。 | -| `_record_tab.py` | 144 | 錄製/回放分頁 mixin。 | +| `_script_tab.py` | 183 | 獨立腳本執行分頁;背景載入與執行,關閉取消並釋放控制項。 | +| `_record_tab.py` | 162 | 獨立錄製/回放檢視;背景工作與共享錄製器狀態,關閉檢視不停止錄製器。 | | `_report_tab.py` | 106 | 報表分頁 mixin。 | | `_i18n_helpers.py` | 79 | 需要即時語言切換的分頁共用的翻譯註冊 mixin。 | | `_validators.py` | 29 | `int_validator()`/`double_validator()`:以 C locale 驗證的數字輸入框 validator,接受的正是 `int()`/`float()` 讀得懂的寫法(預設 locale 在法文、德文下只收小數逗號)。所有數字 `QLineEdit` 都用它。 | @@ -1295,24 +1295,24 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 7,935 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 7,939 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 -> 核心分頁在 `main_widget.py` 的 `_own_tab_builders` 宣告動作;功能分頁實作 `menu_actions()`(目前 41 個檔案有此 hook)。 +> 核心與功能分頁實作 `menu_actions()`(目前 57 個檔案有此 hook);Remote Desktop 由 `main_widget.py` 的 `_own_tab_builders` 保留選用相依套件後備檢視。 > `test/unit_test/headless/test_actions_menu_gui.py` 會守住這個契約——沒有動作宣告的新分頁會讓 CI 失敗。 #### 51 個分頁 | 分頁 | 模組 | 行數 | 職責 | | --- | --- | ---: | --- | -| auto_click | `_auto_click_tab.py` | 295 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | +| auto_click | `_auto_click_tab.py` | 326 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | | screenshot | `_screenshot_tab.py` | 179 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 159 | 樣板裁切、定位、定位全部、定位並點擊。 | -| record | `_record_tab.py` | 144 | 錄製/停止/回放/存檔/載入。 | +| record | `_record_tab.py` | 162 | 錄製/停止/回放/存檔/載入。 | | script_builder | `script_builder/` | 6,909 | **視覺化腳本編輯器**:`command_schema.py`(5,549 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | | flow_editor | `flow_editor/` | 490 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | -| script | `_script_tab.py` | 158 | 載入/執行單檔或整個目錄、內建編輯器執行。 | +| script | `_script_tab.py` | 183 | 載入/執行單檔或整個目錄、內建編輯器執行。 | | recording_editor | `recording_editor_tab.py` | 262 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | | variables | `variables_tab.py` | 169 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 187 | 解鎖保險庫並管理 `${secrets.NAME}`。 | @@ -1406,7 +1406,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,172 個 `test_*.py`/11,385 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,174 個 `test_*.py`/11,393 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1497,7 +1497,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,946 | +| `gui/` | 144 | 39,971 | | `utils/mcp_server/` | 55 | 21,490 | | `utils/remote_desktop/` | 72 | 15,252 | | `utils/executor/` | 11 | 10,702 | @@ -1505,20 +1505,20 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,324 | | `wrapper/` | 25 | 5,996 | -| `windows/` | 24 | 2,265 | +| `windows/` | 24 | 2,270 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | -| `linux_with_x11/` | 19 | 1,369 | +| `linux_with_x11/` | 19 | 1,382 | | `linux_wayland/` | 20 | 3,844 | | `utils/triggers/` | 4 | 1,401 | | `utils/ocr/` | 10 | 1,382 | | `utils/usbip/` | 5 | 1,008 | | `utils/assertion/` | 3 | 888 | -| `osx/` | 17 | 981 | +| `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,283 | -| **總計** | **1,488** | **228,447** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | +| **總計** | **1,488** | **228,505** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 6ab0ad576..23e5756bd 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -9,15 +9,10 @@ rebuilds for the active tab. The Actions menu ---------------- -Two ways a tab surfaces its commands: - -* **Registry actions** — legacy core tabs (Auto Click, Record and Script Executor) - declare ``(label_key, handler)`` pairs when - they are registered in ``gui/main_widget.py``. -* **The** ``menu_actions()`` **hook** — independent tabs, including Screenshot, - Image Detection and Report, expose a - ``menu_actions()`` method returning the same ``[(label_key, handler), ...]`` - shape; the menu bar queries the active tab and renders whatever it returns. +Independent tabs, including Auto Click, Record, Script Executor, Screenshot, +Image Detection and Report, expose ``menu_actions()`` returning +``[(label_key, handler), ...]``. The menu bar queries the active page and +renders its commands. Registry-supplied actions remain supported for embedders. 46 of 48 registered tabs surface their commands this way. **Script Builder** and **Remote Desktop** intentionally keep their interactive panel layouts, and @@ -175,3 +170,18 @@ that closes over the tab. This is a GUI-internal API (it imports ``PySide6``) and is not re-exported by the package facade; the headless functions a tab calls stay usable without it. + +Core panel ownership +-------------------- + +Auto Click owns its timer and snapshots each background input request. Pending +work does not accumulate across timer ticks. Closing cancels future ticks and +checks cancellation between double-click inputs; an entered native call may finish. +Script Executor owns its editor, file/directory settings and cancellable runs. +Opening a script from elsewhere routes through the registered Script page. + +Record owns playback, loaded data and background start/stop/file operations. +Closing stops page-owned work but does not stop the shared recorder. Reopening +reads existing backend capture state; unsupported/custom backends show unknown. +The read-only state does not prove hook health or native input acceptance. +Hiding preserves page state; closing and reopening creates a fresh page. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index 5008d93b4..d665c5a63 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -8,13 +8,9 @@ Actions 選單 ------------ -分頁有兩種方式呈現其指令: - -* **註冊時宣告**——舊式核心分頁(自動點擊、錄製、腳本執行器)在 - ``gui/main_widget.py`` 註冊時宣告 ``(label_key, handler)`` 配對。 -* ``menu_actions()`` **掛鉤**——獨立分頁,包括截圖、影像偵測與報告,提供 ``menu_actions()`` 方法, - 回傳相同的 ``[(label_key, handler), ...]`` 形狀;選單列查詢當前分頁並 - 渲染其回傳內容。 +獨立分頁,包括自動點擊、錄製、腳本執行器、截圖、影像偵測與報告, +提供 ``menu_actions()`` 方法,回傳 ``[(label_key, handler), ...]``。 +選單列查詢當前分頁並呈現其指令;嵌入者仍可透過註冊資料宣告動作。 48 個已註冊分頁中有 46 個以此方式呈現指令。**Script Builder** 與 **Remote Desktop** 刻意保留其互動式面板版面,Actions 選單在這兩頁顯示 @@ -170,3 +166,15 @@ GUI 執行緒執行,原本接在阻塞呼叫後面的程式碼就放在這裡。 關閉分頁會丟棄晚到結果,重新開啟會重設輸入;隱藏則保留輸入。 ``locate_and_click`` 在開始偵測以及移動、點擊前檢查取消,但已進入的原生呼叫仍可能完成。 裁切仍為互動操作,繪圖選項沿用後端的視覺化行為。 + +核心分頁生命週期 +---------------- + +自動點擊、錄製與腳本執行分頁以 ``menu_actions()`` 提供自己的動作, +首次開啟時才建立。自動點擊持有計時器與輸入快照,不累積尚未完成的點擊工作; +關閉會停止後續計時,雙擊之間檢查取消,但已進入的原生呼叫仍可能完成。 +腳本執行分頁持有編輯器、路徑與可取消執行;外部開檔會交給已登錄的腳本分頁。 + +錄製分頁持有播放、載入資料與背景開始/停止/檔案工作。 +關閉不會停止共用錄製器,重開後讀取既有後端狀態;不支援查詢的後端顯示未知。 +此唯讀狀態不證明原生掛鉤健康或輸入已被接受。隱藏保留狀態,關閉後重開則建立新分頁。 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 20f464017..2e2bd0e67 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -762,3 +762,13 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **Evidence:** Implementation suite passed 108 offscreen cases. Independent review passed 21 editor/trigger cases and 8 selected navigation cases without skips. Integration with document/type-contract checks passed 63. Full extras measurement reported the same 11 remaining WebRTC modules for win32, Linux and Darwin; scoped ordinary and real Qt mypy, Ruff and Radon passed. - **Files:** `gui/navigation.py`, `gui/script_builder/step_form_view.py`, `gui/triggers_tab.py`, editor/trigger tests and `test/verify/typing_extras_exempt.txt`. - **Open items:** Remaining WebRTC typing debt and native GUI acceptance remain in `Progress.md`. Tests used offscreen Qt and fake trigger engines. + +## U-20261111-07 · 2026-11-11 · Release core panels while retaining shared recorder ownership · #done #gui + +- **What:** Auto Click, Record and Script now own lazy widgets and cancellable background tasks. Closing a view releases controls; reopening Record reads shared recorder state. macOS snapshots the thread reference and X11 status does not acquire the startup lock. +- **Evidence:** Implementation passed 213 cases plus 17 input-hook checks. Independent review passed 114 cases and found the macOS race, now covered by a deterministic fake regression. Integrated verification passed 137 cases with 2 platform skips. All input backends were faked; native lifecycle acceptance remains in Progress.md. Document, Actions menu, complexity and file-budget gates passed 54 cases after migrating the menu test to the new widget-owned actions. Package Ruff and Bandit passed. Pylint cannot resolve Qt extension members and unavailable macOS/X11 libraries on this host; it was not clean. + +## U-20261111-08 · 2026-11-11 · Reconcile conditional MCP path checks with current evidence · #snapshot #mcp + +- **What:** Corrected the outstanding path-policy description: path-or-other checks absolute/existing paths and file URLs while retaining literals. Ambiguous relative paths, shell interpretation and nested free-form payloads remain outside its guarantee. +- **Evidence:** Existing policy suite passed 54 cases against actual registry schemas and fake handlers. Platform symlink and real-client acceptance remain in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index fcba6380a..205c96e8d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,8 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-08 | 2026-11-11 | Reconcile conditional MCP path checks with current evidence | #snapshot #mcp | [2026-11](2026-11.md) | +| U-20261111-07 | 2026-11-11 | Release core panels while retaining shared recorder ownership | #done #gui | [2026-11](2026-11.md) | | U-20261111-06 | 2026-11-11 | Check navigation and editor widgets against real Qt types | #done #typing | [2026-11](2026-11.md) | | U-20261111-05 | 2026-11-11 | Reconcile mobile and modernization progress with current evidence | #snapshot #progress | [2026-11](2026-11.md) | | U-20261111-04 | 2026-11-11 | Validate media types and restore package complexity checks | #done #typing | [2026-11](2026-11.md) | diff --git a/je_auto_control/gui/_auto_click_tab.py b/je_auto_control/gui/_auto_click_tab.py index 34b1ef98b..c585561fa 100644 --- a/je_auto_control/gui/_auto_click_tab.py +++ b/je_auto_control/gui/_auto_click_tab.py @@ -1,4 +1,9 @@ -from typing import TYPE_CHECKING, Any, Callable, Optional +"""Independent auto-click controls with owned timer and cancellable background input.""" +from dataclasses import dataclass +from functools import partial +from typing import Callable, Optional + +from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( QWidget, QLineEdit, QComboBox, QVBoxLayout, QLabel, @@ -6,8 +11,10 @@ QGroupBox, ) -from je_auto_control.gui._qt_typed import as_widget -from je_auto_control.gui._tab_task import stop_all_script_runs +from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper +from je_auto_control.gui._tab_task import TabTask, stop_all_script_runs +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.gui._validators import int_validator from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.wrapper.auto_control_keyboard import ( @@ -19,26 +26,39 @@ ) -class AutoClickTabMixin: - """ - Mixin that provides the auto-click tab UI and handlers. - Requires the host widget to expose `self.timer`, `self.repeat_count`, - `self.repeat_max` attributes, and the ``TranslatableMixin`` helpers - (``self._tr(...)``) set up by its __init__. - """ +@dataclass(frozen=True) +class _Click: + mouse: bool + key: str + x: int + y: int + count: int + + +def _click(request: _Click) -> None: + for _ in range(request.count): + cancellation_checkpoint() + if request.mouse: + click_mouse(request.key, request.x, request.y) + else: + type_keyboard(request.key) - if TYPE_CHECKING: - # Declared, never defined: the widget this mixin is mixed into owns - # every one of these. The block is stripped at runtime, so nothing - # here can shadow what the host actually binds. - _tr: Callable[..., Any] - _translate: Callable[[str], str] - timer: Any - def _build_auto_click_tab(self) -> QWidget: - tab = QWidget() - outer = QVBoxLayout() +class AutoClickTab(TranslatableMixin, QWidget): + """Own the timer, input snapshots and worker for this auto-click page.""" + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._tr_init() + self.timer = QTimer(self) + self.timer.timeout.connect(self._timer_tick) + self.repeat_count = 0 + self.repeat_max = 0 + self._task = TabTask(self) + self._task.result.connect(self._on_result) + self._task.error.connect(self._on_error) + self._task.finished.connect(self._refresh_status) + outer = QVBoxLayout(self) click_group = self._tr(QGroupBox(), "tab_auto_click") grid = QGridLayout() row = 0 @@ -47,7 +67,7 @@ def _build_auto_click_tab(self) -> QWidget: self.mouse_radio = self._tr(QRadioButton(), "mouse_radio") self.keyboard_radio = self._tr(QRadioButton(), "keyboard_radio") self.mouse_radio.setChecked(True) - self._input_group = QButtonGroup() + self._input_group = QButtonGroup(self) self._input_group.addButton(self.mouse_radio) self._input_group.addButton(self.keyboard_radio) h = QHBoxLayout() @@ -103,7 +123,7 @@ def _build_auto_click_tab(self) -> QWidget: self.repeat_count_times = self._tr(QRadioButton(), "repeat_radio") self.repeat_count_input = self._tr(QLineEdit(), "times") self.repeat_count_input.setValidator(int_validator(1, 999999999)) - rg = QButtonGroup(tab) + rg = QButtonGroup(self) rg.addButton(self.repeat_until_stopped) rg.addButton(self.repeat_count_times) self.repeat_until_stopped.setChecked(True) @@ -159,16 +179,19 @@ def _build_auto_click_tab(self) -> QWidget: scroll_group.setLayout(sc_layout) outer.addWidget(scroll_group) + self.status_label = QLabel() + outer.addWidget(self.status_label) + self._refresh_status() outer.addStretch() self.mouse_radio.toggled.connect(self._update_click_mode) self._update_click_mode() - tab.setLayout(outer) - return tab - def _auto_click_retranslate(self) -> None: + def retranslate(self) -> None: """Re-translate composite labels and combo items that ``_tr`` can't own.""" + super().retranslate() + self._refresh_status() if hasattr(self, "click_type_combo") and hasattr(self, "_click_type_keys"): current_index = self.click_type_combo.currentIndex() self.click_type_combo.clear() @@ -193,12 +216,12 @@ def _start_auto_click(self): try: interval = int(self.interval_input.text()) except ValueError: - QMessageBox.warning(as_widget(self), "Warning", "Interval must be a number") + QMessageBox.warning(self, "Warning", "Interval must be a number") return # The validator's bottom of 1 is a hint only: "0" set a 0 ms timer, # which clicked on every event-loop pass (18,579 clicks in 0.5 s). if interval < 1: - QMessageBox.warning(as_widget(self), "Warning", "Interval must be at least 1 ms") + QMessageBox.warning(self, "Warning", "Interval must be at least 1 ms") return self.repeat_count = 0 try: @@ -206,19 +229,17 @@ def _start_auto_click(self): except ValueError: self.repeat_max = 0 self.timer.setInterval(interval) - try: - self.timer.timeout.disconnect(self._timer_tick) - except RuntimeError: - pass - self.timer.timeout.connect(self._timer_tick) self.timer.start() + self._refresh_status() def _stop_auto_click(self): """Stop the auto-clicker and ask every running script to stop (Ctrl+4).""" - self.timer.stop() + self.dispose() stop_all_script_runs() - def _timer_tick(self): + def _timer_tick(self) -> None: + if self._task.running: + return if self.repeat_until_stopped.isChecked(): self._do_click() elif self.repeat_count_times.isChecked(): @@ -228,68 +249,78 @@ def _timer_tick(self): else: self.repeat_count = 0 self.timer.stop() + self._refresh_status() - def _do_click(self): - try: - is_double = self.click_type_combo.currentIndex() == 1 - if self.mouse_radio.isChecked(): - btn = self.mouse_button_combo.currentText() - x = int(self.cursor_x_input.text() or "0") - y = int(self.cursor_y_input.text() or "0") - click_mouse(btn, x, y) - if is_double: - click_mouse(btn, x, y) - else: - key = self.keyboard_button_combo.currentText() - type_keyboard(key) - if is_double: - type_keyboard(key) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - # AutoControlMouseException / AutoControlCantFindKeyException from a - # throwing backend must land here — otherwise timer.stop() is - # skipped and the auto-click QTimer fires the failing action forever. - self.timer.stop() - QMessageBox.warning(as_widget(self), "Error", str(error)) - - def _get_mouse_pos(self): + def _do_click(self) -> None: + if self._task.running: + return try: - position = get_mouse_position() - if position is None: - # GetCursorPos fails on a locked or secure desktop; the - # backend reports that as None rather than raising. - raise AutoControlException( - "the OS did not report a cursor position", - ) - x, y = position - self._pos_label_suffix = f" ({x}, {y})" - self.pos_label.setText( - self._translate("current_position") + self._pos_label_suffix, - ) - self.cursor_x_input.setText(str(x)) - self.cursor_y_input.setText(str(y)) + mouse = self.mouse_radio.isChecked() + key = self.mouse_button_combo.currentText() if mouse else self.keyboard_button_combo.currentText() + request = _Click(mouse, key, int(self.cursor_x_input.text() or "0"), + int(self.cursor_y_input.text() or "0"), + 2 if self.click_type_combo.currentIndex() == 1 else 1) + self._start_work(partial(_click, request)) except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + self._on_error(error) - def _send_hotkey(self): - try: - keys = [k.strip() for k in self.hotkey_input.text().split(",") if k.strip()] - if keys: - hotkey(keys) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + def _on_error(self, error: object) -> None: + self.timer.stop() + self._refresh_status() + QMessageBox.warning(self, "Error", str(error)) - def _send_write(self): - try: - text = self.write_input.text() - if text: - write(text) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + def _get_mouse_pos(self) -> None: + self._start_work(get_mouse_position, tag="position") - def _send_scroll(self): + def _on_result(self, result: object) -> None: + if self._task.tag != "position": + return + if not isinstance(result, tuple) or len(result) != 2: + self._on_error(AutoControlException("the OS did not report a cursor position")) + return + x, y = result + self._pos_label_suffix = f" ({x}, {y})" + self.pos_label.setText(self._translate("current_position") + self._pos_label_suffix) + self.cursor_x_input.setText(str(x)) + self.cursor_y_input.setText(str(y)) + + def _send_hotkey(self) -> None: + keys = [key.strip() for key in self.hotkey_input.text().split(",") if key.strip()] + if keys: + self._start_work(partial(hotkey, keys)) + + def _send_write(self) -> None: + text = self.write_input.text() + if text: + self._start_work(partial(write, text)) + + def _send_scroll(self) -> None: try: - val = int(self.scroll_value_input.text() or "3") + value = int(self.scroll_value_input.text() or "3") direction = self.scroll_dir_combo.currentText() if self.scroll_dir_combo else "scroll_up" - mouse_scroll(val, scroll_direction=direction) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + self._start_work(partial(mouse_scroll, value, scroll_direction=direction)) + except (ValueError, TypeError) as error: + self._on_error(error) + + def _start_work(self, work: Callable[[], object], *, tag: str = "") -> None: + self._task.start(work, tag=tag) + self._refresh_status() + + def _refresh_status(self) -> None: + key = "task_running" if self.timer.isActive() or self._task.running else "task_stopped" + self.status_label.setText(self._translate(key)) + + def _translate(self, key: str) -> str: + return language_wrapper.translate(key, key) + + def menu_actions(self) -> list[tuple[str, Callable[[], object]]]: + """Expose owned input controls through the workspace Actions menu.""" + return [("start", self._start_auto_click), ("stop", self._stop_auto_click), + ("get_position", self._get_mouse_pos), ("hotkey_send", self._send_hotkey), + ("write_send", self._send_write), ("scroll_send", self._send_scroll)] + + def dispose(self) -> None: + """Stop this page's timer and pending work without stopping other pages.""" + self.timer.stop() + self._task.stop() + self._refresh_status() diff --git a/je_auto_control/gui/_record_tab.py b/je_auto_control/gui/_record_tab.py index 492804af7..64562531e 100644 --- a/je_auto_control/gui/_record_tab.py +++ b/je_auto_control/gui/_record_tab.py @@ -1,4 +1,4 @@ -"""Record / playback tab builder (extracted mixin). +"""Independent recording view and cancellable playback. Playback runs off the GUI thread as a stoppable executor run, one at a time. """ @@ -6,14 +6,15 @@ import functools import json -from typing import TYPE_CHECKING, Any, Callable +from typing import Callable from PySide6.QtWidgets import ( QFileDialog, QLabel, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._tab_task import TabTask, was_stopped -from je_auto_control.gui._qt_typed import as_widget +from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.wrapper import auto_control_record from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.executor.action_executor import execute_action @@ -33,24 +34,19 @@ def _play_actions(actions: list) -> object: return execute_action(actions) -class RecordTabMixin: - """Provides the record/playback tab builder/handlers. +def _start_recording() -> None: + if not record(): + raise AutoControlException("Recording could not start; see the log") - Host widget must expose the ``TranslatableMixin`` API (``self._tr(...)``, - ``self._translate(...)``) and a ``self._record_data`` list holding the - last recording. - """ - if TYPE_CHECKING: - # Declared, never defined: the widget this mixin is mixed into owns - # every one of these. The block is stripped at runtime, so nothing - # here can shadow what the host actually binds. - _tr: Callable[..., Any] - _translate: Callable[[str], str] +class RecordTab(TranslatableMixin, QWidget): + """Owns playback and view state; the shared recorder outlives this page.""" - def _build_record_tab(self) -> QWidget: - tab = QWidget() - layout = QVBoxLayout() + def __init__(self, parent=None): + super().__init__(parent) + self._tr_init() + self._record_data: list = [] + layout = QVBoxLayout(self) # Record/playback/save/load all run from the Actions menu. self._record_status_key = "record_idle" @@ -62,11 +58,14 @@ def _build_record_tab(self) -> QWidget: self.record_list_text = QTextEdit() self.record_list_text.setReadOnly(True) layout.addWidget(self.record_list_text) - tab.setLayout(layout) - self._playback_runs = TabTask(as_widget(self)) + self._playback_runs = TabTask(self) self._playback_runs.error.connect(self._on_playback_error) self._playback_runs.finished.connect(self._on_playback_finished) - return tab + self._work = TabTask(self) + self._work.result.connect(self._on_result) + self._work.error.connect(self._on_playback_error) + self._work.finished.connect(self.sync_with_engine) + self.sync_with_engine() def _apply_record_status_label(self) -> None: if hasattr(self, "record_status_label"): @@ -75,33 +74,45 @@ def _apply_record_status_label(self) -> None: + self._translate(self._record_status_key), ) - def _record_retranslate(self) -> None: + def retranslate(self) -> None: + super().retranslate() self._apply_record_status_label() + def _translate(self, key: str) -> str: + return _t(key) + + def sync_with_engine(self) -> None: + state = getattr(auto_control_record.recorder, "is_recording", None) + self._record_status_key = ( + "task_running" if self._work.running else + "record_playing" if self._playback_runs.running else + "record_recording" if state is True else + "record_idle" if state is False else "record_unknown" + ) + self._apply_record_status_label() + + def showEvent(self, event) -> None: + self.sync_with_engine() + super().showEvent(event) + + def _start_work(self, work: Callable[[], object], *, tag: str = "") -> None: + self._work.start(work, tag=tag) + self.sync_with_engine() + def _start_record(self): - try: - if not record(): - # record() logs its failure and returns False; the status - # said "Recording..." while nothing was recorded. - QMessageBox.warning(as_widget(self), "Error", "Recording could not start; see the log") - return - self._record_status_key = "record_recording" - self._apply_record_status_label() - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + self._start_work(_start_recording, tag="start") def _stop_record(self): - try: - self._record_data = stop_record() or [] - self._record_status_key = "record_idle" - self._apply_record_status_label() - self.record_list_text.setText(json.dumps(self._record_data, indent=2, ensure_ascii=False)) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + self._start_work(stop_record, tag="data") + + def _on_result(self, result: object) -> None: + if self._work.tag == "data" and isinstance(result, list): + self._record_data = result + self.record_list_text.setText(json.dumps(result, indent=2, ensure_ascii=False)) def _playback_record(self): if not self._record_data: - QMessageBox.warning(as_widget(self), "Warning", "No recorded data") + QMessageBox.warning(self, "Warning", "No recorded data") return # The worker gets its own copy: loading or recording again while the # playback runs must not change the list under it. @@ -117,28 +128,35 @@ def _stop_playback(self) -> None: def _on_playback_error(self, error: object) -> None: if not was_stopped(error): - QMessageBox.warning(as_widget(self), "Error", str(error)) + QMessageBox.warning(self, "Error", str(error)) def _on_playback_finished(self) -> None: - self._record_status_key = "record_idle" - self._apply_record_status_label() + self.sync_with_engine() def _save_record(self): try: if not self._record_data: - QMessageBox.warning(as_widget(self), "Warning", "No recorded data") + QMessageBox.warning(self, "Warning", "No recorded data") return - path, _ = QFileDialog.getSaveFileName(as_widget(self), _t("save_record"), "", _JSON_FILE_FILTER) + path, _ = QFileDialog.getSaveFileName(self, _t("save_record"), "", _JSON_FILE_FILTER) if path: - write_action_json(path, self._record_data) + self._start_work(functools.partial(write_action_json, path, copy.deepcopy(self._record_data))) except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + QMessageBox.warning(self, "Error", str(error)) def _load_record(self): try: - path, _ = QFileDialog.getOpenFileName(as_widget(self), _t("load_record"), "", _JSON_FILE_FILTER) + path, _ = QFileDialog.getOpenFileName(self, _t("load_record"), "", _JSON_FILE_FILTER) if path: - self._record_data = read_action_json(path) - self.record_list_text.setText(json.dumps(self._record_data, indent=2, ensure_ascii=False)) + self._start_work(functools.partial(read_action_json, path), tag="data") except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - QMessageBox.warning(as_widget(self), "Error", str(error)) + QMessageBox.warning(self, "Error", str(error)) + + def menu_actions(self) -> list[tuple[str, Callable]]: + return [("start_record", self._start_record), ("stop_record", self._stop_record), + ("playback", self._playback_record), ("stop_playback", self._stop_playback), + ("save_record", self._save_record), ("load_record", self._load_record)] + + def dispose(self) -> None: + self._playback_runs.stop() + self._work.stop() diff --git a/je_auto_control/gui/_script_tab.py b/je_auto_control/gui/_script_tab.py index 2351dd0ab..b7c37a163 100644 --- a/je_auto_control/gui/_script_tab.py +++ b/je_auto_control/gui/_script_tab.py @@ -1,4 +1,4 @@ -"""Script-executor tab builder (extracted mixin). +"""Independent script-executor panel with owned background runs. The three execute commands run the action list off the GUI thread, one run at a time, as a stoppable executor run: the window stays responsive while a @@ -9,7 +9,7 @@ import json from contextlib import nullcontext -from typing import TYPE_CHECKING, Any, Callable, ContextManager +from typing import Any, Callable, ContextManager from PySide6.QtWidgets import ( QFileDialog, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, @@ -17,10 +17,9 @@ ) from je_auto_control.gui._tab_task import TabTask, was_stopped -from je_auto_control.gui._qt_typed import as_widget +from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.manual_run_controls import ManualRunControls, _requested_manual_run -from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.executor.action_executor import execute_action, execute_files from je_auto_control.utils.file_process.get_dir_file_list import get_dir_files_as_list from je_auto_control.utils.json.json_file import ( @@ -53,24 +52,14 @@ def _run_script_text(text: str, capture: Callable[[], ContextManager[object]] = return execute_action(json.loads(text)) -class ScriptTabMixin: - """Provides the script-executor tab builder/handlers. +class ScriptTab(TranslatableMixin, QWidget): + """Own script inputs, manual capture settings and a stoppable background run.""" - Host widget must expose the ``TranslatableMixin`` API (``self._tr(...)``). - """ - - if TYPE_CHECKING: - # Declared, never defined: the widget this mixin is mixed into owns - # every one of these. The block is stripped at runtime, so nothing - # here can shadow what the host actually binds. - _tr: Callable[..., Any] - - def _build_script_tab(self) -> QWidget: - tab = QWidget() - layout = QVBoxLayout() - - # Load/execute commands run from the Actions menu; the tab keeps - # only the path inputs, the editor, and the result view. + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._tr_init() + self._status_key = "" + layout = QVBoxLayout(self) file_h = QHBoxLayout() file_h.addWidget(self._tr(QLabel(), "file_path_label")) self.script_path_input = QLineEdit() @@ -94,23 +83,28 @@ def _build_script_tab(self) -> QWidget: self.script_result_text = QTextEdit() self.script_result_text.setReadOnly(True) layout.addWidget(self.script_result_text) - tab.setLayout(layout) - self._script_runs = TabTask(as_widget(self)) + self._loads = TabTask(self) + self._loads.result.connect(self._loaded_script) + self._loads.error.connect(self._load_error) + self._script_runs = TabTask(self) self._script_runs.result.connect(self._show_script_result) self._script_runs.error.connect(self._show_script_error) - return tab + self._script_runs.finished.connect(self._on_finished) def _start_script_run(self, work: Callable[[], Any]) -> None: """Run ``work`` as this tab's one stoppable script run.""" if not self._script_runs.start_script(work): self.script_result_text.setText(_t("task_busy")) return - self.script_result_text.setText(_t("task_running")) + self._status_key = "task_running" + self.script_result_text.setText(_t(self._status_key)) def _show_script_result(self, result: object) -> None: + self._status_key = "" self.script_result_text.setText(json.dumps(result, indent=2, default=str, ensure_ascii=False)) def _show_script_error(self, error: object) -> None: + self._status_key = "" if was_stopped(error): self.script_result_text.setText(_t("task_stopped")) return @@ -118,18 +112,26 @@ def _show_script_error(self, error: object) -> None: def _stop_script(self) -> None: """Ask the running script to stop; it ends at its next checkpoint.""" - if self._script_runs.stop(): - self.script_result_text.setText(_t("task_stopping")) + if self._script_runs.running: + self._status_key = "task_stopping" + self.script_result_text.setText(_t(self._status_key)) + self._script_runs.stop() - def _browse_script(self): - path, _ = QFileDialog.getOpenFileName(as_widget(self), _t("load_script"), "", _JSON_FILE_FILTER) + def _browse_script(self) -> None: + path, _ = QFileDialog.getOpenFileName(self, _t("load_script"), "", _JSON_FILE_FILTER) if path: + self.load_script(path) + + def load_script(self, path: str) -> None: + """Load a chosen file without starting execution.""" + if self._loads.start(functools.partial(read_action_json, path)): self.script_path_input.setText(path) - try: - data = read_action_json(path) - self.script_editor.setText(json.dumps(data, indent=2, ensure_ascii=False)) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.script_result_text.setText(f"Error loading: {error}") + + def _loaded_script(self, data: object) -> None: + self.script_editor.setText(json.dumps(data, indent=2, ensure_ascii=False)) + + def _load_error(self, error: object) -> None: + self.script_result_text.setText(f"Error loading: {error}") def _execute_script(self): path = self.script_path_input.text() @@ -139,7 +141,7 @@ def _execute_script(self): self._start_script_run(functools.partial(_run_script_file, path, capture)) def _browse_script_dir(self): - path = QFileDialog.getExistingDirectory(as_widget(self), _t("execute_dir_label")) + path = QFileDialog.getExistingDirectory(self, _t("execute_dir_label")) if path: self.script_dir_input.setText(path) @@ -156,3 +158,26 @@ def _execute_manual_script(self): capture = _requested_manual_run(getattr(self, "script_history_controls", None), source_id="gui.editor", script_path="") self._start_script_run(functools.partial(_run_script_text, text, capture)) + + def _on_finished(self) -> None: + if self._status_key in {"task_running", "task_stopping"}: + self._status_key = "task_stopped" + self.script_result_text.setText(_t(self._status_key)) + + def menu_actions(self) -> list[tuple[str, Callable[[], object]]]: + """Expose loading, execution and Stop through Actions.""" + return [("load_script", self._browse_script), ("execute_script", self._execute_script), + ("menu_choose_script_dir", self._browse_script_dir), ("execute_dir", self._execute_dir), + ("execute_editor_script", self._execute_manual_script), ("task_stop", self._stop_script)] + + def retranslate(self) -> None: + """Refresh labels and transient status while preserving output.""" + super().retranslate() + self.script_history_controls.retranslate() + if self._status_key: + self.script_result_text.setText(_t(self._status_key)) + + def dispose(self) -> None: + """Stop this page's run; its controller discards outcomes after destruction.""" + self._script_runs.stop() + self._loads.stop() diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index e44c4527c..b0c50b603 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -789,6 +789,7 @@ "save_record": "Save to JSON", "load_record": "Load JSON", "record_status": "Status:", + "record_unknown": "Unknown", "record_idle": "Idle", "record_recording": "Recording...", "record_list_label": "Recorded Actions:", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index a22bf1e94..d2f1c3e3a 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -683,6 +683,7 @@ "save_record": "JSON 保存", "load_record": "JSON 読込", "record_status": "状態:", + "record_unknown": "不明", "record_idle": "待機", "record_recording": "記録中...", "record_list_label": "記録済みアクション:", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 04c1c34b1..2f0df06ec 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -650,6 +650,7 @@ "save_record": "保存为 JSON", "load_record": "载入 JSON", "record_status": "状态:", + "record_unknown": "未知", "record_idle": "闲置", "record_recording": "录制中...", "record_list_label": "已录制动作:", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index 0f43b45fa..e67dacc9e 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -657,6 +657,7 @@ "save_record": "儲存為 JSON", "load_record": "載入 JSON", "record_status": "狀態:", + "record_unknown": "未知", "record_idle": "閒置", "record_recording": "錄製中...", "record_list_label": "已錄製動作:", diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index 608ab8572..13ea5cba2 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -1,24 +1,19 @@ """Workspace widget: owns the tab bar and the registry of every tab it can open.""" -import json from typing import Any, Dict, List, Optional -from PySide6.QtCore import QTimer, Signal, QObject +from PySide6.QtCore import Signal, QObject from PySide6.QtGui import QKeyEvent, Qt from PySide6.QtWidgets import ( QWidget, QVBoxLayout, QLabel, ) -from je_auto_control.gui._auto_click_tab import AutoClickTabMixin +from je_auto_control.gui._tab_task import stop_all_script_runs from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._record_tab import RecordTabMixin -from je_auto_control.gui._script_tab import ScriptTabMixin from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.tab_registry import ( TAB_SPECS, MenuActions, TabEntry, TabRegistry, WidgetFactory, lazy_factory, ) from je_auto_control.gui.workspace import ScrollableTabs -from je_auto_control.utils.exception.exceptions import AutoControlException -from je_auto_control.utils.json.json_file import read_action_json # Kept under its old name: tests and embedders read ``_tab_entries`` rows as this. _TabEntry = TabEntry @@ -33,8 +28,7 @@ class _WorkerSignals(QObject): # Main Widget # ============================================================================= class AutoControlGUIWidget( - TranslatableMixin, AutoClickTabMixin, - RecordTabMixin, ScriptTabMixin, + TranslatableMixin, QWidget, ): """Owns the QTabWidget and exposes show/hide/list APIs for the menu bar.""" @@ -76,45 +70,10 @@ def __init__(self, parent=None): self.tabs.currentChanged.connect(self._on_current_tab_changed) - self.timer = QTimer() - self.repeat_count = 0 - self.repeat_max = 0 - self._record_data = [] def _own_tab_builders(self) -> Dict[str, Any]: - """Tabs this widget builds itself: ``key -> (builder, menu actions)``. - - The mixin tabs are built now, not on first open: their builders create - attributes other slots read (``script_path_input``, the record status - label), and they are plain forms with nothing running behind them. - """ - return { - "auto_click": (self._build_auto_click_tab(), ( - ("start", self._start_auto_click), - ("stop", self._stop_auto_click), - ("get_position", self._get_mouse_pos), - ("hotkey_send", self._send_hotkey), - ("write_send", self._send_write), - ("scroll_send", self._send_scroll), - )), - "record": (self._build_record_tab(), ( - ("start_record", self._start_record), - ("stop_record", self._stop_record), - ("playback", self._playback_record), - ("stop_playback", self._stop_playback), - ("save_record", self._save_record), - ("load_record", self._load_record), - )), - "script": (self._build_script_tab(), ( - ("load_script", self._browse_script), - ("execute_script", self._execute_script), - ("menu_choose_script_dir", self._browse_script_dir), - ("execute_dir", self._execute_dir), - ("execute_editor_script", self._execute_manual_script), - ("task_stop", self._stop_script), - )), - "remote_desktop": (self._build_remote_desktop_tab, ()), - } + """Remote Desktop keeps its existing optional-dependency fallback.""" + return {"remote_desktop": (self._build_remote_desktop_tab, ())} @staticmethod def _build_remote_desktop_tab() -> QWidget: @@ -298,7 +257,7 @@ def _on_tab_close_requested(self, index: int) -> None: return def close_tab(self, key: str) -> None: - """Release a feature; keep legacy forms and Remote Desktop reusable. + """Release a feature; keep Remote Desktop reusable. Unlike ``hide_tab``, closing a feature discards its local UI state and schedules cleanup of subscriptions and timers. Reopening rebuilds it. @@ -325,7 +284,7 @@ def retranslate(self) -> None: self.tabs.setTabText( index, language_wrapper.translate(entry.title_key, entry.title_key), ) - self._retranslate_core_tabs() + TranslatableMixin.retranslate(self) # Child class tabs get their own retranslate if they implement one. for entry in self._built_entries(): callback = getattr(entry.widget, "retranslate", None) @@ -335,34 +294,22 @@ def retranslate(self) -> None: except (RuntimeError, AttributeError): continue - def _retranslate_core_tabs(self) -> None: - """Relabel retained core forms and their optional manual capture controls.""" - TranslatableMixin.retranslate(self) - capture = getattr(self, "script_history_controls", None) - if capture is not None: - capture.retranslate() - for name in ("_auto_click_retranslate", "_record_retranslate"): - if hasattr(self, name): - getattr(self, name)() - def open_script_file(self, path: str) -> None: """Load a JSON script into the Script Executor tab and focus it.""" - entry = self._find_entry("script") - if entry is not None and not self._is_open(entry): - self.show_tab("script") - self.script_path_input.setText(path) - try: - data = read_action_json(path) - self.script_editor.setText(json.dumps(data, indent=2, ensure_ascii=False)) - except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: - self.script_result_text.setText(f"Error loading: {error}") - return - if entry is not None: - self.tabs.setCurrentWidget(entry.widget) + if self.activate_tab("script"): + entry = self._find_entry("script") + if entry is not None: + entry.widget.load_script(path) # ========================================================================= # Global keyboard shortcut: Ctrl+4 to stop # ========================================================================= + def _stop_auto_click(self) -> None: + entry = self._find_entry("auto_click") + if entry is not None and entry.built: + entry.widget.dispose() + stop_all_script_runs() + def keyPressEvent(self, event: QKeyEvent): if event.modifiers() == Qt.KeyboardModifier.ControlModifier and event.key() == Qt.Key.Key_4: self._stop_auto_click() diff --git a/je_auto_control/gui/tab_registry.py b/je_auto_control/gui/tab_registry.py index ca4e48929..e5d67fb14 100644 --- a/je_auto_control/gui/tab_registry.py +++ b/je_auto_control/gui/tab_registry.py @@ -138,17 +138,17 @@ def close(self, key: str) -> None: # Registration order: it is the order of the View > Tabs menu, of the # navigation panel inside each category, and of the tab bar. A spec without a -# module is one the main widget builds itself (its mixin tabs, and Remote -# Desktop, which needs an optional extra and falls back to a placeholder). +# module is built by the main widget: Remote Desktop needs an optional extra +# and falls back to a placeholder. TAB_SPECS: Tuple[TabSpec, ...] = ( - TabSpec("auto_click", "tab_auto_click", "core"), + TabSpec("auto_click", "tab_auto_click", "core", f"{_GUI}._auto_click_tab", "AutoClickTab"), TabSpec("screenshot", "tab_screenshot", "core", f"{_GUI}._screenshot_tab", "ScreenshotTab"), TabSpec("image_detect", "tab_image_detect", "core", f"{_GUI}._image_detect_tab", "ImageDetectionTab"), - TabSpec("record", "tab_record", "core", default_visible=True), + TabSpec("record", "tab_record", "core", f"{_GUI}._record_tab", "RecordTab", default_visible=True), TabSpec("script_builder", "tab_script_builder", "core", f"{_GUI}.script_builder", "ScriptBuilderTab", default_visible=True), TabSpec("flow_editor", "tab_flow_editor", "editing", f"{_GUI}.flow_editor", "FlowEditorTab"), - TabSpec("script", "tab_script", "editing"), + TabSpec("script", "tab_script", "editing", f"{_GUI}._script_tab", "ScriptTab"), TabSpec("recording_editor", "tab_recording_editor", "editing", f"{_GUI}.recording_editor_tab", "RecordingEditorTab"), TabSpec("variables", "tab_variables", "editing", f"{_GUI}.variables_tab", "VariablesTab"), diff --git a/je_auto_control/linux_with_x11/listener/x11_linux_listener.py b/je_auto_control/linux_with_x11/listener/x11_linux_listener.py index 00c594d62..20275e2c9 100644 --- a/je_auto_control/linux_with_x11/listener/x11_linux_listener.py +++ b/je_auto_control/linux_with_x11/listener/x11_linux_listener.py @@ -241,3 +241,10 @@ def x11_linux_stop_record() -> Queue: """Stop queue insertion; stopping before first use acquires no resources.""" with _listener_lock: return Queue() if _LISTENER is None else _LISTENER.stop_record() + + +def x11_linux_is_recording() -> bool: + """Inspect existing listener state without starting a listener or native query.""" + listener = _LISTENER + return (listener is not None and not listener.closed.is_set() + and listener.failure is None and listener.handler.record_flag) diff --git a/je_auto_control/linux_with_x11/record/x11_linux_record.py b/je_auto_control/linux_with_x11/record/x11_linux_record.py index 3c36be846..fd7588fe2 100644 --- a/je_auto_control/linux_with_x11/record/x11_linux_record.py +++ b/je_auto_control/linux_with_x11/record/x11_linux_record.py @@ -15,6 +15,7 @@ from je_auto_control.linux_with_x11.listener.x11_linux_listener import ( x11_linux_record, + x11_linux_is_recording, x11_linux_stop_record, ) @@ -42,6 +43,11 @@ def __init__(self): self.record_queue: Queue | None = None self.result_queue: Queue | None = None + @property + def is_recording(self) -> bool: + """Report cached listener capture state; this does not test native health.""" + return x11_linux_is_recording() + def record(self) -> None: """ Start recording events diff --git a/je_auto_control/osx/listener/osx_listener.py b/je_auto_control/osx/listener/osx_listener.py index b680e8703..429145344 100644 --- a/je_auto_control/osx/listener/osx_listener.py +++ b/je_auto_control/osx/listener/osx_listener.py @@ -118,6 +118,13 @@ def __init__(self, max_events: int = MAX_EVENTS) -> None: self._thread: Optional[threading.Thread] = None self._tap: Any = None # the CFMachPort from CGEventTapCreate, re-enabled on timeout + @property + def is_recording(self) -> bool: + """Report retained capture state without probing native hook health.""" + thread = self._thread + return (thread is not None and thread.is_alive() + and self._tap is not None and not self._stop.is_set() and self.error is None) + # -- public ------------------------------------------------------------ def start(self) -> None: """Create the tap and record. Raises if the tap cannot be created.""" diff --git a/je_auto_control/utils/input_macro/recorder_base.py b/je_auto_control/utils/input_macro/recorder_base.py index 5de5278e3..fc105a5dd 100644 --- a/je_auto_control/utils/input_macro/recorder_base.py +++ b/je_auto_control/utils/input_macro/recorder_base.py @@ -99,6 +99,14 @@ def __init__(self) -> None: self.result_queue: Optional[Queue] = None self._kinds: Tuple[str, ...] = ALL_KINDS + @property + def is_recording(self) -> Optional[bool]: + """Cached hook state, or unknown for a custom hook without status support.""" + if self.hook is None: + return False + state = getattr(self.hook, "is_recording", None) + return state if isinstance(state, bool) else None + def new_hook(self) -> Any: """Return a fresh, unstarted platform hook. Backends override this.""" raise NotImplementedError diff --git a/je_auto_control/windows/record/win32_input_hook.py b/je_auto_control/windows/record/win32_input_hook.py index 0618e426c..fb7970606 100644 --- a/je_auto_control/windows/record/win32_input_hook.py +++ b/je_auto_control/windows/record/win32_input_hook.py @@ -101,6 +101,11 @@ def __init__(self, max_events: int = MAX_EVENTS) -> None: # still calls that address and the process dies. self._procs: List[Any] = [] + @property + def is_recording(self) -> bool: + """Report retained capture state without probing native hook health.""" + return bool(self._hooks) and bool(self._thread_id) and self.error is None + # -- public ------------------------------------------------------------ def start(self) -> None: """Install the hooks and begin recording. Raises if they cannot be set.""" diff --git a/test/unit_test/headless/_tab_hosts.py b/test/unit_test/headless/_tab_hosts.py index 64b4d534a..d88ca7267 100644 --- a/test/unit_test/headless/_tab_hosts.py +++ b/test/unit_test/headless/_tab_hosts.py @@ -1,38 +1,17 @@ -"""Small real widgets that host the main window's tab mixins. - -The script and record tabs are mixins of ``AutoControlGUIWidget``. Their run -slots start work off the GUI thread and receive its outcome through signals, -so a ``SimpleNamespace`` stub can no longer stand in for ``self``; building -the whole main window for one slot would be far too much. These hosts carry -exactly what one mixin needs. -""" +"""Standalone core panels used by focused GUI tests.""" from typing import Optional -from PySide6.QtWidgets import QWidget - -from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._record_tab import RecordTabMixin -from je_auto_control.gui._script_tab import ScriptTabMixin -from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper +from je_auto_control.gui._record_tab import RecordTab +from je_auto_control.gui._script_tab import ScriptTab -class ScriptHost(TranslatableMixin, ScriptTabMixin, QWidget): +class ScriptHost(ScriptTab): """The Script tab alone.""" - def __init__(self) -> None: - super().__init__() - self._tr_init() - self.page = self._build_script_tab() - -class RecordHost(TranslatableMixin, RecordTabMixin, QWidget): - """The Record tab alone, with ``record_data`` as the last recording.""" +class RecordHost(RecordTab): + """The Record tab seeded with a previous recording.""" def __init__(self, record_data: Optional[list] = None) -> None: super().__init__() - self._tr_init() self._record_data = list(record_data or []) - self.page = self._build_record_tab() - - def _translate(self, key: str) -> str: - return language_wrapper.translate(key, key) diff --git a/test/unit_test/headless/test_actions_menu_gui.py b/test/unit_test/headless/test_actions_menu_gui.py index a525d6d3f..78fb11b27 100644 --- a/test/unit_test/headless/test_actions_menu_gui.py +++ b/test/unit_test/headless/test_actions_menu_gui.py @@ -70,7 +70,10 @@ def entry_actions(entry): record_entry = next(e for e in widget._tab_entries if e.key == "record") widget.tabs.setCurrentWidget(record_entry.widget) report["record_menu_matches"] = ( - widget.current_tab_menu_actions() == list(record_entry.actions) + widget.current_tab_menu_actions() == entry_actions(record_entry) + and [key for key, _ in widget.current_tab_menu_actions()] == [ + "start_record", "stop_record", "playback", "stop_playback", "save_record", "load_record", + ] ) widget.show_tab("variables") diff --git a/test/unit_test/headless/test_core_panel_ownership.py b/test/unit_test/headless/test_core_panel_ownership.py new file mode 100644 index 000000000..8632db608 --- /dev/null +++ b/test/unit_test/headless/test_core_panel_ownership.py @@ -0,0 +1,131 @@ +"""Core-panel ownership with fake input, recording and script services only.""" +import threading +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import QCoreApplication, QEvent +from PySide6.QtWidgets import QApplication, QMessageBox + +from headless._qt_settle import pump_until, settle +from je_auto_control.gui import _auto_click_tab as auto +from je_auto_control.gui import _record_tab as recording +from je_auto_control.gui import _script_tab as script +from je_auto_control.gui.tab_registry import TabEntry, TabRegistry +from je_auto_control.utils.input_macro.recorder_base import InputRecorder + + +@pytest.fixture(autouse=True) +def app(monkeypatch): + application = QApplication.instance() or QApplication([]) + monkeypatch.setattr(QMessageBox, "warning", lambda *args: None) + yield application + QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) + + +@pytest.mark.parametrize("panel", [auto.AutoClickTab, recording.RecordTab, script.ScriptTab]) +def test_close_rebuilds_core_panel_and_its_actions(panel): + entry = TabEntry("core", "core", panel) + registry = TabRegistry([entry]) + old = registry.open("core") + assert old.menu_actions() + registry.close("core") + assert not entry.built + new = registry.open("core") + assert new is not old + assert all(action.__self__ is new for _, action in new.menu_actions()) + registry.close("core") + + +def test_cancel_double_click_stops_second_input_and_does_not_queue_ticks(monkeypatch): + entered, release, exited = threading.Event(), threading.Event(), threading.Event() + calls = [] + + def click(*args): + calls.append(args) + entered.set() + try: + assert release.wait(5) + finally: + exited.set() + + monkeypatch.setattr(auto, "click_mouse", click) + panel = auto.AutoClickTab() + panel.click_type_combo.setCurrentIndex(1) + panel.cursor_x_input.setText("41") + panel._do_click() + try: + assert entered.wait(5) + panel.cursor_x_input.setText("99") + for _ in range(5): + panel._timer_tick() + panel.dispose() + finally: + release.set() + assert exited.wait(5) + assert settle(panel._task, "task") + assert len(calls) == 1 + assert calls[0][1] == 41 + assert not panel.timer.isActive() + panel.deleteLater() + + +def test_record_close_keeps_service_and_reopen_reads_actual_state(monkeypatch): + state = SimpleNamespace(is_recording=True) + stopped = [] + monkeypatch.setattr(recording.auto_control_record, "recorder", state) + monkeypatch.setattr(recording, "stop_record", lambda: stopped.append(True)) + first = recording.RecordTab() + assert first._record_status_key == "record_recording" + first.dispose() + first.deleteLater() + assert stopped == [] + second = recording.RecordTab() + assert second._record_status_key == "record_recording" + state.is_recording = False + second.sync_with_engine() + assert second._record_status_key == "record_idle" + monkeypatch.setattr(recording.auto_control_record, "recorder", object()) + second.sync_with_engine() + assert second._record_status_key == "record_unknown" + second.deleteLater() + + +def test_late_record_load_cannot_update_reopened_panel(monkeypatch): + entered, release, exited = threading.Event(), threading.Event(), threading.Event() + + def read(_path): + entered.set() + try: + assert release.wait(5) + return [["AC_fake"]] + finally: + exited.set() + + monkeypatch.setattr(recording, "read_action_json", read) + monkeypatch.setattr(recording.QFileDialog, "getOpenFileName", lambda *args: ("fake.json", "")) + entry = TabEntry("record", "record", recording.RecordTab) + registry = TabRegistry([entry]) + old = registry.open("record") + old._load_record() + try: + assert entered.wait(5) + registry.close("record") + new = registry.open("record") + finally: + release.set() + assert exited.wait(5) + assert pump_until(lambda: not old._work.running) + assert new.record_list_text.toPlainText() == "" + assert new._record_data == [] + registry.close("record") + + +def test_recorder_status_reports_unknown_custom_hooks_without_starting(): + recorder = InputRecorder() + assert recorder.is_recording is False + recorder.hook = object() + assert recorder.is_recording is None + recorder.hook = SimpleNamespace(is_recording=True) + assert recorder.is_recording is True + recorder.hook.is_recording = False + assert recorder.is_recording is False diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index 0eae0060b..05d3cfebb 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -16,8 +16,8 @@ from je_auto_control.gui.tab_registry import TAB_SPECS, TabEntry, lazy_factory ROOT = pathlib.Path(__file__).resolve().parents[3] -# Built by the main widget itself: its mixin tabs, and Remote Desktop's placeholder fallback. -OWN_TABS = {"auto_click", "record", "script", "remote_desktop"} +# Remote Desktop retains the main widget's optional-dependency fallback. +OWN_TABS = {"remote_desktop"} OPEN_AT_START = ["record", "script_builder", "remote_desktop"] @@ -90,6 +90,8 @@ def test_a_lazy_factory_imports_at_call_time(): "open_at_start": [row["key"] for row in widget.list_registered_tabs() if row["visible"]], "variables_imported_at_start": "je_auto_control.gui.variables_tab" in sys.modules, "presence_imported_at_start": "je_auto_control.gui.presence_tab" in sys.modules, + "auto_click_imported_at_start": "je_auto_control.gui._auto_click_tab" in sys.modules, + "script_imported_at_start": "je_auto_control.gui._script_tab" in sys.modules, "image_detect_imported_at_start": "je_auto_control.gui._image_detect_tab" in sys.modules, } widget.list_registered_tabs() @@ -140,6 +142,8 @@ def test_only_the_start_tabs_and_the_widgets_own_forms_are_built(report): assert not report["variables_imported_at_start"] assert not report["presence_imported_at_start"] assert not report["image_detect_imported_at_start"] + assert not report["auto_click_imported_at_start"] + assert not report["script_imported_at_start"] def test_listing_translating_and_hiding_build_nothing(report): diff --git a/test/unit_test/headless/test_gui_script_runs.py b/test/unit_test/headless/test_gui_script_runs.py index ae31cc20a..0a3a403e2 100644 --- a/test/unit_test/headless/test_gui_script_runs.py +++ b/test/unit_test/headless/test_gui_script_runs.py @@ -159,7 +159,7 @@ def test_ctrl_4_stops_every_running_script(script): def test_the_auto_click_stop_also_stops_scripts(script): - from je_auto_control.gui._auto_click_tab import AutoClickTabMixin + from je_auto_control.gui._auto_click_tab import AutoClickTab owner = QWidget() runs = TabTask(owner) errors = [] @@ -167,10 +167,8 @@ def test_the_auto_click_stop_also_stops_scripts(script): assert runs.start_script(lambda: executor.execute_action(_LONG)) assert script.entered.wait(_WAIT) - class _Host: - timer = QTimer() - - AutoClickTabMixin._stop_auto_click(_Host()) + panel = AutoClickTab() + panel._stop_auto_click() assert settle(runs, "task") assert errors assert was_stopped(errors[0]) diff --git a/test/unit_test/headless/test_gui_slots_menu_audit.py b/test/unit_test/headless/test_gui_slots_menu_audit.py index b504b4918..6760e6ea9 100644 --- a/test/unit_test/headless/test_gui_slots_menu_audit.py +++ b/test/unit_test/headless/test_gui_slots_menu_audit.py @@ -53,7 +53,7 @@ def test_a_zero_interval_is_refused(monkeypatch): monkeypatch.setattr(tab.QMessageBox, "warning", lambda *args: warned.append(args[-1])) stub = types.SimpleNamespace(interval_input=_Text("0"), timer=types.SimpleNamespace(start=lambda: started.append(1))) - tab.AutoClickTabMixin._start_auto_click(stub) + tab.AutoClickTab._start_auto_click(stub) assert warned assert not started @@ -155,10 +155,13 @@ def test_a_recording_that_does_not_start_is_reported(monkeypatch): warned = [] monkeypatch.setattr(tab.QMessageBox, "warning", lambda *args: warned.append(args[-1])) monkeypatch.setattr(tab, "record", lambda: False) - stub = types.SimpleNamespace(_record_status_key="record_idle", _apply_record_status_label=lambda: None) - tab.RecordTabMixin._start_record(stub) + _app() + stub = tab.RecordTab() + stub._start_record() + assert settle(stub._work, "task") assert warned - assert stub._record_status_key == "record_idle" + assert stub._record_status_key != "record_recording" + stub.deleteLater() def test_a_template_is_cropped_into_a_non_ascii_folder(monkeypatch, tmp_path): diff --git a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py index 2e01d194f..33d710cc2 100644 --- a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py +++ b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py @@ -24,10 +24,11 @@ from PySide6.QtCore import QEvent, QObject, Signal # noqa: E402 from PySide6.QtWidgets import ( # noqa: E402 - QApplication, QComboBox, QDialog, QLineEdit, QTabWidget, QTableWidget, QTableWidgetItem, - QTextEdit, QWidget, + QApplication, QComboBox, QDialog, QTabWidget, QTableWidget, QTableWidgetItem, + QWidget, ) +from headless._qt_settle import settle # noqa: E402 from je_auto_control.utils.exception.exceptions import ( # noqa: E402 AutoControlActionException, AutoControlScreenException, ImageNotFoundException, ) @@ -79,11 +80,17 @@ def test_open_script_shows_a_malformed_file(qapp, tmp_path): from je_auto_control.gui.main_widget import AutoControlGUIWidget bad = tmp_path / "bad.json" bad.write_text("[[", encoding="utf-8") + from je_auto_control.gui._script_tab import ScriptTab + panel = ScriptTab() + opened = [] fake = types.SimpleNamespace( - _find_entry=lambda key: None, script_path_input=QLineEdit(), - script_editor=QTextEdit(), script_result_text=QTextEdit()) + activate_tab=lambda key: opened.append(key) or True, + _find_entry=lambda key: types.SimpleNamespace(widget=panel)) AutoControlGUIWidget.open_script_file(fake, str(bad)) - assert fake.script_result_text.toPlainText().startswith("Error loading") + assert opened == ["script"] + assert settle(panel._loads, "task") + assert panel.script_result_text.toPlainText().startswith("Error loading") + panel.deleteLater() def test_image_detection_shows_no_match(qapp, monkeypatch): diff --git a/test/unit_test/headless/test_input_hook_timeline.py b/test/unit_test/headless/test_input_hook_timeline.py index afdcb8850..bf28eb2b5 100644 --- a/test/unit_test/headless/test_input_hook_timeline.py +++ b/test/unit_test/headless/test_input_hook_timeline.py @@ -213,3 +213,17 @@ def test_wiring(): assert "ac_record_stop_timeline" in {t.name for t in build_default_tool_registry()} assert hasattr(ac, "stop_record_timeline") assert "stop_record_timeline" in ac.__all__ + + +def test_hook_status_reads_retained_state_without_native_probe(): + from je_auto_control.windows.record.win32_input_hook import Win32InputHook + hook = Win32InputHook() + assert hook.is_recording is False + hook._hooks = [object(), object()] + hook._thread_id = 1 + assert hook.is_recording is True + hook.error = "failed" + assert hook.is_recording is False + hook.error = None + hook._hooks.clear() + assert hook.is_recording is False diff --git a/test/unit_test/headless/test_manual_history_gui.py b/test/unit_test/headless/test_manual_history_gui.py index 9795fa2e8..5b23a179e 100644 --- a/test/unit_test/headless/test_manual_history_gui.py +++ b/test/unit_test/headless/test_manual_history_gui.py @@ -11,7 +11,7 @@ import je_auto_control as ac from je_auto_control.gui.manual_run_controls import ManualRunControls -from je_auto_control.gui._script_tab import ScriptTabMixin +from je_auto_control.gui._script_tab import ScriptTab from je_auto_control.gui.script_builder.builder_tab import ScriptBuilderTab from je_auto_control.gui.script_builder.step_model import action_to_step from je_auto_control.utils.run_history import manual as manual_module @@ -59,7 +59,7 @@ def test_editor_capture_preserves_result_and_links_opted_in_owner(app, store, tm editor.setPlainText(json.dumps([["AC_set_var", {"name": "x", "value": 1}]])) host = _host(output, script_editor=editor, script_history_controls=controls) try: - ScriptTabMixin._execute_manual_script(host) + ScriptTab._execute_manual_script(host) assert json.loads(output.toPlainText()) assert len(ac.read_events(journal)) == 2 rows = store.list_runs() @@ -81,7 +81,7 @@ def test_file_execution_records_its_source_path(app, store, tmp_path): source, output = QLineEdit(str(script)), QTextEdit() host = _host(output, script_path_input=source, script_history_controls=controls) try: - ScriptTabMixin._execute_script(host) + ScriptTab._execute_script(host) assert store.list_runs()[0].script_path == str(script) assert json.loads(output.toPlainText()) finally: @@ -137,7 +137,7 @@ def test_directory_execution_records_one_batch_and_all_snapshots(app, store, tmp source, output = QLineEdit(str(directory)), QTextEdit() host = _host(output, script_dir_input=source, script_history_controls=controls) try: - ScriptTabMixin._execute_dir(host) + ScriptTab._execute_dir(host) assert len(json.loads(output.toPlainText())) == 2 assert len(store.list_runs()) == 1 assert len(ac.read_events(journal)) == 4 diff --git a/test/unit_test/headless/test_r3_gui_slot_exceptions.py b/test/unit_test/headless/test_r3_gui_slot_exceptions.py index b747a377b..0804cdedd 100644 --- a/test/unit_test/headless/test_r3_gui_slot_exceptions.py +++ b/test/unit_test/headless/test_r3_gui_slot_exceptions.py @@ -62,7 +62,6 @@ def test_builder_run_slot_surfaces_autocontrol_exception(monkeypatch): # --- Finding 6: main_widget record / script slots -------------------------- def test_playback_record_slot_surfaces_autocontrol_exception(monkeypatch): - import je_auto_control.gui.main_widget as mw import je_auto_control.gui._record_tab as rt warned = {} monkeypatch.setattr(rt.QMessageBox, "warning", @@ -72,7 +71,6 @@ def test_playback_record_slot_surfaces_autocontrol_exception(monkeypatch): _raiser(AutoControlExecuteActionException("boom")), ) from headless._tab_hosts import RecordHost - assert mw.AutoControlGUIWidget._playback_record is RecordHost._playback_record _app() host = RecordHost([["AC_ok"]]) host._playback_record() # must not raise @@ -81,7 +79,6 @@ def test_playback_record_slot_surfaces_autocontrol_exception(monkeypatch): def test_execute_script_slot_surfaces_autocontrol_exception(monkeypatch): - import je_auto_control.gui.main_widget as mw import je_auto_control.gui._script_tab as st captured = {} monkeypatch.setattr(st, "read_executable_action_json", lambda _p: [["AC_ok"]]) @@ -90,7 +87,6 @@ def test_execute_script_slot_surfaces_autocontrol_exception(monkeypatch): _raiser(AutoControlExecuteActionException("boom")), ) from headless._tab_hosts import ScriptHost - assert mw.AutoControlGUIWidget._execute_script is ScriptHost._execute_script _app() host = ScriptHost() host.script_path_input.setText("some.json") @@ -142,18 +138,15 @@ def test_do_click_stops_timer_on_backend_exception(monkeypatch): ac, "click_mouse", _raiser(AutoControlMouseException("no backend")), ) - stops = {"n": 0} - stub = types.SimpleNamespace( - click_type_combo=types.SimpleNamespace(currentIndex=lambda: 0), - mouse_radio=types.SimpleNamespace(isChecked=lambda: True), - mouse_button_combo=types.SimpleNamespace(currentText=lambda: "mouse_left"), - cursor_x_input=types.SimpleNamespace(text=lambda: "0"), - cursor_y_input=types.SimpleNamespace(text=lambda: "0"), - timer=types.SimpleNamespace(stop=lambda: stops.__setitem__("n", stops["n"] + 1)), - ) - - ac.AutoClickTabMixin._do_click(stub) # must not raise - assert stops["n"] == 1 # the failing auto-click QTimer was stopped + from PySide6.QtWidgets import QApplication + app = QApplication.instance() or QApplication([]) + panel = ac.AutoClickTab() + panel.timer.start(60000) + panel._do_click() + assert settle(panel._task, "task") + assert not panel.timer.isActive() + panel.deleteLater() + app.processEvents() # --- Finding 10: suite load-file tolerates a bad file ---------------------- diff --git a/test/unit_test/headless/test_recorder_status_snapshots.py b/test/unit_test/headless/test_recorder_status_snapshots.py new file mode 100644 index 000000000..02ea98fed --- /dev/null +++ b/test/unit_test/headless/test_recorder_status_snapshots.py @@ -0,0 +1,50 @@ +"""macOS status snapshots use fake thread state and a constants-only Quartz module.""" +import importlib.util +from pathlib import Path +import sys +from types import ModuleType, SimpleNamespace + +import je_auto_control + + +_QUARTZ_CONSTANTS = ( + "kCGEventLeftMouseDown", "kCGEventLeftMouseUp", "kCGEventRightMouseDown", + "kCGEventRightMouseUp", "kCGEventOtherMouseDown", "kCGEventOtherMouseUp", + "kCGEventFlagMaskCommand", "kCGEventFlagMaskShift", "kCGEventFlagMaskAlphaShift", + "kCGEventFlagMaskAlternate", "kCGEventFlagMaskControl", "kCGEventFlagMaskSecondaryFn", + "kCGEventKeyDown", "kCGEventKeyUp", "kCGEventFlagsChanged", "kCGEventScrollWheel", + "kCGEventTapDisabledByTimeout", "kCGEventTapDisabledByUserInput", +) + + +def test_stop_clearing_thread_during_status_read_is_safe(monkeypatch): + quartz = ModuleType("Quartz") + for value, name in enumerate(_QUARTZ_CONSTANTS): + setattr(quartz, name, value) + path = Path(je_auto_control.__file__).parent / "osx/listener/osx_listener.py" + spec = importlib.util.spec_from_file_location("_osx_status_under_test", path) + module = importlib.util.module_from_spec(spec) + with monkeypatch.context() as loading: + loading.setattr(sys, "platform", "darwin") + loading.setitem(sys.modules, "Quartz", quartz) + spec.loader.exec_module(module) + + class StoppingTap(module.OSXInputTap): + stop_during_read = False + + def __getattribute__(self, name): + value = super().__getattribute__(name) + if name == "_thread" and self.stop_during_read: + self.stop_during_read = False + self._thread = None + self._stop.set() + return value + + tap = StoppingTap() + assert tap.is_recording is False + tap._thread = SimpleNamespace(is_alive=lambda: True) + tap._tap = object() + assert tap.is_recording is True + tap.stop_during_read = True + assert tap.is_recording is False + assert tap._thread is None diff --git a/test/unit_test/headless/test_x11_lazy_startup.py b/test/unit_test/headless/test_x11_lazy_startup.py index b43c86540..38b1fa517 100644 --- a/test/unit_test/headless/test_x11_lazy_startup.py +++ b/test/unit_test/headless/test_x11_lazy_startup.py @@ -436,3 +436,29 @@ def refuse_start(*args, **kwargs): env.update(JE_AUTOCONTROL_LINUX_BACKEND=backend, JE_AUTOCONTROL_LINUX_DISPLAY_SERVER="x11") result = subprocess.run([sys.executable, "-c", script], env=env, capture_output=True, text=True, timeout=60) assert result.returncode == 0, result.stdout + result.stderr + + +def test_record_status_is_nonblocking_and_never_acquires_listener(x11, monkeypatch): + class RefuseLock: + def __enter__(self): + raise AssertionError("status must not wait on listener startup") + + def __exit__(self, *args): + return False + + monkeypatch.setattr(x11.listener, "_listener_lock", RefuseLock()) + assert x11.listener.x11_linux_is_recording() is False + listener = SimpleNamespace(closed=Event(), failure=None, + handler=SimpleNamespace(record_flag=True)) + monkeypatch.setattr(x11.listener, "_LISTENER", listener) + assert x11.listener.x11_linux_is_recording() is True + assert x11.recorder.x11_linux_recorder.is_recording is True + listener.handler.record_flag = False + assert x11.listener.x11_linux_is_recording() is False + listener.handler.record_flag = True + listener.failure = RuntimeError("listener stopped") + assert x11.listener.x11_linux_is_recording() is False + listener.failure = None + listener.closed.set() + assert x11.listener.x11_linux_is_recording() is False + assert x11.calls == [] From 6ff7d43a0fe03ac79dbeb0e8b122d60383c9fe15 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:54:09 +0800 Subject: [PATCH 019/161] Split MCP adapters into strict domain modules --- Progress.md | 1 - architecture.md | 6 +- architecture_explore.md | 25 +- docs/updates/2026-11.md | 6 + docs/updates/README.md | 1 + .../utils/mcp_server/tools/_factories.py | 511 +++--- .../utils/mcp_server/tools/_handlers.py | 2 +- .../tools/_handlers_accessibility_executor.py | 383 +++++ .../tools/_handlers_automation_executor.py | 236 +++ .../tools/_handlers_data_executor.py | 428 +++++ .../tools/_handlers_desktop_executor.py | 225 +++ .../tools/_handlers_executor_bridge.py | 1429 ----------------- .../mcp_server/tools/_handlers_locators.py | 2 +- .../tools/_handlers_mobile_executor.py | 135 ++ .../tools/_handlers_vision_executor.py | 564 +++++++ pyproject.toml | 6 + .../test_agent_executor_mcp_wiring.py | 2 +- .../headless/test_android_uiautomator.py | 2 +- test/unit_test/headless/test_drag_pacing.py | 4 +- .../headless/test_mcp_executor_adapters.py | 71 + test/verify/typing_strict_baseline.txt | 1 - 21 files changed, 2339 insertions(+), 1701 deletions(-) create mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_accessibility_executor.py create mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_automation_executor.py create mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_data_executor.py create mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_desktop_executor.py delete mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_executor_bridge.py create mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_mobile_executor.py create mode 100644 je_auto_control/utils/mcp_server/tools/_handlers_vision_executor.py create mode 100644 test/unit_test/headless/test_mcp_executor_adapters.py diff --git a/Progress.md b/Progress.md index abb224a12..656586b22 100644 --- a/Progress.md +++ b/Progress.md @@ -724,7 +724,6 @@ typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 | 檔案 | 行數 | 為何還沒拆 | | --- | ---: | --- | -| `utils/mcp_server/tools/_handlers_executor_bridge.py` | 1,429 | 純委派函式(函式內匯入後立即轉呼叫,沒有分支),不適用 flat data tables 豁免。需先定義領域邊界再拆分。 | **本質豁免(flat data tables)**:`utils/mcp_server/tools/_factories.py`、 `utils/executor/action_executor.py`、`gui/script_builder/command_schema.py`、 diff --git a/architecture.md b/architecture.md index bfd9838bd..355a142e6 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,9 @@ # AutoControl Architecture +MCP executor adapters are grouped by accessibility, automation, data, desktop, +mobile and vision. Factories bind the same tool schemas to these strict modules; +each adapter imports its executor function only when called. + Navigation handles optional Qt tree items through one iterator. Script fields are read and written through their concrete editor types, and trigger actions retain typed common arguments while checking missing table cells before use. @@ -754,7 +758,7 @@ wrapper/auto_control_record.record → OS listener (e.g. windows/record/win32_in 5. Optional MCP tool: factory in `utils/mcp_server/tools/_factories.py`, adapter in the themed handler module — `_handlers_input.py`, `_handlers_screen.py`, `_handlers_system.py`, `_handlers_runs.py`, `_handlers_scheduling.py`, `_handlers_remote.py`, `_handlers_locators.py`, `_handlers_operations.py`, - `_handlers_qa.py`, `_handlers_executor_bridge.py` (a three-line delegation to an executor function), or + `_handlers_qa.py`, the six `_handlers__executor.py` modules (lazy executor delegation), or `_handlers.py` for data, text and the WebRunner bridge. 6. GUI: thin widget in `gui/`, registered by one `TabSpec` row in `gui/tab_registry.py` (module and class name, so it is imported only when opened) with commands exposed through `menu_actions()`; strings in every diff --git a/architecture_explore.md b/architecture_explore.md index ab0757f01..aebad1ad7 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,500 | -| 程式碼總行數 | 229,250 | +| Python 模組總數(含周邊子專案) | 1,505 | +| 程式碼總行數 | 229,797 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -512,7 +512,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,207 行。 +> 14 個套件、約 52,754 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -526,7 +526,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 21,490 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,037 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 660 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | @@ -739,11 +739,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(21,490 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,037 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `tools/_factories.py` | 9,383 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | +| `tools/_factories.py` | 9,388 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | | `tools/_handlers.py` | 547 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | | `tools/_handlers_qa.py` | 619 | 同一種 adapter,QA 主題:斷言 DSL、資料驅動、SQL/PDF/郵件/HTTP 步驟、codegen、視覺回歸、狀態機、flaky 偵測與隔離、suite runner、無障礙稽核、裝置矩陣、媒體斷言。從 `_handlers.py` 依主題拆出的第一塊(750 行上限);兩者互不引用。 | | `tools/_handlers_input.py` | 221 | 同一種 adapter,輸入主題:滑鼠、鍵盤、虛擬手把(ViGEm)。 | @@ -765,7 +765,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_diagnostics.py` | 51 | 主動唯讀診斷 MCP;共用 report、request-owned 取消與進度,拒絕外部 token/授權資料。 | | `tools/_handlers_scheduling.py` | 200 | 同一種 adapter,排程主題:排程器、觸發器、熱鍵常駐。 | | `tools/_handlers_remote.py` | 66 | 同一種 adapter,遠端桌面的 host 與 viewer。 | -| `tools/_handlers_executor_bridge.py` | 1,429 | 252 個純委派(中位數 3 行,最長的 16 行全是參數簽章):每個都是 `from action_executor import _x` 再 `return _x(...)`,沒有分支邏輯。超過 750 行,理由記在 `Progress.md` 的豁免表(再切只能照 MCP 工廠領域分,會把同一種委派散進十幾個沒有語意邊界的檔)。 | +| `tools/_handlers_accessibility_executor.py` | 383 | 35 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | +| `tools/_handlers_automation_executor.py` | 236 | 33 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | +| `tools/_handlers_data_executor.py` | 428 | 70 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | +| `tools/_handlers_desktop_executor.py` | 225 | 35 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | +| `tools/_handlers_mobile_executor.py` | 135 | 10 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | +| `tools/_handlers_vision_executor.py` | 564 | 70 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_locators.py` | 436 | 同一種 adapter,定位主題:無障礙樹、智慧等待、自我修復、螢幕觀察、座標空間、視覺與 OCR、影像去重、元件倉庫、A/B 定位。 | | `tools/_handlers_operations.py` | 655 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | | `server.py` | 744 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、工具與 resource/prompt 處理器;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | @@ -1406,7 +1411,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,174 個 `test_*.py`/11,393 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,175 個 `test_*.py`/11,394 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1498,7 +1503,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | | `gui/` | 144 | 39,971 | -| `utils/mcp_server/` | 55 | 21,490 | +| `utils/mcp_server/` | 60 | 22,037 | | `utils/remote_desktop/` | 72 | 15,252 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | @@ -1518,7 +1523,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,488** | **228,505** | +| **總計** | **1,493** | **229,052** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 2e2bd0e67..329b6d417 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -772,3 +772,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Corrected the outstanding path-policy description: path-or-other checks absolute/existing paths and file URLs while retaining literals. Ambiguous relative paths, shell interpretation and nested free-form payloads remain outside its guarantee. - **Evidence:** Existing policy suite passed 54 cases against actual registry schemas and fake handlers. Platform symlink and real-client acceptance remain in Progress.md. + +## U-20261111-09 · 2026-11-11 · Split MCP executor adapters along strict domain boundaries · #done #mcp + +- **What:** Replaced the oversized bridge with six domain modules and migrated all private callers. Each module uses strict typing; the obsolete strict baseline row and size exemption were removed. Executor imports remain lazy. +- **Evidence:** Independent review authenticated the original snapshot and verified 253 function bodies/defaults/original annotations, 506 fake forwarding calls and 820 unchanged tool descriptors. Implementation passed 240 tests; independent review passed 61; integration with document and whole-package budget gates passed 88. Scoped three-target mypy and Ruff passed. No desktop or device commands executed. +- **Open items:** Remaining strict typing and full validation are tracked in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index 205c96e8d..729521078 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-09 | 2026-11-11 | Split MCP executor adapters along strict domain boundaries | #done #mcp | [2026-11](2026-11.md) | | U-20261111-08 | 2026-11-11 | Reconcile conditional MCP path checks with current evidence | #snapshot #mcp | [2026-11](2026-11.md) | | U-20261111-07 | 2026-11-11 | Release core panels while retaining shared recorder ownership | #done #gui | [2026-11](2026-11.md) | | U-20261111-06 | 2026-11-11 | Check navigation and editor widgets against real Qt types | #done #typing | [2026-11](2026-11.md) | diff --git a/je_auto_control/utils/mcp_server/tools/_factories.py b/je_auto_control/utils/mcp_server/tools/_factories.py index 93e3fe1c4..94361eac9 100644 --- a/je_auto_control/utils/mcp_server/tools/_factories.py +++ b/je_auto_control/utils/mcp_server/tools/_factories.py @@ -19,7 +19,12 @@ from je_auto_control.utils.mcp_server.tools import _handlers_qa as hq from je_auto_control.utils.mcp_server.tools import _handlers_operations as h_ops from je_auto_control.utils.mcp_server.tools import _handlers_locators as h_loc -from je_auto_control.utils.mcp_server.tools import _handlers_executor_bridge as h_exec +from je_auto_control.utils.mcp_server.tools import _handlers_accessibility_executor as h_accessibility_exec +from je_auto_control.utils.mcp_server.tools import _handlers_automation_executor as h_automation_exec +from je_auto_control.utils.mcp_server.tools import _handlers_data_executor as h_data_exec +from je_auto_control.utils.mcp_server.tools import _handlers_desktop_executor as h_desktop_exec +from je_auto_control.utils.mcp_server.tools import _handlers_mobile_executor as h_mobile_exec +from je_auto_control.utils.mcp_server.tools import _handlers_vision_executor as h_vision_exec from je_auto_control.utils.mcp_server.tools import _handlers_input as h_input from je_auto_control.utils.mcp_server.tools import _handlers_screen as h_screen from je_auto_control.utils.mcp_server.tools import _handlers_system as h_system @@ -1075,7 +1080,7 @@ def android_widget_tools() -> List[MCPTool]: "Returns {x1, y1, x2, y2}. Raises if no match " "within timeout_s."), input_schema=schema(selector_schema), - handler=h_exec.android_find_element, + handler=h_mobile_exec.android_find_element, annotations=READ_ONLY, ), MCPTool( @@ -1084,7 +1089,7 @@ def android_widget_tools() -> List[MCPTool]: "Returns {x, y} click centre. Driven by " "uiautomator2 so the daemon sees the press."), input_schema=schema(selector_schema), - handler=h_exec.android_click_element, + handler=h_mobile_exec.android_click_element, annotations=DESTRUCTIVE, ), MCPTool( @@ -1092,7 +1097,7 @@ def android_widget_tools() -> List[MCPTool]: description=("Return the device's current widget tree as " "an XML string."), input_schema=schema({"serial": {"type": "string"}}), - handler=h_exec.android_dump_hierarchy, + handler=h_mobile_exec.android_dump_hierarchy, annotations=READ_ONLY, ), ] @@ -1116,7 +1121,7 @@ def ios_tools() -> List[MCPTool]: "y": {"type": "integer"}, "url": {"type": "string"}, }, required=["x", "y"]), - handler=h_exec.ios_tap, + handler=h_mobile_exec.ios_tap, annotations=DESTRUCTIVE, ), MCPTool( @@ -1131,7 +1136,7 @@ def ios_tools() -> List[MCPTool]: "duration_s": {"type": "number"}, "url": {"type": "string"}, }, required=["x1", "y1", "x2", "y2"]), - handler=h_exec.ios_swipe, + handler=h_mobile_exec.ios_swipe, annotations=DESTRUCTIVE, ), MCPTool( @@ -1141,7 +1146,7 @@ def ios_tools() -> List[MCPTool]: "text": {"type": "string"}, "url": {"type": "string"}, }, required=["text"]), - handler=h_exec.ios_type, + handler=h_mobile_exec.ios_type, annotations=DESTRUCTIVE, ), MCPTool( @@ -1151,7 +1156,7 @@ def ios_tools() -> List[MCPTool]: "file_path": {"type": "string", "format": "path"}, "url": {"type": "string"}, }, required=["file_path"]), - handler=h_exec.ios_screenshot, + handler=h_mobile_exec.ios_screenshot, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -1159,21 +1164,21 @@ def ios_tools() -> List[MCPTool]: description=("Find an XCUITest element by name / class_name / " "predicate. Returns {x1, y1, x2, y2}."), input_schema=schema(selector_schema), - handler=h_exec.ios_find_element, + handler=h_mobile_exec.ios_find_element, annotations=READ_ONLY, ), MCPTool( name="ac_ios_click_element", description="Tap the first XCUITest element matching the selectors.", input_schema=schema(selector_schema), - handler=h_exec.ios_click_element, + handler=h_mobile_exec.ios_click_element, annotations=DESTRUCTIVE, ), MCPTool( name="ac_ios_dump_source", description="Return the XCUITest page source XML for the active app.", input_schema=schema({"url": {"type": "string"}}), - handler=h_exec.ios_dump_source, + handler=h_mobile_exec.ios_dump_source, annotations=READ_ONLY, ), ] @@ -1215,7 +1220,7 @@ def redaction_tools() -> List[MCPTool]: "ocr": {"type": "array", "items": {"type": "object"}}, }, required=["file_path"]), - handler=h_exec.redact_screenshot, + handler=h_vision_exec.redact_screenshot, annotations=SIDE_EFFECT_ONLY, ), ] @@ -1260,7 +1265,7 @@ def computer_use_tools() -> List[MCPTool]: "model": {"type": "string"}, "max_tokens": {"type": "integer"}, }, required=["goal"]), - handler=h_exec.run_agent, + handler=h_automation_exec.run_agent, annotations=DESTRUCTIVE, ), ] @@ -1416,7 +1421,7 @@ def a11y_control_tools() -> List[MCPTool]: "(ExpandCollapsePattern). Located by name/role/app_name/" "automation_id. Returns True on success."), input_schema=schema(dict(_M)), - handler=h_exec.expand_control, + handler=h_accessibility_exec.expand_control, annotations=DESTRUCTIVE, ), MCPTool( @@ -1424,7 +1429,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Collapse a tree node / combobox / expander natively " "(ExpandCollapsePattern). Returns True on success."), input_schema=schema(dict(_M)), - handler=h_exec.collapse_control, + handler=h_accessibility_exec.collapse_control, annotations=DESTRUCTIVE, ), MCPTool( @@ -1432,7 +1437,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Read a control's expand state via ExpandCollapsePattern: " "{state: expanded|collapsed|partial|leaf|null}."), input_schema=schema(dict(_M)), - handler=h_exec.control_expand_state, + handler=h_accessibility_exec.control_expand_state, annotations=READ_ONLY, ), MCPTool( @@ -1440,7 +1445,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Select a list / tree / tab item natively " "(SelectionItemPattern). Returns True on success."), input_schema=schema(dict(_M)), - handler=h_exec.select_control_item, + handler=h_accessibility_exec.select_control_item, annotations=DESTRUCTIVE, ), MCPTool( @@ -1448,7 +1453,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Read a slider / progress / spinner range via " "RangeValuePattern: {found, range:{value,minimum,maximum}}."), input_schema=schema(dict(_M)), - handler=h_exec.control_range, + handler=h_accessibility_exec.control_range, annotations=READ_ONLY, ), MCPTool( @@ -1457,7 +1462,7 @@ def a11y_control_tools() -> List[MCPTool]: "(RangeValuePattern). Returns True on success."), input_schema=schema({"value": {"type": "number"}, **_M}, required=["value"]), - handler=h_exec.set_control_range, + handler=h_accessibility_exec.set_control_range, annotations=DESTRUCTIVE, ), MCPTool( @@ -1465,7 +1470,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Scroll a control into view before acting " "(ScrollItemPattern). Returns True on success."), input_schema=schema(dict(_M)), - handler=h_exec.scroll_control_into_view, + handler=h_accessibility_exec.scroll_control_into_view, annotations=DESTRUCTIVE, ), MCPTool( @@ -1486,7 +1491,7 @@ def a11y_control_tools() -> List[MCPTool]: "app_name": {"type": "string"}, "automation_id": {"type": "string"}}, required=["item_name"]), - handler=h_exec.realize_item, + handler=h_accessibility_exec.realize_item, annotations=NON_DESTRUCTIVE, ), MCPTool( @@ -1496,7 +1501,7 @@ def a11y_control_tools() -> List[MCPTool]: "item_status, accelerator_key, access_key, " "orientation}}. Check 'enabled' before clicking."), input_schema=schema(dict(_M)), - handler=h_exec.get_element_properties, + handler=h_accessibility_exec.get_element_properties, annotations=READ_ONLY, ), MCPTool( @@ -1504,7 +1509,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Read a native table's header labels via TablePattern: " "{found, headers:{columns:[...], rows:[...]}}."), input_schema=schema(dict(_M)), - handler=h_exec.table_headers, + handler=h_accessibility_exec.table_headers, annotations=READ_ONLY, ), MCPTool( @@ -1515,7 +1520,7 @@ def a11y_control_tools() -> List[MCPTool]: input_schema=schema({"row": {"type": "integer"}, "column": {"type": "integer"}, **_M}, required=["row", "column"]), - handler=h_exec.table_cell, + handler=h_accessibility_exec.table_cell, annotations=READ_ONLY, ), MCPTool( @@ -1527,7 +1532,7 @@ def a11y_control_tools() -> List[MCPTool]: input_schema=schema({"row": {"type": "integer"}, "column_header": {"type": "string"}, **_M}, required=["row", "column_header"]), - handler=h_exec.cell_by_header, + handler=h_accessibility_exec.cell_by_header, annotations=READ_ONLY, ), MCPTool( @@ -1538,7 +1543,7 @@ def a11y_control_tools() -> List[MCPTool]: input_schema=schema({"x": {"type": "number"}, "y": {"type": "number"}, **_M}, required=["x", "y"]), - handler=h_exec.move_element, + handler=h_accessibility_exec.move_element, annotations=DESTRUCTIVE, ), MCPTool( @@ -1548,7 +1553,7 @@ def a11y_control_tools() -> List[MCPTool]: input_schema=schema({"width": {"type": "number"}, "height": {"type": "number"}, **_M}, required=["width", "height"]), - handler=h_exec.resize_element, + handler=h_accessibility_exec.resize_element, annotations=DESTRUCTIVE, ), MCPTool( @@ -1560,7 +1565,7 @@ def a11y_control_tools() -> List[MCPTool]: "state": {"type": "string", "enum": ["normal", "maximized", "minimized"]}, **_M}, required=["state"]), - handler=h_exec.set_window_state, + handler=h_accessibility_exec.set_window_state, annotations=DESTRUCTIVE, ), MCPTool( @@ -1570,7 +1575,7 @@ def a11y_control_tools() -> List[MCPTool]: "closing|null}. A reliable 'is this window ready / " "modal-blocked?' signal."), input_schema=schema(dict(_M)), - handler=h_exec.window_interaction_state, + handler=h_accessibility_exec.window_interaction_state, annotations=READ_ONLY, ), MCPTool( @@ -1581,7 +1586,7 @@ def a11y_control_tools() -> List[MCPTool]: "last-resort read for legacy Win32 controls UIA can't " "model."), input_schema=schema(dict(_M)), - handler=h_exec.legacy_info, + handler=h_accessibility_exec.legacy_info, annotations=READ_ONLY, ), MCPTool( @@ -1591,7 +1596,7 @@ def a11y_control_tools() -> List[MCPTool]: "Value/Invoke/Toggle all do nothing. Returns True on " "success."), input_schema=schema(dict(_M)), - handler=h_exec.legacy_default_action, + handler=h_accessibility_exec.legacy_default_action, annotations=DESTRUCTIVE, ), MCPTool( @@ -1600,7 +1605,7 @@ def a11y_control_tools() -> List[MCPTool]: "{found, selection:{items:[names], can_select_multiple, " "is_required}} — what's selected in a listbox/grid/tab."), input_schema=schema(dict(_M)), - handler=h_exec.get_selection, + handler=h_accessibility_exec.get_selection, annotations=READ_ONLY, ), MCPTool( @@ -1609,7 +1614,7 @@ def a11y_control_tools() -> List[MCPTool]: "MultipleViewPattern: {found, views:{current, views:" "[names]}} — e.g. Explorer list / details / tile."), input_schema=schema(dict(_M)), - handler=h_exec.list_views, + handler=h_accessibility_exec.list_views, annotations=READ_ONLY, ), MCPTool( @@ -1618,7 +1623,7 @@ def a11y_control_tools() -> List[MCPTool]: "MultipleViewPattern. Returns True on success."), input_schema=schema({"view": {"type": "string"}, **_M}, required=["view"]), - handler=h_exec.set_view, + handler=h_accessibility_exec.set_view, annotations=DESTRUCTIVE, ), MCPTool( @@ -1628,7 +1633,7 @@ def a11y_control_tools() -> List[MCPTool]: "Returns {changed, element} or {changed: false} on " "'timeout' seconds (default 5)."), input_schema=schema({"timeout": {"type": "number"}}), - handler=h_exec.wait_for_focus_change, + handler=h_accessibility_exec.wait_for_focus_change, annotations=READ_ONLY, ), MCPTool( @@ -1637,7 +1642,7 @@ def a11y_control_tools() -> List[MCPTool]: "{text}. Works on multiline edits / RichEdit / document " "controls where ac_control_get_value returns empty."), input_schema=schema(dict(_M)), - handler=h_exec.get_control_text, + handler=h_accessibility_exec.get_control_text, annotations=READ_ONLY, ), MCPTool( @@ -1649,7 +1654,7 @@ def a11y_control_tools() -> List[MCPTool]: input_schema=schema({"text": {"type": "string"}, "ignore_case": {"type": "boolean"}, **_M}, required=["text"]), - handler=h_exec.find_control_text, + handler=h_accessibility_exec.find_control_text, annotations=READ_ONLY, ), MCPTool( @@ -1661,7 +1666,7 @@ def a11y_control_tools() -> List[MCPTool]: input_schema=schema({"text": {"type": "string"}, "ignore_case": {"type": "boolean"}, **_M}, required=["text"]), - handler=h_exec.select_control_text, + handler=h_accessibility_exec.select_control_text, annotations=DESTRUCTIVE, ), MCPTool( @@ -1670,7 +1675,7 @@ def a11y_control_tools() -> List[MCPTool]: "attributes: {found, attributes:{font_name, font_size, " "bold, italic, foreground_color}}."), input_schema=schema(dict(_M)), - handler=h_exec.control_text_attributes, + handler=h_accessibility_exec.control_text_attributes, annotations=READ_ONLY, ), MCPTool( @@ -1678,7 +1683,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Read a control's currently selected text via " "TextPattern: {text} ('' when nothing selected)."), input_schema=schema(dict(_M)), - handler=h_exec.get_selected_text, + handler=h_accessibility_exec.get_selected_text, annotations=READ_ONLY, ), MCPTool( @@ -1686,7 +1691,7 @@ def a11y_control_tools() -> List[MCPTool]: description=("Read only the on-screen text of a control via " "TextPattern.GetVisibleRanges: {text}."), input_schema=schema(dict(_M)), - handler=h_exec.get_visible_text, + handler=h_accessibility_exec.get_visible_text, annotations=READ_ONLY, ), ] @@ -1717,7 +1722,7 @@ def a11y_tree_tools() -> List[MCPTool]: "app_name": {"type": "string"}, "max_results": {"type": "integer"}, }), - handler=h_exec.walk_tree, + handler=h_accessibility_exec.walk_tree, annotations=READ_ONLY, ), MCPTool( @@ -1727,7 +1732,7 @@ def a11y_tree_tools() -> List[MCPTool]: "already-friendly roles pass through unchanged."), input_schema=schema({"role": {"type": "string"}}, required=["role"]), - handler=h_exec.humanize_role, + handler=h_accessibility_exec.humanize_role, annotations=READ_ONLY, ), MCPTool( @@ -1739,7 +1744,7 @@ def a11y_tree_tools() -> List[MCPTool]: "app_name": {"type": "string"}, "max_results": {"type": "integer"}, }), - handler=h_exec.tab_order, + handler=h_accessibility_exec.tab_order, annotations=READ_ONLY, ), MCPTool( @@ -1751,7 +1756,7 @@ def a11y_tree_tools() -> List[MCPTool]: "app_name": {"type": "string"}, "max_results": {"type": "integer"}, }), - handler=h_exec.audit_focus_order, + handler=h_accessibility_exec.audit_focus_order, annotations=READ_ONLY, ), MCPTool( @@ -1765,7 +1770,7 @@ def a11y_tree_tools() -> List[MCPTool]: "app_name": {"type": "string"}, "automation_id": {"type": "string"}, }), - handler=h_exec.focus_control, + handler=h_accessibility_exec.focus_control, annotations=DESTRUCTIVE, ), MCPTool( @@ -1779,7 +1784,7 @@ def a11y_tree_tools() -> List[MCPTool]: "poll_interval_s": {"type": "number"}, "min_movement_px": {"type": "integer"}, }), - handler=h_exec.a11y_record_start, + handler=h_accessibility_exec.a11y_record_start, annotations=NON_DESTRUCTIVE, ), MCPTool( @@ -1787,7 +1792,7 @@ def a11y_tree_tools() -> List[MCPTool]: description=("Stop the recorder and return every captured " "event in chronological order."), input_schema=schema({}), - handler=h_exec.a11y_record_stop, + handler=h_accessibility_exec.a11y_record_stop, annotations=NON_DESTRUCTIVE, ), ] @@ -1940,7 +1945,7 @@ def smart_wait_tools() -> List[MCPTool]: "poll_interval_s": {"type": "number"}, "gone_for_s": {"type": "number"}}, required=["image"]), - handler=h_exec.wait_image_gone, + handler=h_vision_exec.wait_image_gone, annotations=READ_ONLY, ), MCPTool( @@ -1953,7 +1958,7 @@ def smart_wait_tools() -> List[MCPTool]: "poll_interval_s": {"type": "number"}, "gone_for_s": {"type": "number"}}, required=["text"]), - handler=h_exec.wait_text_gone, + handler=h_vision_exec.wait_text_gone, annotations=READ_ONLY, ), MCPTool( @@ -1971,7 +1976,7 @@ def smart_wait_tools() -> List[MCPTool]: "timeout_s": {"type": "number"}, "poll_interval_s": {"type": "number"}}, required=["target_rgb"]), - handler=h_exec.wait_color, + handler=h_vision_exec.wait_color, annotations=READ_ONLY, ), MCPTool( @@ -1986,7 +1991,7 @@ def smart_wait_tools() -> List[MCPTool]: "timeout_s": {"type": "number"}, "poll_interval_s": {"type": "number"}}, required=["pattern"]), - handler=h_exec.wait_window_title, + handler=h_vision_exec.wait_window_title, annotations=READ_ONLY, ), MCPTool( @@ -2298,7 +2303,7 @@ def anchor_locator_tools() -> List[MCPTool]: "max_distance_px": {"type": "number"}, "ordinal": {"type": "integer"}, }, required=["anchor", "target"]), - handler=h_exec.anchor_locate, + handler=h_vision_exec.anchor_locate, annotations=READ_ONLY, ), MCPTool( @@ -2314,7 +2319,7 @@ def anchor_locator_tools() -> List[MCPTool]: "right_of", "near"]}, "max_distance_px": {"type": "number"}, }, required=["anchor", "target"]), - handler=h_exec.anchor_locate_all, + handler=h_vision_exec.anchor_locate_all, annotations=READ_ONLY, ), MCPTool( @@ -3522,7 +3527,7 @@ def resilience_tools() -> List[MCPTool]: "threshold": {"type": "integer"}, "reset_s": {"type": "number"}}, required=["name", "actions"]), - handler=h_exec.circuit_call, + handler=h_automation_exec.circuit_call, annotations=DESTRUCTIVE, ), ] @@ -3668,7 +3673,7 @@ def color_region_tools() -> List[MCPTool]: "min_area": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["rgb"]), - handler=h_exec.find_color_region, + handler=h_vision_exec.find_color_region, annotations=READ_ONLY, ), ] @@ -3691,7 +3696,7 @@ def feature_match_tools() -> List[MCPTool]: "ratio": {"type": "number"}, "min_inliers": {"type": "integer"}}, required=["template"]), - handler=h_exec.feature_match, + handler=h_vision_exec.feature_match, annotations=READ_ONLY, ), ] @@ -3711,7 +3716,7 @@ def shape_locator_tools() -> List[MCPTool]: "min_area": {"type": "integer"}, "max_area": {"type": "integer"}}, required=[]), - handler=h_exec.find_shapes, + handler=h_vision_exec.find_shapes, annotations=READ_ONLY, ), MCPTool( @@ -3729,7 +3734,7 @@ def shape_locator_tools() -> List[MCPTool]: "aspect_range": {"type": "array", "items": {"type": "number"}}, "epsilon": {"type": "number"}}, required=[]), - handler=h_exec.find_rectangles, + handler=h_vision_exec.find_rectangles, annotations=READ_ONLY, ), ] @@ -3750,7 +3755,7 @@ def window_layout_tools() -> List[MCPTool]: "screen": {"type": "array", "items": {"type": "integer"}}, "gap": {"type": "integer"}}, required=["slot"]), - handler=h_exec.tile_rect, + handler=h_desktop_exec.tile_rect, annotations=READ_ONLY, ), MCPTool( @@ -3765,7 +3770,7 @@ def window_layout_tools() -> List[MCPTool]: "screen": {"type": "array", "items": {"type": "integer"}}, "gap": {"type": "integer"}}, required=["rows", "cols"]), - handler=h_exec.grid_rects, + handler=h_desktop_exec.grid_rects, annotations=READ_ONLY, ), MCPTool( @@ -3780,7 +3785,7 @@ def window_layout_tools() -> List[MCPTool]: "offset": {"type": "integer"}, "size": {"type": "array", "items": {"type": "integer"}}}, required=["count"]), - handler=h_exec.cascade_rects, + handler=h_desktop_exec.cascade_rects, annotations=READ_ONLY, ), ] @@ -3799,7 +3804,7 @@ def window_arrange_tools() -> List[MCPTool]: "cols": {"type": "integer"}, "gap": {"type": "integer"}}, required=["titles"]), - handler=h_exec.arrange_grid, + handler=h_desktop_exec.arrange_grid, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -3811,7 +3816,7 @@ def window_arrange_tools() -> List[MCPTool]: "titles": {"type": "array", "items": {"type": "string"}}, "offset": {"type": "integer"}}, required=["titles"]), - handler=h_exec.arrange_cascade, + handler=h_desktop_exec.arrange_cascade, annotations=SIDE_EFFECT_ONLY, ), ] @@ -3836,7 +3841,7 @@ def preprocess_tools() -> List[MCPTool]: "block_size": {"type": "integer"}, "c": {"type": "integer"}}, required=["output_path"]), - handler=h_exec.preprocess_image, + handler=h_vision_exec.preprocess_image, annotations=SIDE_EFFECT_ONLY, ), ] @@ -3852,7 +3857,7 @@ def monitor_layout_tools() -> List[MCPTool]: "screen_size, this exposes per-monitor origins (which may " "be negative) for multi-display placement."), input_schema=schema({}, required=[]), - handler=h_exec.enumerate_monitors, + handler=h_desktop_exec.enumerate_monitors, annotations=READ_ONLY, ), MCPTool( @@ -3864,7 +3869,7 @@ def monitor_layout_tools() -> List[MCPTool]: "x": {"type": "integer"}, "y": {"type": "integer"}}, required=["x", "y"]), - handler=h_exec.monitor_at_point, + handler=h_desktop_exec.monitor_at_point, annotations=READ_ONLY, ), ] @@ -3887,7 +3892,7 @@ def actionability_tools() -> List[MCPTool]: "min_score": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.wait_actionable, + handler=h_vision_exec.wait_actionable, annotations=READ_ONLY, ), ] @@ -3907,7 +3912,7 @@ def element_parse_tools() -> List[MCPTool]: "a11y": {"type": "array", "items": {"type": "object"}}, "iou_threshold": {"type": "number"}}, required=[]), - handler=h_exec.fuse_elements, + handler=h_vision_exec.fuse_elements, annotations=READ_ONLY, ), MCPTool( @@ -3919,7 +3924,7 @@ def element_parse_tools() -> List[MCPTool]: "elements": {"type": "array", "items": {"type": "object"}}, "row_tol": {"type": "integer"}}, required=["elements"]), - handler=h_exec.reading_order, + handler=h_vision_exec.reading_order, annotations=READ_ONLY, ), ] @@ -3939,7 +3944,7 @@ def hsv_segment_tools() -> List[MCPTool]: "min_area": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["lower_hsv", "upper_hsv"]), - handler=h_exec.segment_hsv, + handler=h_vision_exec.segment_hsv, annotations=READ_ONLY, ), MCPTool( @@ -3956,7 +3961,7 @@ def hsv_segment_tools() -> List[MCPTool]: "min_area": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["hue"]), - handler=h_exec.dominant_hue_regions, + handler=h_vision_exec.dominant_hue_regions, annotations=READ_ONLY, ), ] @@ -3978,7 +3983,7 @@ def text_regions_tools() -> List[MCPTool]: "max_aspect": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.find_text_regions, + handler=h_vision_exec.find_text_regions, annotations=READ_ONLY, ), MCPTool( @@ -3990,7 +3995,7 @@ def text_regions_tools() -> List[MCPTool]: "y_tolerance": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.find_text_lines, + handler=h_vision_exec.find_text_lines, annotations=READ_ONLY, ), ] @@ -4010,7 +4015,7 @@ def edge_lines_tools() -> List[MCPTool]: "orientation": {"type": "string"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.find_lines, + handler=h_vision_exec.find_lines, annotations=READ_ONLY, ), MCPTool( @@ -4023,7 +4028,7 @@ def edge_lines_tools() -> List[MCPTool]: "tol": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.find_grid, + handler=h_vision_exec.find_grid, annotations=READ_ONLY, ), MCPTool( @@ -4037,7 +4042,7 @@ def edge_lines_tools() -> List[MCPTool]: "tol": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.find_separators, + handler=h_vision_exec.find_separators, annotations=READ_ONLY, ), ] @@ -4061,7 +4066,7 @@ def expect_poll_tools() -> List[MCPTool]: "timeout_s": {"type": "number"}, "interval_s": {"type": "number"}}, required=["action"]), - handler=h_exec.expect_poll, + handler=h_automation_exec.expect_poll, annotations=DESTRUCTIVE, ), ] @@ -4080,7 +4085,7 @@ def locator_chain_tools() -> List[MCPTool]: "boxes": {"type": "array", "items": {"type": "object"}}, "ops": {"type": "array", "items": {"type": "object"}}}, required=["boxes"]), - handler=h_exec.locate_chain, + handler=h_vision_exec.locate_chain, annotations=READ_ONLY, ), ] @@ -4098,7 +4103,7 @@ def rich_clipboard_tools() -> List[MCPTool]: "html": {"type": "string"}, "fragment_plaintext": {"type": "string"}}, required=["html"]), - handler=h_exec.set_clipboard_html, + handler=h_desktop_exec.set_clipboard_html, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -4106,7 +4111,7 @@ def rich_clipboard_tools() -> List[MCPTool]: description=("Read the clipboard's HTML fragment (CF_HTML, Windows). " "Returns {found, html}."), input_schema=schema({}, required=[]), - handler=h_exec.get_clipboard_html, + handler=h_desktop_exec.get_clipboard_html, annotations=READ_ONLY, ), ] @@ -4123,7 +4128,7 @@ def clipboard_files_tools() -> List[MCPTool]: input_schema=schema({ "paths": {"type": "array", "items": {"type": "string", "format": "path"}}}, required=["paths"]), - handler=h_exec.set_clipboard_files, + handler=h_desktop_exec.set_clipboard_files, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -4131,7 +4136,7 @@ def clipboard_files_tools() -> List[MCPTool]: description=("Read the clipboard's file-drop list (CF_HDROP, Windows). " "Returns {found, paths}."), input_schema=schema({}, required=[]), - handler=h_exec.get_clipboard_files, + handler=h_desktop_exec.get_clipboard_files, annotations=READ_ONLY, ), MCPTool( @@ -4140,7 +4145,7 @@ def clipboard_files_tools() -> List[MCPTool]: "pastes as styled text into Word / rich editors (Windows). " "Also seeds plain text. Returns {set, length}."), input_schema=schema({"text": {"type": "string"}}, required=["text"]), - handler=h_exec.set_clipboard_rtf, + handler=h_desktop_exec.set_clipboard_rtf, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -4148,7 +4153,7 @@ def clipboard_files_tools() -> List[MCPTool]: description=("Read the clipboard's RTF document string (Windows). " "Returns {found, rtf}."), input_schema=schema({}, required=[]), - handler=h_exec.get_clipboard_rtf, + handler=h_desktop_exec.get_clipboard_rtf, annotations=READ_ONLY, ), MCPTool( @@ -4162,7 +4167,7 @@ def clipboard_files_tools() -> List[MCPTool]: "items": {"type": "array", "items": {"type": "string"}}}, "delimiter": {"type": "string"}}, required=["rows"]), - handler=h_exec.set_clipboard_csv, + handler=h_desktop_exec.set_clipboard_csv, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -4171,7 +4176,7 @@ def clipboard_files_tools() -> List[MCPTool]: "strings (Windows). 'delimiter' defaults to ','. " "Returns {found, rows}."), input_schema=schema({"delimiter": {"type": "string"}}), - handler=h_exec.get_clipboard_csv, + handler=h_desktop_exec.get_clipboard_csv, annotations=READ_ONLY, ), MCPTool( @@ -4181,7 +4186,7 @@ def clipboard_files_tools() -> List[MCPTool]: "{categories, formats:[{id,name,category}], has_text, " "has_image, has_files}."), input_schema=schema({}, required=[]), - handler=h_exec.clipboard_formats, + handler=h_desktop_exec.clipboard_formats, annotations=READ_ONLY, ), MCPTool( @@ -4191,7 +4196,7 @@ def clipboard_files_tools() -> List[MCPTool]: "same summary as ac_clipboard_formats."), input_schema=schema({"formats": {"type": "array"}}, required=["formats"]), - handler=h_exec.classify_formats, + handler=h_desktop_exec.classify_formats, annotations=READ_ONLY, ), MCPTool( @@ -4202,7 +4207,7 @@ def clipboard_files_tools() -> List[MCPTool]: input_schema=schema({"before": {"type": "array"}, "after": {"type": "array"}}, required=["before", "after"]), - handler=h_exec.diff_formats, + handler=h_desktop_exec.diff_formats, annotations=READ_ONLY, ), MCPTool( @@ -4214,7 +4219,7 @@ def clipboard_files_tools() -> List[MCPTool]: "paths": {"type": "array", "items": {"type": "string", "format": "path"}}, "point": {"type": "array", "items": {"type": "integer"}}}, required=["paths"]), - handler=h_exec.plan_file_drop, + handler=h_desktop_exec.plan_file_drop, annotations=READ_ONLY, ), MCPTool( @@ -4227,7 +4232,7 @@ def clipboard_files_tools() -> List[MCPTool]: "paths": {"type": "array", "items": {"type": "string", "format": "path"}}, "point": {"type": "array", "items": {"type": "integer"}}}, required=["hwnd", "paths"]), - handler=h_exec.drop_files, + handler=h_desktop_exec.drop_files, annotations=DESTRUCTIVE, ), ] @@ -4247,7 +4252,7 @@ def img_histogram_tools() -> List[MCPTool]: "space": {"type": "string"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.image_histogram, + handler=h_vision_exec.image_histogram, annotations=READ_ONLY, ), MCPTool( @@ -4264,7 +4269,7 @@ def img_histogram_tools() -> List[MCPTool]: "space": {"type": "string"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["reference"]), - handler=h_exec.histogram_changed, + handler=h_vision_exec.histogram_changed, annotations=READ_ONLY, ), MCPTool( @@ -4276,7 +4281,7 @@ def img_histogram_tools() -> List[MCPTool]: input_schema=schema({ "source": {"type": "string", "format": "path"}, "region": {"type": "array", "items": {"type": "integer"}}}), - handler=h_exec.image_quality, + handler=h_vision_exec.image_quality, annotations=READ_ONLY, ), MCPTool( @@ -4290,7 +4295,7 @@ def img_histogram_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "min_sharpness": {"type": "number"}, "min_contrast": {"type": "number"}}), - handler=h_exec.quality_gate, + handler=h_vision_exec.quality_gate, annotations=READ_ONLY, ), MCPTool( @@ -4306,7 +4311,7 @@ def img_histogram_tools() -> List[MCPTool]: "scales": {"type": "array", "items": {"type": "number"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.detect_scale, + handler=h_vision_exec.detect_scale, annotations=READ_ONLY, ), MCPTool( @@ -4322,7 +4327,7 @@ def img_histogram_tools() -> List[MCPTool]: "scales": {"type": "array", "items": {"type": "number"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.scale_sweep, + handler=h_vision_exec.scale_sweep, annotations=READ_ONLY, ), MCPTool( @@ -4337,7 +4342,7 @@ def img_histogram_tools() -> List[MCPTool]: "size": {"type": "integer"}, "threshold": {"type": "number"}, "min_area": {"type": "integer"}}), - handler=h_exec.salient_regions, + handler=h_vision_exec.salient_regions, annotations=READ_ONLY, ), MCPTool( @@ -4351,7 +4356,7 @@ def img_histogram_tools() -> List[MCPTool]: "size": {"type": "integer"}, "threshold": {"type": "number"}, "min_area": {"type": "integer"}}), - handler=h_exec.most_salient, + handler=h_vision_exec.most_salient, annotations=READ_ONLY, ), MCPTool( @@ -4556,7 +4561,7 @@ def motion_regions_tools() -> List[MCPTool]: "min_area": {"type": "integer"}, "blur": {"type": "integer"}}, required=["before"]), - handler=h_exec.changed_regions, + handler=h_vision_exec.changed_regions, annotations=READ_ONLY, ), MCPTool( @@ -4570,7 +4575,7 @@ def motion_regions_tools() -> List[MCPTool]: "threshold": {"type": "integer"}, "min_area": {"type": "integer"}}, required=["before"]), - handler=h_exec.has_motion, + handler=h_vision_exec.has_motion, annotations=READ_ONLY, ), ] @@ -4586,7 +4591,7 @@ def window_zorder_tools() -> List[MCPTool]: "title": {"type": "string"}, "on": {"type": "boolean"}}, required=["title"]), - handler=h_exec.set_topmost, + handler=h_desktop_exec.set_topmost, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -4594,7 +4599,7 @@ def window_zorder_tools() -> List[MCPTool]: description=("Raise the window matching 'title' to the top of the " "z-order. Returns {applied}. Windows only."), input_schema=schema({"title": {"type": "string"}}, required=["title"]), - handler=h_exec.bring_to_front, + handler=h_desktop_exec.bring_to_front, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -4602,7 +4607,7 @@ def window_zorder_tools() -> List[MCPTool]: description=("Send the window matching 'title' to the bottom of the " "z-order. Returns {applied}. Windows only."), input_schema=schema({"title": {"type": "string"}}, required=["title"]), - handler=h_exec.send_to_back, + handler=h_desktop_exec.send_to_back, annotations=SIDE_EFFECT_ONLY, ), ] @@ -4621,7 +4626,7 @@ def soft_assert_tools() -> List[MCPTool]: "checks": {"type": "array", "items": {"type": "object"}}, "raise_on_fail": {"type": "boolean"}}, required=["checks"]), - handler=h_exec.soft_assert, + handler=h_automation_exec.soft_assert, annotations=READ_ONLY, ), ] @@ -4643,7 +4648,7 @@ def perceptual_diff_tools() -> List[MCPTool]: "include_aa": {"type": "boolean"}, "max_diff_ratio": {"type": "number"}}, required=["actual", "expected"]), - handler=h_exec.perceptual_diff, + handler=h_vision_exec.perceptual_diff, annotations=READ_ONLY, ), ] @@ -4657,7 +4662,7 @@ def window_geometry_tools() -> List[MCPTool]: "excluding title bar / borders) of the window matching " "'title'. Returns {found, rect}. Windows only."), input_schema=schema({"title": {"type": "string"}}, required=["title"]), - handler=h_exec.get_client_rect, + handler=h_desktop_exec.get_client_rect, annotations=READ_ONLY, ), MCPTool( @@ -4670,7 +4675,7 @@ def window_geometry_tools() -> List[MCPTool]: "x": {"type": "integer"}, "y": {"type": "integer"}}, required=["title", "x", "y"]), - handler=h_exec.client_point, + handler=h_desktop_exec.client_point, annotations=READ_ONLY, ), ] @@ -4688,7 +4693,7 @@ def cua_action_tools() -> List[MCPTool]: "payload": {"type": "object"}, "source": {"type": "string"}}, required=["payload"]), - handler=h_exec.cua_command, + handler=h_automation_exec.cua_command, annotations=READ_ONLY, ), ] @@ -4708,7 +4713,7 @@ def observation_tools() -> List[MCPTool]: "viewport": {"type": "array", "items": {"type": "integer"}}, "max_elements": {"type": "integer"}}, required=["elements"]), - handler=h_exec.serialize_observation, + handler=h_automation_exec.serialize_observation, annotations=READ_ONLY, ), MCPTool( @@ -4721,7 +4726,7 @@ def observation_tools() -> List[MCPTool]: "viewport": {"type": "array", "items": {"type": "integer"}}, "max_elements": {"type": "integer"}}, required=["elements"]), - handler=h_exec.observation_index, + handler=h_automation_exec.observation_index, annotations=READ_ONLY, ), MCPTool( @@ -4740,7 +4745,7 @@ def observation_tools() -> List[MCPTool]: "max_lines": {"type": "integer"}, "interactive_only": {"type": "boolean"}}, required=["prev", "curr"]), - handler=h_exec.delta_observation, + handler=h_automation_exec.delta_observation, annotations=READ_ONLY, ), MCPTool( @@ -4756,7 +4761,7 @@ def observation_tools() -> List[MCPTool]: "action": {"type": "object"}, "radius": {"type": "integer"}}, required=["before", "after", "action"]), - handler=h_exec.classify_effect, + handler=h_automation_exec.classify_effect, annotations=READ_ONLY, ), MCPTool( @@ -4769,7 +4774,7 @@ def observation_tools() -> List[MCPTool]: "point": {"type": "array", "items": {"type": "integer"}}, "radius": {"type": "integer"}}, required=["before", "after", "point"]), - handler=h_exec.effect_near_point, + handler=h_automation_exec.effect_near_point, annotations=READ_ONLY, ), MCPTool( @@ -4785,7 +4790,7 @@ def observation_tools() -> List[MCPTool]: "spec": {"type": "object"}, "before": {"type": "array", "items": {"type": "object"}}}, required=["after", "spec"]), - handler=h_exec.check_postcondition, + handler=h_automation_exec.check_postcondition, annotations=READ_ONLY, ), MCPTool( @@ -4799,7 +4804,7 @@ def observation_tools() -> List[MCPTool]: "verdict": {"type": "string"}, "max_attempts": {"type": "integer"}}, required=["verdict"]), - handler=h_exec.plan_repair, + handler=h_automation_exec.plan_repair, annotations=READ_ONLY, ), MCPTool( @@ -4815,7 +4820,7 @@ def observation_tools() -> List[MCPTool]: "items": {"type": "number"}}}, "cluster_radius": {"type": "number"}}, required=["candidates"]), - handler=h_exec.consensus_point, + handler=h_automation_exec.consensus_point, annotations=READ_ONLY, ), MCPTool( @@ -4829,7 +4834,7 @@ def observation_tools() -> List[MCPTool]: "items": {"type": "number"}}}, "elements": {"type": "array", "items": {"type": "object"}}}, required=["candidates", "elements"]), - handler=h_exec.consensus_element, + handler=h_automation_exec.consensus_element, annotations=READ_ONLY, ), MCPTool( @@ -4844,7 +4849,7 @@ def observation_tools() -> List[MCPTool]: "quiet_samples": {"type": "integer"}, "max_churn": {"type": "number"}}, required=["churns"]), - handler=h_exec.settle_point, + handler=h_automation_exec.settle_point, annotations=READ_ONLY, ), MCPTool( @@ -4861,7 +4866,7 @@ def observation_tools() -> List[MCPTool]: "postcondition": {"type": "object"}, "radius": {"type": "integer"}}, required=["action", "before", "after"]), - handler=h_exec.build_critic_record, + handler=h_automation_exec.build_critic_record, annotations=READ_ONLY, ), MCPTool( @@ -4871,7 +4876,7 @@ def observation_tools() -> List[MCPTool]: "process_score (0..1), reasons}. Deterministic, no model."), input_schema=schema({"record": {"type": "object"}}, required=["record"]), - handler=h_exec.score_step, + handler=h_automation_exec.score_step, annotations=READ_ONLY, ), ] @@ -4891,7 +4896,7 @@ def action_grounding_tools() -> List[MCPTool]: "screen": {"type": "array", "items": {"type": "integer"}}, "targets": {"type": "array", "items": {"type": "object"}}}, required=["action"]), - handler=h_exec.validate_action, + handler=h_automation_exec.validate_action, annotations=READ_ONLY, ), ] @@ -4907,7 +4912,7 @@ def agent_replay_tools() -> List[MCPTool]: "observation, action, result} steps. Returns {count, " "results}. Side-effecting (runs the actions)."), input_schema=schema({"trace": {"type": "array"}}, required=["trace"]), - handler=h_exec.replay_trace, + handler=h_automation_exec.replay_trace, annotations=DESTRUCTIVE, ), ] @@ -4926,7 +4931,7 @@ def element_diff_tools() -> List[MCPTool]: "after": {"type": "array", "items": {"type": "object"}}, "iou_threshold": {"type": "number"}}, required=["before", "after"]), - handler=h_exec.match_elements, + handler=h_automation_exec.match_elements, annotations=READ_ONLY, ), MCPTool( @@ -4939,7 +4944,7 @@ def element_diff_tools() -> List[MCPTool]: "prior": {"type": "array", "items": {"type": "object"}}, "iou_threshold": {"type": "number"}}, required=["elements"]), - handler=h_exec.assign_stable_ids, + handler=h_automation_exec.assign_stable_ids, annotations=READ_ONLY, ), ] @@ -4959,7 +4964,7 @@ def element_scoring_tools() -> List[MCPTool]: "want_name": {"type": "string"}, "anchor": {"type": "array", "items": {"type": "integer"}}}, required=["candidates"]), - handler=h_exec.score_candidates, + handler=h_automation_exec.score_candidates, annotations=READ_ONLY, ), MCPTool( @@ -4972,7 +4977,7 @@ def element_scoring_tools() -> List[MCPTool]: "want_name": {"type": "string"}, "anchor": {"type": "array", "items": {"type": "integer"}}}, required=["candidates"]), - handler=h_exec.best_candidate, + handler=h_automation_exec.best_candidate, annotations=READ_ONLY, ), ] @@ -4990,7 +4995,7 @@ def barcode_tools() -> List[MCPTool]: "source": {"type": "string", "format": "path"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=[]), - handler=h_exec.read_barcodes, + handler=h_vision_exec.read_barcodes, annotations=READ_ONLY, ), ] @@ -5013,7 +5018,7 @@ def ssim_tools() -> List[MCPTool]: "items": {"type": "integer"}}}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["reference"]), - handler=h_exec.ssim_compare, + handler=h_vision_exec.ssim_compare, annotations=READ_ONLY, ), MCPTool( @@ -5033,7 +5038,7 @@ def ssim_tools() -> List[MCPTool]: "min_area": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["reference"]), - handler=h_exec.ssim_changed_regions, + handler=h_vision_exec.ssim_changed_regions, annotations=READ_ONLY, ), ] @@ -5054,7 +5059,7 @@ def visual_match_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.match_template, + handler=h_vision_exec.match_template, annotations=READ_ONLY, ), MCPTool( @@ -5069,7 +5074,7 @@ def visual_match_tools() -> List[MCPTool]: "nms_iou": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.match_template_all, + handler=h_vision_exec.match_template_all, annotations=READ_ONLY, ), MCPTool( @@ -5085,7 +5090,7 @@ def visual_match_tools() -> List[MCPTool]: "min_score": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.match_masked, + handler=h_vision_exec.match_masked, annotations=READ_ONLY, ), MCPTool( @@ -5100,7 +5105,7 @@ def visual_match_tools() -> List[MCPTool]: "nms_iou": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.match_masked_all, + handler=h_vision_exec.match_masked_all, annotations=READ_ONLY, ), ] @@ -5123,7 +5128,7 @@ def rotated_match_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.match_rotated, + handler=h_vision_exec.match_rotated, annotations=READ_ONLY, ), MCPTool( @@ -5140,7 +5145,7 @@ def rotated_match_tools() -> List[MCPTool]: "nms_iou": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.match_rotated_all, + handler=h_vision_exec.match_rotated_all, annotations=READ_ONLY, ), MCPTool( @@ -5159,7 +5164,7 @@ def rotated_match_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.match_with_trust, + handler=h_vision_exec.match_with_trust, annotations=READ_ONLY, ), MCPTool( @@ -5174,7 +5179,7 @@ def rotated_match_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.auto_threshold, + handler=h_vision_exec.auto_threshold, annotations=READ_ONLY, ), MCPTool( @@ -5190,7 +5195,7 @@ def rotated_match_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.match_auto, + handler=h_vision_exec.match_auto, annotations=READ_ONLY, ), MCPTool( @@ -5206,7 +5211,7 @@ def rotated_match_tools() -> List[MCPTool]: "scales": {"type": "array", "items": {"type": "number"}}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.edge_match, + handler=h_vision_exec.edge_match, annotations=READ_ONLY, ), MCPTool( @@ -5221,7 +5226,7 @@ def rotated_match_tools() -> List[MCPTool]: "nms_iou": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.edge_match_all, + handler=h_vision_exec.edge_match_all, annotations=READ_ONLY, ), MCPTool( @@ -5237,7 +5242,7 @@ def rotated_match_tools() -> List[MCPTool]: "region": {"type": "array", "items": {"type": "integer"}}, "method": {"type": "string"}}, required=["template"]), - handler=h_exec.match_subpixel, + handler=h_vision_exec.match_subpixel, annotations=READ_ONLY, ), MCPTool( @@ -5255,7 +5260,7 @@ def rotated_match_tools() -> List[MCPTool]: "min_votes": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["templates"]), - handler=h_exec.match_ensemble, + handler=h_vision_exec.match_ensemble, annotations=READ_ONLY, ), MCPTool( @@ -5269,7 +5274,7 @@ def rotated_match_tools() -> List[MCPTool]: "agree_px": {"type": "number"}, "min_votes": {"type": "integer"}}, required=["centers"]), - handler=h_exec.vote_centers, + handler=h_vision_exec.vote_centers, annotations=READ_ONLY, ), MCPTool( @@ -5287,7 +5292,7 @@ def rotated_match_tools() -> List[MCPTool]: "scales": {"type": "array", "items": {"type": "number"}}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.match_color, + handler=h_vision_exec.match_color, annotations=READ_ONLY, ), MCPTool( @@ -5303,7 +5308,7 @@ def rotated_match_tools() -> List[MCPTool]: "nms_iou": {"type": "number"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["template"]), - handler=h_exec.match_color_all, + handler=h_vision_exec.match_color_all, annotations=READ_ONLY, ), MCPTool( @@ -5317,7 +5322,7 @@ def rotated_match_tools() -> List[MCPTool]: "frames": {"type": "array", "items": {"type": "string", "format": "path"}}, "settle_threshold": {"type": "number"}}, required=["frames"]), - handler=h_exec.region_stability, + handler=h_vision_exec.region_stability, annotations=READ_ONLY, ), MCPTool( @@ -5333,7 +5338,7 @@ def rotated_match_tools() -> List[MCPTool]: "min_score": {"type": "number"}, "agree_px": {"type": "number"}}, required=["template", "frames"]), - handler=h_exec.match_persistence, + handler=h_vision_exec.match_persistence, annotations=READ_ONLY, ), ] @@ -5352,7 +5357,7 @@ def screen_grid_tools() -> List[MCPTool]: "cols": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["rows", "cols"]), - handler=h_exec.grid_cells, + handler=h_vision_exec.grid_cells, annotations=READ_ONLY, ), MCPTool( @@ -5366,7 +5371,7 @@ def screen_grid_tools() -> List[MCPTool]: "cols": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["x", "y", "rows", "cols"]), - handler=h_exec.cell_for_point, + handler=h_vision_exec.cell_for_point, annotations=READ_ONLY, ), MCPTool( @@ -5379,7 +5384,7 @@ def screen_grid_tools() -> List[MCPTool]: "cols": {"type": "integer"}, "region": {"type": "array", "items": {"type": "integer"}}}, required=["label", "rows", "cols"]), - handler=h_exec.point_for_cell, + handler=h_vision_exec.point_for_cell, annotations=READ_ONLY, ), MCPTool( @@ -5394,7 +5399,7 @@ def screen_grid_tools() -> List[MCPTool]: "text_boxes": {"type": "array", "items": {"type": "object"}}, "overlap": {"type": "number"}}, required=["grid", "text_boxes"]), - handler=h_exec.populate_table, + handler=h_vision_exec.populate_table, annotations=READ_ONLY, ), MCPTool( @@ -5408,7 +5413,7 @@ def screen_grid_tools() -> List[MCPTool]: "page_width": {"type": "integer"}, "min_gap": {"type": "integer"}}, required=["boxes"]), - handler=h_exec.column_gutters, + handler=h_vision_exec.column_gutters, annotations=READ_ONLY, ), MCPTool( @@ -5425,7 +5430,7 @@ def screen_grid_tools() -> List[MCPTool]: "min_cols": {"type": "integer"}, "min_rows": {"type": "integer"}}, required=["boxes"]), - handler=h_exec.detect_borderless_table, + handler=h_vision_exec.detect_borderless_table, annotations=READ_ONLY, ), MCPTool( @@ -5440,7 +5445,7 @@ def screen_grid_tools() -> List[MCPTool]: "directions": {"type": "array", "items": {"type": "string"}}, "max_gap": {"type": "integer"}}, required=["text_boxes"]), - handler=h_exec.associate_fields, + handler=h_vision_exec.associate_fields, annotations=READ_ONLY, ), MCPTool( @@ -5452,7 +5457,7 @@ def screen_grid_tools() -> List[MCPTool]: "labels": {"type": "array", "items": {"type": "object"}}, "widgets": {"type": "array", "items": {"type": "object"}}}, required=["labels", "widgets"]), - handler=h_exec.match_labels_to_widgets, + handler=h_vision_exec.match_labels_to_widgets, annotations=READ_ONLY, ), MCPTool( @@ -5466,7 +5471,7 @@ def screen_grid_tools() -> List[MCPTool]: "boxes": {"type": "array", "items": {"type": "object"}}, "min_gap": {"type": "integer"}}, required=["boxes"]), - handler=h_exec.flow_order, + handler=h_vision_exec.flow_order, annotations=READ_ONLY, ), MCPTool( @@ -5478,7 +5483,7 @@ def screen_grid_tools() -> List[MCPTool]: "boxes": {"type": "array", "items": {"type": "object"}}, "min_gap": {"type": "integer"}}, required=["boxes"]), - handler=h_exec.xy_cut, + handler=h_vision_exec.xy_cut, annotations=READ_ONLY, ), MCPTool( @@ -5491,7 +5496,7 @@ def screen_grid_tools() -> List[MCPTool]: "lines": {"type": "array", "items": {"type": "object"}}, "line_gap_factor": {"type": "number"}}, required=["lines"]), - handler=h_exec.group_paragraphs, + handler=h_vision_exec.group_paragraphs, annotations=READ_ONLY, ), MCPTool( @@ -5503,7 +5508,7 @@ def screen_grid_tools() -> List[MCPTool]: input_schema=schema({ "lines": {"type": "array", "items": {"type": "object"}}}, required=["lines"]), - handler=h_exec.detect_lists, + handler=h_vision_exec.detect_lists, annotations=READ_ONLY, ), MCPTool( @@ -5516,7 +5521,7 @@ def screen_grid_tools() -> List[MCPTool]: "lines": {"type": "array", "items": {"type": "object"}}, "heading_ratio": {"type": "number"}}, required=["lines"]), - handler=h_exec.classify_lines, + handler=h_vision_exec.classify_lines, annotations=READ_ONLY, ), MCPTool( @@ -5528,7 +5533,7 @@ def screen_grid_tools() -> List[MCPTool]: "lines": {"type": "array", "items": {"type": "object"}}, "heading_ratio": {"type": "number"}}, required=["lines"]), - handler=h_exec.outline, + handler=h_vision_exec.outline, annotations=READ_ONLY, ), ] @@ -5551,7 +5556,7 @@ def grid_locator_tools() -> List[MCPTool]: "row_tolerance": {"type": "integer"}, "box_format": {"type": "string", "enum": ["xywh", "ltrb"]}}, required=["boxes", "row", "col"]), - handler=h_exec.grid_cell, + handler=h_vision_exec.grid_cell, annotations=READ_ONLY, ), ] @@ -5569,7 +5574,7 @@ def modifier_state_tools() -> List[MCPTool]: "modifiers": {"type": "array", "items": {"type": "string"}}, "actions": {"type": "array"}}, required=["modifiers", "actions"]), - handler=h_exec.with_modifiers, + handler=h_desktop_exec.with_modifiers, annotations=DESTRUCTIVE, ), ] @@ -5586,7 +5591,7 @@ def text_unicode_tools() -> List[MCPTool]: input_schema=schema( {"text": {"type": "string"}, "modifier": {"type": "string"}}, required=["text"]), - handler=h_exec.type_unicode, + handler=h_desktop_exec.type_unicode, annotations=DESTRUCTIVE, ), MCPTool( @@ -5598,7 +5603,7 @@ def text_unicode_tools() -> List[MCPTool]: "silently do nothing while still reporting success. " "Sends one inert keystroke (F13) to find out."), input_schema=schema({}), - handler=h_exec.input_reachable, + handler=h_desktop_exec.input_reachable, annotations=SIDE_EFFECT_ONLY, ), MCPTool( @@ -5608,7 +5613,7 @@ def text_unicode_tools() -> List[MCPTool]: "backend that supports it (Windows). " "Returns {ops, plan, method, code_units}."), input_schema=schema({"text": {"type": "string"}}, required=["text"]), - handler=h_exec.type_unicode_keys, + handler=h_desktop_exec.type_unicode_keys, annotations=DESTRUCTIVE, ), MCPTool( @@ -5620,7 +5625,7 @@ def text_unicode_tools() -> List[MCPTool]: input_schema=schema( {"text": {"type": "string"}, "modifier": {"type": "string"}}, required=["text"]), - handler=h_exec.type_unicode_text, + handler=h_desktop_exec.type_unicode_text, annotations=DESTRUCTIVE, ), ] @@ -5635,7 +5640,7 @@ def mouse_relative_tools() -> List[MCPTool]: input_schema=schema( {"dx": {"type": "integer"}, "dy": {"type": "integer"}}, required=["dx", "dy"]), - handler=h_exec.move_mouse_relative, + handler=h_desktop_exec.move_mouse_relative, annotations=SIDE_EFFECT_ONLY, ), ] @@ -5653,7 +5658,7 @@ def key_hold_tools() -> List[MCPTool]: "duration_s": {"type": "number"}, "rate_hz": {"type": "number"}}, required=["key", "duration_s"]), - handler=h_exec.hold_key, + handler=h_desktop_exec.hold_key, annotations=DESTRUCTIVE, ), ] @@ -5671,7 +5676,7 @@ def field_entry_tools() -> List[MCPTool]: "text": {"type": "string"}, "clear": {"type": "string"}, "paste": {"type": "boolean"}, "modifier": {"type": "string"}}, required=["text"]), - handler=h_exec.set_field_text, + handler=h_desktop_exec.set_field_text, annotations=DESTRUCTIVE, ), ] @@ -5691,7 +5696,7 @@ def mouse_path_tools() -> List[MCPTool]: "easing": {"type": "string"}, "per_segment_steps": {"type": "integer"}}, required=["waypoints"]), - handler=h_exec.move_along_path, + handler=h_desktop_exec.move_along_path, annotations=DESTRUCTIVE, ), MCPTool( @@ -5711,7 +5716,7 @@ def mouse_path_tools() -> List[MCPTool]: "step_delay_s": {"type": "number", "minimum": 0}, "settle_s": {"type": "number", "minimum": 0}}, required=["waypoints"]), - handler=h_exec.drag_path, + handler=h_desktop_exec.drag_path, annotations=DESTRUCTIVE, ), ] @@ -6611,7 +6616,7 @@ def http_conditional_tools() -> List[MCPTool]: description=("Parse the 'headers' Cache-Control into {directives} " "(max-age as int, flags as true)."), input_schema=schema({"headers": {"type": "object"}}, ["headers"]), - handler=h_exec.parse_cache_control, + handler=h_data_exec.parse_cache_control, annotations=READ_ONLY, ), MCPTool( @@ -6620,7 +6625,7 @@ def http_conditional_tools() -> List[MCPTool]: "cache_control) from an HTTP 'response'. Returns " "{validators}."), input_schema=schema({"response": {"type": "object"}}, ["response"]), - handler=h_exec.store_validators, + handler=h_data_exec.store_validators, annotations=READ_ONLY, ), ] @@ -6636,7 +6641,7 @@ def cookie_jar_tools() -> List[MCPTool]: input_schema=schema( {"set_cookies": {"type": ["string", "array"]}}, ["set_cookies"]), - handler=h_exec.cookie_header, + handler=h_data_exec.cookie_header, annotations=READ_ONLY, ), MCPTool( @@ -6644,7 +6649,7 @@ def cookie_jar_tools() -> List[MCPTool]: description=("Parse one Set-Cookie 'header' into {cookie: {name, " "value, attributes}} (or null)."), input_schema=schema({"header": {"type": "string"}}, ["header"]), - handler=h_exec.parse_set_cookie, + handler=h_data_exec.parse_set_cookie, annotations=READ_ONLY, ), ] @@ -6661,7 +6666,7 @@ def http_content_tools() -> List[MCPTool]: {"headers": {"type": "object"}, "body_base64": {"type": "string"}}, ["headers", "body_base64"]), - handler=h_exec.decode_body, + handler=h_data_exec.decode_body, annotations=READ_ONLY, ), MCPTool( @@ -6670,7 +6675,7 @@ def http_content_tools() -> List[MCPTool]: "Accept-Encoding) into {values}: [token, q] sorted by q " "descending."), input_schema=schema({"header": {"type": "string"}}, ["header"]), - handler=h_exec.parse_quality_values, + handler=h_data_exec.parse_quality_values, annotations=READ_ONLY, ), ] @@ -6688,7 +6693,7 @@ def multipart_tools() -> List[MCPTool]: {"fields": {"type": "object"}, "files": {"type": "array"}, "boundary": {"type": "string"}}, []), - handler=h_exec.build_multipart, + handler=h_data_exec.build_multipart, annotations=READ_ONLY, ), MCPTool( @@ -6699,7 +6704,7 @@ def multipart_tools() -> List[MCPTool]: {"content_type": {"type": "string"}, "body_base64": {"type": "string"}}, ["content_type", "body_base64"]), - handler=h_exec.parse_multipart, + handler=h_data_exec.parse_multipart, annotations=READ_ONLY, ), ] @@ -6713,7 +6718,7 @@ def link_header_tools() -> List[MCPTool]: "(each {uri, rel, params}), handling quoted params and " "multiple links."), input_schema=schema({"value": {"type": "string"}}, ["value"]), - handler=h_exec.parse_link_header, + handler=h_data_exec.parse_link_header, annotations=READ_ONLY, ), MCPTool( @@ -6721,7 +6726,7 @@ def link_header_tools() -> List[MCPTool]: description=("Return the rel=next URL from a Link header 'value' as " "{url} (null when absent)."), input_schema=schema({"value": {"type": "string"}}, ["value"]), - handler=h_exec.next_url, + handler=h_data_exec.next_url, annotations=READ_ONLY, ), ] @@ -6739,7 +6744,7 @@ def referential_tools() -> List[MCPTool]: {"child_rows": rows, "child_col": {"type": "string"}, "parent_rows": rows, "parent_col": {"type": "string"}}, ["child_rows", "child_col", "parent_rows", "parent_col"]), - handler=h_exec.check_foreign_key, + handler=h_data_exec.check_foreign_key, annotations=READ_ONLY, ), MCPTool( @@ -6750,7 +6755,7 @@ def referential_tools() -> List[MCPTool]: input_schema=schema( {"rows": rows, "cols": {"type": ["string", "array"]}}, ["rows", "cols"]), - handler=h_exec.check_unique_key, + handler=h_data_exec.check_unique_key, annotations=READ_ONLY, ), MCPTool( @@ -6761,7 +6766,7 @@ def referential_tools() -> List[MCPTool]: {"rows": rows, "col": {"type": "string"}, "allowed": {"type": "array"}}, ["rows", "col", "allowed"]), - handler=h_exec.check_accepted_values, + handler=h_data_exec.check_accepted_values, annotations=READ_ONLY, ), MCPTool( @@ -6772,7 +6777,7 @@ def referential_tools() -> List[MCPTool]: {"rows": rows, "minimum": {"type": "integer"}, "maximum": {"type": "integer"}}, ["rows"]), - handler=h_exec.check_row_count, + handler=h_data_exec.check_row_count, annotations=READ_ONLY, ), ] @@ -6791,7 +6796,7 @@ def dataset_diff_tools() -> List[MCPTool]: {"old_rows": rows_schema, "new_rows": rows_schema, "key": key_schema}, ["old_rows", "new_rows", "key"]), - handler=h_exec.diff_rows, + handler=h_data_exec.diff_rows, annotations=READ_ONLY, ), MCPTool( @@ -6803,7 +6808,7 @@ def dataset_diff_tools() -> List[MCPTool]: {"old_rows": rows_schema, "new_rows": rows_schema, "key": key_schema}, ["old_rows", "new_rows", "key"]), - handler=h_exec.cell_changes, + handler=h_data_exec.cell_changes, annotations=READ_ONLY, ), ] @@ -6821,7 +6826,7 @@ def optimistic_tools() -> List[MCPTool]: "value": {"type": "object"}, "expected_version": {"type": "integer"}}, ["name", "key", "value"]), - handler=h_exec.cas_put, + handler=h_data_exec.cas_put, annotations=NON_DESTRUCTIVE, ), MCPTool( @@ -6831,7 +6836,7 @@ def optimistic_tools() -> List[MCPTool]: input_schema=schema( {"name": {"type": "string"}, "key": {"type": "string"}}, ["name", "key"]), - handler=h_exec.cas_get, + handler=h_data_exec.cas_get, annotations=READ_ONLY, ), ] @@ -6846,7 +6851,7 @@ def outbox_tools() -> List[MCPTool]: input_schema=schema( {"name": {"type": "string"}, "event": {"type": "object"}}, ["name", "event"]), - handler=h_exec.outbox_enqueue, + handler=h_data_exec.outbox_enqueue, annotations=NON_DESTRUCTIVE, ), MCPTool( @@ -6854,7 +6859,7 @@ def outbox_tools() -> List[MCPTool]: description=("List the pending entries of named outbox 'name'. " "Returns {pending}."), input_schema=schema({"name": {"type": "string"}}, ["name"]), - handler=h_exec.outbox_pending, + handler=h_data_exec.outbox_pending, annotations=READ_ONLY, ), ] @@ -6873,7 +6878,7 @@ def locale_collation_tools() -> List[MCPTool]: "tailoring": {"type": "string"}, "reverse": {"type": "boolean"}}, ["items"]), - handler=h_exec.collation_sort, + handler=h_data_exec.collation_sort, annotations=READ_ONLY, ), MCPTool( @@ -6885,7 +6890,7 @@ def locale_collation_tools() -> List[MCPTool]: "strength": {"type": "string"}, "tailoring": {"type": "string"}}, ["first", "second"]), - handler=h_exec.collation_compare, + handler=h_data_exec.collation_compare, annotations=READ_ONLY, ), ] @@ -6898,7 +6903,7 @@ def confusables_tools() -> List[MCPTool]: description=("Homoglyph / mixed-script spoofing report for 'text'. " "Returns {skeleton, homoglyphs, mixed_script, scripts}."), input_schema=schema({"text": {"type": "string"}}, ["text"]), - handler=h_exec.confusable_scan, + handler=h_data_exec.confusable_scan, annotations=READ_ONLY, ), MCPTool( @@ -6908,7 +6913,7 @@ def confusables_tools() -> List[MCPTool]: input_schema=schema( {"first": {"type": "string"}, "second": {"type": "string"}}, ["first", "second"]), - handler=h_exec.confusable_compare, + handler=h_data_exec.confusable_compare, annotations=READ_ONLY, ), ] @@ -6921,7 +6926,7 @@ def readability_tools() -> List[MCPTool]: description=("Readability report for 'text': Flesch reading ease, " "Flesch-Kincaid grade, Gunning Fog, SMOG, ARI + counts."), input_schema=schema({"text": {"type": "string"}}, ["text"]), - handler=h_exec.readability_report, + handler=h_data_exec.readability_report, annotations=READ_ONLY, ), ] @@ -6937,7 +6942,7 @@ def list_format_tools() -> List[MCPTool]: {"items": {"type": "array", "items": {"type": "string"}}, "style": {"type": "string"}, "locale": {"type": "string"}}, ["items"]), - handler=h_exec.format_list, + handler=h_data_exec.format_list, annotations=READ_ONLY, ), ] @@ -6953,7 +6958,7 @@ def gettext_catalog_tools() -> List[MCPTool]: {"po": {"type": "string"}, "msgid": {"type": "string"}, "context": {"type": "string"}}, ["po", "msgid"]), - handler=h_exec.gettext_translate, + handler=h_data_exec.gettext_translate, annotations=READ_ONLY, ), MCPTool( @@ -6964,7 +6969,7 @@ def gettext_catalog_tools() -> List[MCPTool]: {"po": {"type": "string"}, "msgid": {"type": "string"}, "msgid_plural": {"type": "string"}, "n": {"type": "integer"}}, ["po", "msgid", "msgid_plural", "n"]), - handler=h_exec.gettext_ngettext, + handler=h_data_exec.gettext_ngettext, annotations=READ_ONLY, ), ] @@ -6979,7 +6984,7 @@ def checksum_tools() -> List[MCPTool]: input_schema=schema( {"scheme": {"type": "string"}, "number": {"type": "string"}}, ["scheme", "number"]), - handler=h_exec.checksum_validate, + handler=h_data_exec.checksum_validate, annotations=READ_ONLY, ), MCPTool( @@ -6990,7 +6995,7 @@ def checksum_tools() -> List[MCPTool]: input_schema=schema( {"scheme": {"type": "string"}, "partial": {"type": "string"}}, ["scheme", "partial"]), - handler=h_exec.checksum_digit, + handler=h_data_exec.checksum_digit, annotations=READ_ONLY, ), ] @@ -7007,7 +7012,7 @@ def message_format_tools() -> List[MCPTool]: {"pattern": {"type": "string"}, "args": {"type": "object"}, "locale": {"type": "string"}}, ["pattern"]), - handler=h_exec.format_message, + handler=h_data_exec.format_message, annotations=READ_ONLY, ), ] @@ -7020,7 +7025,7 @@ def bidi_check_tools() -> List[MCPTool]: description=("Bidirectional-text QA for 'text': bidi controls, " "nesting balance, base direction, Trojan-source flag."), input_schema=schema({"text": {"type": "string"}}, ["text"]), - handler=h_exec.bidi_check, + handler=h_data_exec.bidi_check, annotations=READ_ONLY, ), MCPTool( @@ -7028,7 +7033,7 @@ def bidi_check_tools() -> List[MCPTool]: description=("Remove every bidi control character from 'text'. " "Returns {text}."), input_schema=schema({"text": {"type": "string"}}, ["text"]), - handler=h_exec.bidi_strip, + handler=h_data_exec.bidi_strip, annotations=NON_DESTRUCTIVE, ), ] @@ -7045,7 +7050,7 @@ def sequence_gap_tools() -> List[MCPTool]: {"name": {"type": "string"}, "stream_id": {"type": "string"}, "seq": {"type": "integer"}}, ["name", "stream_id", "seq"]), - handler=h_exec.sequence_observe, + handler=h_data_exec.sequence_observe, annotations=NON_DESTRUCTIVE, ), ] @@ -7062,7 +7067,7 @@ def dedup_window_tools() -> List[MCPTool]: {"name": {"type": "string"}, "message_id": {"type": "string"}, "ttl_s": {"type": "number"}}, ["name", "message_id"]), - handler=h_exec.dedup_check, + handler=h_data_exec.dedup_check, annotations=NON_DESTRUCTIVE, ), ] @@ -7079,7 +7084,7 @@ def idempotency_tools() -> List[MCPTool]: {"name": {"type": "string"}, "key": {"type": "string"}, "request": {"type": "object"}}, ["name", "key"]), - handler=h_exec.idempotency_begin, + handler=h_data_exec.idempotency_begin, annotations=NON_DESTRUCTIVE, ), MCPTool( @@ -7090,7 +7095,7 @@ def idempotency_tools() -> List[MCPTool]: {"name": {"type": "string"}, "key": {"type": "string"}, "response": {"type": "object"}}, ["name", "key", "response"]), - handler=h_exec.idempotency_complete, + handler=h_data_exec.idempotency_complete, annotations=NON_DESTRUCTIVE, ), MCPTool( @@ -7101,7 +7106,7 @@ def idempotency_tools() -> List[MCPTool]: input_schema=schema( {"name": {"type": "string"}, "key": {"type": "string"}}, ["name", "key"]), - handler=h_exec.idempotency_release, + handler=h_data_exec.idempotency_release, annotations=NON_DESTRUCTIVE, ), ] @@ -7116,7 +7121,7 @@ def smoothing_tools() -> List[MCPTool]: input_schema=schema( {"values": {"type": "array"}, "window": {"type": "integer"}}, ["values", "window"]), - handler=h_exec.sma, + handler=h_data_exec.sma, annotations=READ_ONLY, ), MCPTool( @@ -7126,7 +7131,7 @@ def smoothing_tools() -> List[MCPTool]: input_schema=schema( {"values": {"type": "array"}, "alpha": {"type": "number"}}, ["values"]), - handler=h_exec.ewma, + handler=h_data_exec.ewma, annotations=READ_ONLY, ), ] @@ -7143,7 +7148,7 @@ def anomaly_tools() -> List[MCPTool]: {"values": {"type": "array"}, "method": {"type": "string"}, "threshold": {"type": "number"}}, ["values"]), - handler=h_exec.detect_anomalies, + handler=h_data_exec.detect_anomalies, annotations=READ_ONLY, ), ] @@ -7159,7 +7164,7 @@ def timeseries_tools() -> List[MCPTool]: input_schema=schema( {"series": {"type": "array"}, "window_s": {"type": "number"}}, ["series"]), - handler=h_exec.ts_rate, + handler=h_data_exec.ts_rate, annotations=READ_ONLY, ), MCPTool( @@ -7171,7 +7176,7 @@ def timeseries_tools() -> List[MCPTool]: {"series": {"type": "array"}, "bucket_s": {"type": "number"}, "agg": {"type": "string"}}, ["series", "bucket_s"]), - handler=h_exec.ts_downsample, + handler=h_data_exec.ts_downsample, annotations=READ_ONLY, ), ] @@ -7188,7 +7193,7 @@ def schema_compat_tools() -> List[MCPTool]: {"old": {"type": "object"}, "new": {"type": "object"}, "mode": {"type": "string"}}, ["old", "new"]), - handler=h_exec.check_compatibility, + handler=h_data_exec.check_compatibility, annotations=READ_ONLY, ), ] @@ -7207,7 +7212,7 @@ def data_drift_tools() -> List[MCPTool]: {"reference": seq_schema, "current": seq_schema, "threshold": {"type": "number"}, "bins": {"type": "integer"}}, ["reference", "current"]), - handler=h_exec.detect_drift, + handler=h_data_exec.detect_drift, annotations=READ_ONLY, ), MCPTool( @@ -7218,7 +7223,7 @@ def data_drift_tools() -> List[MCPTool]: input_schema=schema( {"reference": seq_schema, "current": seq_schema}, ["reference", "current"]), - handler=h_exec.categorical_drift, + handler=h_data_exec.categorical_drift, annotations=READ_ONLY, ), ] @@ -7233,7 +7238,7 @@ def layered_config_tools() -> List[MCPTool]: "mapping, priority?}; higher priority wins) into a " "single {config}."), input_schema=schema({"layers": layer_schema}, ["layers"]), - handler=h_exec.resolve_config, + handler=h_data_exec.resolve_config, annotations=READ_ONLY, ), MCPTool( @@ -7243,7 +7248,7 @@ def layered_config_tools() -> List[MCPTool]: input_schema=schema( {"layers": layer_schema, "key": {"type": "string"}}, ["layers", "key"]), - handler=h_exec.explain_config, + handler=h_data_exec.explain_config, annotations=READ_ONLY, ), ] @@ -7257,7 +7262,7 @@ def sse_client_tools() -> List[MCPTool]: "'text' blob into {events} (event/data/id/retry), " "flushing a trailing event without a final blank line."), input_schema=schema({"text": {"type": "string"}}, ["text"]), - handler=h_exec.parse_sse, + handler=h_data_exec.parse_sse, annotations=READ_ONLY, ), ] @@ -7270,7 +7275,7 @@ def dotenv_tools() -> List[MCPTool]: description=("Parse .env 'text' (KEY=VALUE lines, export prefixes, " "quoting, escapes, inline comments) into {values}."), input_schema=schema({"text": {"type": "string"}}, ["text"]), - handler=h_exec.parse_dotenv, + handler=h_data_exec.parse_dotenv, annotations=READ_ONLY, ), MCPTool( @@ -7280,7 +7285,7 @@ def dotenv_tools() -> List[MCPTool]: input_schema=schema( {"path": {"type": "string", "format": "path"}, "override": {"type": "boolean"}}, ["path"]), - handler=h_exec.load_dotenv, + handler=h_data_exec.load_dotenv, annotations=READ_ONLY, ), ] @@ -7295,7 +7300,7 @@ def http_problem_tools() -> List[MCPTool]: "{problem} (type/title/status/detail/instance + " "extensions) or null when not a problem document."), input_schema=schema({"response": {"type": "object"}}, ["response"]), - handler=h_exec.parse_problem, + handler=h_data_exec.parse_problem, annotations=READ_ONLY, ), ] @@ -7312,7 +7317,7 @@ def data_profile_tools() -> List[MCPTool]: input_schema=schema( {"rows": {"type": "array"}, "columns": {"type": "array"}}, ["rows"]), - handler=h_exec.profile_rows, + handler=h_data_exec.profile_rows, annotations=READ_ONLY, ), MCPTool( @@ -7323,7 +7328,7 @@ def data_profile_tools() -> List[MCPTool]: input_schema=schema( {"rows": {"type": "array"}, "columns": {"type": "array"}}, ["rows"]), - handler=h_exec.infer_schema, + handler=h_data_exec.infer_schema, annotations=READ_ONLY, ), ] @@ -7339,7 +7344,7 @@ def config_redaction_tools() -> List[MCPTool]: input_schema=schema( {"obj": {"type": "object"}, "mask": {"type": "string"}}, ["obj"]), - handler=h_exec.redact_config, + handler=h_data_exec.redact_config, annotations=READ_ONLY, ), MCPTool( @@ -7350,7 +7355,7 @@ def config_redaction_tools() -> List[MCPTool]: input_schema=schema( {"text": {"type": "string"}, "mask": {"type": "string"}}, ["text"]), - handler=h_exec.redact_secret_text, + handler=h_data_exec.redact_secret_text, annotations=READ_ONLY, ), ] @@ -7366,7 +7371,7 @@ def config_schema_tools() -> List[MCPTool]: input_schema=schema( {"schema": {"type": "object"}, "config": {"type": "object"}}, ["schema", "config"]), - handler=h_exec.validate_config, + handler=h_data_exec.validate_config, annotations=READ_ONLY, ), ] @@ -7379,7 +7384,7 @@ def secret_ref_tools() -> List[MCPTool]: description=("Resolve a value reference 'ref' (env://VAR, " "file://path, or secret://name) to {value}."), input_schema=schema({"ref": {"type": "string", "format": "value-ref"}}, ["ref"]), - handler=h_exec.resolve_ref, + handler=h_data_exec.resolve_ref, annotations=READ_ONLY, ), MCPTool( @@ -7387,7 +7392,7 @@ def secret_ref_tools() -> List[MCPTool]: description=("Recursively resolve every env:// / file:// / secret:// " "reference inside 'obj'. Returns {resolved}."), input_schema=schema({"obj": {"type": "object", "format": "value-ref"}}, ["obj"]), - handler=h_exec.resolve_refs, + handler=h_data_exec.resolve_refs, annotations=READ_ONLY, ), ] @@ -7405,7 +7410,7 @@ def otlp_export_tools() -> List[MCPTool]: {"spans": {"type": "array"}, "resource_attrs": {"type": "object"}}, ["spans"]), - handler=h_exec.spans_to_otlp, + handler=h_data_exec.spans_to_otlp, annotations=READ_ONLY, ), ] @@ -7420,7 +7425,7 @@ def near_dup_tools() -> List[MCPTool]: input_schema=schema( {"text": {"type": "string"}, "bits": {"type": "integer"}}, ["text"]), - handler=h_exec.simhash, + handler=h_data_exec.simhash, annotations=READ_ONLY, ), MCPTool( @@ -7431,7 +7436,7 @@ def near_dup_tools() -> List[MCPTool]: {"texts": {"type": "array"}, "max_distance": {"type": "integer"}}, ["texts"]), - handler=h_exec.near_duplicates, + handler=h_data_exec.near_duplicates, annotations=READ_ONLY, ), ] @@ -7448,7 +7453,7 @@ def text_similarity_tools() -> List[MCPTool]: {"a": {"type": "string"}, "b": {"type": "string"}, "metric": {"type": "string"}}, ["a", "b"]), - handler=h_exec.text_similarity, + handler=h_data_exec.text_similarity, annotations=READ_ONLY, ), ] @@ -7466,7 +7471,7 @@ def text_normalize_tools() -> List[MCPTool]: "casefold": {"type": "boolean"}, "collapse_ws": {"type": "boolean"}}, ["text"]), - handler=h_exec.normalize_text, + handler=h_data_exec.normalize_text, annotations=READ_ONLY, ), MCPTool( @@ -7477,7 +7482,7 @@ def text_normalize_tools() -> List[MCPTool]: input_schema=schema( {"text": {"type": "string"}, "sep": {"type": "string"}}, ["text"]), - handler=h_exec.slugify, + handler=h_data_exec.slugify, annotations=READ_ONLY, ), ] @@ -7490,7 +7495,7 @@ def canonical_log_tools() -> List[MCPTool]: description=("Build a canonical (wide-event) log line from a " "'fields' object. Returns {line, json}."), input_schema=schema({"fields": {"type": "object"}}, ["fields"]), - handler=h_exec.canonical_log, + handler=h_data_exec.canonical_log, annotations=READ_ONLY, ), ] @@ -7503,7 +7508,7 @@ def baggage_tools() -> List[MCPTool]: description=("Parse a W3C 'baggage' header (percent-encoded " "key=value list, optional ;metadata) into {items}."), input_schema=schema({"header": {"type": "string"}}, ["header"]), - handler=h_exec.baggage_parse, + handler=h_data_exec.baggage_parse, annotations=READ_ONLY, ), MCPTool( @@ -7511,7 +7516,7 @@ def baggage_tools() -> List[MCPTool]: description=("Serialise an 'items' object into a percent-encoded " "W3C baggage {header}."), input_schema=schema({"items": {"type": "object"}}, ["items"]), - handler=h_exec.baggage_format, + handler=h_data_exec.baggage_format, annotations=READ_ONLY, ), ] @@ -7529,7 +7534,7 @@ def trace_context_tools() -> List[MCPTool]: {"headers": {"type": "object"}, "traceparent": {"type": "string"}}, []), - handler=h_exec.trace_inject, + handler=h_data_exec.trace_inject, annotations=READ_ONLY, ), MCPTool( @@ -7537,7 +7542,7 @@ def trace_context_tools() -> List[MCPTool]: description=("Extract a W3C trace context from request 'headers'. " "Returns {context} (or null when no traceparent)."), input_schema=schema({"headers": {"type": "object"}}, ["headers"]), - handler=h_exec.trace_extract, + handler=h_data_exec.trace_extract, annotations=READ_ONLY, ), ] @@ -7572,7 +7577,7 @@ def bulkhead_tools() -> List[MCPTool]: "max_concurrent": {"type": "integer"}, "actions": {"type": "array"}}, ["name", "max_concurrent", "actions"]), - handler=h_exec.bulkhead_run, + handler=h_automation_exec.bulkhead_run, annotations=DESTRUCTIVE, ), MCPTool( @@ -7640,7 +7645,7 @@ def chaos_tools() -> List[MCPTool]: " — verify steady state, inject faults, re-verify, roll " "back. Returns the journal {status, deviated, ...}."), input_schema=schema({"spec": {"type": "object"}}, ["spec"]), - handler=h_exec.run_chaos, + handler=h_automation_exec.run_chaos, annotations=DESTRUCTIVE, ), ] @@ -9040,7 +9045,7 @@ def flakiness_tools() -> List[MCPTool]: input_schema=schema({"error": {"type": "string"}, "length": {"type": "integer"}}, required=["error"]), - handler=h_exec.failure_signature, + handler=h_automation_exec.failure_signature, annotations=READ_ONLY, ), MCPTool( @@ -9051,7 +9056,7 @@ def flakiness_tools() -> List[MCPTool]: input_schema=schema({ "errors": {"type": "array", "items": {"type": "string"}}}, required=["errors"]), - handler=h_exec.group_failures, + handler=h_automation_exec.group_failures, annotations=READ_ONLY, ), MCPTool( @@ -9067,7 +9072,7 @@ def flakiness_tools() -> List[MCPTool]: "key": {"type": "string"}, "regress_factor": {"type": "number"}}, required=["before", "after"]), - handler=h_exec.diff_runs, + handler=h_automation_exec.diff_runs, annotations=READ_ONLY, ), MCPTool( @@ -9083,7 +9088,7 @@ def flakiness_tools() -> List[MCPTool]: "threshold": {"type": "number"}, "min_size": {"type": "integer"}}, required=["runs"]), - handler=h_exec.failure_clusters, + handler=h_automation_exec.failure_clusters, annotations=READ_ONLY, ), MCPTool( @@ -9096,7 +9101,7 @@ def flakiness_tools() -> List[MCPTool]: "items": {"type": "array", "items": {"type": "string"}}}, "threshold": {"type": "number"}}, required=["runs"]), - handler=h_exec.cofailure_pairs, + handler=h_automation_exec.cofailure_pairs, annotations=READ_ONLY, ), MCPTool( @@ -9108,7 +9113,7 @@ def flakiness_tools() -> List[MCPTool]: input_schema=schema({ "steps": {"type": "array", "items": {"type": "object"}}}, required=["steps"]), - handler=h_exec.build_timeline, + handler=h_automation_exec.build_timeline, annotations=READ_ONLY, ), MCPTool( @@ -9120,7 +9125,7 @@ def flakiness_tools() -> List[MCPTool]: "steps": {"type": "array", "items": {"type": "object"}}, "top": {"type": "integer"}}, required=["steps"]), - handler=h_exec.critical_steps, + handler=h_automation_exec.critical_steps, annotations=READ_ONLY, ), ] diff --git a/je_auto_control/utils/mcp_server/tools/_handlers.py b/je_auto_control/utils/mcp_server/tools/_handlers.py index 2eeb88b4b..fbd992ae1 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers.py @@ -8,7 +8,7 @@ import os from typing import Any, Dict, List -from je_auto_control.utils.mcp_server.tools._handlers_executor_bridge import ( +from je_auto_control.utils.mcp_server.tools._handlers_vision_executor import ( anchor_locate, ) from je_auto_control.utils.mcp_server.tools._handlers_operations import ( diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_accessibility_executor.py b/je_auto_control/utils/mcp_server/tools/_handlers_accessibility_executor.py new file mode 100644 index 000000000..572df133d --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_handlers_accessibility_executor.py @@ -0,0 +1,383 @@ +"""MCP accessibility adapters delegating lazily to executor commands. + +Annotations mirror the executor JSON boundary, including heterogeneous payloads. +""" + +from typing import Any, Dict, List, Optional + + +def expand_control( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _expand_control + + return _expand_control(name, role, app_name, automation_id) + + +def collapse_control( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _collapse_control + + return _collapse_control(name, role, app_name, automation_id) + + +def control_expand_state( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _control_expand_state + + return _control_expand_state(name, role, app_name, automation_id) + + +def select_control_item( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _select_control_item + + return _select_control_item(name, role, app_name, automation_id) + + +def control_range( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _control_range + + return _control_range(name, role, app_name, automation_id) + + +def set_control_range( + value: Any, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _set_control_range + + return _set_control_range(value, name, role, app_name, automation_id) + + +def scroll_control_into_view( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _scroll_control_into_view + + return _scroll_control_into_view(name, role, app_name, automation_id) + + +def get_control_text( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_control_text + + return _get_control_text(name, role, app_name, automation_id) + + +def find_control_text( + text: str, + ignore_case: Any = True, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _find_control_text + + return _find_control_text(text, ignore_case, name, role, app_name, automation_id) + + +def select_control_text( + text: str, + ignore_case: Any = True, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _select_control_text + + return _select_control_text(text, ignore_case, name, role, app_name, automation_id) + + +def control_text_attributes( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _control_text_attributes + + return _control_text_attributes(name, role, app_name, automation_id) + + +def realize_item( + item_name: str, + by: str = "name", + container_name: Optional[str] = None, + container_role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _realize_item + + return _realize_item(item_name, by, container_name, container_role, app_name, automation_id) + + +def get_element_properties( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_element_properties + + return _get_element_properties(name, role, app_name, automation_id) + + +def table_headers( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _table_headers + + return _table_headers(name, role, app_name, automation_id) + + +def table_cell( + row: Any, + column: Any, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _table_cell + + return _table_cell(row, column, name, role, app_name, automation_id) + + +def cell_by_header( + row: Any, + column_header: str, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cell_by_header + + return _cell_by_header(row, column_header, name, role, app_name, automation_id) + + +def move_element( + x: Any, + y: Any, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _move_element + + return _move_element(x, y, name, role, app_name, automation_id) + + +def resize_element( + width: Any, + height: Any, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _resize_element + + return _resize_element(width, height, name, role, app_name, automation_id) + + +def set_window_state( + state: str, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _set_window_state + + return _set_window_state(state, name, role, app_name, automation_id) + + +def window_interaction_state( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _window_interaction_state + + return _window_interaction_state(name, role, app_name, automation_id) + + +def legacy_info( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _legacy_info + + return _legacy_info(name, role, app_name, automation_id) + + +def legacy_default_action( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _legacy_default_action + + return _legacy_default_action(name, role, app_name, automation_id) + + +def get_selection( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_selection + + return _get_selection(name, role, app_name, automation_id) + + +def list_views( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _list_views + + return _list_views(name, role, app_name, automation_id) + + +def set_view( + view: str, + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _set_view + + return _set_view(view, name, role, app_name, automation_id) + + +def wait_for_focus_change(timeout: Any = 5.0) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _wait_for_focus_change + + return _wait_for_focus_change(timeout) + + +def get_selected_text( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_selected_text + + return _get_selected_text(name, role, app_name, automation_id) + + +def get_visible_text( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_visible_text + + return _get_visible_text(name, role, app_name, automation_id) + + +def walk_tree(app_name: Optional[str] = None, max_results: int = 500) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _walk_tree + + return _walk_tree(app_name, max_results) + + +def humanize_role(role: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _humanize_role + + return _humanize_role(role) + + +def tab_order(app_name: Optional[str] = None, max_results: int = 500) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _tab_order + + return _tab_order(app_name, max_results) + + +def audit_focus_order(app_name: Optional[str] = None, max_results: int = 500) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _audit_focus_order + + return _audit_focus_order(app_name, max_results) + + +def focus_control( + name: Optional[str] = None, + role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None, +) -> bool: + from je_auto_control.utils.executor.action_executor import _focus_control + + return _focus_control(name, role, app_name, automation_id) + + +def a11y_record_start( + app_name: Optional[str] = None, poll_interval_s: float = 0.25, min_movement_px: int = 8 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import ( + _a11y_record_start, + ) + + return _a11y_record_start( + app_name=app_name, + poll_interval_s=float(poll_interval_s), + min_movement_px=int(min_movement_px), + ) + + +def a11y_record_stop() -> List[Dict[str, Any]]: + from je_auto_control.utils.executor.action_executor import ( + _a11y_record_stop, + ) + + return _a11y_record_stop() diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_automation_executor.py b/je_auto_control/utils/mcp_server/tools/_handlers_automation_executor.py new file mode 100644 index 000000000..f88ef441c --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_handlers_automation_executor.py @@ -0,0 +1,236 @@ +"""MCP automation adapters delegating lazily to executor commands. + +Annotations mirror the executor JSON boundary, including heterogeneous payloads. +""" + +from typing import Any, Callable, Dict, List, Optional + + +def _observe_handler(actions: List[Any]) -> Callable[[str, Any], None]: + # The executor's own builder: each firing runs in a fresh variable scope + # seeded with what the registering tool call could see (normally nothing). + from je_auto_control.utils.executor.action_executor import ( + _observe_handler as build_handler, + ) + + return build_handler(actions) + + +def circuit_call(name: str, actions: List[Any], threshold: int = 5, reset_s: float = 30.0) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _circuit_call + + return _circuit_call(name, actions, threshold=int(threshold), reset_s=float(reset_s)) + + +def run_chaos(spec: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _run_chaos + + return _run_chaos(spec) + + +def bulkhead_run(name: str, max_concurrent: int, actions: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _bulkhead_run + + return _bulkhead_run(name, max_concurrent, actions) + + +def expect_poll( + action: Any, key: Any = None, op: str = "truthy", expected: Any = None, timeout_s: Any = 5.0, interval_s: Any = 0.25 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _expect_poll + + return _expect_poll(action, key, op, expected, timeout_s, interval_s) + + +def failure_signature(error: str, length: Any = 12) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _failure_signature + + return _failure_signature(error, length) + + +def group_failures(errors: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _group_failures + + return _group_failures(errors) + + +def diff_runs(before: Any, after: Any, key: str = "name", regress_factor: Any = 1.5) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _diff_runs + + return _diff_runs(before, after, key, regress_factor) + + +def failure_clusters(runs: Any, threshold: Any = 0.5, min_size: Any = 2) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _failure_clusters + + return _failure_clusters(runs, threshold, min_size) + + +def cofailure_pairs(runs: Any, threshold: Any = 0.5) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cofailure_pairs + + return _cofailure_pairs(runs, threshold) + + +def build_timeline(steps: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _build_timeline + + return _build_timeline(steps) + + +def critical_steps(steps: Any, top: Any = 3) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _critical_steps + + return _critical_steps(steps, top) + + +def soft_assert(checks: Any, raise_on_fail: Any = False) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _soft_assert + + return _soft_assert(checks, raise_on_fail) + + +def cua_command(payload: Any, source: str = "canonical") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cua_command + + return _cua_command(payload, source) + + +def serialize_observation(elements: Any, viewport: Any = None, max_elements: Any = 80) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _serialize_observation + + return _serialize_observation(elements, viewport, max_elements) + + +def observation_index(elements: Any, viewport: Any = None, max_elements: Any = 80) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _observation_index + + return _observation_index(elements, viewport, max_elements) + + +def delta_observation( + prev: Any, + curr: Any, + viewport: Any = None, + max_elements: Any = 80, + max_lines: Any = 40, + interactive_only: Any = True, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _delta_observation + + return _delta_observation(prev, curr, viewport, max_elements, max_lines, interactive_only) + + +def classify_effect(before: Any, after: Any, action: Any, radius: Any = 64) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _classify_effect + + return _classify_effect(before, after, action, radius) + + +def effect_near_point(before: Any, after: Any, point: Any, radius: Any = 64) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _effect_near_point + + return _effect_near_point(before, after, point, radius) + + +def check_postcondition(after: Any, spec: Any, before: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _check_postcondition + + return _check_postcondition(after, spec, before) + + +def plan_repair(verdict: Any, max_attempts: Any = 3) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _plan_repair + + return _plan_repair(verdict, max_attempts) + + +def consensus_point(candidates: Any, cluster_radius: Any = 24) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _consensus_point + + return _consensus_point(candidates, cluster_radius) + + +def consensus_element(candidates: Any, elements: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _consensus_element + + return _consensus_element(candidates, elements) + + +def settle_point(churns: Any, quiet_samples: Any = 3, max_churn: Any = 1.0) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _settle_point + + return _settle_point(churns, quiet_samples, max_churn) + + +def build_critic_record( + action: Any, before: Any, after: Any, postcondition: Any = None, radius: Any = 64 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _build_critic_record + + return _build_critic_record(action, before, after, postcondition, radius) + + +def score_step(record: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _score_step + + return _score_step(record) + + +def validate_action(action: Any, screen: Any = None, targets: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _validate_action + + return _validate_action(action, screen, targets) + + +def replay_trace(trace: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _replay_trace + + return _replay_trace(trace) + + +def match_elements(before: Any, after: Any, iou_threshold: Any = 0.5) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_elements + + return _match_elements(before, after, iou_threshold) + + +def assign_stable_ids(elements: Any, prior: Any = None, iou_threshold: Any = 0.5) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _assign_stable_ids + + return _assign_stable_ids(elements, prior, iou_threshold) + + +def score_candidates( + candidates: Any, want_role: Any = None, want_name: Any = None, anchor: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _score_candidates + + return _score_candidates(candidates, want_role, want_name, anchor) + + +def best_candidate(candidates: Any, want_role: Any = None, want_name: Any = None, anchor: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _best_candidate + + return _best_candidate(candidates, want_role, want_name, anchor) + + +def run_agent( + goal: str, + backend: str = "anthropic", + max_steps: int = 25, + wall_seconds: float = 300.0, + model: Optional[str] = None, + max_tokens: int = 1024, +) -> Dict[str, Any]: + """Drive the generic plan→act→verify→retry AgentLoop against ``goal``.""" + from je_auto_control.utils.executor.action_executor import _run_agent + + return _run_agent( + goal=goal, + backend=backend, + max_steps=int(max_steps), + wall_seconds=float(wall_seconds), + model=model, + max_tokens=int(max_tokens), + ) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_data_executor.py b/je_auto_control/utils/mcp_server/tools/_handlers_data_executor.py new file mode 100644 index 000000000..c973a2e93 --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_handlers_data_executor.py @@ -0,0 +1,428 @@ +"""MCP data adapters delegating lazily to executor commands. + +Annotations mirror the executor JSON boundary, including heterogeneous payloads. +""" + +from typing import Any, Dict + + +def trace_inject(headers: Any = None, traceparent: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _trace_inject + + return _trace_inject(headers, traceparent) + + +def trace_extract(headers: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _trace_extract + + return _trace_extract(headers) + + +def baggage_parse(header: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _baggage_parse + + return _baggage_parse(header) + + +def baggage_format(items: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _baggage_format + + return _baggage_format(items) + + +def normalize_text(text: str, form: str = "NFKC", casefold: Any = True, collapse_ws: Any = True) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _normalize_text + + return _normalize_text(text, form, casefold, collapse_ws) + + +def slugify(text: str, sep: str = "-") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _slugify + + return _slugify(text, sep) + + +def text_similarity(a: str, b: str, metric: str = "jaro_winkler") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _text_similarity + + return _text_similarity(a, b, metric) + + +def simhash(text: str, bits: Any = 64) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _simhash + + return _simhash(text, bits) + + +def near_duplicates(texts: Any, max_distance: Any = 3) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _near_duplicates + + return _near_duplicates(texts, max_distance) + + +def canonical_log(fields: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _canonical_log + + return _canonical_log(fields) + + +def spans_to_otlp(spans: Any, resource_attrs: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _spans_to_otlp + + return _spans_to_otlp(spans, resource_attrs) + + +def validate_config(schema: Any, config: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _validate_config + + return _validate_config(schema, config) + + +def resolve_ref(ref: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _resolve_ref + + return _resolve_ref(ref) + + +def resolve_refs(obj: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _resolve_refs + + return _resolve_refs(obj) + + +def parse_link_header(value: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_link_header + + return _parse_link_header(value) + + +def next_url(value: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _next_url + + return _next_url(value) + + +def build_multipart(fields: Any = None, files: Any = None, boundary: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _build_multipart + + return _build_multipart(fields, files, boundary) + + +def parse_multipart(content_type: str, body_base64: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_multipart + + return _parse_multipart(content_type, body_base64) + + +def decode_body(headers: Any, body_base64: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _decode_body + + return _decode_body(headers, body_base64) + + +def parse_quality_values(header: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_quality_values + + return _parse_quality_values(header) + + +def cookie_header(set_cookies: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cookie_header + + return _cookie_header(set_cookies) + + +def parse_set_cookie(header: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_set_cookie + + return _parse_set_cookie(header) + + +def parse_cache_control(headers: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_cache_control + + return _parse_cache_control(headers) + + +def store_validators(response: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _store_validators + + return _store_validators(response) + + +def redact_config(obj: Any, mask: str = "***") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _redact_config + + return _redact_config(obj, mask) + + +def redact_secret_text(text: str, mask: str = "***") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _redact_secret_text + + return _redact_secret_text(text, mask) + + +def profile_rows(rows: Any, columns: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _profile_rows + + return _profile_rows(rows, columns) + + +def infer_schema(rows: Any, columns: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _infer_schema + + return _infer_schema(rows, columns) + + +def parse_problem(response: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_problem + + return _parse_problem(response) + + +def parse_dotenv(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_dotenv + + return _parse_dotenv(text) + + +def load_dotenv(path: str, override: Any = False) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _load_dotenv + + return _load_dotenv(path, override) + + +def parse_sse(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _parse_sse + + return _parse_sse(text) + + +def resolve_config(layers: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _resolve_config + + return _resolve_config(layers) + + +def explain_config(layers: Any, key: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _explain_config + + return _explain_config(layers, key) + + +def check_compatibility(old: Any, new: Any, mode: str = "backward") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _check_compatibility + + return _check_compatibility(old, new, mode) + + +def ts_rate(series: Any, window_s: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _ts_rate + + return _ts_rate(series, window_s) + + +def ts_downsample(series: Any, bucket_s: Any, agg: str = "avg") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _ts_downsample + + return _ts_downsample(series, bucket_s, agg) + + +def detect_anomalies(values: Any, method: str = "mad", threshold: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _detect_anomalies + + return _detect_anomalies(values, method, threshold) + + +def sma(values: Any, window: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _sma + + return _sma(values, window) + + +def ewma(values: Any, alpha: Any = 0.3) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _ewma + + return _ewma(values, alpha) + + +def idempotency_begin(name: str, key: str, request: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _idempotency_begin + + return _idempotency_begin(name, key, request) + + +def idempotency_complete(name: str, key: str, response: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _idempotency_complete + + return _idempotency_complete(name, key, response) + + +def idempotency_release(name: str, key: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _idempotency_release + + return _idempotency_release(name, key) + + +def dedup_check(name: str, message_id: str, ttl_s: Any = 3600) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _dedup_check + + return _dedup_check(name, message_id, ttl_s) + + +def sequence_observe(name: str, stream_id: str, seq: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _sequence_observe + + return _sequence_observe(name, stream_id, seq) + + +def cas_put(name: str, key: str, value: Any, expected_version: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cas_put + + return _cas_put(name, key, value, expected_version) + + +def cas_get(name: str, key: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cas_get + + return _cas_get(name, key) + + +def outbox_enqueue(name: str, event: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _outbox_enqueue + + return _outbox_enqueue(name, event) + + +def outbox_pending(name: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _outbox_pending + + return _outbox_pending(name) + + +def collation_sort( + items: Any, strength: str = "tertiary", tailoring: Any = None, reverse: Any = False +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _collation_sort + + return _collation_sort(items, strength, tailoring, reverse) + + +def collation_compare(first: str, second: str, strength: str = "tertiary", tailoring: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _collation_compare + + return _collation_compare(first, second, strength, tailoring) + + +def confusable_scan(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _confusable_scan + + return _confusable_scan(text) + + +def confusable_compare(first: str, second: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _confusable_compare + + return _confusable_compare(first, second) + + +def readability_report(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _readability_report + + return _readability_report(text) + + +def bidi_check(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _bidi_check + + return _bidi_check(text) + + +def bidi_strip(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _bidi_strip + + return _bidi_strip(text) + + +def format_list(items: Any, style: str = "and", locale: str = "en") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _format_list + + return _format_list(items, style, locale) + + +def format_message(pattern: str, args: Any = None, locale: str = "en") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _format_message + + return _format_message(pattern, args, locale) + + +def gettext_translate(po: str, msgid: str, context: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _gettext_translate + + return _gettext_translate(po, msgid, context) + + +def gettext_ngettext(po: str, msgid: str, msgid_plural: str, n: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _gettext_ngettext + + return _gettext_ngettext(po, msgid, msgid_plural, n) + + +def checksum_validate(scheme: str, number: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _checksum_validate + + return _checksum_validate(scheme, number) + + +def checksum_digit(scheme: str, partial: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _checksum_digit + + return _checksum_digit(scheme, partial) + + +def detect_drift(reference: Any, current: Any, threshold: Any = 0.25, bins: Any = 10) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _detect_drift + + return _detect_drift(reference, current, threshold, bins) + + +def categorical_drift(reference: Any, current: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _categorical_drift + + return _categorical_drift(reference, current) + + +def diff_rows(old_rows: Any, new_rows: Any, key: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _diff_rows + + return _diff_rows(old_rows, new_rows, key) + + +def cell_changes(old_rows: Any, new_rows: Any, key: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cell_changes + + return _cell_changes(old_rows, new_rows, key) + + +def check_foreign_key(child_rows: Any, child_col: str, parent_rows: Any, parent_col: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _check_foreign_key + + return _check_foreign_key(child_rows, child_col, parent_rows, parent_col) + + +def check_unique_key(rows: Any, cols: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _check_unique_key + + return _check_unique_key(rows, cols) + + +def check_accepted_values(rows: Any, col: str, allowed: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _check_accepted_values + + return _check_accepted_values(rows, col, allowed) + + +def check_row_count(rows: Any, minimum: Any = None, maximum: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _check_row_count + + return _check_row_count(rows, minimum, maximum) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_desktop_executor.py b/je_auto_control/utils/mcp_server/tools/_handlers_desktop_executor.py new file mode 100644 index 000000000..30bc09bf4 --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_handlers_desktop_executor.py @@ -0,0 +1,225 @@ +"""MCP desktop adapters delegating lazily to executor commands. + +Annotations mirror the executor JSON boundary, including heterogeneous payloads. +""" + +from typing import Any, Dict + + +def move_along_path(waypoints: Any, easing: str = "linear", per_segment_steps: Any = 20) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _move_along_path + + return _move_along_path(waypoints, easing, per_segment_steps) + + +def drag_path( + waypoints: Any, + button: str = "mouse_left", + easing: str = "linear", + per_segment_steps: Any = 20, + step_delay_s: Any = 0.0, + settle_s: Any = 0.0, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _drag_path + + return _drag_path(waypoints, button, easing, per_segment_steps, step_delay_s, settle_s) + + +def set_field_text(text: str, clear: str = "select_all", paste: Any = False, modifier: str = "ctrl") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _set_field_text + + return _set_field_text(text, clear, paste, modifier) + + +def hold_key(key: str, duration_s: Any = 1.0, rate_hz: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _hold_key + + return _hold_key(key, duration_s, rate_hz) + + +def move_mouse_relative(dx: Any, dy: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _move_mouse_relative + + return _move_mouse_relative(dx, dy) + + +def input_reachable() -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import ( + _input_reachable, + ) + + return _input_reachable() + + +def type_unicode(text: str, modifier: str = "ctrl") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _type_unicode + + return _type_unicode(text, modifier) + + +def type_unicode_keys(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _type_unicode_keys + + return _type_unicode_keys(text) + + +def type_unicode_text(text: str, modifier: str = "ctrl") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _type_unicode_text + + return _type_unicode_text(text, modifier) + + +def with_modifiers(modifiers: Any, actions: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _with_modifiers + + return _with_modifiers(modifiers, actions) + + +def tile_rect(slot: str, screen: Any = None, gap: Any = 0) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _tile_rect + + return _tile_rect(slot, screen, gap) + + +def grid_rects(rows: Any, cols: Any, screen: Any = None, gap: Any = 0) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _grid_rects + + return _grid_rects(rows, cols, screen, gap) + + +def cascade_rects(count: Any, screen: Any = None, offset: Any = 30, size: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cascade_rects + + return _cascade_rects(count, screen, offset, size) + + +def arrange_grid(titles: Any, rows: Any = None, cols: Any = None, gap: Any = 0) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _arrange_grid + + return _arrange_grid(titles, rows, cols, gap) + + +def arrange_cascade(titles: Any, offset: Any = 30) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _arrange_cascade + + return _arrange_cascade(titles, offset) + + +def enumerate_monitors() -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _enumerate_monitors + + return _enumerate_monitors() + + +def monitor_at_point(x: Any, y: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _monitor_at_point + + return _monitor_at_point(x, y) + + +def set_clipboard_html(html: str, fragment_plaintext: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _set_clipboard_html + + return _set_clipboard_html(html, fragment_plaintext) + + +def get_clipboard_html() -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_clipboard_html + + return _get_clipboard_html() + + +def set_clipboard_files(paths: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _set_clipboard_files + + return _set_clipboard_files(paths) + + +def get_clipboard_files() -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_clipboard_files + + return _get_clipboard_files() + + +def set_clipboard_rtf(text: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _set_clipboard_rtf + + return _set_clipboard_rtf(text) + + +def get_clipboard_rtf() -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_clipboard_rtf + + return _get_clipboard_rtf() + + +def set_clipboard_csv(rows: Any, delimiter: str = ",") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _set_clipboard_csv + + return _set_clipboard_csv(rows, delimiter) + + +def get_clipboard_csv(delimiter: str = ",") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_clipboard_csv + + return _get_clipboard_csv(delimiter) + + +def clipboard_formats() -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _clipboard_formats + + return _clipboard_formats() + + +def classify_formats(formats: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _classify_formats + + return _classify_formats(formats) + + +def diff_formats(before: Any, after: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _diff_formats + + return _diff_formats(before, after) + + +def plan_file_drop(paths: Any, point: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _plan_file_drop + + return _plan_file_drop(paths, point) + + +def drop_files(hwnd: Any, paths: Any, point: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _drop_files + + return _drop_files(hwnd, paths, point) + + +def set_topmost(title: str, on: Any = True) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _set_topmost + + return _set_topmost(title, on) + + +def bring_to_front(title: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _bring_to_front + + return _bring_to_front(title) + + +def send_to_back(title: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _send_to_back + + return _send_to_back(title) + + +def get_client_rect(title: str) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _get_client_rect + + return _get_client_rect(title) + + +def client_point(title: str, x: Any, y: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _client_point + + return _client_point(title, x, y) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_executor_bridge.py b/je_auto_control/utils/mcp_server/tools/_handlers_executor_bridge.py deleted file mode 100644 index 1b235eb16..000000000 --- a/je_auto_control/utils/mcp_server/tools/_handlers_executor_bridge.py +++ /dev/null @@ -1,1429 +0,0 @@ -"""MCP adapters that delegate straight to the executor's own implementation. - -Same contract as :mod:`._handlers` -- normalise arguments and return values so -they survive the JSON-RPC boundary, with every project import lazy -- split out -by theme because ``_handlers.py`` is over the 750-line limit. -""" -from typing import Any, Dict, List, Optional - - -def expand_control(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _expand_control - return _expand_control(name, role, app_name, automation_id) - - -def collapse_control(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _collapse_control - return _collapse_control(name, role, app_name, automation_id) - - -def control_expand_state(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _control_expand_state - return _control_expand_state(name, role, app_name, automation_id) - - -def select_control_item(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _select_control_item - return _select_control_item(name, role, app_name, automation_id) - - -def control_range(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _control_range - return _control_range(name, role, app_name, automation_id) - - -def set_control_range(value, name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _set_control_range - return _set_control_range(value, name, role, app_name, automation_id) - - -def scroll_control_into_view(name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _scroll_control_into_view - return _scroll_control_into_view(name, role, app_name, automation_id) - - -def get_control_text(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _get_control_text - return _get_control_text(name, role, app_name, automation_id) - - -def find_control_text(text, ignore_case=True, name=None, role=None, - app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _find_control_text - return _find_control_text(text, ignore_case, name, role, app_name, - automation_id) - - -def select_control_text(text, ignore_case=True, name=None, role=None, - app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _select_control_text - return _select_control_text(text, ignore_case, name, role, app_name, - automation_id) - - -def control_text_attributes(name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _control_text_attributes - return _control_text_attributes(name, role, app_name, automation_id) - - -def realize_item(item_name, by="name", container_name=None, container_role=None, - app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _realize_item - return _realize_item(item_name, by, container_name, container_role, - app_name, automation_id) - - -def get_element_properties(name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _get_element_properties - return _get_element_properties(name, role, app_name, automation_id) - - -def table_headers(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _table_headers - return _table_headers(name, role, app_name, automation_id) - - -def table_cell(row, column, name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _table_cell - return _table_cell(row, column, name, role, app_name, automation_id) - - -def cell_by_header(row, column_header, name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _cell_by_header - return _cell_by_header(row, column_header, name, role, app_name, - automation_id) - - -def move_element(x, y, name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _move_element - return _move_element(x, y, name, role, app_name, automation_id) - - -def resize_element(width, height, name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _resize_element - return _resize_element(width, height, name, role, app_name, automation_id) - - -def set_window_state(state, name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _set_window_state - return _set_window_state(state, name, role, app_name, automation_id) - - -def window_interaction_state(name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _window_interaction_state - return _window_interaction_state(name, role, app_name, automation_id) - - -def legacy_info(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _legacy_info - return _legacy_info(name, role, app_name, automation_id) - - -def legacy_default_action(name=None, role=None, app_name=None, - automation_id=None): - from je_auto_control.utils.executor.action_executor import _legacy_default_action - return _legacy_default_action(name, role, app_name, automation_id) - - -def get_selection(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _get_selection - return _get_selection(name, role, app_name, automation_id) - - -def list_views(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _list_views - return _list_views(name, role, app_name, automation_id) - - -def set_view(view, name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _set_view - return _set_view(view, name, role, app_name, automation_id) - - -def wait_for_focus_change(timeout=5.0): - from je_auto_control.utils.executor.action_executor import _wait_for_focus_change - return _wait_for_focus_change(timeout) - - -def get_selected_text(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _get_selected_text - return _get_selected_text(name, role, app_name, automation_id) - - -def get_visible_text(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _get_visible_text - return _get_visible_text(name, role, app_name, automation_id) - - -def _observe_handler(actions): - # The executor's own builder: each firing runs in a fresh variable scope - # seeded with what the registering tool call could see (normally nothing). - from je_auto_control.utils.executor.action_executor import ( - _observe_handler as build_handler, - ) - return build_handler(actions) - - -def circuit_call(name, actions, threshold=5, reset_s=30.0): - from je_auto_control.utils.executor.action_executor import _circuit_call - return _circuit_call(name, actions, threshold=int(threshold), - reset_s=float(reset_s)) - - -def run_chaos(spec): - from je_auto_control.utils.executor.action_executor import _run_chaos - return _run_chaos(spec) - - -def bulkhead_run(name, max_concurrent, actions): - from je_auto_control.utils.executor.action_executor import _bulkhead_run - return _bulkhead_run(name, max_concurrent, actions) - - -def trace_inject(headers=None, traceparent=None): - from je_auto_control.utils.executor.action_executor import _trace_inject - return _trace_inject(headers, traceparent) - - -def trace_extract(headers): - from je_auto_control.utils.executor.action_executor import _trace_extract - return _trace_extract(headers) - - -def baggage_parse(header): - from je_auto_control.utils.executor.action_executor import _baggage_parse - return _baggage_parse(header) - - -def baggage_format(items): - from je_auto_control.utils.executor.action_executor import _baggage_format - return _baggage_format(items) - - -def normalize_text(text, form="NFKC", casefold=True, collapse_ws=True): - from je_auto_control.utils.executor.action_executor import _normalize_text - return _normalize_text(text, form, casefold, collapse_ws) - - -def slugify(text, sep="-"): - from je_auto_control.utils.executor.action_executor import _slugify - return _slugify(text, sep) - - -def text_similarity(a, b, metric="jaro_winkler"): - from je_auto_control.utils.executor.action_executor import _text_similarity - return _text_similarity(a, b, metric) - - -def simhash(text, bits=64): - from je_auto_control.utils.executor.action_executor import _simhash - return _simhash(text, bits) - - -def near_duplicates(texts, max_distance=3): - from je_auto_control.utils.executor.action_executor import _near_duplicates - return _near_duplicates(texts, max_distance) - - -def canonical_log(fields): - from je_auto_control.utils.executor.action_executor import _canonical_log - return _canonical_log(fields) - - -def spans_to_otlp(spans, resource_attrs=None): - from je_auto_control.utils.executor.action_executor import _spans_to_otlp - return _spans_to_otlp(spans, resource_attrs) - - -def validate_config(schema, config): - from je_auto_control.utils.executor.action_executor import _validate_config - return _validate_config(schema, config) - - -def resolve_ref(ref): - from je_auto_control.utils.executor.action_executor import _resolve_ref - return _resolve_ref(ref) - - -def resolve_refs(obj): - from je_auto_control.utils.executor.action_executor import _resolve_refs - return _resolve_refs(obj) - - -def parse_link_header(value): - from je_auto_control.utils.executor.action_executor import _parse_link_header - return _parse_link_header(value) - - -def next_url(value): - from je_auto_control.utils.executor.action_executor import _next_url - return _next_url(value) - - -def build_multipart(fields=None, files=None, boundary=None): - from je_auto_control.utils.executor.action_executor import _build_multipart - return _build_multipart(fields, files, boundary) - - -def parse_multipart(content_type, body_base64): - from je_auto_control.utils.executor.action_executor import _parse_multipart - return _parse_multipart(content_type, body_base64) - - -def decode_body(headers, body_base64): - from je_auto_control.utils.executor.action_executor import _decode_body - return _decode_body(headers, body_base64) - - -def parse_quality_values(header): - from je_auto_control.utils.executor.action_executor import _parse_quality_values - return _parse_quality_values(header) - - -def cookie_header(set_cookies): - from je_auto_control.utils.executor.action_executor import _cookie_header - return _cookie_header(set_cookies) - - -def parse_set_cookie(header): - from je_auto_control.utils.executor.action_executor import _parse_set_cookie - return _parse_set_cookie(header) - - -def parse_cache_control(headers): - from je_auto_control.utils.executor.action_executor import _parse_cache_control - return _parse_cache_control(headers) - - -def store_validators(response): - from je_auto_control.utils.executor.action_executor import _store_validators - return _store_validators(response) - - -def redact_config(obj, mask="***"): - from je_auto_control.utils.executor.action_executor import _redact_config - return _redact_config(obj, mask) - - -def redact_secret_text(text, mask="***"): - from je_auto_control.utils.executor.action_executor import _redact_secret_text - return _redact_secret_text(text, mask) - - -def profile_rows(rows, columns=None): - from je_auto_control.utils.executor.action_executor import _profile_rows - return _profile_rows(rows, columns) - - -def infer_schema(rows, columns=None): - from je_auto_control.utils.executor.action_executor import _infer_schema - return _infer_schema(rows, columns) - - -def parse_problem(response): - from je_auto_control.utils.executor.action_executor import _parse_problem - return _parse_problem(response) - - -def parse_dotenv(text): - from je_auto_control.utils.executor.action_executor import _parse_dotenv - return _parse_dotenv(text) - - -def load_dotenv(path, override=False): - from je_auto_control.utils.executor.action_executor import _load_dotenv - return _load_dotenv(path, override) - - -def parse_sse(text): - from je_auto_control.utils.executor.action_executor import _parse_sse - return _parse_sse(text) - - -def resolve_config(layers): - from je_auto_control.utils.executor.action_executor import _resolve_config - return _resolve_config(layers) - - -def explain_config(layers, key): - from je_auto_control.utils.executor.action_executor import _explain_config - return _explain_config(layers, key) - - -def check_compatibility(old, new, mode="backward"): - from je_auto_control.utils.executor.action_executor import _check_compatibility - return _check_compatibility(old, new, mode) - - -def ts_rate(series, window_s=None): - from je_auto_control.utils.executor.action_executor import _ts_rate - return _ts_rate(series, window_s) - - -def ts_downsample(series, bucket_s, agg="avg"): - from je_auto_control.utils.executor.action_executor import _ts_downsample - return _ts_downsample(series, bucket_s, agg) - - -def detect_anomalies(values, method="mad", threshold=None): - from je_auto_control.utils.executor.action_executor import _detect_anomalies - return _detect_anomalies(values, method, threshold) - - -def sma(values, window): - from je_auto_control.utils.executor.action_executor import _sma - return _sma(values, window) - - -def ewma(values, alpha=0.3): - from je_auto_control.utils.executor.action_executor import _ewma - return _ewma(values, alpha) - - -def idempotency_begin(name, key, request=None): - from je_auto_control.utils.executor.action_executor import _idempotency_begin - return _idempotency_begin(name, key, request) - - -def idempotency_complete(name, key, response): - from je_auto_control.utils.executor.action_executor import _idempotency_complete - return _idempotency_complete(name, key, response) - - -def idempotency_release(name, key): - from je_auto_control.utils.executor.action_executor import _idempotency_release - return _idempotency_release(name, key) - - -def dedup_check(name, message_id, ttl_s=3600): - from je_auto_control.utils.executor.action_executor import _dedup_check - return _dedup_check(name, message_id, ttl_s) - - -def sequence_observe(name, stream_id, seq): - from je_auto_control.utils.executor.action_executor import _sequence_observe - return _sequence_observe(name, stream_id, seq) - - -def cas_put(name, key, value, expected_version=None): - from je_auto_control.utils.executor.action_executor import _cas_put - return _cas_put(name, key, value, expected_version) - - -def cas_get(name, key): - from je_auto_control.utils.executor.action_executor import _cas_get - return _cas_get(name, key) - - -def outbox_enqueue(name, event): - from je_auto_control.utils.executor.action_executor import _outbox_enqueue - return _outbox_enqueue(name, event) - - -def outbox_pending(name): - from je_auto_control.utils.executor.action_executor import _outbox_pending - return _outbox_pending(name) - - -def collation_sort(items, strength="tertiary", tailoring=None, reverse=False): - from je_auto_control.utils.executor.action_executor import _collation_sort - return _collation_sort(items, strength, tailoring, reverse) - - -def collation_compare(first, second, strength="tertiary", tailoring=None): - from je_auto_control.utils.executor.action_executor import _collation_compare - return _collation_compare(first, second, strength, tailoring) - - -def confusable_scan(text): - from je_auto_control.utils.executor.action_executor import _confusable_scan - return _confusable_scan(text) - - -def confusable_compare(first, second): - from je_auto_control.utils.executor.action_executor import _confusable_compare - return _confusable_compare(first, second) - - -def readability_report(text): - from je_auto_control.utils.executor.action_executor import _readability_report - return _readability_report(text) - - -def bidi_check(text): - from je_auto_control.utils.executor.action_executor import _bidi_check - return _bidi_check(text) - - -def bidi_strip(text): - from je_auto_control.utils.executor.action_executor import _bidi_strip - return _bidi_strip(text) - - -def format_list(items, style="and", locale="en"): - from je_auto_control.utils.executor.action_executor import _format_list - return _format_list(items, style, locale) - - -def format_message(pattern, args=None, locale="en"): - from je_auto_control.utils.executor.action_executor import _format_message - return _format_message(pattern, args, locale) - - -def gettext_translate(po, msgid, context=None): - from je_auto_control.utils.executor.action_executor import _gettext_translate - return _gettext_translate(po, msgid, context) - - -def gettext_ngettext(po, msgid, msgid_plural, n): - from je_auto_control.utils.executor.action_executor import _gettext_ngettext - return _gettext_ngettext(po, msgid, msgid_plural, n) - - -def checksum_validate(scheme, number): - from je_auto_control.utils.executor.action_executor import _checksum_validate - return _checksum_validate(scheme, number) - - -def checksum_digit(scheme, partial): - from je_auto_control.utils.executor.action_executor import _checksum_digit - return _checksum_digit(scheme, partial) - - -def move_along_path(waypoints, easing="linear", per_segment_steps=20): - from je_auto_control.utils.executor.action_executor import _move_along_path - return _move_along_path(waypoints, easing, per_segment_steps) - - -def drag_path(waypoints, button="mouse_left", easing="linear", - per_segment_steps=20, step_delay_s=0.0, settle_s=0.0): - from je_auto_control.utils.executor.action_executor import _drag_path - return _drag_path(waypoints, button, easing, per_segment_steps, step_delay_s, settle_s) - - -def set_field_text(text, clear="select_all", paste=False, modifier="ctrl"): - from je_auto_control.utils.executor.action_executor import _set_field_text - return _set_field_text(text, clear, paste, modifier) - - -def hold_key(key, duration_s=1.0, rate_hz=None): - from je_auto_control.utils.executor.action_executor import _hold_key - return _hold_key(key, duration_s, rate_hz) - - -def move_mouse_relative(dx, dy): - from je_auto_control.utils.executor.action_executor import _move_mouse_relative - return _move_mouse_relative(dx, dy) - - -def input_reachable(): - from je_auto_control.utils.executor.action_executor import ( - _input_reachable, - ) - return _input_reachable() - - -def type_unicode(text, modifier="ctrl"): - from je_auto_control.utils.executor.action_executor import _type_unicode - return _type_unicode(text, modifier) - - -def type_unicode_keys(text): - from je_auto_control.utils.executor.action_executor import _type_unicode_keys - return _type_unicode_keys(text) - - -def type_unicode_text(text, modifier="ctrl"): - from je_auto_control.utils.executor.action_executor import _type_unicode_text - return _type_unicode_text(text, modifier) - - -def with_modifiers(modifiers, actions): - from je_auto_control.utils.executor.action_executor import _with_modifiers - return _with_modifiers(modifiers, actions) - - -def grid_cell(boxes, row, col, row_tolerance=10, box_format="xywh"): - from je_auto_control.utils.executor.action_executor import _grid_cell - return _grid_cell(boxes, row, col, row_tolerance, box_format) - - -def match_template(template, min_score=0.8, scales=None, region=None, - method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _match_template - return _match_template(template, min_score, scales, region, method) - - -def match_template_all(template, min_score=0.8, max_results=20, nms_iou=0.3, - region=None): - from je_auto_control.utils.executor.action_executor import _match_template_all - return _match_template_all(template, min_score, max_results, nms_iou, region) - - -def match_masked(template, mask=None, min_score=0.9, region=None): - from je_auto_control.utils.executor.action_executor import _match_masked - return _match_masked(template, mask, min_score, region) - - -def match_masked_all(template, mask=None, min_score=0.9, max_results=20, - nms_iou=0.3, region=None): - from je_auto_control.utils.executor.action_executor import _match_masked_all - return _match_masked_all(template, mask, min_score, max_results, nms_iou, - region) - - -def match_rotated(template, min_score=0.8, scales=None, angles=None, - region=None, method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _match_rotated - return _match_rotated(template, min_score, scales, angles, region, method) - - -def match_rotated_all(template, min_score=0.8, scales=None, angles=None, - max_results=20, nms_iou=0.3, region=None): - from je_auto_control.utils.executor.action_executor import _match_rotated_all - return _match_rotated_all(template, min_score, scales, angles, max_results, - nms_iou, region) - - -def match_with_trust(template, min_score=0.0, scales=None, ambiguous_ratio=0.9, - region=None, method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _match_with_trust - return _match_with_trust(template, min_score, scales, ambiguous_ratio, - region, method) - - -def auto_threshold(template, region=None, method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _auto_threshold - return _auto_threshold(template, region, method) - - -def match_auto(template, floor=0.5, max_results=20, region=None, - method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _match_auto - return _match_auto(template, floor, max_results, region, method) - - -def edge_match(template, min_score=0.7, scales=None, region=None): - from je_auto_control.utils.executor.action_executor import _edge_match - return _edge_match(template, min_score, scales, region) - - -def edge_match_all(template, min_score=0.7, max_results=20, nms_iou=0.3, - region=None): - from je_auto_control.utils.executor.action_executor import _edge_match_all - return _edge_match_all(template, min_score, max_results, nms_iou, region) - - -def match_subpixel(template, min_score=0.0, region=None, method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _match_subpixel - return _match_subpixel(template, min_score, region, method) - - -def vote_centers(centers, agree_px=10, min_votes=2): - from je_auto_control.utils.executor.action_executor import _vote_centers - return _vote_centers(centers, agree_px, min_votes) - - -def match_ensemble(templates, min_score=0.8, agree_px=10, min_votes=2, region=None): - from je_auto_control.utils.executor.action_executor import _match_ensemble - return _match_ensemble(templates, min_score, agree_px, min_votes, region) - - -def match_color(template, channels=None, min_score=0.7, scales=None, region=None): - from je_auto_control.utils.executor.action_executor import _match_color - return _match_color(template, channels, min_score, scales, region) - - -def match_color_all(template, channels=None, min_score=0.7, max_results=20, - nms_iou=0.3, region=None): - from je_auto_control.utils.executor.action_executor import _match_color_all - return _match_color_all(template, channels, min_score, max_results, nms_iou, - region) - - -def region_stability(frames, settle_threshold=0.99): - from je_auto_control.utils.executor.action_executor import _region_stability - return _region_stability(frames, settle_threshold) - - -def match_persistence(template, frames, min_score=0.8, agree_px=8): - from je_auto_control.utils.executor.action_executor import _match_persistence - return _match_persistence(template, frames, min_score, agree_px) - - -def grid_cells(rows, cols, region=None): - from je_auto_control.utils.executor.action_executor import _grid_cells - return _grid_cells(rows, cols, region) - - -def cell_for_point(x, y, rows, cols, region=None): - from je_auto_control.utils.executor.action_executor import _cell_for_point - return _cell_for_point(x, y, rows, cols, region) - - -def point_for_cell(label, rows, cols, region=None): - from je_auto_control.utils.executor.action_executor import _point_for_cell - return _point_for_cell(label, rows, cols, region) - - -def populate_table(grid, text_boxes, overlap=0.4): - from je_auto_control.utils.executor.action_executor import _populate_table - return _populate_table(grid, text_boxes, overlap) - - -def column_gutters(boxes, page_width=None, min_gap=8): - from je_auto_control.utils.executor.action_executor import _column_gutters - return _column_gutters(boxes, page_width, min_gap) - - -def detect_borderless_table(boxes, page_width=None, min_gap=8, min_cols=2, - min_rows=2): - from je_auto_control.utils.executor.action_executor import _detect_borderless_table - return _detect_borderless_table(boxes, page_width, min_gap, min_cols, min_rows) - - -def associate_fields(text_boxes, directions=None, max_gap=150): - from je_auto_control.utils.executor.action_executor import _associate_fields - return _associate_fields(text_boxes, directions, max_gap) - - -def match_labels_to_widgets(labels, widgets): - from je_auto_control.utils.executor.action_executor import _match_labels_to_widgets - return _match_labels_to_widgets(labels, widgets) - - -def flow_order(boxes, min_gap=12): - from je_auto_control.utils.executor.action_executor import _flow_order - return _flow_order(boxes, min_gap) - - -def xy_cut(boxes, min_gap=12): - from je_auto_control.utils.executor.action_executor import _xy_cut - return _xy_cut(boxes, min_gap) - - -def group_paragraphs(lines, line_gap_factor=1.6): - from je_auto_control.utils.executor.action_executor import _group_paragraphs - return _group_paragraphs(lines, line_gap_factor) - - -def detect_lists(lines): - from je_auto_control.utils.executor.action_executor import _detect_lists - return _detect_lists(lines) - - -def classify_lines(lines, heading_ratio=1.2): - from je_auto_control.utils.executor.action_executor import _classify_lines - return _classify_lines(lines, heading_ratio) - - -def outline(lines, heading_ratio=1.2): - from je_auto_control.utils.executor.action_executor import _outline - return _outline(lines, heading_ratio) - - -def find_color_region(rgb, tolerance=20, min_area=50, region=None): - from je_auto_control.utils.executor.action_executor import _find_color_region - return _find_color_region(rgb, tolerance, min_area, region) - - -def ssim_compare(reference, current=None, ignore=None, region=None): - from je_auto_control.utils.executor.action_executor import _ssim_compare - return _ssim_compare(reference, current, ignore, region) - - -def ssim_changed_regions(reference, current=None, ignore=None, threshold=0.35, - min_area=50, region=None): - from je_auto_control.utils.executor.action_executor import _ssim_changed_regions - return _ssim_changed_regions(reference, current, ignore, threshold, min_area, - region) - - -def feature_match(template, region=None, max_features=500, ratio=0.75, - min_inliers=10): - from je_auto_control.utils.executor.action_executor import _feature_match - return _feature_match(template, region, max_features, ratio, min_inliers) - - -def find_shapes(region=None, min_area=400, max_area=None): - from je_auto_control.utils.executor.action_executor import _find_shapes - return _find_shapes(region, min_area, max_area) - - -def find_rectangles(region=None, min_area=400, max_area=None, aspect_range=None, - epsilon=0.04): - from je_auto_control.utils.executor.action_executor import _find_rectangles - return _find_rectangles(region, min_area, max_area, aspect_range, epsilon) - - -def tile_rect(slot, screen=None, gap=0): - from je_auto_control.utils.executor.action_executor import _tile_rect - return _tile_rect(slot, screen, gap) - - -def grid_rects(rows, cols, screen=None, gap=0): - from je_auto_control.utils.executor.action_executor import _grid_rects - return _grid_rects(rows, cols, screen, gap) - - -def cascade_rects(count, screen=None, offset=30, size=None): - from je_auto_control.utils.executor.action_executor import _cascade_rects - return _cascade_rects(count, screen, offset, size) - - -def arrange_grid(titles, rows=None, cols=None, gap=0): - from je_auto_control.utils.executor.action_executor import _arrange_grid - return _arrange_grid(titles, rows, cols, gap) - - -def arrange_cascade(titles, offset=30): - from je_auto_control.utils.executor.action_executor import _arrange_cascade - return _arrange_cascade(titles, offset) - - -def preprocess_image(output_path, source=None, steps=None, scale=2.0, region=None, - block_size=31, c=11): - from je_auto_control.utils.executor.action_executor import _preprocess_image - return _preprocess_image(output_path, source, steps, scale, region, - block_size, c) - - -def enumerate_monitors(): - from je_auto_control.utils.executor.action_executor import _enumerate_monitors - return _enumerate_monitors() - - -def monitor_at_point(x, y): - from je_auto_control.utils.executor.action_executor import _monitor_at_point - return _monitor_at_point(x, y) - - -def wait_actionable(template, timeout_s=5.0, stable_for_s=0.3, min_score=0.8, - region=None): - from je_auto_control.utils.executor.action_executor import _wait_actionable - return _wait_actionable(template, timeout_s, stable_for_s, min_score, region) - - -def fuse_elements(ocr=None, icon=None, a11y=None, iou_threshold=0.9): - from je_auto_control.utils.executor.action_executor import _fuse_elements - return _fuse_elements(ocr, icon, a11y, iou_threshold) - - -def reading_order(elements, row_tol=12): - from je_auto_control.utils.executor.action_executor import _reading_order - return _reading_order(elements, row_tol) - - -def segment_hsv(lower_hsv, upper_hsv, min_area=50, region=None): - from je_auto_control.utils.executor.action_executor import _segment_hsv - return _segment_hsv(lower_hsv, upper_hsv, min_area, region) - - -def dominant_hue_regions(hue, hue_tol=10, sat_min=80, val_min=80, min_area=50, - region=None): - from je_auto_control.utils.executor.action_executor import _dominant_hue_regions - return _dominant_hue_regions(hue, hue_tol, sat_min, val_min, min_area, region) - - -def find_text_regions(min_area=60, max_area=None, merge=True, max_aspect=12.0, - region=None): - from je_auto_control.utils.executor.action_executor import _find_text_regions - return _find_text_regions(min_area, max_area, merge, max_aspect, region) - - -def find_text_lines(y_tolerance=8, region=None): - from je_auto_control.utils.executor.action_executor import _find_text_lines - return _find_text_lines(y_tolerance, region) - - -def find_lines(min_length=80, max_gap=10, orientation="any", region=None): - from je_auto_control.utils.executor.action_executor import _find_lines - return _find_lines(min_length, max_gap, orientation, region) - - -def find_grid(min_length=120, tol=10, region=None): - from je_auto_control.utils.executor.action_executor import _find_grid - return _find_grid(min_length, tol, region) - - -def find_separators(axis="horizontal", min_length=120, tol=10, region=None): - from je_auto_control.utils.executor.action_executor import _find_separators - return _find_separators(axis, min_length, tol, region) - - -def expect_poll(action, key=None, op="truthy", expected=None, timeout_s=5.0, - interval_s=0.25): - from je_auto_control.utils.executor.action_executor import _expect_poll - return _expect_poll(action, key, op, expected, timeout_s, interval_s) - - -def locate_chain(boxes, ops=None): - from je_auto_control.utils.executor.action_executor import _locate_chain - return _locate_chain(boxes, ops) - - -def set_clipboard_html(html, fragment_plaintext=None): - from je_auto_control.utils.executor.action_executor import _set_clipboard_html - return _set_clipboard_html(html, fragment_plaintext) - - -def get_clipboard_html(): - from je_auto_control.utils.executor.action_executor import _get_clipboard_html - return _get_clipboard_html() - - -def set_clipboard_files(paths): - from je_auto_control.utils.executor.action_executor import _set_clipboard_files - return _set_clipboard_files(paths) - - -def get_clipboard_files(): - from je_auto_control.utils.executor.action_executor import _get_clipboard_files - return _get_clipboard_files() - - -def set_clipboard_rtf(text): - from je_auto_control.utils.executor.action_executor import _set_clipboard_rtf - return _set_clipboard_rtf(text) - - -def get_clipboard_rtf(): - from je_auto_control.utils.executor.action_executor import _get_clipboard_rtf - return _get_clipboard_rtf() - - -def set_clipboard_csv(rows, delimiter=","): - from je_auto_control.utils.executor.action_executor import _set_clipboard_csv - return _set_clipboard_csv(rows, delimiter) - - -def get_clipboard_csv(delimiter=","): - from je_auto_control.utils.executor.action_executor import _get_clipboard_csv - return _get_clipboard_csv(delimiter) - - -def clipboard_formats(): - from je_auto_control.utils.executor.action_executor import _clipboard_formats - return _clipboard_formats() - - -def classify_formats(formats): - from je_auto_control.utils.executor.action_executor import _classify_formats - return _classify_formats(formats) - - -def diff_formats(before, after): - from je_auto_control.utils.executor.action_executor import _diff_formats - return _diff_formats(before, after) - - -def plan_file_drop(paths, point=None): - from je_auto_control.utils.executor.action_executor import _plan_file_drop - return _plan_file_drop(paths, point) - - -def drop_files(hwnd, paths, point=None): - from je_auto_control.utils.executor.action_executor import _drop_files - return _drop_files(hwnd, paths, point) - - -def image_quality(source=None, region=None): - from je_auto_control.utils.executor.action_executor import _image_quality - return _image_quality(source, region) - - -def quality_gate(source=None, region=None, min_sharpness=100.0, - min_contrast=12.0): - from je_auto_control.utils.executor.action_executor import _quality_gate - return _quality_gate(source, region, min_sharpness, min_contrast) - - -def detect_scale(template, haystack=None, region=None, scales=None, - method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _detect_scale - return _detect_scale(template, haystack, region, scales, method) - - -def scale_sweep(template, haystack=None, region=None, scales=None, - method="ccoeff_normed"): - from je_auto_control.utils.executor.action_executor import _scale_sweep - return _scale_sweep(template, haystack, region, scales, method) - - -def salient_regions(source=None, region=None, size=64, threshold=None, - min_area=4): - from je_auto_control.utils.executor.action_executor import _salient_regions - return _salient_regions(source, region, size, threshold, min_area) - - -def most_salient(source=None, region=None, size=64, threshold=None, min_area=4): - from je_auto_control.utils.executor.action_executor import _most_salient - return _most_salient(source, region, size, threshold, min_area) - - -def failure_signature(error, length=12): - from je_auto_control.utils.executor.action_executor import _failure_signature - return _failure_signature(error, length) - - -def group_failures(errors): - from je_auto_control.utils.executor.action_executor import _group_failures - return _group_failures(errors) - - -def diff_runs(before, after, key="name", regress_factor=1.5): - from je_auto_control.utils.executor.action_executor import _diff_runs - return _diff_runs(before, after, key, regress_factor) - - -def failure_clusters(runs, threshold=0.5, min_size=2): - from je_auto_control.utils.executor.action_executor import _failure_clusters - return _failure_clusters(runs, threshold, min_size) - - -def cofailure_pairs(runs, threshold=0.5): - from je_auto_control.utils.executor.action_executor import _cofailure_pairs - return _cofailure_pairs(runs, threshold) - - -def build_timeline(steps): - from je_auto_control.utils.executor.action_executor import _build_timeline - return _build_timeline(steps) - - -def critical_steps(steps, top=3): - from je_auto_control.utils.executor.action_executor import _critical_steps - return _critical_steps(steps, top) - - -def image_histogram(source=None, bins=32, space="hsv", region=None): - from je_auto_control.utils.executor.action_executor import _image_histogram - return _image_histogram(source, bins, space, region) - - -def histogram_changed(reference, current=None, method="correlation", - threshold=0.9, space="hsv", region=None): - from je_auto_control.utils.executor.action_executor import _histogram_changed - return _histogram_changed(reference, current, method, threshold, space, region) - - -def changed_regions(before, after=None, threshold=25, min_area=80, blur=5): - from je_auto_control.utils.executor.action_executor import _changed_regions - return _changed_regions(before, after, threshold, min_area, blur) - - -def has_motion(before, after=None, threshold=25, min_area=80): - from je_auto_control.utils.executor.action_executor import _has_motion - return _has_motion(before, after, threshold, min_area) - - -def set_topmost(title, on=True): - from je_auto_control.utils.executor.action_executor import _set_topmost - return _set_topmost(title, on) - - -def bring_to_front(title): - from je_auto_control.utils.executor.action_executor import _bring_to_front - return _bring_to_front(title) - - -def send_to_back(title): - from je_auto_control.utils.executor.action_executor import _send_to_back - return _send_to_back(title) - - -def soft_assert(checks, raise_on_fail=False): - from je_auto_control.utils.executor.action_executor import _soft_assert - return _soft_assert(checks, raise_on_fail) - - -def perceptual_diff(actual, expected, threshold=0.1, include_aa=False, - max_diff_ratio=None): - from je_auto_control.utils.executor.action_executor import _perceptual_diff - return _perceptual_diff(actual, expected, threshold, include_aa, max_diff_ratio) - - -def get_client_rect(title): - from je_auto_control.utils.executor.action_executor import _get_client_rect - return _get_client_rect(title) - - -def client_point(title, x, y): - from je_auto_control.utils.executor.action_executor import _client_point - return _client_point(title, x, y) - - -def cua_command(payload, source="canonical"): - from je_auto_control.utils.executor.action_executor import _cua_command - return _cua_command(payload, source) - - -def serialize_observation(elements, viewport=None, max_elements=80): - from je_auto_control.utils.executor.action_executor import _serialize_observation - return _serialize_observation(elements, viewport, max_elements) - - -def observation_index(elements, viewport=None, max_elements=80): - from je_auto_control.utils.executor.action_executor import _observation_index - return _observation_index(elements, viewport, max_elements) - - -def delta_observation(prev, curr, viewport=None, max_elements=80, max_lines=40, - interactive_only=True): - from je_auto_control.utils.executor.action_executor import _delta_observation - return _delta_observation(prev, curr, viewport, max_elements, max_lines, - interactive_only) - - -def classify_effect(before, after, action, radius=64): - from je_auto_control.utils.executor.action_executor import _classify_effect - return _classify_effect(before, after, action, radius) - - -def effect_near_point(before, after, point, radius=64): - from je_auto_control.utils.executor.action_executor import _effect_near_point - return _effect_near_point(before, after, point, radius) - - -def check_postcondition(after, spec, before=None): - from je_auto_control.utils.executor.action_executor import _check_postcondition - return _check_postcondition(after, spec, before) - - -def plan_repair(verdict, max_attempts=3): - from je_auto_control.utils.executor.action_executor import _plan_repair - return _plan_repair(verdict, max_attempts) - - -def consensus_point(candidates, cluster_radius=24): - from je_auto_control.utils.executor.action_executor import _consensus_point - return _consensus_point(candidates, cluster_radius) - - -def consensus_element(candidates, elements): - from je_auto_control.utils.executor.action_executor import _consensus_element - return _consensus_element(candidates, elements) - - -def settle_point(churns, quiet_samples=3, max_churn=1.0): - from je_auto_control.utils.executor.action_executor import _settle_point - return _settle_point(churns, quiet_samples, max_churn) - - -def build_critic_record(action, before, after, postcondition=None, radius=64): - from je_auto_control.utils.executor.action_executor import _build_critic_record - return _build_critic_record(action, before, after, postcondition, radius) - - -def score_step(record): - from je_auto_control.utils.executor.action_executor import _score_step - return _score_step(record) - - -def validate_action(action, screen=None, targets=None): - from je_auto_control.utils.executor.action_executor import _validate_action - return _validate_action(action, screen, targets) - - -def replay_trace(trace): - from je_auto_control.utils.executor.action_executor import _replay_trace - return _replay_trace(trace) - - -def match_elements(before, after, iou_threshold=0.5): - from je_auto_control.utils.executor.action_executor import _match_elements - return _match_elements(before, after, iou_threshold) - - -def assign_stable_ids(elements, prior=None, iou_threshold=0.5): - from je_auto_control.utils.executor.action_executor import _assign_stable_ids - return _assign_stable_ids(elements, prior, iou_threshold) - - -def score_candidates(candidates, want_role=None, want_name=None, anchor=None): - from je_auto_control.utils.executor.action_executor import _score_candidates - return _score_candidates(candidates, want_role, want_name, anchor) - - -def best_candidate(candidates, want_role=None, want_name=None, anchor=None): - from je_auto_control.utils.executor.action_executor import _best_candidate - return _best_candidate(candidates, want_role, want_name, anchor) - - -def read_barcodes(source=None, region=None): - from je_auto_control.utils.executor.action_executor import _read_barcodes - return _read_barcodes(source, region) - - -def detect_drift(reference, current, threshold=0.25, bins=10): - from je_auto_control.utils.executor.action_executor import _detect_drift - return _detect_drift(reference, current, threshold, bins) - - -def categorical_drift(reference, current): - from je_auto_control.utils.executor.action_executor import _categorical_drift - return _categorical_drift(reference, current) - - -def diff_rows(old_rows, new_rows, key): - from je_auto_control.utils.executor.action_executor import _diff_rows - return _diff_rows(old_rows, new_rows, key) - - -def cell_changes(old_rows, new_rows, key): - from je_auto_control.utils.executor.action_executor import _cell_changes - return _cell_changes(old_rows, new_rows, key) - - -def check_foreign_key(child_rows, child_col, parent_rows, parent_col): - from je_auto_control.utils.executor.action_executor import _check_foreign_key - return _check_foreign_key(child_rows, child_col, parent_rows, parent_col) - - -def check_unique_key(rows, cols): - from je_auto_control.utils.executor.action_executor import _check_unique_key - return _check_unique_key(rows, cols) - - -def check_accepted_values(rows, col, allowed): - from je_auto_control.utils.executor.action_executor import _check_accepted_values - return _check_accepted_values(rows, col, allowed) - - -def check_row_count(rows, minimum=None, maximum=None): - from je_auto_control.utils.executor.action_executor import _check_row_count - return _check_row_count(rows, minimum, maximum) - - -def walk_tree(app_name=None, max_results: int = 500): - from je_auto_control.utils.executor.action_executor import _walk_tree - return _walk_tree(app_name, max_results) - - -def humanize_role(role): - from je_auto_control.utils.executor.action_executor import _humanize_role - return _humanize_role(role) - - -def tab_order(app_name=None, max_results: int = 500): - from je_auto_control.utils.executor.action_executor import _tab_order - return _tab_order(app_name, max_results) - - -def audit_focus_order(app_name=None, max_results: int = 500): - from je_auto_control.utils.executor.action_executor import _audit_focus_order - return _audit_focus_order(app_name, max_results) - - -def focus_control(name=None, role=None, app_name=None, automation_id=None): - from je_auto_control.utils.executor.action_executor import _focus_control - return _focus_control(name, role, app_name, automation_id) - - -def a11y_record_start(app_name: Optional[str] = None, - poll_interval_s: float = 0.25, - min_movement_px: int = 8) -> Dict[str, Any]: - from je_auto_control.utils.executor.action_executor import ( - _a11y_record_start, - ) - return _a11y_record_start( - app_name=app_name, - poll_interval_s=float(poll_interval_s), - min_movement_px=int(min_movement_px), - ) - - -def a11y_record_stop() -> List[Dict[str, Any]]: - from je_auto_control.utils.executor.action_executor import ( - _a11y_record_stop, - ) - return _a11y_record_stop() - - -def wait_image_gone(image, detect_threshold: float = 1.0, - timeout_s: float = 10.0, poll_interval_s: float = 0.2, - gone_for_s: float = 0.0) -> Dict[str, Any]: - from je_auto_control.utils.executor.action_executor import _wait_image_gone - return _wait_image_gone(image, detect_threshold, timeout_s, - poll_interval_s, gone_for_s) - - -def wait_text_gone(text: str, timeout_s: float = 10.0, - poll_interval_s: float = 0.2, - gone_for_s: float = 0.0) -> Dict[str, Any]: - from je_auto_control.utils.executor.action_executor import _wait_text_gone - return _wait_text_gone(text, timeout_s, poll_interval_s, gone_for_s) - - -def wait_color(target_rgb, region=None, tolerance=10, min_fraction=0.5, - present=True, timeout_s=10.0, poll_interval_s=0.2): - from je_auto_control.utils.executor.action_executor import _wait_color - return _wait_color(target_rgb, region, tolerance, min_fraction, - present, timeout_s, poll_interval_s) - - -def wait_window_title(pattern, present=True, regex=True, timeout_s=10.0, - poll_interval_s=0.2): - from je_auto_control.utils.executor.action_executor import _wait_window_title - return _wait_window_title(pattern, present, regex, timeout_s, - poll_interval_s) - - -def anchor_locate(anchor: Dict[str, Any], target: Dict[str, Any], - relation: str = "near", - max_distance_px: float = 200.0, - ordinal: int = 1) -> Dict[str, Any]: - from je_auto_control.utils.executor.action_executor import _anchor_locate - return _anchor_locate(anchor, target, relation, max_distance_px, ordinal) - - -def anchor_locate_all(anchor: Dict[str, Any], target: Dict[str, Any], - relation: str = "near", - max_distance_px: float = 200.0) -> Dict[str, Any]: - from je_auto_control.utils.executor.action_executor import _anchor_locate_all - return _anchor_locate_all(anchor, target, relation, max_distance_px) - - -def run_agent(goal: str, - backend: str = "anthropic", - max_steps: int = 25, - wall_seconds: float = 300.0, - model: Optional[str] = None, - max_tokens: int = 1024) -> Dict[str, Any]: - """Drive the generic plan→act→verify→retry AgentLoop against ``goal``.""" - from je_auto_control.utils.executor.action_executor import _run_agent - return _run_agent( - goal=goal, backend=backend, - max_steps=int(max_steps), wall_seconds=float(wall_seconds), - model=model, max_tokens=int(max_tokens), - ) - - -def redact_screenshot(file_path: str, - output_path: Optional[str] = None, - policy: str = "moderate", - regions: Optional[List[List[int]]] = None, - accessibility: Optional[List[Dict[str, Any]]] = None, - ocr: Optional[List[Dict[str, Any]]] = None, - ) -> Dict[str, Any]: - """Blur PII regions in a saved screenshot via the redaction engine.""" - from je_auto_control.utils.executor.action_executor import ( - _redact_screenshot, - ) - return _redact_screenshot( - file_path=file_path, output_path=output_path, - policy=policy, regions=regions, - accessibility=accessibility, ocr=ocr, - ) - - -def android_find_element(text: Optional[str] = None, - resource_id: Optional[str] = None, - description: Optional[str] = None, - class_name: Optional[str] = None, - timeout_s: float = 5.0, - serial: Optional[str] = None, - ) -> Dict[str, int]: - """Find an Android widget via uiautomator2; return its bounding rect.""" - from je_auto_control.utils.executor.action_executor import ( - _ac_android_find_element, - ) - return _ac_android_find_element( - text=text, resource_id=resource_id, description=description, - class_name=class_name, timeout_s=timeout_s, serial=serial, - ) - - -def android_click_element(text: Optional[str] = None, - resource_id: Optional[str] = None, - description: Optional[str] = None, - class_name: Optional[str] = None, - timeout_s: float = 5.0, - serial: Optional[str] = None, - ) -> Dict[str, int]: - """Tap the first widget matching the selectors; return click centre.""" - from je_auto_control.utils.executor.action_executor import ( - _ac_android_click_element, - ) - return _ac_android_click_element( - text=text, resource_id=resource_id, description=description, - class_name=class_name, timeout_s=timeout_s, serial=serial, - ) - - -def android_dump_hierarchy(serial: Optional[str] = None) -> str: - """Return the device's widget tree as an XML string.""" - from je_auto_control.utils.executor.action_executor import ( - _ac_android_dump_hierarchy, - ) - return _ac_android_dump_hierarchy(serial=serial) - - -def ios_tap(x: int, y: int, - url: Optional[str] = None) -> Dict[str, int]: - from je_auto_control.utils.executor.action_executor import _ac_ios_tap - return _ac_ios_tap(x=int(x), y=int(y), url=url) - - -def ios_swipe(x1: int, y1: int, x2: int, y2: int, - duration_s: float = 0.5, - url: Optional[str] = None) -> Dict[str, Any]: - from je_auto_control.utils.executor.action_executor import _ac_ios_swipe - return _ac_ios_swipe(x1=int(x1), y1=int(y1), x2=int(x2), y2=int(y2), - duration_s=float(duration_s), url=url) - - -def ios_type(text: str, url: Optional[str] = None) -> str: - from je_auto_control.utils.executor.action_executor import _ac_ios_type - return _ac_ios_type(text=text, url=url) - - -def ios_screenshot(file_path: str, url: Optional[str] = None) -> str: - from je_auto_control.utils.executor.action_executor import ( - _ac_ios_screenshot, - ) - return _ac_ios_screenshot(file_path=file_path, url=url) - - -def ios_find_element(name: Optional[str] = None, - class_name: Optional[str] = None, - predicate: Optional[str] = None, - timeout_s: float = 5.0, - url: Optional[str] = None) -> Dict[str, int]: - from je_auto_control.utils.executor.action_executor import ( - _ac_ios_find_element, - ) - return _ac_ios_find_element( - name=name, class_name=class_name, predicate=predicate, - timeout_s=float(timeout_s), url=url, - ) - - -def ios_click_element(name: Optional[str] = None, - class_name: Optional[str] = None, - predicate: Optional[str] = None, - timeout_s: float = 5.0, - url: Optional[str] = None) -> Dict[str, int]: - from je_auto_control.utils.executor.action_executor import ( - _ac_ios_click_element, - ) - return _ac_ios_click_element( - name=name, class_name=class_name, predicate=predicate, - timeout_s=float(timeout_s), url=url, - ) - - -def ios_dump_source(url: Optional[str] = None) -> str: - from je_auto_control.utils.executor.action_executor import ( - _ac_ios_dump_source, - ) - return _ac_ios_dump_source(url=url) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_locators.py b/je_auto_control/utils/mcp_server/tools/_handlers_locators.py index 5a322a459..c5709a464 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_locators.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_locators.py @@ -7,7 +7,7 @@ import math from typing import Any, Dict, List, Optional -from je_auto_control.utils.mcp_server.tools._handlers_executor_bridge import ( +from je_auto_control.utils.mcp_server.tools._handlers_automation_executor import ( _observe_handler, ) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_mobile_executor.py b/je_auto_control/utils/mcp_server/tools/_handlers_mobile_executor.py new file mode 100644 index 000000000..df7735220 --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_handlers_mobile_executor.py @@ -0,0 +1,135 @@ +"""MCP mobile adapters delegating lazily to executor commands. + +Annotations mirror the executor JSON boundary, including heterogeneous payloads. +""" + +from typing import Any, Dict, Optional + + +def android_find_element( + text: Optional[str] = None, + resource_id: Optional[str] = None, + description: Optional[str] = None, + class_name: Optional[str] = None, + timeout_s: float = 5.0, + serial: Optional[str] = None, +) -> Dict[str, int]: + """Find an Android widget via uiautomator2; return its bounding rect.""" + from je_auto_control.utils.executor.action_executor import ( + _ac_android_find_element, + ) + + return _ac_android_find_element( + text=text, + resource_id=resource_id, + description=description, + class_name=class_name, + timeout_s=timeout_s, + serial=serial, + ) + + +def android_click_element( + text: Optional[str] = None, + resource_id: Optional[str] = None, + description: Optional[str] = None, + class_name: Optional[str] = None, + timeout_s: float = 5.0, + serial: Optional[str] = None, +) -> Dict[str, int]: + """Tap the first widget matching the selectors; return click centre.""" + from je_auto_control.utils.executor.action_executor import ( + _ac_android_click_element, + ) + + return _ac_android_click_element( + text=text, + resource_id=resource_id, + description=description, + class_name=class_name, + timeout_s=timeout_s, + serial=serial, + ) + + +def android_dump_hierarchy(serial: Optional[str] = None) -> str: + """Return the device's widget tree as an XML string.""" + from je_auto_control.utils.executor.action_executor import ( + _ac_android_dump_hierarchy, + ) + + return _ac_android_dump_hierarchy(serial=serial) + + +def ios_tap(x: int, y: int, url: Optional[str] = None) -> Dict[str, int]: + from je_auto_control.utils.executor.action_executor import _ac_ios_tap + + return _ac_ios_tap(x=int(x), y=int(y), url=url) + + +def ios_swipe(x1: int, y1: int, x2: int, y2: int, duration_s: float = 0.5, url: Optional[str] = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _ac_ios_swipe + + return _ac_ios_swipe(x1=int(x1), y1=int(y1), x2=int(x2), y2=int(y2), duration_s=float(duration_s), url=url) + + +def ios_type(text: str, url: Optional[str] = None) -> str: + from je_auto_control.utils.executor.action_executor import _ac_ios_type + + return _ac_ios_type(text=text, url=url) + + +def ios_screenshot(file_path: str, url: Optional[str] = None) -> str: + from je_auto_control.utils.executor.action_executor import ( + _ac_ios_screenshot, + ) + + return _ac_ios_screenshot(file_path=file_path, url=url) + + +def ios_find_element( + name: Optional[str] = None, + class_name: Optional[str] = None, + predicate: Optional[str] = None, + timeout_s: float = 5.0, + url: Optional[str] = None, +) -> Dict[str, int]: + from je_auto_control.utils.executor.action_executor import ( + _ac_ios_find_element, + ) + + return _ac_ios_find_element( + name=name, + class_name=class_name, + predicate=predicate, + timeout_s=float(timeout_s), + url=url, + ) + + +def ios_click_element( + name: Optional[str] = None, + class_name: Optional[str] = None, + predicate: Optional[str] = None, + timeout_s: float = 5.0, + url: Optional[str] = None, +) -> Dict[str, int]: + from je_auto_control.utils.executor.action_executor import ( + _ac_ios_click_element, + ) + + return _ac_ios_click_element( + name=name, + class_name=class_name, + predicate=predicate, + timeout_s=float(timeout_s), + url=url, + ) + + +def ios_dump_source(url: Optional[str] = None) -> str: + from je_auto_control.utils.executor.action_executor import ( + _ac_ios_dump_source, + ) + + return _ac_ios_dump_source(url=url) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_vision_executor.py b/je_auto_control/utils/mcp_server/tools/_handlers_vision_executor.py new file mode 100644 index 000000000..48db8cb66 --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_handlers_vision_executor.py @@ -0,0 +1,564 @@ +"""MCP vision adapters delegating lazily to executor commands. + +Annotations mirror the executor JSON boundary, including heterogeneous payloads. +""" + +from typing import Any, Dict, List, Optional + + +def grid_cell(boxes: Any, row: Any, col: Any, row_tolerance: Any = 10, box_format: str = "xywh") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _grid_cell + + return _grid_cell(boxes, row, col, row_tolerance, box_format) + + +def match_template( + template: str, min_score: Any = 0.8, scales: Any = None, region: Any = None, method: str = "ccoeff_normed" +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_template + + return _match_template(template, min_score, scales, region, method) + + +def match_template_all( + template: str, min_score: Any = 0.8, max_results: Any = 20, nms_iou: Any = 0.3, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_template_all + + return _match_template_all(template, min_score, max_results, nms_iou, region) + + +def match_masked(template: str, mask: Any = None, min_score: Any = 0.9, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_masked + + return _match_masked(template, mask, min_score, region) + + +def match_masked_all( + template: str, mask: Any = None, min_score: Any = 0.9, max_results: Any = 20, nms_iou: Any = 0.3, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_masked_all + + return _match_masked_all(template, mask, min_score, max_results, nms_iou, region) + + +def match_rotated( + template: str, + min_score: Any = 0.8, + scales: Any = None, + angles: Any = None, + region: Any = None, + method: str = "ccoeff_normed", +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_rotated + + return _match_rotated(template, min_score, scales, angles, region, method) + + +def match_rotated_all( + template: str, + min_score: Any = 0.8, + scales: Any = None, + angles: Any = None, + max_results: Any = 20, + nms_iou: Any = 0.3, + region: Any = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_rotated_all + + return _match_rotated_all(template, min_score, scales, angles, max_results, nms_iou, region) + + +def match_with_trust( + template: str, + min_score: Any = 0.0, + scales: Any = None, + ambiguous_ratio: Any = 0.9, + region: Any = None, + method: str = "ccoeff_normed", +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_with_trust + + return _match_with_trust(template, min_score, scales, ambiguous_ratio, region, method) + + +def auto_threshold(template: str, region: Any = None, method: str = "ccoeff_normed") -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _auto_threshold + + return _auto_threshold(template, region, method) + + +def match_auto( + template: str, floor: Any = 0.5, max_results: Any = 20, region: Any = None, method: str = "ccoeff_normed" +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_auto + + return _match_auto(template, floor, max_results, region, method) + + +def edge_match(template: str, min_score: Any = 0.7, scales: Any = None, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _edge_match + + return _edge_match(template, min_score, scales, region) + + +def edge_match_all( + template: str, min_score: Any = 0.7, max_results: Any = 20, nms_iou: Any = 0.3, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _edge_match_all + + return _edge_match_all(template, min_score, max_results, nms_iou, region) + + +def match_subpixel( + template: str, min_score: Any = 0.0, region: Any = None, method: str = "ccoeff_normed" +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_subpixel + + return _match_subpixel(template, min_score, region, method) + + +def vote_centers(centers: Any, agree_px: Any = 10, min_votes: Any = 2) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _vote_centers + + return _vote_centers(centers, agree_px, min_votes) + + +def match_ensemble( + templates: Any, min_score: Any = 0.8, agree_px: Any = 10, min_votes: Any = 2, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_ensemble + + return _match_ensemble(templates, min_score, agree_px, min_votes, region) + + +def match_color( + template: str, channels: Any = None, min_score: Any = 0.7, scales: Any = None, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_color + + return _match_color(template, channels, min_score, scales, region) + + +def match_color_all( + template: str, + channels: Any = None, + min_score: Any = 0.7, + max_results: Any = 20, + nms_iou: Any = 0.3, + region: Any = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_color_all + + return _match_color_all(template, channels, min_score, max_results, nms_iou, region) + + +def region_stability(frames: Any, settle_threshold: Any = 0.99) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _region_stability + + return _region_stability(frames, settle_threshold) + + +def match_persistence(template: str, frames: Any, min_score: Any = 0.8, agree_px: Any = 8) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_persistence + + return _match_persistence(template, frames, min_score, agree_px) + + +def grid_cells(rows: Any, cols: Any, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _grid_cells + + return _grid_cells(rows, cols, region) + + +def cell_for_point(x: Any, y: Any, rows: Any, cols: Any, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _cell_for_point + + return _cell_for_point(x, y, rows, cols, region) + + +def point_for_cell(label: str, rows: Any, cols: Any, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _point_for_cell + + return _point_for_cell(label, rows, cols, region) + + +def populate_table(grid: Any, text_boxes: Any, overlap: Any = 0.4) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _populate_table + + return _populate_table(grid, text_boxes, overlap) + + +def column_gutters(boxes: Any, page_width: Any = None, min_gap: Any = 8) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _column_gutters + + return _column_gutters(boxes, page_width, min_gap) + + +def detect_borderless_table( + boxes: Any, page_width: Any = None, min_gap: Any = 8, min_cols: Any = 2, min_rows: Any = 2 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _detect_borderless_table + + return _detect_borderless_table(boxes, page_width, min_gap, min_cols, min_rows) + + +def associate_fields(text_boxes: Any, directions: Any = None, max_gap: Any = 150) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _associate_fields + + return _associate_fields(text_boxes, directions, max_gap) + + +def match_labels_to_widgets(labels: Any, widgets: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _match_labels_to_widgets + + return _match_labels_to_widgets(labels, widgets) + + +def flow_order(boxes: Any, min_gap: Any = 12) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _flow_order + + return _flow_order(boxes, min_gap) + + +def xy_cut(boxes: Any, min_gap: Any = 12) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _xy_cut + + return _xy_cut(boxes, min_gap) + + +def group_paragraphs(lines: Any, line_gap_factor: Any = 1.6) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _group_paragraphs + + return _group_paragraphs(lines, line_gap_factor) + + +def detect_lists(lines: Any) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _detect_lists + + return _detect_lists(lines) + + +def classify_lines(lines: Any, heading_ratio: Any = 1.2) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _classify_lines + + return _classify_lines(lines, heading_ratio) + + +def outline(lines: Any, heading_ratio: Any = 1.2) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _outline + + return _outline(lines, heading_ratio) + + +def find_color_region(rgb: Any, tolerance: Any = 20, min_area: Any = 50, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_color_region + + return _find_color_region(rgb, tolerance, min_area, region) + + +def ssim_compare(reference: str, current: Any = None, ignore: Any = None, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _ssim_compare + + return _ssim_compare(reference, current, ignore, region) + + +def ssim_changed_regions( + reference: str, + current: Any = None, + ignore: Any = None, + threshold: Any = 0.35, + min_area: Any = 50, + region: Any = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _ssim_changed_regions + + return _ssim_changed_regions(reference, current, ignore, threshold, min_area, region) + + +def feature_match( + template: str, region: Any = None, max_features: Any = 500, ratio: Any = 0.75, min_inliers: Any = 10 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _feature_match + + return _feature_match(template, region, max_features, ratio, min_inliers) + + +def find_shapes(region: Any = None, min_area: Any = 400, max_area: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_shapes + + return _find_shapes(region, min_area, max_area) + + +def find_rectangles( + region: Any = None, min_area: Any = 400, max_area: Any = None, aspect_range: Any = None, epsilon: Any = 0.04 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_rectangles + + return _find_rectangles(region, min_area, max_area, aspect_range, epsilon) + + +def preprocess_image( + output_path: str, + source: Any = None, + steps: Any = None, + scale: Any = 2.0, + region: Any = None, + block_size: Any = 31, + c: Any = 11, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _preprocess_image + + return _preprocess_image(output_path, source, steps, scale, region, block_size, c) + + +def wait_actionable( + template: str, timeout_s: Any = 5.0, stable_for_s: Any = 0.3, min_score: Any = 0.8, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _wait_actionable + + return _wait_actionable(template, timeout_s, stable_for_s, min_score, region) + + +def fuse_elements(ocr: Any = None, icon: Any = None, a11y: Any = None, iou_threshold: Any = 0.9) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _fuse_elements + + return _fuse_elements(ocr, icon, a11y, iou_threshold) + + +def reading_order(elements: Any, row_tol: Any = 12) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _reading_order + + return _reading_order(elements, row_tol) + + +def segment_hsv(lower_hsv: Any, upper_hsv: Any, min_area: Any = 50, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _segment_hsv + + return _segment_hsv(lower_hsv, upper_hsv, min_area, region) + + +def dominant_hue_regions( + hue: Any, hue_tol: Any = 10, sat_min: Any = 80, val_min: Any = 80, min_area: Any = 50, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _dominant_hue_regions + + return _dominant_hue_regions(hue, hue_tol, sat_min, val_min, min_area, region) + + +def find_text_regions( + min_area: Any = 60, max_area: Any = None, merge: Any = True, max_aspect: Any = 12.0, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_text_regions + + return _find_text_regions(min_area, max_area, merge, max_aspect, region) + + +def find_text_lines(y_tolerance: Any = 8, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_text_lines + + return _find_text_lines(y_tolerance, region) + + +def find_lines(min_length: Any = 80, max_gap: Any = 10, orientation: str = "any", region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_lines + + return _find_lines(min_length, max_gap, orientation, region) + + +def find_grid(min_length: Any = 120, tol: Any = 10, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_grid + + return _find_grid(min_length, tol, region) + + +def find_separators( + axis: str = "horizontal", min_length: Any = 120, tol: Any = 10, region: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _find_separators + + return _find_separators(axis, min_length, tol, region) + + +def locate_chain(boxes: Any, ops: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _locate_chain + + return _locate_chain(boxes, ops) + + +def image_quality(source: Any = None, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _image_quality + + return _image_quality(source, region) + + +def quality_gate( + source: Any = None, region: Any = None, min_sharpness: Any = 100.0, min_contrast: Any = 12.0 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _quality_gate + + return _quality_gate(source, region, min_sharpness, min_contrast) + + +def detect_scale( + template: Any, haystack: Any = None, region: Any = None, scales: Any = None, method: str = "ccoeff_normed" +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _detect_scale + + return _detect_scale(template, haystack, region, scales, method) + + +def scale_sweep( + template: Any, haystack: Any = None, region: Any = None, scales: Any = None, method: str = "ccoeff_normed" +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _scale_sweep + + return _scale_sweep(template, haystack, region, scales, method) + + +def salient_regions( + source: Any = None, region: Any = None, size: Any = 64, threshold: Any = None, min_area: Any = 4 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _salient_regions + + return _salient_regions(source, region, size, threshold, min_area) + + +def most_salient( + source: Any = None, region: Any = None, size: Any = 64, threshold: Any = None, min_area: Any = 4 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _most_salient + + return _most_salient(source, region, size, threshold, min_area) + + +def image_histogram(source: Any = None, bins: Any = 32, space: str = "hsv", region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _image_histogram + + return _image_histogram(source, bins, space, region) + + +def histogram_changed( + reference: str, + current: Any = None, + method: str = "correlation", + threshold: Any = 0.9, + space: str = "hsv", + region: Any = None, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _histogram_changed + + return _histogram_changed(reference, current, method, threshold, space, region) + + +def changed_regions( + before: str, after: Any = None, threshold: Any = 25, min_area: Any = 80, blur: Any = 5 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _changed_regions + + return _changed_regions(before, after, threshold, min_area, blur) + + +def has_motion(before: str, after: Any = None, threshold: Any = 25, min_area: Any = 80) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _has_motion + + return _has_motion(before, after, threshold, min_area) + + +def perceptual_diff( + actual: str, expected: str, threshold: Any = 0.1, include_aa: Any = False, max_diff_ratio: Any = None +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _perceptual_diff + + return _perceptual_diff(actual, expected, threshold, include_aa, max_diff_ratio) + + +def read_barcodes(source: Any = None, region: Any = None) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _read_barcodes + + return _read_barcodes(source, region) + + +def wait_image_gone( + image: Any, + detect_threshold: float = 1.0, + timeout_s: float = 10.0, + poll_interval_s: float = 0.2, + gone_for_s: float = 0.0, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _wait_image_gone + + return _wait_image_gone(image, detect_threshold, timeout_s, poll_interval_s, gone_for_s) + + +def wait_text_gone( + text: str, timeout_s: float = 10.0, poll_interval_s: float = 0.2, gone_for_s: float = 0.0 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _wait_text_gone + + return _wait_text_gone(text, timeout_s, poll_interval_s, gone_for_s) + + +def wait_color( + target_rgb: Any, + region: Any = None, + tolerance: int = 10, + min_fraction: float = 0.5, + present: bool = True, + timeout_s: float = 10.0, + poll_interval_s: float = 0.2, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _wait_color + + return _wait_color(target_rgb, region, tolerance, min_fraction, present, timeout_s, poll_interval_s) + + +def wait_window_title( + pattern: str, present: bool = True, regex: bool = True, timeout_s: float = 10.0, poll_interval_s: float = 0.2 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _wait_window_title + + return _wait_window_title(pattern, present, regex, timeout_s, poll_interval_s) + + +def anchor_locate( + anchor: Dict[str, Any], + target: Dict[str, Any], + relation: str = "near", + max_distance_px: float = 200.0, + ordinal: int = 1, +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _anchor_locate + + return _anchor_locate(anchor, target, relation, max_distance_px, ordinal) + + +def anchor_locate_all( + anchor: Dict[str, Any], target: Dict[str, Any], relation: str = "near", max_distance_px: float = 200.0 +) -> Dict[str, Any]: + from je_auto_control.utils.executor.action_executor import _anchor_locate_all + + return _anchor_locate_all(anchor, target, relation, max_distance_px) + + +def redact_screenshot( + file_path: str, + output_path: Optional[str] = None, + policy: str = "moderate", + regions: Optional[List[List[int]]] = None, + accessibility: Optional[List[Dict[str, Any]]] = None, + ocr: Optional[List[Dict[str, Any]]] = None, +) -> Dict[str, Any]: + """Blur PII regions in a saved screenshot via the redaction engine.""" + from je_auto_control.utils.executor.action_executor import ( + _redact_screenshot, + ) + + return _redact_screenshot( + file_path=file_path, + output_path=output_path, + policy=policy, + regions=regions, + accessibility=accessibility, + ocr=ocr, + ) diff --git a/pyproject.toml b/pyproject.toml index 73b7f4cb8..c306b5edb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -404,6 +404,12 @@ module = [ "je_auto_control.utils.config_sync.store", "je_auto_control.utils.config_sync.versions", "je_auto_control.utils.generate_report.report_path", + "je_auto_control.utils.mcp_server.tools._handlers_accessibility_executor", + "je_auto_control.utils.mcp_server.tools._handlers_automation_executor", + "je_auto_control.utils.mcp_server.tools._handlers_data_executor", + "je_auto_control.utils.mcp_server.tools._handlers_desktop_executor", + "je_auto_control.utils.mcp_server.tools._handlers_mobile_executor", + "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", "je_auto_control.utils.mcp_server._argument_policy", "je_auto_control.utils.mcp_server._authz", "je_auto_control.utils.mcp_server._http_origin", diff --git a/test/unit_test/headless/test_agent_executor_mcp_wiring.py b/test/unit_test/headless/test_agent_executor_mcp_wiring.py index e9c991e86..3d0d67d3f 100644 --- a/test/unit_test/headless/test_agent_executor_mcp_wiring.py +++ b/test/unit_test/headless/test_agent_executor_mcp_wiring.py @@ -64,7 +64,7 @@ def test_mcp_handler_round_trips(monkeypatch): _patch_backends(monkeypatch, [ {"stop": True, "message": "mcp-ok"}, ]) - from je_auto_control.utils.mcp_server.tools._handlers_executor_bridge import ( + from je_auto_control.utils.mcp_server.tools._handlers_automation_executor import ( run_agent, ) record = run_agent( diff --git a/test/unit_test/headless/test_android_uiautomator.py b/test/unit_test/headless/test_android_uiautomator.py index 95e75f25a..72e115d19 100644 --- a/test/unit_test/headless/test_android_uiautomator.py +++ b/test/unit_test/headless/test_android_uiautomator.py @@ -147,7 +147,7 @@ def test_mcp_handler_round_trip(monkeypatch): "je_auto_control.android.click_element", lambda **kw: (50, 75), ) - from je_auto_control.utils.mcp_server.tools._handlers_executor_bridge import ( + from je_auto_control.utils.mcp_server.tools._handlers_mobile_executor import ( android_click_element, ) assert android_click_element(text="Next") == {"x": 50, "y": 75} diff --git a/test/unit_test/headless/test_drag_pacing.py b/test/unit_test/headless/test_drag_pacing.py index 80096fde5..2330c6f5c 100644 --- a/test/unit_test/headless/test_drag_pacing.py +++ b/test/unit_test/headless/test_drag_pacing.py @@ -173,13 +173,13 @@ def test_the_executor_adapters_forward_the_pacing(timeline, monkeypatch): def test_the_mcp_handlers_forward_the_pacing(timeline, monkeypatch): - from je_auto_control.utils.mcp_server.tools import _handlers, _handlers_executor_bridge + from je_auto_control.utils.mcp_server.tools import _handlers, _handlers_desktop_executor monkeypatch.setattr(tween_module, "_default_sink", timeline.sink) monkeypatch.setattr(path_module, "_default_sink", timeline.sink) assert _handlers.tween_drag([0, 0], [10, 0], steps=1, settle_s=0.05) == {"points": 2} assert ("sleep", 0.05, None) in timeline.entries timeline.entries.clear() - _handlers_executor_bridge.drag_path([[0, 0], [5, 5]], per_segment_steps=1, step_delay_s=0.06) + _handlers_desktop_executor.drag_path([[0, 0], [5, 5]], per_segment_steps=1, step_delay_s=0.06) assert ("sleep", 0.06, None) in timeline.entries diff --git a/test/unit_test/headless/test_mcp_executor_adapters.py b/test/unit_test/headless/test_mcp_executor_adapters.py new file mode 100644 index 000000000..d8a054153 --- /dev/null +++ b/test/unit_test/headless/test_mcp_executor_adapters.py @@ -0,0 +1,71 @@ +"""Registry adapters preserve executor forwarding without driving native inputs.""" + +from unittest.mock import Mock + +import pytest + +from je_auto_control.utils.executor import action_executor +from je_auto_control.utils.mcp_server.tools import build_default_tool_registry + + +@pytest.mark.parametrize( + "domain,tool_name,params,target,args,kwargs", + [ + ( + "accessibility", + "ac_a11y_record_start", + {"poll_interval_s": "0.5", "min_movement_px": "12"}, + "_a11y_record_start", + (), + {"app_name": None, "poll_interval_s": 0.5, "min_movement_px": 12}, + ), + ("data", "ac_normalize_text", {"text": "Example"}, "_normalize_text", ("Example", "NFKC", True, True), {}), + ( + "desktop", + "ac_drag_path", + {"waypoints": [[1, 2], [3, 4]]}, + "_drag_path", + ([[1, 2], [3, 4]], "mouse_left", "linear", 20, 0.0, 0.0), + {}, + ), + ( + "automation", + "ac_run_agent", + {"goal": "fake only", "max_steps": "2"}, + "_run_agent", + (), + { + "goal": "fake only", + "backend": "anthropic", + "max_steps": 2, + "wall_seconds": 300.0, + "model": None, + "max_tokens": 1024, + }, + ), + ( + "mobile", + "ac_ios_swipe", + {"x1": "1", "y1": "2", "x2": "3", "y2": "4"}, + "_ac_ios_swipe", + (), + {"x1": 1, "y1": 2, "x2": 3, "y2": 4, "duration_s": 0.5, "url": None}, + ), + ( + "vision", + "ac_match_template", + {"template": "fake.png"}, + "_match_template", + ("fake.png", 0.8, None, None, "ccoeff_normed"), + {}, + ), + ], +) +def test_domain_adapter_forwarding(monkeypatch, domain, tool_name, params, target, args, kwargs): + result = {"stub_result": [1, 2, 3]} + stub = Mock(return_value=result) + monkeypatch.setattr(action_executor, target, stub) + tool = next(tool for tool in build_default_tool_registry() if tool.name == tool_name) + assert tool.handler.__module__.endswith(f"._handlers_{domain}_executor") + assert tool.handler(**params) is result + stub.assert_called_once_with(*args, **kwargs) diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 398f68efe..276567681 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -600,7 +600,6 @@ je_auto_control.utils.mcp_server.tools je_auto_control.utils.mcp_server.tools._base je_auto_control.utils.mcp_server.tools._factories je_auto_control.utils.mcp_server.tools._handlers -je_auto_control.utils.mcp_server.tools._handlers_executor_bridge je_auto_control.utils.mcp_server.tools._handlers_input je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations From 2c5809db478b88c45fc000d162cbb8d26ba85993 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 16:57:52 +0800 Subject: [PATCH 020/161] Isolate default EI input behind an owned worker --- Progress.md | 14 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture.md | 7 + architecture_explore.md | 18 +- docs/API_LIFECYCLE.md | 18 + .../Eng/doc/new_features/v2_features_doc.rst | 9 + .../Zh/doc/new_features/v2_features_doc.rst | 9 + docs/updates/2026-11.md | 6 + docs/updates/README.md | 1 + je_auto_control/linux_wayland/ei_default.py | 121 +++++ je_auto_control/linux_wayland/ei_protocol.py | 116 +++++ je_auto_control/linux_wayland/ei_transport.py | 255 ++++++++++ je_auto_control/linux_wayland/ei_worker.py | 161 +++++++ je_auto_control/linux_wayland/libei.py | 78 +-- test/fixtures/ei_worker_fixture.py | 40 ++ .../test_wayland_capability_states.py | 34 +- .../headless/test_wayland_input_authority.py | 18 +- test/unit_test/headless/test_wayland_libei.py | 4 +- .../headless/test_wayland_region_authority.py | 8 +- .../headless/test_wayland_worker_cleanup.py | 448 ++++++++++++++++++ 22 files changed, 1260 insertions(+), 111 deletions(-) create mode 100644 je_auto_control/linux_wayland/ei_default.py create mode 100644 je_auto_control/linux_wayland/ei_protocol.py create mode 100644 je_auto_control/linux_wayland/ei_transport.py create mode 100644 je_auto_control/linux_wayland/ei_worker.py create mode 100644 test/fixtures/ei_worker_fixture.py create mode 100644 test/unit_test/headless/test_wayland_worker_cleanup.py diff --git a/Progress.md b/Progress.md index 656586b22..48554248e 100644 --- a/Progress.md +++ b/Progress.md @@ -203,14 +203,14 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` --- -## libei 半開交握的資源隔離尚未完成 +## libei 半開交握的原生資源回收尚待驗證 -`TODO` — D2 helper 隔離;不能直接移除 `linux_wayland/libei.py::_teardown` 的半開保護。 +`TODO` — D2 預設輸入路徑已有具有限 IPC/期限/取消的獨立 EI helper;仍需原生驗收, +不能直接移除 `linux_wayland/libei.py::_teardown` 的半開保護。 -需依 D2 計畫把原生配置、portal/交握、事件送出與 teardown 放進擁有的 helper, -補上有界 IPC、request ID、逾時與取消,以及 parent close/reap。 -半開交握失敗仍會留下 context/fd;直接重複建立 backend 可能重複累積, -需驗證 helper 結束後資源可回收,且取消不影響其他擁有者。 +直接使用 `LibeiBackend` 的路徑仍在呼叫程序內;半開交握失敗仍可能留下 context/fd。 +須在支援的原生環境驗證預設 helper 結束後的 context/fd 回收、原生按鍵釋放與其他擁有者不受影響。 +合成子程序的退出、ACK 與 cleanup 回覆不等於合成器已釋放輸入,也不能解除未知輸入結果。 `docker/libei_verify.py` 與 `docker/eis_verify.py` 保留原生故障/成功邊界檢查; 裝置暫停與序號回讀、真實合成器權限流程仍待對應環境驗證。 @@ -529,7 +529,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev `WIP` — 改版仍缺以下內容;原生平台與正式環境驗收缺口另列於後。 計畫 D1 仍缺 portal session 關閉/恢復、compositor 重啟的狀態與原生驗收、 擷取結果與擁有者 context 的接合,以及原生 session 的重試/取消/停止控制。 -D2 仍缺 helper 隔離與半開交握資源回收;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 +D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 H 已有三平台型別 gate 與縮減中的真實相依型別豁免;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 diff --git a/README.md b/README.md index 6b3c5752b..2a1cc1e79 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ Auto Click, Record and Script Executor own their controls and background tasks. Windows, macOS, X11 and Wayland use different backends. Available features depend on system permissions and optional dependencies; Windows ARM64 has additional limitations. See the installation guide before choosing a deployment target. +Wayland NORMAL input runs libei and portal calls in an owned helper process. Timeouts, cancellation and uncertain replies retire that helper without replay or automatic provider fallback. The direct `LibeiBackend` API remains in-process. Helper retirement is not proof that a compositor released input; native acceptance remains pending. + Managed agent tasks and cross-host transfers include experimental features. See the implementation notes and project progress before relying on them in production. ## Documentation diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 301f26e63..e515214bf 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -43,6 +43,8 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, Windows、macOS、X11 与 Wayland 使用不同后端,实际功能取决于系统权限与可选依赖。Windows ARM64 另有限制,部署前请先阅读安装文件。 +Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用。超时、取消或回复不确定时会退役该进程,不重播输入或自动切换提供者。直接使用 `LibeiBackend` 仍在调用端进程内执行;子进程退役不代表合成器已释放输入,原生验收仍待执行。 + 受管理的 Agent 任务与跨主机传输包含实验性功能;采用前请查看实现记录与项目进度中的验收状态。 ## 文件 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 931511f58..fdc26b582 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -43,6 +43,8 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, Windows、macOS、X11 與 Wayland 使用不同後端,實際功能取決於系統權限與選配依賴。Windows ARM64 另有限制,部署前請先閱讀安裝文件。 +Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫。逾時、取消或回覆不確定時會退役該程序,不重播輸入或自動切換供應者。直接使用 `LibeiBackend` 仍在呼叫端程序內執行;子程序退役不代表合成器已釋放輸入,原生驗收仍待執行。 + 受管理的 Agent 任務與跨主機傳輸包含實驗性功能;採用前請查看實作紀錄與專案進度中的驗收狀態。 ## 文件 diff --git a/architecture.md b/architecture.md index 355a142e6..2414e50b7 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,12 @@ # AutoControl Architecture +Wayland default EI input uses a bounded domain protocol over the existing owned +helper channel. Native allocation, portal consent, emission and teardown stay in +that child. Reply validation and emission acknowledgement share the request lock; +uncertain outcomes retire the owner without replay. Passive cache inspection does +not acquire consent. Raw LibeiBackend remains in-process, including its half-open +teardown guard; process retirement does not establish compositor input release. + MCP executor adapters are grouped by accessibility, automation, data, desktop, mobile and vision. Factories bind the same tool schemas to these strict modules; each adapter imports its executor function only when called. diff --git a/architecture_explore.md b/architecture_explore.md index aebad1ad7..9288c7a5e 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,505 | -| 程式碼總行數 | 229,797 | +| Python 模組總數(含周邊子專案) | 1,509 | +| 程式碼總行數 | 230,390 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -248,7 +248,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `uinput/keyboard.py` | 44 | uinput 鍵盤後端,介面與 X11 版一致。 | | `uinput/mouse.py` | 130 | uinput 滑鼠後端。 | -#### Linux Wayland(`linux_wayland/`,20 檔/3,844 行) +#### Linux Wayland(`linux_wayland/`,24 檔/4,437 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -260,7 +260,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `_select_input.py` | 103 | 決定使用原生 libei 或 CLI shim;`active_backend()` 是 keyboard/mouse 的唯一入口,`emitted()` 僅容許未分類的選用後端缺席退回 CLI;明確原生選擇、權限/裝置/協定拒絕保持失敗。 | | `_layout.py` | 83 | 版面原點的共用查詢。擷取與輸入不是同一個座標空間,差的就是這個原點:libei 的 region offset 是 `uint32`(描述不了負原點),`ydotool mousemove --absolute` 的原點是合成器夾取的那個角落——兩條路都要減掉它,所以放在這裡而不是各自複製。讀數快取一秒——擷取那一側刻意不快取,但 ydotool 每次絕對移動都會問,不快取等於每次移動多開一個 `wlr-randr` 行程。 | | `oeffis.py` | 223 | liboeffis 綁定:跑完 RemoteDesktop portal 交握,交出 EIS fd;請求後的拒絕/逾時/失敗保留明確狀態。 | -| `libei.py` | 731 | libei 綁定、撤銷閂鎖與只快取中繼資料的失敗狀態;完整握手(seat 綁定能力 → 由事件取得 device → start_emulating → 每次發送後 frame)。另負責絕對指標的座標空間:讀回裝置的 region,把版面座標映射進去,沒有任何 region 涵蓋就以 failed 拒絕,停止隱含 CLI 備援與後續點擊(不撤銷 sender)。 快取觀測不讀事件,完整就緒涵蓋全部請求的事件種類。 | +| `libei.py` | 671 | libei 綁定、撤銷閂鎖與只快取中繼資料的失敗狀態;完整握手(seat 綁定能力 → 由事件取得 device → start_emulating → 每次發送後 frame)。公開預設存取轉交 ei_default;直接建構仍在程序內。另負責絕對指標的座標空間:讀回裝置的 region,把版面座標映射進去,沒有任何 region 涵蓋就以 failed 拒絕,停止隱含 CLI 備援與後續點擊(不撤銷 sender)。 快取觀測不讀事件,完整就緒涵蓋全部請求的事件種類。 | +| `ei_protocol.py` | 116 | 有界事件批次與版本封包,嚴格驗證事件與數值。 | +| `ei_worker.py` | 161 | 子程序原生 EI 擁有者;逐請求回覆與輸入清理。 | +| `ei_transport.py` | 255 | 共用 owned channel 的 EI 客戶端;期限、取消、ACK 鎖內驗證與失敗保留。 | +| `ei_default.py` | 121 | 預設 EI 客戶端快取、被動診斷與明確重設。 | | `mouse.py` | 387 | 滑鼠後端:移動、按鈕與捲動都 libei 優先,僅選用缺席時退回 ydotool;權限/裝置拒絕不重送;送往 libei 時垂直捲動軸取負(kernel `REL_WHEEL` 與 `wl_pointer` 正負號相反)。退到 ydotool 的絕對移動會先減掉版面原點(`--absolute` 是相對於版面左上角,不是版面座標的 `(0, 0)`),並依 `pointer_accel_mode()` 處理指標加速度——倍率讀不回來,只有操作者知道,所以由 `JE_AUTOCONTROL_WAYLAND_POINTER_ACCEL` 宣告:未設定=每個行程警告一次後照送、`flat`=已關掉加速度故靜靜送出、`strict`=拒絕這次移動。 | | `keyboard.py` | 206 | 鍵盤後端:按鍵/組合鍵 libei 優先,權限拒絕不改走 CLI;中斷時逐一釋放原後端已按下的鍵。文字仍用 wtype。 | | `keymap.py` | 155 | 友善鍵名 → evdev key code。 | @@ -1411,7 +1415,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,175 個 `test_*.py`/11,394 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,176 個 `test_*.py`/11,416 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1514,7 +1518,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | -| `linux_wayland/` | 20 | 3,844 | +| `linux_wayland/` | 24 | 4,437 | | `utils/triggers/` | 4 | 1,401 | | `utils/ocr/` | 10 | 1,382 | | `utils/usbip/` | 5 | 1,008 | @@ -1523,7 +1527,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,493** | **229,052** | +| **總計** | **1,497** | **229,645** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/API_LIFECYCLE.md b/docs/API_LIFECYCLE.md index 56faff4df..efe449561 100644 --- a/docs/API_LIFECYCLE.md +++ b/docs/API_LIFECYCLE.md @@ -1437,3 +1437,21 @@ desktop tasks remain unavailable. This transport is not full Linux application o Installed wheel and source distributions include the REST Dashboard and Swagger HTML, CSS and JavaScript resources. The same localhost REST routes and authentication rules apply to an installed package; serving static pages grants no task or desktop input authority. + +### Owned Wayland EI sender + +NORMAL's default selector caches an `EiWorkerClient`; its fixed helper entry owns +raw `LibeiBackend`, portal handles and a pressed-input ledger. The direct/injected +`LibeiBackend` API remains in-process and outside this isolation boundary. +Passive diagnostics use cached metadata. A loadability probe starts the helper +without portal consent; only connect requests consent. Optional absence may use +CLI; permission, revocation, protocol and uncertain-send failures never do. + +Requests have sequence IDs, at most 128 events and 16 KiB frames. Client deadlines +include its request-lock queue. Lost replies and cancellation retire the owner; +there is no automatic replay or replacement worker. Explicit reset permits a new +owner only after successful retirement; failed close retains its handle for retry. +Graceful close attempts all tracked releases before teardown. An acknowledgement +means worker emission, not application delivery; process death/reap does not prove +compositor input release. Synthetic IPC tests cover ownership, while native +half-open teardown and compositor release acceptance remain unexecuted here. diff --git a/docs/source/Eng/doc/new_features/v2_features_doc.rst b/docs/source/Eng/doc/new_features/v2_features_doc.rst index 164f30655..096977b23 100644 --- a/docs/source/Eng/doc/new_features/v2_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v2_features_doc.rst @@ -520,6 +520,15 @@ Override:: Wayland libei native backend ---------------------------- +NORMAL's default EI sender now owns a fixed helper process for libei and portal +calls. The direct ``LibeiBackend`` API remains in-process. Batches are bounded to +128 events and 16 KiB; deadlines include client queue time. Uncertain replies +and cancellation retire the helper without replay or provider fallback. Failed +close retains ownership for explicit retry. Emission acknowledgements and process +retirement do not prove application delivery or compositor input release; native +acceptance remains pending. + + ctypes binding to ``libei.so.*`` that bypasses the CLI shims for microsecond-latency input. Opt-in via ``JE_AUTOCONTROL_WAYLAND_INPUT_BACKEND=libei|cli|auto``; the diff --git a/docs/source/Zh/doc/new_features/v2_features_doc.rst b/docs/source/Zh/doc/new_features/v2_features_doc.rst index f499e86e9..93fbc553c 100644 --- a/docs/source/Zh/doc/new_features/v2_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v2_features_doc.rst @@ -453,6 +453,15 @@ Wayland CLI backend Wayland libei native backend ---------------------------- +NORMAL's default EI sender now owns a fixed helper process for libei and portal +calls. The direct ``LibeiBackend`` API remains in-process. Batches are bounded to +128 events and 16 KiB; deadlines include client queue time. Uncertain replies +and cancellation retire the helper without replay or provider fallback. Failed +close retains ownership for explicit retry. Emission acknowledgements and process +retirement do not prove application delivery or compositor input release; native +acceptance remains pending. + + 對 ``libei.so.*`` 的 ctypes 綁定,繞過 CLI shim 取得微秒級延遲。 以 ``JE_AUTOCONTROL_WAYLAND_INPUT_BACKEND=libei|cli|auto`` 啟用; ``auto`` (預設)只在選用原生後端缺席時改用 CLI。portal 拒絕/逾時、 diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 329b6d417..e0635531c 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -778,3 +778,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Replaced the oversized bridge with six domain modules and migrated all private callers. Each module uses strict typing; the obsolete strict baseline row and size exemption were removed. Executor imports remain lazy. - **Evidence:** Independent review authenticated the original snapshot and verified 253 function bodies/defaults/original annotations, 506 fake forwarding calls and 820 unchanged tool descriptors. Implementation passed 240 tests; independent review passed 61; integration with document and whole-package budget gates passed 88. Scoped three-target mypy and Ruff passed. No desktop or device commands executed. - **Open items:** Remaining strict typing and full validation are tracked in Progress.md. + +## U-20261111-10 · 2026-11-11 · Isolate default EI input in an owned helper · #done #wayland + +- **What:** Added bounded EI messages, owned worker/client and default cache integration. Requests share a deadline, cancellation and retained failed-close ownership. Invalid ACKs retire before another caller may emit. The direct in-process API and half-open guard remain. +- **Evidence:** Implementation regression suite passed 273 cases with 6 platform skips. Independent review passed 217 and reproduced an ACK race, fixed with three deterministic concurrent regressions. Final worker suite passed 34; integrated EI tests passed 220. Scoped mypy, Ruff, Bandit and Radon passed. All native backends were fake; real child tests used a synthetic fixture. Integration document/complexity gates passed 44 cases; full three-target ordinary typing reported zero errors. Scoped Pylint error checks passed. +- **Open items:** Native context/fd recovery, compositor input release, consent and pause semantics remain in Progress.md. Helper retirement is not native release evidence. diff --git a/docs/updates/README.md b/docs/updates/README.md index 729521078..399d63c5b 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-10 | 2026-11-11 | Isolate default EI input in an owned helper | #done #wayland | [2026-11](2026-11.md) | | U-20261111-09 | 2026-11-11 | Split MCP executor adapters along strict domain boundaries | #done #mcp | [2026-11](2026-11.md) | | U-20261111-08 | 2026-11-11 | Reconcile conditional MCP path checks with current evidence | #snapshot #mcp | [2026-11](2026-11.md) | | U-20261111-07 | 2026-11-11 | Release core panels while retaining shared recorder ownership | #done #gui | [2026-11](2026-11.md) | diff --git a/je_auto_control/linux_wayland/ei_default.py b/je_auto_control/linux_wayland/ei_default.py new file mode 100644 index 000000000..ba28e6943 --- /dev/null +++ b/je_auto_control/linux_wayland/ei_default.py @@ -0,0 +1,121 @@ +"""Default owned EI sender cache; failed retirement retains its owner.""" +from typing import Optional +import threading + +from je_auto_control.linux_wayland._input_state import InputFailure, blocked_input +from je_auto_control.linux_wayland.ei_protocol import InputBackend +from je_auto_control.linux_wayland.ei_transport import EiWorkerClient +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption + + +def _new_default_backend() -> InputBackend: + return EiWorkerClient() + + +_DEFAULT_BACKEND: Optional[InputBackend] = None +_PROBE_FAILED = False +_NEEDS_CONNECT = False +_BLOCKED_PROBE: Optional[InputFailure] = None +_DEFAULT_LOCK = threading.Lock() + + +def _retire_after_failure(backend: InputBackend, error: BaseException) -> None: + from je_auto_control.linux_wayland.libei import LibeiUnavailable + global _BLOCKED_PROBE + try: + backend.disconnect() + except BaseException as cleanup_error: # reason: retain owner and preserve original controls + _BLOCKED_PROBE = InputFailure('failed', 'libei', 'EI helper retirement failed', fallback_allowed=False) + raise_caused_run_interruption(error) + raise_caused_run_interruption(cleanup_error) + if not isinstance(cleanup_error, Exception): + raise + raise LibeiUnavailable('EI helper retirement failed', state='failed') from cleanup_error + + +def connected_backend() -> Optional[InputBackend]: + """Return a connected backend, or None — probing at most once. + + The probe involves a portal round trip and a consent dialog, so a host + where libei cannot be used must pay for that discovery once rather than + on every keystroke. Only optional absence returns None. Authority/protocol + refusals retain inert metadata and raise until an explicit reset/retry. + """ + from je_auto_control.linux_wayland.libei import LibeiUnavailable + global _DEFAULT_BACKEND, _PROBE_FAILED, _BLOCKED_PROBE, _NEEDS_CONNECT + with _DEFAULT_LOCK: + if _BLOCKED_PROBE is not None: + raise LibeiUnavailable(_BLOCKED_PROBE.message, state=_BLOCKED_PROBE.state, + fallback_allowed=_BLOCKED_PROBE.fallback_allowed) + if _PROBE_FAILED: + return None + if _DEFAULT_BACKEND is None: + _DEFAULT_BACKEND = _new_default_backend() + _NEEDS_CONNECT = True + backend = _DEFAULT_BACKEND + try: + if not backend.is_available: + backend.disconnect() + _DEFAULT_BACKEND = None + _PROBE_FAILED = True + return None + if _NEEDS_CONNECT: + backend.connect() + _NEEDS_CONNECT = False + except BaseException as error: # reason: retire cancellation without losing ownership + _retire_after_failure(backend, error) + _DEFAULT_BACKEND = None + blocked = blocked_input(error) + _PROBE_FAILED = True + if blocked is not None: + _BLOCKED_PROBE = blocked[1] + raise blocked[0] + if not isinstance(error, (LibeiUnavailable, OSError, ValueError, AttributeError)): + raise + return None + return backend + + +def _observed_input_state() -> tuple[Optional[str], bool]: + """Inert snapshot for passive diagnostics; never construct a backend or wait on the portal-probe lock.""" + failure = _BLOCKED_PROBE + if failure is not None: + return failure.state, failure.fallback_allowed + backend = _DEFAULT_BACKEND + if backend is None: + return ('unavailable', True) if _PROBE_FAILED else (None, False) + return backend.observed_state(), False + + +def get_default_backend() -> Optional[InputBackend]: + """Return a cached helper without requesting portal consent.""" + from je_auto_control.linux_wayland.libei import LibeiUnavailable + global _DEFAULT_BACKEND, _NEEDS_CONNECT, _PROBE_FAILED + with _DEFAULT_LOCK: + if _BLOCKED_PROBE is not None: + raise LibeiUnavailable(_BLOCKED_PROBE.message, state=_BLOCKED_PROBE.state, + fallback_allowed=_BLOCKED_PROBE.fallback_allowed) + if _PROBE_FAILED: + return None + if _DEFAULT_BACKEND is None: + _DEFAULT_BACKEND = _new_default_backend() + _NEEDS_CONNECT = True + backend = _DEFAULT_BACKEND + if backend.is_available: + return backend + backend.disconnect() + _DEFAULT_BACKEND = None + _PROBE_FAILED = True + return None + + +def reset_default_backend() -> None: + """Explicitly retire the cached sender/refusal so a later request may seek a fresh grant.""" + global _DEFAULT_BACKEND, _PROBE_FAILED, _BLOCKED_PROBE, _NEEDS_CONNECT + with _DEFAULT_LOCK: + if _DEFAULT_BACKEND is not None: + _DEFAULT_BACKEND.disconnect() + _DEFAULT_BACKEND = None + _PROBE_FAILED = False + _NEEDS_CONNECT = False + _BLOCKED_PROBE = None diff --git a/je_auto_control/linux_wayland/ei_protocol.py b/je_auto_control/linux_wayland/ei_protocol.py new file mode 100644 index 000000000..e58cf4f68 --- /dev/null +++ b/je_auto_control/linux_wayland/ei_protocol.py @@ -0,0 +1,116 @@ +"""Bounded event batches and versioned replies for the owned EI helper.""" +from __future__ import annotations + +from dataclasses import dataclass +import json +import math +from typing import Any, Protocol, Sequence + +from je_auto_control.utils.exception.exceptions import AutoControlException + +MAX_PACKET = 16384 +MAX_EVENTS = 128 +_ARITY = {"press_key": 1, "release_key": 1, "press_button": 1, "release_button": 1, + "set_position": 2, "scroll": 2} + + +class EiProtocolError(AutoControlException, ValueError): + """The private EI wire contract was not satisfied.""" + + +class InputBackend(Protocol): + """Operations shared by the low-level backend and its owned-process proxy.""" + + @property + def is_available(self) -> bool: ... + @property + def is_connected(self) -> bool: ... + def observed_state(self) -> str: ... + def connect(self, *, timeout: float = 5.0, socket_path: bytes | None = None) -> None: ... + def disconnect(self) -> None: ... + def press_key(self, keycode: int) -> None: ... + def release_key(self, keycode: int) -> None: ... + def press_button(self, button_code: int) -> None: ... + def release_button(self, button_code: int) -> None: ... + def set_position(self, x: int, y: int) -> None: ... + def scroll(self, dx: int, dy: int) -> None: ... + + +def timeout_value(value: Any) -> float: + """Validate a finite positive deadline before queue admission.""" + if (type(value) not in (int, float) or not math.isfinite(value) or not 0 < value <= 60): + raise EiProtocolError("EI timeout must be finite and within 60 seconds") + return float(value) + + +@dataclass(frozen=True) +class InputEvent: + """One reviewed operation with bounded integer arguments.""" + + kind: str + arguments: tuple[int, ...] + + def __post_init__(self) -> None: + if not isinstance(self.kind, str) or self.kind not in _ARITY: + raise EiProtocolError("unknown EI event") + values = tuple(self.arguments) + if len(values) != _ARITY[self.kind]: + raise EiProtocolError("invalid EI event arity") + ceiling = 65535 if len(values) == 1 else (1 << 24) - 1 + floor = 0 if len(values) == 1 else -ceiling + if any(type(value) is not int or not floor <= value <= ceiling for value in values): + raise EiProtocolError("invalid EI event argument") + object.__setattr__(self, "arguments", values) + + def wire(self) -> dict[str, Any]: + """Return a detached event object for the private transport.""" + return {"kind": self.kind, "arguments": list(self.arguments)} + + +@dataclass(frozen=True) +class InputAck: + """Worker emission count, not a compositor application or input-release receipt.""" + + emitted: int + + +def events_from_wire(value: Any) -> tuple[InputEvent, ...]: + """Validate the entire batch before any backend emission.""" + if not isinstance(value, list) or not 1 <= len(value) <= MAX_EVENTS: + raise EiProtocolError("EI batch exceeds its bound") + result = [] + for item in value: + if not isinstance(item, dict) or set(item) != {"kind", "arguments"}: + raise EiProtocolError("invalid EI event fields") + if not isinstance(item["arguments"], list): + raise EiProtocolError("invalid EI event arguments") + result.append(InputEvent(item["kind"], tuple(item["arguments"]))) + return tuple(result) + + +def batch_wire(events: Sequence[InputEvent]) -> list[dict[str, Any]]: + """Validate and serialize a bounded typed batch.""" + if not 1 <= len(events) <= MAX_EVENTS or any(not isinstance(event, InputEvent) for event in events): + raise EiProtocolError("invalid EI batch") + result = [event.wire() for event in events] + events_from_wire(result) + encode(result) + return result + + +def encode(value: Any) -> bytes: + """Encode one bounded JSON line; never truncate a protocol message.""" + packet = json.dumps(value, ensure_ascii=True, allow_nan=False, separators=(",", ":")).encode() + b"\n" + if len(packet) > MAX_PACKET: + raise EiProtocolError("EI packet exceeds its bound") + return packet + + +def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + """Reject ambiguous duplicate fields in an incoming object.""" + result: dict[str, Any] = {} + for name, value in pairs: + if name in result: + raise EiProtocolError("duplicate EI field") + result[name] = value + return result diff --git a/je_auto_control/linux_wayland/ei_transport.py b/je_auto_control/linux_wayland/ei_transport.py new file mode 100644 index 000000000..40b1a44f5 --- /dev/null +++ b/je_auto_control/linux_wayland/ei_transport.py @@ -0,0 +1,255 @@ +"""Cancellable EI domain RPC over the existing owned helper channel.""" +from __future__ import annotations + +import sys +import threading +import time +from typing import Any, Callable, Sequence + +from je_auto_control.linux_wayland._input_state import InputFailure +from je_auto_control.linux_wayland.ei_protocol import ( + EiProtocolError, InputAck, InputEvent, batch_wire, encode, timeout_value, +) +from je_auto_control.utils.agent_runtime.owned_channel_factory import HelperChannel +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption +from je_auto_control.utils.exception.exceptions import AutoControlException + + +def _channel() -> HelperChannel: + from je_auto_control.utils.agent_runtime.owned_channel_factory import owned_channel + return owned_channel([sys.executable, "-u", "-m", "je_auto_control.linux_wayland.ei_worker"], display=True) + + +def _refuse(status: InputFailure) -> None: + from je_auto_control.linux_wayland.libei import LibeiUnavailable + error = LibeiUnavailable(status.message, state=status.state, fallback_allowed=status.fallback_allowed) + error.status = status + raise error + + +class EiWorkerClient: + """Own one EI helper; failed or uncertain operations never reconnect or replay.""" + + def __init__(self, *, factory: Callable[[], HelperChannel] = _channel) -> None: + self._factory = factory + self._channel: HelperChannel | None = None + self._starting = False + self._request_lock = threading.Lock() + self._lifecycle_lock = threading.Lock() + self._closed = threading.Event() + self._sequence = 0 + self._available: bool | None = None + self._connected = False + self._state = "unverified" + self._failure: InputFailure | None = None + self.cleanup_confirmed = False + + @property + def retired(self) -> bool: + """Report owned-channel retirement only; this is not native input-release evidence.""" + channel = self._channel + return self._closed.is_set() and not self._starting and (channel is None or channel.retired) + + @property + def is_available(self) -> bool: + """Probe loadability in the helper, without requesting portal consent.""" + if self._available is None: + self._request("probe", {}, 5.0) + return bool(self._available) + + @property + def is_connected(self) -> bool: + """Read cached connection state without performing IPC.""" + return self._connected and not self._closed.is_set() and self._failure is None + + def observed_state(self) -> str: + """Return passive cached metadata without probing, consent or a lock wait.""" + return self._failure.state if self._failure is not None else self._state + + def _acquire(self, deadline: float) -> None: + while True: + cancellation_checkpoint() + remaining = deadline - time.monotonic() + if remaining <= 0: + raise EiProtocolError("EI request queue deadline exhausted") + if self._request_lock.acquire(timeout=min(remaining, 0.05)): + return + + def _owned(self) -> HelperChannel: + with self._lifecycle_lock: + if self._closed.is_set(): + raise EiProtocolError("EI helper has closed") + if self._channel is not None: + return self._channel + self._starting = True + try: + channel = self._factory() + with self._lifecycle_lock: + self._channel = channel + finally: + self._starting = False + if self._closed.is_set(): + channel.close() + raise EiProtocolError("EI helper closed during startup") + return channel + + def _remember_state(self, value: dict[str, Any]) -> None: + if (type(value.get("available")) is not bool or type(value.get("connected")) is not bool + or value.get("state") not in {"available", "unverified", "paused", "revoked"}): + raise EiProtocolError("invalid EI state reply") + self._available, self._connected, self._state = value["available"], value["connected"], value["state"] + + def _reply(self, reply: Any, operation: str, arguments: dict[str, Any]) -> dict[str, Any]: + encode(reply) + if (not isinstance(reply, dict) or type(reply.get("version")) is not int or reply["version"] != 1 + or type(reply.get("sequence")) is not int or reply["sequence"] != self._sequence + or type(reply.get("ok")) is not bool): + raise EiProtocolError("invalid EI reply") + if not reply["ok"]: + self._failure_reply(reply) + if set(reply) != {"version", "sequence", "ok", "value"} or not isinstance(reply["value"], dict): + raise EiProtocolError("invalid EI success reply") + value = reply["value"] + return self._value(value, operation, arguments) + + def _value(self, value: dict[str, Any], operation: str, arguments: dict[str, Any]) -> dict[str, Any]: + if operation == "disconnect": + if set(value) != {"cleaned"} or type(value["cleaned"]) is not bool: + raise EiProtocolError("invalid EI cleanup reply") + else: + fields = {"available", "connected", "state"} | ({"emitted"} if operation == "send" else set()) + if set(value) != fields: + raise EiProtocolError("invalid EI state fields") + if operation == "send": + if type(value["emitted"]) is not int or value["emitted"] != len(arguments["events"]): + raise EiProtocolError("incomplete EI acknowledgement") + self._remember_state(value) + return value + + def _failure_reply(self, reply: dict[str, Any]) -> None: + if set(reply) != {"version", "sequence", "ok", "failure"}: + raise EiProtocolError("invalid EI failure reply") + failure = reply["failure"] + if not isinstance(failure, dict) or set(failure) != {"state", "backend", "fallback_allowed"}: + raise EiProtocolError("invalid EI failure fields") + self._failure = InputFailure(message="EI helper refused the operation", **failure) + _refuse(self._failure) + + def _exchange(self, operation: str, arguments: dict[str, Any], deadline: float, + check: Callable[[], None] = cancellation_checkpoint) -> dict[str, Any]: + channel = self._owned() + self._sequence += 1 + payload = {"version": 1, "sequence": self._sequence, "arguments": arguments} + encode({"id": "0" * 32, "operation": operation, "payload": payload}) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise EiProtocolError("EI request deadline exhausted") + reply = channel.request(operation, payload, timeout=remaining, check=check) + check() + if self._closed.is_set(): + raise EiProtocolError("EI reply arrived after close") + return self._reply(reply, operation, arguments) + + def _retire_failed(self, error: BaseException) -> None: + if self._failure is None: + self._failure = InputFailure("failed", "libei", "EI helper outcome is uncertain", fallback_allowed=False) + self._closed.set() + channel = self._channel + if channel is not None: + try: + channel.close() + except (AutoControlException, OSError, RuntimeError, ValueError): + pass + raise_caused_run_interruption(error) + if not isinstance(error, Exception): + raise error + _refuse(self._failure) + + def _request(self, operation: str, arguments: dict[str, Any], timeout_s: float) -> dict[str, Any]: + deadline = time.monotonic() + timeout_value(timeout_s) + if self._failure is not None: + _refuse(self._failure) + self._acquire(deadline) + try: + try: + return self._exchange(operation, arguments, deadline) + except BaseException as error: # reason: cancellation must retire this owned helper before propagating + self._retire_failed(error) + raise + finally: + self._request_lock.release() + + def connect(self, *, timeout: float = 3.0, socket_path: bytes | None = None) -> None: + """Connect this existing worker once; no parent process loads native EI.""" + timeout_value(timeout) + if socket_path is not None and (not isinstance(socket_path, bytes) or len(socket_path) > 1024 + or b"\0" in socket_path): + raise EiProtocolError("invalid EI socket path") + if not self.is_connected: + self._request("connect", {"timeout": timeout, "socket_path": None if socket_path is None + else socket_path.hex()}, timeout) + + def send(self, events: Sequence[InputEvent], *, timeout_s: float = 5.0) -> InputAck: + """Emit one bounded batch with no retry after any uncertain result.""" + batch = batch_wire(events) + result = self._request("send", {"events": batch}, timeout_s) + return InputAck(result["emitted"]) + + def press_key(self, keycode: int) -> None: + """Emit a key press through the owned helper.""" + self.send((InputEvent("press_key", (keycode,)),)) + + def release_key(self, keycode: int) -> None: + """Emit a key release through the owned helper.""" + self.send((InputEvent("release_key", (keycode,)),)) + + def press_button(self, button_code: int) -> None: + """Emit a button press through the owned helper.""" + self.send((InputEvent("press_button", (button_code,)),)) + + def release_button(self, button_code: int) -> None: + """Emit a button release through the owned helper.""" + self.send((InputEvent("release_button", (button_code,)),)) + + def click_button(self, button_code: int) -> None: + """Emit press/release together as a validated batch.""" + self.send((InputEvent("press_button", (button_code,)), InputEvent("release_button", (button_code,)))) + + def set_position(self, x: int, y: int) -> None: + """Emit an absolute position through the owned helper.""" + self.send((InputEvent("set_position", (x, y)),)) + + def scroll(self, dx: int, dy: int) -> None: + """Emit discrete wheel detents through the owned helper.""" + self.send((InputEvent("scroll", (dx, dy)),)) + + def disconnect(self) -> None: + """Attempt graceful release when idle, then retire without waiting for a pending RPC.""" + channel = self._channel + if channel is None: + with self._lifecycle_lock: + self._closed.set() + channel = self._channel + if channel is None: + if self._starting: + raise EiProtocolError("EI helper startup retirement is unconfirmed") + return + acquired = self._request_lock.acquire(blocking=False) + try: + if acquired and not self._closed.is_set(): + try: + result = self._exchange("disconnect", {}, time.monotonic() + 1.0, lambda: None) + self.cleanup_confirmed = result["cleaned"] + except (AutoControlException, OSError, RuntimeError, ValueError): + self.cleanup_confirmed = False + self._closed.set() + self._connected = False + channel.close() + if not channel.retired: + raise EiProtocolError("EI helper retirement is unconfirmed") + finally: + if acquired: + self._request_lock.release() + + close = disconnect diff --git a/je_auto_control/linux_wayland/ei_worker.py b/je_auto_control/linux_wayland/ei_worker.py new file mode 100644 index 000000000..02fa07627 --- /dev/null +++ b/je_auto_control/linux_wayland/ei_worker.py @@ -0,0 +1,161 @@ +"""Fixed owned-helper entry point; only this process loads and drives native EI.""" +from __future__ import annotations + +import json +import sys +from typing import Any, BinaryIO, Callable + +from je_auto_control.linux_wayland.ei_protocol import ( + EiProtocolError, InputBackend, InputEvent, MAX_PACKET, encode, events_from_wire, timeout_value, unique_object, +) +from je_auto_control.linux_wayland._input_state import InputFailure +from je_auto_control.utils.exception.exceptions import AutoControlException + + +def _native_backend() -> InputBackend: + from je_auto_control.linux_wayland.libei import LibeiBackend + return LibeiBackend() + + +class EiWorker: + """Own one native backend and its pressed-input ledger until process retirement.""" + + def __init__(self, factory: Callable[[], InputBackend] = _native_backend) -> None: + self._factory = factory + self._backend: InputBackend | None = None + self._sequence = 0 + self._failed = False + self._pressed: set[tuple[str, int]] = set() + + def _get_backend(self) -> InputBackend: + if self._backend is None: + self._backend = self._factory() + return self._backend + + def _state(self) -> dict[str, Any]: + backend = self._get_backend() + return {"available": backend.is_available, "connected": backend.is_connected, + "state": backend.observed_state()} + + def _emit(self, event: InputEvent) -> None: + backend = self._get_backend() + group = "key" if event.kind.endswith("key") else "button" + if event.kind.startswith("press_"): + self._pressed.add((group, event.arguments[0])) + getattr(backend, event.kind)(*event.arguments) + if event.kind.startswith("release_"): + self._pressed.discard((group, event.arguments[0])) + + def close(self) -> bool: + """Attempt every owned release and teardown; report only local cleanup success.""" + backend = self._backend + if backend is None: + return True + cleaned = True + for kind, code in tuple(self._pressed): + try: + getattr(backend, "release_" + kind)(code) + self._pressed.discard((kind, code)) + except (AutoControlException, OSError, RuntimeError, ValueError): + cleaned = False + try: + backend.disconnect() + except (AutoControlException, OSError, RuntimeError, ValueError): + cleaned = False + return cleaned + + def _execute(self, operation: str, arguments: dict[str, Any]) -> dict[str, Any]: + if operation in {"probe", "state", "disconnect"}: + if arguments: + raise EiProtocolError("unexpected EI arguments") + if operation == "disconnect": + return {"cleaned": self.close()} + return self._state() + if operation == "connect": + self._connect(arguments) + return self._state() + if operation != "send" or set(arguments) != {"events"}: + raise EiProtocolError("unknown EI operation") + events = events_from_wire(arguments["events"]) + for event in events: + self._emit(event) + return {"emitted": len(events), **self._state()} + + def _connect(self, arguments: dict[str, Any]) -> None: + if set(arguments) != {"timeout", "socket_path"}: + raise EiProtocolError("invalid EI connect fields") + timeout = timeout_value(arguments["timeout"]) + path = arguments["socket_path"] + if path is not None and (not isinstance(path, str) or len(path) > 2048 or "\0" in path): + raise EiProtocolError("invalid EI socket path") + socket_path = None if path is None else bytes.fromhex(path) + if socket_path is not None and (not socket_path or b"\0" in socket_path): + raise EiProtocolError("invalid EI socket path") + self._get_backend().connect(timeout=timeout, socket_path=socket_path) + + def _envelope(self, message: Any) -> tuple[str, str, dict[str, Any]]: + """Validate correlation and sequence before touching native state.""" + if not isinstance(message, dict) or set(message) != {"id", "operation", "payload"}: + raise EiProtocolError("invalid EI envelope") + request_id, operation, payload = message["id"], message["operation"], message["payload"] + if not isinstance(request_id, str) or not request_id or len(request_id) > 128: + raise EiProtocolError("invalid EI request ID") + self._payload(payload, operation) + return request_id, operation, payload["arguments"] + + def _payload(self, payload: Any, operation: Any) -> None: + if (not isinstance(payload, dict) or set(payload) != {"version", "sequence", "arguments"} + or type(payload["version"]) is not int or payload["version"] != 1 + or type(payload["sequence"]) is not int or payload["sequence"] != self._sequence + 1 + or not isinstance(payload["arguments"], dict) or not isinstance(operation, str)): + raise EiProtocolError("invalid EI request sequence") + + def handle(self, message: Any) -> tuple[dict[str, Any], bool]: + """Preserve expected authority failures as protocol data.""" + request_id, operation, arguments = self._envelope(message) + self._sequence += 1 + result: dict[str, Any] = {"version": 1, "sequence": self._sequence} + try: + if self._failed and operation != "disconnect": + raise EiProtocolError("EI session has failed") + value = self._execute(operation, arguments) + result.update(ok=True, value=value) + except (AutoControlException, OSError, RuntimeError, ValueError, AttributeError) as error: + self._failed = True + status = getattr(error, "status", None) + if not isinstance(status, InputFailure) or operation == "send": + status = InputFailure("failed", "libei", "EI helper operation failed", fallback_allowed=False) + result.update(ok=False, failure={"state": status.state, "backend": status.backend, + "fallback_allowed": status.fallback_allowed}) + return {"id": request_id, "result": result}, operation == "disconnect" + + def run(self, source: BinaryIO, sink: BinaryIO) -> None: + """Read bounded inherited-pipe frames; EOF and malformed input retire this worker.""" + try: + while line := source.readline(MAX_PACKET + 1): + if len(line) > MAX_PACKET or not line.endswith(b"\n"): + return + try: + message = json.loads(line, object_pairs_hook=unique_object) + reply, stop = self.handle(message) + except (ValueError, RecursionError): + return + sink.write(encode(reply)) + sink.flush() + if stop: + return + finally: + self.close() + + +def main() -> None: + """Launch the fixed worker with parent-death retirement, never a caller-selected factory.""" + if len(sys.argv) != 1: + raise SystemExit(2) + from je_auto_control.utils.agent_runtime.parent_watch import start_parent_watch + start_parent_watch() + EiWorker().run(sys.stdin.buffer, sys.stdout.buffer) + + +if __name__ == "__main__": + main() diff --git a/je_auto_control/linux_wayland/libei.py b/je_auto_control/linux_wayland/libei.py index 4b807370c..e2ffa2223 100644 --- a/je_auto_control/linux_wayland/libei.py +++ b/je_auto_control/linux_wayland/libei.py @@ -1,5 +1,9 @@ """ctypes binding for libei — Wayland's input-emulation protocol. +``LibeiBackend`` is the explicitly in-process low-level API, including injected +symbols. NORMAL's default selector uses an owned helper through ``ei_default``; +only that default path isolates native EI and portal faults from the caller. + libei is not a "call a function and a key is pressed" library. A sender has to complete a handshake before it may emit anything: @@ -652,75 +656,11 @@ def _quietly(action: Callable[[], object]) -> None: pass -_DEFAULT_BACKEND: Optional[LibeiBackend] = None -_PROBE_FAILED = False -_BLOCKED_PROBE: Optional[InputFailure] = None -_DEFAULT_LOCK = threading.Lock() - - -def connected_backend() -> Optional[LibeiBackend]: - """Return a connected backend, or None — probing at most once. - - The probe involves a portal round trip and a consent dialog, so a host - where libei cannot be used must pay for that discovery once rather than - on every keystroke. Only optional absence returns None. Authority/protocol - refusals retain inert metadata and raise until an explicit reset/retry. - """ - global _DEFAULT_BACKEND, _PROBE_FAILED, _BLOCKED_PROBE - with _DEFAULT_LOCK: - if _BLOCKED_PROBE is not None: - raise LibeiUnavailable(_BLOCKED_PROBE.message, state=_BLOCKED_PROBE.state, - fallback_allowed=_BLOCKED_PROBE.fallback_allowed) - if _DEFAULT_BACKEND is not None: - return _DEFAULT_BACKEND - if _PROBE_FAILED: - return None - backend = LibeiBackend() - if not backend.is_available: - _PROBE_FAILED = True - return None - try: - backend.connect() - except (LibeiUnavailable, OSError, ValueError, AttributeError) as error: - blocked = blocked_input(error) - _PROBE_FAILED = True - if blocked is not None: - _BLOCKED_PROBE = blocked[1] - raise blocked[0] - return None - _DEFAULT_BACKEND = backend - return _DEFAULT_BACKEND - - -def _observed_input_state() -> tuple[Optional[str], bool]: - """Inert snapshot for passive diagnostics; never construct a backend or wait on the portal-probe lock.""" - failure = _BLOCKED_PROBE - if failure is not None: - return failure.state, failure.fallback_allowed - backend = _DEFAULT_BACKEND - if backend is None: - return ('unavailable', True) if _PROBE_FAILED else (None, False) - return backend.observed_state(), False - - -def get_default_backend() -> Optional[LibeiBackend]: - """Return the cached backend if libei resolved, without connecting.""" - with _DEFAULT_LOCK: - if _DEFAULT_BACKEND is not None: - return _DEFAULT_BACKEND - backend = LibeiBackend() - return backend if backend.is_available else None - - -def reset_default_backend() -> None: - """Explicitly retire the cached sender/refusal so a later request may seek a fresh grant.""" - global _DEFAULT_BACKEND, _PROBE_FAILED, _BLOCKED_PROBE - with _DEFAULT_LOCK: - if _DEFAULT_BACKEND is not None: - _quietly(_DEFAULT_BACKEND.disconnect) - _DEFAULT_BACKEND = None - _PROBE_FAILED = False - _BLOCKED_PROBE = None +# Compatibility imports preserve the public low-level module entry points. +from je_auto_control.linux_wayland.ei_default import ( # noqa: E402 # reason: compatibility cache imports follow native definitions to avoid a cycle + connected_backend, get_default_backend, reset_default_backend, + _observed_input_state as _observed_input_state, +) __all__ = [ diff --git a/test/fixtures/ei_worker_fixture.py b/test/fixtures/ei_worker_fixture.py new file mode 100644 index 000000000..152180743 --- /dev/null +++ b/test/fixtures/ei_worker_fixture.py @@ -0,0 +1,40 @@ +"""Synthetic owned EI child; no native libraries or desktop operations are imported.""" +import sys +import os +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from je_auto_control.linux_wayland.ei_worker import EiWorker # noqa: E402 # reason: load the tested worktree after inserting its root +from je_auto_control.utils.agent_runtime.parent_watch import start_parent_watch # noqa: E402 # reason: load the tested worktree after inserting its root + + +class SyntheticBackend: + """Only process protocol and ownership are exercised by this fixture.""" + + is_available = True + is_connected = False + + def connect(self, **_kwargs): + self.is_connected = True + + def disconnect(self): + self.is_connected = False + + def observed_state(self): + return "available" if self.is_connected else "unverified" + + def press_key(self, code): + if code == 999: + os._exit(17) # synthetic lost reply after accepting the operation + if code == 998: + time.sleep(30) # synthetic stalled native call, retired by the parent + + def __getattr__(self, _name): + return lambda *_args: None + + +if __name__ == "__main__": + start_parent_watch() + EiWorker(SyntheticBackend).run(sys.stdin.buffer, sys.stdout.buffer) diff --git a/test/unit_test/headless/test_wayland_capability_states.py b/test/unit_test/headless/test_wayland_capability_states.py index 41cc24343..d62a11667 100644 --- a/test/unit_test/headless/test_wayland_capability_states.py +++ b/test/unit_test/headless/test_wayland_capability_states.py @@ -1,4 +1,6 @@ """Passive capability snapshots separate prerequisites, observed authority and XWayland scope.""" +from je_auto_control.linux_wayland import ei_default + import importlib import json import sys @@ -26,8 +28,8 @@ def context(api, *, env=None, tools=(), **kwargs): def test_cancel_does_not_fallback_silently(api, monkeypatch): - monkeypatch.setattr(libei, '_BLOCKED_PROBE', InputFailure('needs_permission', 'portal', 'private detail')) - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', None) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', InputFailure('needs_permission', 'portal', 'private detail')) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', None) monkeypatch.setattr(api.sys, 'platform', 'linux') monkeypatch.setitem(api.os.environ, 'XDG_SESSION_TYPE', 'wayland') monkeypatch.setattr(api.shutil, 'which', lambda _name: '/controlled/executable') @@ -42,8 +44,8 @@ def test_revoked_session_cannot_send(api, monkeypatch): writes = [] backend = libei.LibeiBackend(symbols=SimpleNamespace(ei_device_keyboard_key=lambda *_args: writes.append(True))) backend._ei, backend._revoked = 1, True - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) monkeypatch.setattr(api.sys, 'platform', 'linux') monkeypatch.setitem(api.os.environ, 'XDG_SESSION_TYPE', 'wayland') with pytest.raises(libei.LibeiUnavailable): @@ -146,9 +148,9 @@ def test_context_rejects_mismatched_observation_and_status_shape(api): def test_current_context_does_not_load_native_libraries_connect_or_execute_tools(api, monkeypatch): def forbidden(*_args, **_kwargs): pytest.fail('passive probing attempted a native library/session/tool operation') - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', None) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) - monkeypatch.setattr(libei, '_PROBE_FAILED', False) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', None) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_PROBE_FAILED', False) monkeypatch.setattr(libei, 'bind', forbidden) monkeypatch.setattr(libei, 'get_default_backend', forbidden) monkeypatch.setattr(libei, 'connected_backend', forbidden) @@ -164,8 +166,8 @@ def test_existing_sender_busy_on_another_thread_is_observed_without_waiting(api, backend = libei.LibeiBackend(symbols=SimpleNamespace()) attempts = [] backend._lock = SimpleNamespace(acquire=lambda *, blocking: attempts.append(blocking) or False) - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) monkeypatch.setattr(api.sys, 'platform', 'linux') monkeypatch.setitem(api.os.environ, 'XDG_SESSION_TYPE', 'wayland') snapshot = api.probe_capabilities(api.BackendContext.current()) @@ -189,8 +191,8 @@ def forbidden(*_args): backend._devices = {capability: 8 for capability in libei._WANTED_CAPS} backend._emulating = {8: not paused} monkeypatch.setattr(backend, '_pump', forbidden) - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) monkeypatch.setattr(api.sys, 'platform', 'linux') monkeypatch.setitem(api.os.environ, 'XDG_SESSION_TYPE', 'wayland') snapshot = api.probe_capabilities(api.BackendContext.current()) @@ -210,8 +212,8 @@ def test_cached_native_readiness_covers_all_requested_event_families(api, monkey backend._emulating[backend._devices[libei.EI_DEVICE_CAP_BUTTON]] = False else: del backend._devices[libei.EI_DEVICE_CAP_POINTER_ABSOLUTE] - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) monkeypatch.setitem(api.os.environ, 'XDG_SESSION_TYPE', 'wayland') snapshot = api.probe_capabilities(api.BackendContext.current()) assert snapshot.input.state == expected @@ -221,9 +223,9 @@ def test_cached_native_readiness_covers_all_requested_event_families(api, monkey @pytest.mark.parametrize('choice,backend,state', [('auto', 'ydotool', 'unverified'), ('libei', 'libei', 'needs_dependency')]) def test_only_observed_optional_absence_allows_automatic_cli_diagnostics(api, monkeypatch, choice, backend, state): - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', None) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) - monkeypatch.setattr(libei, '_PROBE_FAILED', True) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', None) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_PROBE_FAILED', True) monkeypatch.setattr(api.sys, 'platform', 'linux') monkeypatch.setitem(api.os.environ, 'XDG_SESSION_TYPE', 'wayland') monkeypatch.setitem(api.os.environ, 'JE_AUTOCONTROL_WAYLAND_INPUT_BACKEND', choice) diff --git a/test/unit_test/headless/test_wayland_input_authority.py b/test/unit_test/headless/test_wayland_input_authority.py index 679f1bd2e..deaf65962 100644 --- a/test/unit_test/headless/test_wayland_input_authority.py +++ b/test/unit_test/headless/test_wayland_input_authority.py @@ -1,4 +1,6 @@ """Real native state-machine refusals must not silently switch to an independently privileged CLI.""" +from je_auto_control.linux_wayland import ei_default + from unittest.mock import MagicMock import asyncio from concurrent.futures import CancelledError @@ -43,7 +45,7 @@ def test_cancelled_portal_stops_every_layer_and_remains_blocked_without_another_ portal = FakeOeffis(events=[event], error=b'operator refused the request') backend = libei.LibeiBackend(symbols=native, portal_connect=lambda: oeffis.connect_eis_fd(symbols=portal)) - monkeypatch.setattr(libei, 'LibeiBackend', lambda: backend) + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: backend) monkeypatch.setenv('JE_AUTOCONTROL_WAYLAND_INPUT_BACKEND', forced) commands = capture_cli(monkeypatch) execute = (lambda: keyboard.press_key(28)) if operation == 'key' else (lambda: mouse.set_position(20, 30)) @@ -60,7 +62,7 @@ def test_cancelled_portal_stops_every_layer_and_remains_blocked_without_another_ @pytest.mark.parametrize('operation', ['key', 'pointer', 'chord']) def test_revoked_or_paused_native_devices_cannot_send_via_the_cli(monkeypatch, event, operation): backend, native = _connected(session=MagicMock()) - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) device = POINTER_DEVICE if operation == 'pointer' else KEYBOARD_DEVICE native.pending = [(event, device)] commands = capture_cli(monkeypatch) @@ -122,7 +124,7 @@ def test_an_explicit_cli_choice_can_follow_a_portal_refusal_without_reopening_it portal = FakeOeffis(events=[oeffis.OEFFIS_EVENT_CLOSED]) backend = libei.LibeiBackend(symbols=FakeLibei(), portal_connect=lambda: oeffis.connect_eis_fd(symbols=portal)) - monkeypatch.setattr(libei, 'LibeiBackend', lambda: backend) + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: backend) commands = capture_cli(monkeypatch) with pytest.raises(libei.LibeiUnavailable) as caught: keyboard.press_key(28) @@ -138,7 +140,7 @@ def test_explicit_reset_allows_a_fresh_portal_grant_and_native_input(monkeypatch portal = FakeOeffis(events=[oeffis.OEFFIS_EVENT_CLOSED]) backend = libei.LibeiBackend(symbols=FakeLibei(), portal_connect=lambda: oeffis.connect_eis_fd(symbols=portal)) - monkeypatch.setattr(libei, 'LibeiBackend', lambda: backend) + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: backend) commands = capture_cli(monkeypatch) with pytest.raises(libei.LibeiUnavailable): keyboard.press_key(28) @@ -153,7 +155,7 @@ def test_explicit_reset_allows_a_fresh_portal_grant_and_native_input(monkeypatch @pytest.mark.parametrize('kind', ['pause', 'remove']) def test_native_device_resume_or_replacement_can_restore_the_same_live_session(monkeypatch, kind): backend, native = _connected() - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) commands = capture_cli(monkeypatch) event = libei.EI_EVENT_DEVICE_PAUSED if kind == 'pause' else libei.EI_EVENT_DEVICE_REMOVED native.pending = [(event, KEYBOARD_DEVICE)] @@ -193,7 +195,7 @@ def test_portal_timeout_remains_a_permission_refusal_not_a_cli_request(monkeypat portal = FakeOeffis() backend = libei.LibeiBackend(symbols=FakeLibei(), portal_connect=lambda: oeffis.connect_eis_fd(symbols=portal, timeout=0)) - monkeypatch.setattr(libei, 'LibeiBackend', lambda: backend) + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: backend) commands = capture_cli(monkeypatch) with pytest.raises(libei.LibeiUnavailable) as caught: keyboard.press_key(28) @@ -207,7 +209,7 @@ def test_incomplete_native_handshake_stops_and_closes_its_portal_session(monkeyp backend = libei.LibeiBackend(symbols=FakeLibei(events=[]), portal_connect=lambda: (7, session)) connect = backend.connect monkeypatch.setattr(backend, 'connect', lambda: connect(timeout=0)) - monkeypatch.setattr(libei, 'LibeiBackend', lambda: backend) + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: backend) commands = capture_cli(monkeypatch) for _ in range(2): with pytest.raises(libei.LibeiUnavailable) as caught: @@ -231,7 +233,7 @@ def test_native_failure_after_a_portal_grant_cannot_select_cli(monkeypatch, phas else: native.ei_dispatch = MagicMock(side_effect=(OSError('controlled dispatch failure') if failure == 'exception' else libei.LibeiUnavailable('controlled protocol failure'))) - monkeypatch.setattr(libei, 'LibeiBackend', lambda: backend) + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: backend) commands = capture_cli(monkeypatch) for _ in range(2): with pytest.raises(libei.LibeiUnavailable) as caught: diff --git a/test/unit_test/headless/test_wayland_libei.py b/test/unit_test/headless/test_wayland_libei.py index 1f802c8d7..a109eb202 100644 --- a/test/unit_test/headless/test_wayland_libei.py +++ b/test/unit_test/headless/test_wayland_libei.py @@ -12,6 +12,8 @@ that does not reach a live device raises ``LibeiUnavailable``, which the keyboard and mouse modules turn into "use the ydotool CLI". """ +from je_auto_control.linux_wayland import ei_default + from unittest.mock import MagicMock, patch import pytest @@ -736,7 +738,7 @@ def connect(self, **_kwargs): raise LibeiUnavailable("no portal here") try: - with patch.object(libei_mod, "LibeiBackend", _Failing): + with patch.object(ei_default, "_new_default_backend", _Failing): assert libei_mod.connected_backend() is None assert libei_mod.connected_backend() is None assert libei_mod.connected_backend() is None diff --git a/test/unit_test/headless/test_wayland_region_authority.py b/test/unit_test/headless/test_wayland_region_authority.py index 9c86481d0..7b0d46a3a 100644 --- a/test/unit_test/headless/test_wayland_region_authority.py +++ b/test/unit_test/headless/test_wayland_region_authority.py @@ -1,4 +1,6 @@ """A refused native coordinate cannot change input origin or allow a subsequent click to escape its region.""" +from je_auto_control.linux_wayland import ei_default + import asyncio from concurrent.futures import CancelledError from types import SimpleNamespace @@ -20,9 +22,9 @@ def sender(monkeypatch): native = FakeLibei(regions={POINTER_DEVICE: [(0, 0, 100, 100)]}) backend, _ = _connected(native) native.calls.clear() - monkeypatch.setattr(libei, '_DEFAULT_BACKEND', backend) - monkeypatch.setattr(libei, '_BLOCKED_PROBE', None) - monkeypatch.setattr(libei, '_PROBE_FAILED', False) + monkeypatch.setattr(ei_default, '_DEFAULT_BACKEND', backend) + monkeypatch.setattr(ei_default, '_BLOCKED_PROBE', None) + monkeypatch.setattr(ei_default, '_PROBE_FAILED', False) monkeypatch.setattr(libei, 'layout_origin', lambda: (0, 0)) monkeypatch.setattr(mouse, 'layout_origin', lambda: (0, 0)) commands = [] diff --git a/test/unit_test/headless/test_wayland_worker_cleanup.py b/test/unit_test/headless/test_wayland_worker_cleanup.py new file mode 100644 index 000000000..f66a6a4db --- /dev/null +++ b/test/unit_test/headless/test_wayland_worker_cleanup.py @@ -0,0 +1,448 @@ +"""Owned EI protocol and process retirement with synthetic backends only.""" +import io +from concurrent.futures import CancelledError +import json +from pathlib import Path +import sys +import threading +import time + +import pytest + +from je_auto_control.linux_wayland.ei_protocol import EiProtocolError, InputEvent, MAX_EVENTS, MAX_PACKET, encode +from je_auto_control.linux_wayland.ei_transport import EiWorkerClient +from je_auto_control.linux_wayland.ei_worker import EiWorker +from je_auto_control.linux_wayland.libei import LibeiUnavailable +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope + + +@pytest.fixture +def default_cache(monkeypatch): + from je_auto_control.linux_wayland import ei_default + ei_default.reset_default_backend() + proxy, channel = client() + monkeypatch.setattr(ei_default, '_new_default_backend', lambda: proxy) + yield ei_default, proxy, channel + channel.fail_close = False + ei_default.reset_default_backend() + + +def test_default_probe_has_no_consent_and_connect_reuses_owner(default_cache): + cache, proxy, channel = default_cache + assert cache.get_default_backend() is proxy + assert channel.calls == ['probe'] + assert channel.backend.calls == [] + assert cache.connected_backend() is proxy + assert cache.connected_backend() is proxy + assert channel.calls == ['probe', 'connect'] + + +def test_default_refusal_is_cached_without_new_worker_or_fallback(default_cache): + cache, proxy, channel = default_cache + channel.backend.failure = LibeiUnavailable('refused', state='needs_permission') + with pytest.raises(LibeiUnavailable): + cache.connected_backend() + calls = list(channel.calls) + with pytest.raises(LibeiUnavailable) as caught: + cache.get_default_backend() + assert caught.value.state == 'needs_permission' + assert channel.calls == calls + assert proxy.retired + + +def test_default_failed_close_retains_owner_for_explicit_retry(default_cache): + cache, proxy, channel = default_cache + cache.connected_backend() + channel.fail_close = True + with pytest.raises(EiProtocolError): + cache.reset_default_backend() + assert cache._DEFAULT_BACKEND is proxy + assert not proxy.retired + channel.fail_close = False + cache.reset_default_backend() + assert proxy.retired and cache._DEFAULT_BACKEND is None + + +def test_default_optional_absence_is_probed_once(default_cache): + cache, proxy, channel = default_cache + channel.backend.is_available = False + assert cache.get_default_backend() is None + assert cache.get_default_backend() is None + assert channel.calls == ['probe', 'disconnect'] + assert proxy.retired + + +class Backend: + is_available = True + is_connected = False + + def __init__(self): + self.calls = [] + self.failure = None + + def observed_state(self): + return "available" if self.is_connected else "unverified" + + def connect(self, **kwargs): + self.calls.append(("connect", kwargs)) + if self.failure: + raise self.failure + self.is_connected = True + + def disconnect(self): + self.calls.append(("disconnect",)) + self.is_connected = False + + def __getattr__(self, name): + def emit(*values): + self.calls.append((name, *values)) + if self.failure: + raise self.failure + return emit + + +class Channel: + retired = False + + def __init__(self, backend=None): + self.backend = backend or Backend() + self.worker = EiWorker(lambda: self.backend) + self.calls = [] + self.fail_close = False + self.change_reply = lambda reply: reply + + def request(self, operation, payload, *, timeout, check): + check() + self.calls.append(operation) + reply, _ = self.worker.handle({"id": "request", "operation": operation, "payload": payload}) + return self.change_reply(reply["result"]) + + def close(self): + if not self.fail_close: + self.retired = True + + +def client(backend=None): + channel = Channel(backend) + return EiWorkerClient(factory=lambda: channel), channel + + +def envelope(operation, arguments, sequence=1): + return {"id": "request", "operation": operation, + "payload": {"version": 1, "sequence": sequence, "arguments": arguments}} + + +def test_probe_is_passive_and_graceful_close_releases_owned_keys_and_buttons(): + proxy, channel = client() + assert proxy.is_available and not proxy.is_connected + assert channel.backend.calls == [] + proxy.connect() + proxy.press_key(28) + proxy.press_button(272) + assert proxy.observed_state() == "available" + proxy.disconnect() + assert ("release_key", 28) in channel.backend.calls + assert ("release_button", 272) in channel.backend.calls + assert proxy.retired and proxy.cleanup_confirmed + with pytest.raises(LibeiUnavailable): + proxy.send((InputEvent("press_key", (28,)),)) + + +@pytest.mark.parametrize("kind,args", [("shell", (1,)), ("press_key", (True,)), ("press_key", (-1,)), + ("scroll", (1,)), ("set_position", (1.5, 2))]) +def test_invalid_event_rejected_before_native_or_worker_creation(kind, args): + with pytest.raises(EiProtocolError): + InputEvent(kind, args) + + +def test_entire_batch_is_validated_before_emission(): + backend = Backend() + worker = EiWorker(lambda: backend) + events = [InputEvent("press_key", (28,)).wire(), {"kind": "press_key", "arguments": [True]}] + reply, _ = worker.handle(envelope("send", {"events": events})) + assert not reply["result"]["ok"] and backend.calls == [] + proxy, channel = client() + with pytest.raises(EiProtocolError): + proxy.send((InputEvent("press_key", (28,)),) * (MAX_EVENTS + 1)) + assert channel.calls == [] + + +@pytest.mark.parametrize("state,fallback", [("unavailable", True), ("needs_permission", False), + ("revoked", False), ("paused", False)]) +def test_connect_preserves_authority_failure_and_never_retries(state, fallback): + backend = Backend() + backend.failure = LibeiUnavailable("private native message", state=state) + proxy, channel = client(backend) + for _ in range(2): + with pytest.raises(LibeiUnavailable) as caught: + proxy.connect() + assert caught.value.status.fallback_allowed is fallback + assert caught.value.state == state + assert "private" not in str(caught.value) + assert channel.calls == ["connect"] and proxy.retired + + +def test_failed_send_is_uncertain_and_cannot_enable_optional_fallback(): + proxy, channel = client() + proxy.connect() + channel.backend.failure = LibeiUnavailable("unknown emission") + with pytest.raises(LibeiUnavailable) as caught: + proxy.press_key(28) + assert not caught.value.status.fallback_allowed + with pytest.raises(LibeiUnavailable): + proxy.press_key(28) + assert channel.calls == ["connect", "send"] + + +@pytest.mark.parametrize("change", [ + lambda reply: {**reply, "sequence": 0}, + lambda reply: {**reply, "version": True}, + lambda reply: {**reply, "foreign": 1}, +]) +def test_malformed_reply_retires_and_latches_no_replay(change): + proxy, channel = client() + channel.change_reply = change + with pytest.raises(LibeiUnavailable): + proxy.connect() + with pytest.raises(LibeiUnavailable): + proxy.connect() + assert channel.calls == ["connect"] and proxy.retired + + +def test_partial_acknowledgement_is_not_success(): + proxy, channel = client() + channel.change_reply = lambda reply: {**reply, "value": {**reply["value"], "emitted": 0}} + with pytest.raises(LibeiUnavailable): + proxy.send((InputEvent("press_key", (28,)),)) + assert proxy.retired and not proxy.cleanup_confirmed + + +@pytest.mark.parametrize('emitted', [0, True, '1']) +def test_bad_ack_retires_before_a_queued_send_can_emit(monkeypatch, emitted): + proxy, channel = client() + retiring, release_retirement, second_queued = threading.Event(), threading.Event(), threading.Event() + errors = [] + admission = [] + original_retire, original_acquire = proxy._retire_failed, proxy._acquire + + def retire(error): + retiring.set() + assert release_retirement.wait(2) + original_retire(error) + + def acquire(deadline): + if retiring.is_set(): + available = proxy._request_lock.acquire(blocking=False) + admission.append(available) + if available: + proxy._request_lock.release() + second_queued.set() + original_acquire(deadline) + + def send(code): + try: + proxy.press_key(code) + except LibeiUnavailable as error: + errors.append(error) + + def reply(value): + if len(channel.calls) == 1: + return {**value, 'value': {**value['value'], 'emitted': emitted}} + return value + + monkeypatch.setattr(proxy, '_retire_failed', retire) + monkeypatch.setattr(proxy, '_acquire', acquire) + channel.change_reply = reply + first, second = threading.Thread(target=send, args=(28,)), threading.Thread(target=send, args=(29,)) + first.start() + try: + assert retiring.wait(2) + second.start() + assert second_queued.wait(2) + assert admission == [False] + assert ('press_key', 29) not in channel.backend.calls + finally: + release_retirement.set() + first.join(2) + if second.ident is not None: + second.join(2) + proxy.disconnect() + assert not first.is_alive() and not second.is_alive() + assert len(errors) == 2 + assert channel.calls == ['send'] and proxy.retired + + +def test_failed_close_retains_owner_for_retry(): + proxy, channel = client() + proxy.connect() + channel.fail_close = True + with pytest.raises(EiProtocolError, match="retirement"): + proxy.disconnect() + assert not proxy.retired + channel.fail_close = False + proxy.disconnect() + assert proxy.retired + + +def test_cancellation_after_native_call_retires_and_preserves_signal(): + proxy, channel = client() + token = CancellationToken("ei-test") + original = channel.request + + def cancel(*args, **kwargs): + result = original(*args, **kwargs) + token.cancel() + return result + + channel.request = cancel + with cancellation_scope(token), pytest.raises(Exception) as caught: + proxy.connect() + assert type(caught.value).__name__ == "CancelledError" + assert proxy.retired + + +def test_queue_time_is_inside_deadline_without_retiring_another_request(): + proxy, channel = client() + proxy._request_lock.acquire() + start = time.monotonic() + try: + with pytest.raises(EiProtocolError, match="queue deadline"): + proxy.send((InputEvent("press_key", (28,)),), timeout_s=0.02) + finally: + proxy._request_lock.release() + assert time.monotonic() - start < 0.5 + assert channel.calls == [] + + +def test_close_during_startup_keeps_late_handle_owned(): + entered, release = threading.Event(), threading.Event() + channel = Channel() + + def factory(): + entered.set() + assert release.wait(2) + return channel + + proxy = EiWorkerClient(factory=factory) + errors = [] + + def connect(): + try: + proxy.connect() + except LibeiUnavailable as error: + errors.append(error) + + thread = threading.Thread(target=connect) + thread.start() + try: + assert entered.wait(2) + with pytest.raises(EiProtocolError, match="startup retirement"): + proxy.close() + assert not proxy.retired + finally: + release.set() + thread.join(2) + assert not thread.is_alive() and errors and proxy.retired and channel.calls == [] + + +def test_duplicate_sequence_and_oversized_frames_do_not_emit(): + backend = Backend() + worker = EiWorker(lambda: backend) + request = envelope("send", {"events": [InputEvent("press_key", (28,)).wire()]}) + worker.handle(request) + with pytest.raises(EiProtocolError): + worker.handle(request) + assert backend.calls == [("press_key", 28)] + sink = io.BytesIO() + worker.run(io.BytesIO(b"x" * (MAX_PACKET + 1)), sink) + assert sink.getvalue() == b"" + assert ("release_key", 28) in backend.calls + + +def test_synthetic_owned_child_uses_real_ipc_and_retires_without_touching_native(): + from je_auto_control.utils.agent_runtime.native_channel import OwnedChannel + fixture = Path(__file__).resolve().parents[2] / "fixtures" / "ei_worker_fixture.py" + channels = [] + + def factory(): + channel = OwnedChannel([sys.executable, "-u", str(fixture)]) + channels.append(channel) + return channel + + left, right = EiWorkerClient(factory=factory), EiWorkerClient(factory=factory) + try: + left.connect() + right.connect() + assert left.send((InputEvent("press_key", (28,)),)).emitted == 1 + left.close() + assert left.retired and left.cleanup_confirmed + assert right.send((InputEvent("set_position", (10, 20)),)).emitted == 1 + assert not right.retired + finally: + left.close() + right.close() + assert right.retired and all(channel.retired for channel in channels) + + +def test_eof_releases_ledger_and_emits_bounded_reply(): + backend = Backend() + source = io.BytesIO(encode(envelope("send", {"events": [InputEvent("press_key", (28,)).wire()]}))) + sink = io.BytesIO() + EiWorker(lambda: backend).run(source, sink) + assert json.loads(sink.getvalue())["result"]["value"]["emitted"] == 1 + assert backend.calls[-2:] == [("release_key", 28), ("disconnect",)] + + +@pytest.mark.parametrize('code', [998, 999]) +def test_real_child_lost_or_stalled_reply_retires_without_replay(code): + from je_auto_control.utils.agent_runtime.native_channel import OwnedChannel + fixture = Path(__file__).resolve().parents[2] / 'fixtures' / 'ei_worker_fixture.py' + channels = [] + + def factory(): + channel = OwnedChannel([sys.executable, '-u', str(fixture)]) + channels.append(channel) + return channel + + proxy = EiWorkerClient(factory=factory) + try: + proxy.connect() + with pytest.raises(LibeiUnavailable) as caught: + proxy.send((InputEvent('press_key', (code,)),), timeout_s=0.15) + assert not caught.value.status.fallback_allowed + assert proxy.retired + with pytest.raises(LibeiUnavailable): + proxy.press_key(28) + assert len(channels) == 1 + finally: + proxy.disconnect() + + +def test_cleanup_attempts_every_release_even_when_one_fails(): + backend = Backend() + worker = EiWorker(lambda: backend) + worker.handle(envelope('send', {'events': [InputEvent('press_key', (28,)).wire(), + InputEvent('press_button', (272,)).wire()]})) + backend.failure = RuntimeError('release refused') + assert not worker.close() + assert ('release_key', 28) in backend.calls + assert ('release_button', 272) in backend.calls + assert ('disconnect',) in backend.calls + + +def test_cancelling_real_stalled_child_preserves_control_and_reaps(): + from je_auto_control.utils.agent_runtime.native_channel import OwnedChannel + fixture = Path(__file__).resolve().parents[2] / 'fixtures' / 'ei_worker_fixture.py' + proxy = EiWorkerClient(factory=lambda: OwnedChannel([sys.executable, '-u', str(fixture)])) + token = CancellationToken('ei-real-cancel') + timer = threading.Timer(0.15, token.cancel) + try: + proxy.connect() + timer.start() + with cancellation_scope(token), pytest.raises(CancelledError): + proxy.send((InputEvent('press_key', (998,)),), timeout_s=2) + assert proxy.retired + finally: + timer.cancel() + timer.join() + proxy.disconnect() From 3d8c320caba628264ea8332bd27091e321e18e54 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 17:01:13 +0800 Subject: [PATCH 021/161] Enroll EI helper modules in strict type checking --- docs/updates/2026-11.md | 6 ++++++ docs/updates/README.md | 1 + pyproject.toml | 4 ++++ 3 files changed, 11 insertions(+) diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index e0635531c..5a8c2595f 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -784,3 +784,9 @@ Index and query commands: [README.md](README.md). New entries go at the end. - **What:** Added bounded EI messages, owned worker/client and default cache integration. Requests share a deadline, cancellation and retained failed-close ownership. Invalid ACKs retire before another caller may emit. The direct in-process API and half-open guard remain. - **Evidence:** Implementation regression suite passed 273 cases with 6 platform skips. Independent review passed 217 and reproduced an ACK race, fixed with three deterministic concurrent regressions. Final worker suite passed 34; integrated EI tests passed 220. Scoped mypy, Ruff, Bandit and Radon passed. All native backends were fake; real child tests used a synthetic fixture. Integration document/complexity gates passed 44 cases; full three-target ordinary typing reported zero errors. Scoped Pylint error checks passed. - **Open items:** Native context/fd recovery, compositor input release, consent and pause semantics remain in Progress.md. Helper retirement is not native release evidence. + +## U-20261111-11 · 2026-11-11 · Enroll EI helpers in the strict typing gate · #done #typing + +- **What:** Added all four new EI modules to the explicit strict override. This corrects the registration gap found by the full typing-tier contract test; the debt baseline did not grow. +- **Evidence:** Strict checks passed on win32, Linux and Darwin; typing-tier and document-line gates passed 19 cases. The original 7cb7fde2 full-suite baseline completed with 17,879 passed, 160 skipped, 16 subtests and one existing complexity-gate failure; coverage was 87.66%. Those five complexity blocks have since passed the integrated package gate. This baseline is not a final-suite result for the changed tree. +- **Open items:** Final fixed-source validation remains in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index 399d63c5b..53ee7e247 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-11 | 2026-11-11 | Enroll EI helpers in the strict typing gate | #done #typing | [2026-11](2026-11.md) | | U-20261111-10 | 2026-11-11 | Isolate default EI input in an owned helper | #done #wayland | [2026-11](2026-11.md) | | U-20261111-09 | 2026-11-11 | Split MCP executor adapters along strict domain boundaries | #done #mcp | [2026-11](2026-11.md) | | U-20261111-08 | 2026-11-11 | Reconcile conditional MCP path checks with current evidence | #snapshot #mcp | [2026-11](2026-11.md) | diff --git a/pyproject.toml b/pyproject.toml index c306b5edb..dc337492c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -382,6 +382,10 @@ module = [ "je_auto_control.gui.theme", "je_auto_control.ios.apps", "je_auto_control.ios.session", + "je_auto_control.linux_wayland.ei_default", + "je_auto_control.linux_wayland.ei_protocol", + "je_auto_control.linux_wayland.ei_transport", + "je_auto_control.linux_wayland.ei_worker", "je_auto_control.linux_wayland.global_shortcuts", "je_auto_control.linux_wayland.input_events", "je_auto_control.utils.action_journal", From c39829283052e765e84245ad1d500405971bfdf4 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 17:07:48 +0800 Subject: [PATCH 022/161] Check composed WebRTC panels against real Qt contracts --- Progress.md | 5 +- architecture.md | 4 + architecture_explore.md | 17 +- docs/updates/2026-11-b.md | 12 ++ docs/updates/README.md | 5 +- .../gui/remote_desktop/advanced_group.py | 32 ++-- .../remote_desktop/webrtc_host_connection.py | 5 +- .../gui/remote_desktop/webrtc_host_media.py | 5 +- .../remote_desktop/webrtc_host_sessions.py | 9 +- .../gui/remote_desktop/webrtc_host_trust.py | 5 +- .../gui/remote_desktop/webrtc_host_ui.py | 7 +- .../gui/remote_desktop/webrtc_panel_common.py | 14 +- .../gui/remote_desktop/webrtc_panel_state.py | 156 ++++++++++++++++++ .../webrtc_viewer_address_book.py | 5 +- .../webrtc_viewer_connection.py | 5 +- .../gui/remote_desktop/webrtc_viewer_files.py | 6 +- .../gui/remote_desktop/webrtc_viewer_media.py | 5 +- .../gui/remote_desktop/webrtc_viewer_ui.py | 5 +- pyproject.toml | 1 + .../test_remote_desktop_optional_codec_ui.py | 18 +- test/verify/typing_extras_exempt.txt | 14 +- 21 files changed, 270 insertions(+), 65 deletions(-) create mode 100644 docs/updates/2026-11-b.md create mode 100644 je_auto_control/gui/remote_desktop/webrtc_panel_state.py diff --git a/Progress.md b/Progress.md index 48554248e..cf12bdf72 100644 --- a/Progress.md +++ b/Progress.md @@ -125,8 +125,7 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 系統匣路徑在 offscreen 下沒有 tray,`_on_tray_open` 是直接呼叫測的。基準(`benchmarks/gui_*.py`)CI 仍不設門檻。 - **把 Python 建的 widget 放進分頁列在結束時崩潰**:已查明觸發條件——分頁列按鈕上接了 Python callable、又有排隊中的 `deleteLater()`、而行程經 `os._exit` 離開; 先把 deferred delete 沖掉就不會。機制(Qt 在行程結束時釋放那個 slot)是推論,沒有 C 堆疊可看。`_tab_close_icon.py` 沒有改回自訂按鈕。 -- **對真實 Qt 型別的型別檢查**:`test/verify/typing_extras_exempt.txt` 從 70 個模組降到 11 個 WebRTC 面板 mixin, - 只准變少。`QImage.fromData(x, "JPEG")` 的 5 處保留 `# type: ignore[arg-type]`: +- **Qt binding 與 stub 的差異**:`QImage.fromData(x, "JPEG")` 的 5 處仍保留 `# type: ignore[arg-type]`: stub 要 bytes,實際的 binding 對 bytes 丟 `ValueError`。 - 遠端桌面的輸入改成佇列送出後,`AC_remote_send_input` 回的 `{"sent": True}` 意思是「已排入」;`SO_SNDTIMEO` 的 POSIX 包法與經 TLS socket 的行為沒在這台機器上驗過。 - 沒在 macOS/Linux 上看過新的關閉鈕、捲動與重設樣式;沒在真的多螢幕桌面試過視窗位置還原;PyBreeze 沒有對這一版跑過;各語系新增的字串(日文、簡體中文)沒有母語者看過。 @@ -532,7 +531,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與縮減中的真實相依型別豁免;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 diff --git a/architecture.md b/architecture.md index 2414e50b7..5db7fbac8 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,9 @@ # AutoControl Architecture +WebRTC host and viewer mixins share concrete typed state and slot contracts. +Initialization remains in the composed panels. STUN/TURN controls use a common +contract; the host supplies a separate optional hardware-codec owner. + Wayland default EI input uses a bounded domain protocol over the existing owned helper channel. Native allocation, portal consent, emission and teardown stay in that child. Reply validation and emission acknowledgement share the request lock; diff --git a/architecture_explore.md b/architecture_explore.md index 9288c7a5e..5fba9cc75 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,509 | -| 程式碼總行數 | 230,390 | +| Python 模組總數(含周邊子專案) | 1,510 | +| 程式碼總行數 | 230,573 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1354,7 +1354,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 369 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 144 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 192 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(17 檔) | 7,979 | 見下。 | +| remote_desktop | `remote_desktop/`(17 檔) | 8,162 | 見下。 | | presence | `presence_tab.py` | 164 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 260 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 318 | 管理多個遠端 AutoControl REST 端點。 | @@ -1372,15 +1372,16 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,35 檔/7,979 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,36 檔/8,162 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | | `folder_sync_controls.py` | 70 | Translate the existing folder toggle into owned start, reconnect handoff and explicit baseline reset. | | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | +| `webrtc_panel_state.py` | 156 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | | `webrtc_panel.py` | 417 | WebRTC 子分頁主體。 | | `webrtc_dialogs.py` | 520 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | -| `advanced_group.py` | 98 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含它寫回面板的 Protocol。 | +| `advanced_group.py` | 104 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 73 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | | `connection_screen.py` | 679 | Quick Connect —— AnyDesk 風格單畫面入口。 | | `viewer_panel.py` | 623 | 「控制另一台機器」子分頁。 | @@ -1415,7 +1416,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,176 個 `test_*.py`/11,416 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,176 個 `test_*.py`/11,417 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1506,7 +1507,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 144 | 39,971 | +| `gui/` | 145 | 40,154 | | `utils/mcp_server/` | 60 | 22,037 | | `utils/remote_desktop/` | 72 | 15,252 | | `utils/executor/` | 11 | 10,702 | @@ -1527,7 +1528,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,497** | **229,645** | +| **總計** | **1,498** | **229,828** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md new file mode 100644 index 000000000..475918717 --- /dev/null +++ b/docs/updates/2026-11-b.md @@ -0,0 +1,12 @@ +# Updates · November 2026 (continued) + +## U-20261111-12 · 2026-11-11 · Remove remaining WebRTC Qt typing exemptions · #done #typing + +- **What:** Added concrete host/viewer shared state and callable contracts, separated optional host codec controls from common STUN/TURN fields, and migrated all builder callers. The measured extras exemption list is empty on all three targets, without new Any, casts or ignores. +- **Evidence:** Implementation passed 110 focused offscreen tests and 7 final codec cases. Independent review passed 34 cases and real-Qt typing for all 36 subsystem modules. Integration passed 35 cases including strict-tier registration, plus 44 document/quality gates. Full integrated extras typing reported zero errors on all three targets. Ordinary subsystem typing passed all three targets; Ruff and Bandit passed. No native audio, capture or input ran. +- **Open items:** Existing Qt binding/stub mismatches, broader strict typing and native GUI acceptance remain in Progress.md. + +## U-20261111-13 · 2026-11-11 · Validate the integrated implementation and package artifacts · #snapshot #verification + +- **Evidence:** At 3d8c320c, all changed-test suites passed 540 cases with 2 platform skips. Sphinx HTML built with warnings as errors. Isolated builds produced wheel and sdist without modifying the shared environment; all 42 changed package files in the wheel matched source bytes, and the removed MCP bridge was absent. The first no-isolation attempt could not import the unavailable setuptools backend; the isolated build succeeded. +- **Limits:** This checkpoint predates U-20261111-12. Final fixed-source full-suite and native acceptance remain in Progress.md; no deployment or shared installation occurred. diff --git a/docs/updates/README.md b/docs/updates/README.md index 53ee7e247..8f4bb0c45 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,8 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-13 | 2026-11-11 | Validate integrated implementation and package artifacts | #snapshot #verification | [2026-11-b](2026-11-b.md) | +| U-20261111-12 | 2026-11-11 | Remove remaining WebRTC Qt typing exemptions | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261111-11 | 2026-11-11 | Enroll EI helpers in the strict typing gate | #done #typing | [2026-11](2026-11.md) | | U-20261111-10 | 2026-11-11 | Isolate default EI input in an owned helper | #done #wayland | [2026-11](2026-11.md) | | U-20261111-09 | 2026-11-11 | Split MCP executor adapters along strict domain boundaries | #done #mcp | [2026-11](2026-11.md) | @@ -630,7 +632,8 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11.md](2026-11.md) | 2026-11 | 32 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 2 | +| [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | | [2026-10-d.md](2026-10-d.md) | 2026-10 | 15 | diff --git a/je_auto_control/gui/remote_desktop/advanced_group.py b/je_auto_control/gui/remote_desktop/advanced_group.py index 4232a202c..578c34fd1 100644 --- a/je_auto_control/gui/remote_desktop/advanced_group.py +++ b/je_auto_control/gui/remote_desktop/advanced_group.py @@ -7,12 +7,13 @@ its line-count cap. The panel argument is therefore a :class:`AdvancedGroupHost`: what the builder -reads (``_tr``, ``_on_hw_codec_changed``) and what it sets (the five widgets). +reads (``_tr``) and what it sets (the four text edits). The optional codec +owner has its own :class:`HardwareCodecGroupHost` contract. Imports ``PySide6`` — it is GUI-only by construction. """ from __future__ import annotations -from typing import Any, Protocol, TypeVar +from typing import Protocol, TypeVar from PySide6.QtWidgets import ( QComboBox, QGridLayout, QGroupBox, QLabel, QLineEdit, QWidget, @@ -32,27 +33,32 @@ class AdvancedGroupHost(Protocol): """A WebRTC panel, seen from the advanced group it hosts. - ``_tr`` and ``_on_hw_codec_changed`` are read; the five widget + ``_tr`` is read; the four text-edit attributes are *assigned* by :func:`build_advanced_group`, which is why this cannot be the plain ``TranslatableMixin`` the parameter used to name — that class has none of them. """ - _stun_edit: Any - _turn_edit: Any - _turn_user_edit: Any - _turn_cred_edit: Any - _hw_codec_combo: Any + _stun_edit: QLineEdit + _turn_edit: QLineEdit + _turn_user_edit: QLineEdit + _turn_cred_edit: QLineEdit def _tr(self, widget: _W, key: str, setter: str = "") -> _W: """Register ``widget`` for live re-translation and return it.""" + +class HardwareCodecGroupHost(AdvancedGroupHost, Protocol): + """The optional host-only codec picker and its change handler.""" + + _hw_codec_combo: QComboBox + def _on_hw_codec_changed(self) -> None: """React to the hardware-codec selection changing.""" def build_advanced_group(panel: AdvancedGroupHost, - include_hw_codec: bool = False) -> QGroupBox: + *, hardware_codec: HardwareCodecGroupHost | None = None) -> QGroupBox: """Shared 'Advanced' STUN/TURN (+ optional hw codec) group.""" group = panel._tr(QGroupBox(), "rd_webrtc_advanced_group") grid = QGridLayout() @@ -69,13 +75,13 @@ def build_advanced_group(panel: AdvancedGroupHost, panel._turn_cred_edit = QLineEdit() panel._turn_cred_edit.setEchoMode(QLineEdit.EchoMode.Password) grid.addWidget(panel._turn_cred_edit, 2, 3) - if include_hw_codec: - _add_hw_codec_row(panel, grid) + if hardware_codec is not None: + _add_hw_codec_row(hardware_codec, grid) group.setLayout(grid) return group -def _add_hw_codec_row(panel: AdvancedGroupHost, grid: QGridLayout) -> None: +def _add_hw_codec_row(panel: HardwareCodecGroupHost, grid: QGridLayout) -> None: """Add the hardware-codec picker, pre-selected to the active codec.""" grid.addWidget(panel._tr(QLabel(), "rd_webrtc_hw_codec_label"), 3, 0) combo = QComboBox() @@ -95,4 +101,4 @@ def _add_hw_codec_row(panel: AdvancedGroupHost, grid: QGridLayout) -> None: combo.currentIndexChanged.connect(lambda _i: panel._on_hw_codec_changed()) -__all__ = ["DEFAULT_STUN", "AdvancedGroupHost", "build_advanced_group"] +__all__ = ["DEFAULT_STUN", "AdvancedGroupHost", "HardwareCodecGroupHost", "build_advanced_group"] diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py index 7904b6a72..5bcea73d8 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart + import functools import threading from typing import TYPE_CHECKING, Optional, Tuple @@ -30,7 +32,6 @@ else: from je_auto_control.utils.remote_desktop import MultiViewerHost from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _read_webrtc_config, start_panel_task, ) @@ -78,7 +79,7 @@ def _advertise_failed(error: object) -> None: autocontrol_logger.debug("lan advertise: %r", error) -class _HostConnectionMixin(_PanelPart): +class _HostConnectionMixin(_HostPanelPart): """Methods of ``_WebRTCHostPanel``; the module docstring says which group.""" # State this group owns; the panel's __init__ sets the starting values. diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_media.py b/je_auto_control/gui/remote_desktop/webrtc_host_media.py index 66c61b497..50d693eff 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_media.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_media.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart + from typing import Optional @@ -35,12 +37,11 @@ StatsPoller, StatsSnapshot, ) from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _DEFAULT_MONITOR, _QUALITY_DOT_STYLE, _av_frame_to_qimage, ) -class _HostMediaMixin(_PanelPart): +class _HostMediaMixin(_HostPanelPart): """Methods of ``_WebRTCHostPanel``; the module docstring says which group.""" # State this group owns; the panel's __init__ sets the starting values. diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py index 2c44150e1..6c1b0aa81 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py @@ -5,8 +5,10 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart + import functools -from typing import Callable, Dict, Optional +from typing import Callable, Mapping, Optional from PySide6.QtCore import QPoint, Qt from PySide6.QtWidgets import ( @@ -24,7 +26,6 @@ from je_auto_control.utils.remote_desktop.webrtc_stats import ( StatsPoller, StatsSnapshot, ) -from je_auto_control.gui.remote_desktop.webrtc_panel_common import _PanelPart def _stop_session(host: MultiViewerHostT, sid: str) -> None: @@ -35,7 +36,7 @@ def _stop_session(host: MultiViewerHostT, sid: str) -> None: autocontrol_logger.warning("disconnect session: %r", error) -class _HostSessionsMixin(_PanelPart): +class _HostSessionsMixin(_HostPanelPart): """Methods of ``_WebRTCHostPanel``; the module docstring says which group.""" def _on_session_count(self, count: int) -> None: @@ -199,7 +200,7 @@ def _on_sessions_context_menu(self, position: QPoint) -> None: ) self._dispatch_session_menu(chosen, actions, sid, viewer_id) - def _dispatch_session_menu(self, chosen: object, actions: Dict[str, object], + def _dispatch_session_menu(self, chosen: object, actions: Mapping[str, object], sid: str, viewer_id: str) -> None: """Run the action chosen from the sessions context menu.""" if chosen is actions["disconnect"]: diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_trust.py b/je_auto_control/gui/remote_desktop/webrtc_host_trust.py index be3ab9887..2b81ad1d3 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_trust.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_trust.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart + import functools import os from typing import Any @@ -22,14 +24,13 @@ ) from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _JSON_FILE_FILTER, start_panel_task, ) from je_auto_control.gui.tab_task_controller import CancellationToken -class _HostTrustMixin(_PanelPart): +class _HostTrustMixin(_HostPanelPart): """Methods of ``_WebRTCHostPanel``; the module docstring says which group.""" def _on_view_audit(self) -> None: diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_ui.py b/je_auto_control/gui/remote_desktop/webrtc_host_ui.py index bad1d026c..5925f7b59 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_ui.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_ui.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart + from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -26,12 +28,11 @@ generate_host_id, ) from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _DEFAULT_FPS, _DEFAULT_SIGNALING_URL, _QUALITY_DOT_STYLE, ) -class _HostUiMixin(_PanelPart): +class _HostUiMixin(_HostPanelPart): """Methods of ``_WebRTCHostPanel``; the module docstring says which group.""" def _build_ui(self) -> None: @@ -39,7 +40,7 @@ def _build_ui(self) -> None: layout.addWidget(self._build_signaling_group()) layout.addWidget(self._build_config_group()) layout.addWidget(self._build_manual_group()) - layout.addWidget(build_advanced_group(self, include_hw_codec=True)) + layout.addWidget(build_advanced_group(self, hardware_codec=self)) layout.addWidget(build_trusted_group(self)) self._status_label = QLabel(_t("rd_webrtc_status_idle")) layout.addWidget(self._status_label) diff --git a/je_auto_control/gui/remote_desktop/webrtc_panel_common.py b/je_auto_control/gui/remote_desktop/webrtc_panel_common.py index fde914521..92556ff3d 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_panel_common.py +++ b/je_auto_control/gui/remote_desktop/webrtc_panel_common.py @@ -6,7 +6,7 @@ from PySide6.QtCore import QObject, Signal from PySide6.QtGui import QImage -from PySide6.QtWidgets import QWidget +from PySide6.QtWidgets import QLabel, QLineEdit, QWidget from je_auto_control.gui.remote_desktop._webrtc_types import AvFrameT, WebRTCConfigT from je_auto_control.gui._i18n_helpers import TranslatableMixin @@ -78,6 +78,16 @@ class _PanelPart(TranslatableMixin, QWidget): # Set by each panel's __init__: shutdowns of sessions the panel let go of. _stops: StopQueue + _status_label: QLabel + _signals: _PanelSignals + _stun_edit: QLineEdit + _turn_edit: QLineEdit + _turn_user_edit: QLineEdit + _turn_cred_edit: QLineEdit + _server_edit: QLineEdit + _host_id_edit: QLineEdit + _secret_edit: QLineEdit + _token_edit: QLineEdit def _show_idle(self) -> None: """Show "idle" -- or "stopping" while a session this panel let go of is still closing.""" @@ -138,7 +148,7 @@ def _read_region(panel: QWidget) -> Optional[Tuple[int, ...]]: return tuple(parts) if len(parts) == 4 else None -def _read_webrtc_config(panel: QWidget) -> WebRTCConfigT: +def _read_webrtc_config(panel: _PanelPart) -> WebRTCConfigT: """Build a WebRTCConfig from the advanced group + monitor/fps fields.""" from je_auto_control.utils.remote_desktop.webrtc_transport import ( _DEFAULT_STUN_SERVERS, diff --git a/je_auto_control/gui/remote_desktop/webrtc_panel_state.py b/je_auto_control/gui/remote_desktop/webrtc_panel_state.py new file mode 100644 index 000000000..ce7dbc110 --- /dev/null +++ b/je_auto_control/gui/remote_desktop/webrtc_panel_state.py @@ -0,0 +1,156 @@ +"""Typed state and slot contracts of the composed WebRTC host and viewer widgets.""" +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, Optional, Sequence + +from je_auto_control.gui.remote_desktop.webrtc_panel_common import _PanelPart + +if TYPE_CHECKING: + from PySide6.QtCore import QPoint, QTimer + from PySide6.QtWidgets import ( + QCheckBox, QComboBox, QLabel, QLineEdit, QPushButton, QSpinBox, QTableWidget, QTextEdit, + ) + from je_auto_control.gui.remote_desktop._webrtc_types import AvFrameT, MultiViewerHostT, WebRTCDesktopViewerT + from je_auto_control.gui.remote_desktop.annotation_overlay import HostAnnotationOverlay + from je_auto_control.gui.remote_desktop.viewer_screen_window import ViewerScreenWindow + from je_auto_control.gui.remote_desktop.remote_screen_window import RemoteScreenWindow + from je_auto_control.gui.remote_desktop.tray_icon import HostTrayIcon + from je_auto_control.gui.remote_desktop.frame_display import _FrameDisplay + from je_auto_control.gui.remote_desktop.sparkline import Sparkline + from je_auto_control.gui.remote_desktop.webrtc_dialogs import AddressBookList, RemoteFilesTable, TrustedViewersList + from je_auto_control.utils.remote_desktop.session_quality_cache import SessionQualityCache + from je_auto_control.utils.remote_desktop.webrtc_stats import StatsPoller + from je_auto_control.utils.remote_desktop.trust_list import TrustList + from je_auto_control.utils.remote_desktop.address_book import AddressBook + from je_auto_control.utils.remote_desktop.fingerprint import KnownHosts + + +class _HostPanelPart(_PanelPart): + """State initialized by the host panel and slots supplied by its mixins.""" + + _accept_viewer_video_check: QCheckBox + _adaptive_check: QCheckBox + _annotation_overlay: Optional[HostAnnotationOverlay] + _answer_input: QTextEdit + _fps_spin: QSpinBox + _host_quality_dot: QLabel + _hw_codec_combo: QComboBox + _ip_whitelist_edit: QTextEdit + _max_bitrate_spin: QSpinBox + _maybe_start_adaptive: Callable[[], None] + _monitor_combo: QComboBox + _multi_host: Optional[MultiViewerHostT] + _offer_view: QTextEdit + _on_apply_answer: Callable[[], None] + _on_clear_trust: Callable[[], None] + _on_disconnect_selected: Callable[[], None] + _on_export_trust: Callable[[], None] + _on_generate_offer: Callable[[], None] + _on_hw_codec_changed: Callable[[], None] + _on_import_trust: Callable[[], None] + _on_monitor_changed: Callable[[int], None] + _on_pick_region: Callable[[], None] + _on_publish_via_server: Callable[[], None] + _on_push_file: Callable[[], None] + _on_regen_id: Callable[[], None] + _on_remove_trust: Callable[[str], None] + _on_remove_trust_button: Callable[[], None] + _on_session_authed: Callable[[str], None] + _on_sessions_context_menu: Callable[[QPoint], None] + _on_stop: Callable[[], None] + _on_toggle_accept_opus_audio: Callable[[bool], None] + _on_toggle_accept_viewer_video: Callable[[bool], None] + _on_toggle_adaptive: Callable[[bool], None] + _on_toggle_blanking: Callable[[bool], None] + _on_toggle_mic_receive: Callable[[bool], None] + _on_toggle_readonly: Callable[[bool], None] + _on_view_audit: Callable[[], None] + _populate_monitor_combo: Callable[[], None] + _readonly_check: QCheckBox + _region_edit: QLineEdit + _require_multi_host: Callable[[], MultiViewerHostT] + _reset_host_quality_dot: Callable[[], None] + _session_cache: SessionQualityCache + _session_pollers: dict[str, StatsPoller] + _sessions_label: QLabel + _sessions_table: QTableWidget + _set_hosting: Callable[[bool], None] + _show_error: Callable[[Exception], None] + _stop_adaptive: Callable[[], None] + _stopping_sessions: set[str] + _tray: Optional[HostTrayIcon] + _trust_list: TrustList + _trust_session_viewer: Callable[[str], None] + _trusted_list: TrustedViewersList + _viewer_screen_window: Optional[ViewerScreenWindow] + + +class _ViewerPanelPart(_PanelPart): + """State initialized by the viewer panel and slots supplied by its mixins.""" + + _address_book: AddressBook + _address_list: AddressBookList + _answer_view: QTextEdit + _auto_reconnect_check: QCheckBox + _bandwidth_combo: QComboBox + _bitrate_spark: Sparkline + _close_screen_window: Callable[[], None] + _ensure_screen_window: Callable[[], RemoteScreenWindow] + _frame_display: _FrameDisplay + _known_hosts: KnownHosts + _mic_btn: QPushButton + _offer_input: QTextEdit + _on_ab_clear: Callable[[], None] + _on_ab_export: Callable[[], None] + _on_ab_import: Callable[[], None] + _on_address_chosen: Callable[[dict[str, object]], None] + _on_address_favorite: Callable[[dict[str, object]], None] + _on_address_removed: Callable[[dict[str, object]], None] + _on_address_tags: Callable[[dict[str, object]], None] + _on_av_frame: Callable[[AvFrameT], None] + _on_browse_delete_button: Callable[[], None] + _on_browse_pull_button: Callable[[], None] + _on_browse_refresh: Callable[[], None] + _on_connect_selected_address: Callable[[], None] + _on_connect_via_server: Callable[[], None] + _on_copy_name: Callable[[str], None] + _on_create_answer: Callable[[], None] + _on_delete_names: Callable[[Sequence[str]], None] + _on_lan_browse: Callable[[], None] + _on_manage_known_hosts: Callable[[], None] + _on_pen_clear: Callable[[], None] + _on_pull_names: Callable[[Sequence[str]], None] + _on_received_file: Callable[[object], None] + _on_remove_selected_address: Callable[[], None] + _on_save_current_address: Callable[[], None] + _on_send_cad: Callable[[], None] + _on_send_file: Callable[[], None] + _on_stop: Callable[[], None] + _on_sync_browse: Callable[[], None] + _on_toggle_mic: Callable[[bool], None] + _on_toggle_pen: Callable[[bool], None] + _on_toggle_recording: Callable[[bool], None] + _on_toggle_share_my_screen: Callable[[bool], None] + _on_toggle_share_opus_mic: Callable[[bool], None] + _on_toggle_sync: Callable[[bool], None] + _on_upload_paths: Callable[[Sequence[str]], None] + _on_wake_on_lan: Callable[[], None] + _pen_btn: QPushButton + _quality_dot: QLabel + _reconnect_delay_spin: QSpinBox + _reconnect_max_spin: QSpinBox + _reconnect_timer: QTimer + _record_btn: QPushButton + _refresh_address_book: Callable[[], None] + _remote_files_table: RemoteFilesTable + _screen_window: Optional[RemoteScreenWindow] + _show_error: Callable[[Exception], None] + _start_stats_polling: Callable[[], None] + _stats_label: QLabel + _stop_stats_polling: Callable[[], None] + _sync_btn: QPushButton + _sync_dir_edit: QLineEdit + _tag_filter_combo: QComboBox + _viewer: Optional[WebRTCDesktopViewerT] + _viewer_id: Optional[str] + _wire_input_signals: Callable[[], None] diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_address_book.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_address_book.py index a6d3c04ab..c506c29a2 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_address_book.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_address_book.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _ViewerPanelPart + from typing import Any, Dict, Optional from PySide6.QtWidgets import ( @@ -22,12 +24,11 @@ send_magic_packet, ) from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _JSON_FILE_FILTER, ) -class _ViewerAddressBookMixin(_PanelPart): +class _ViewerAddressBookMixin(_ViewerPanelPart): """Methods of ``_WebRTCViewerPanel``; the module docstring says which group.""" @staticmethod diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py index 1db202f5a..7c0877638 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _ViewerPanelPart + import functools from typing import TYPE_CHECKING, Callable, Optional @@ -31,7 +33,6 @@ else: from je_auto_control.utils.remote_desktop import WebRTCDesktopViewer from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _read_webrtc_config, ) @@ -45,7 +46,7 @@ def _process_offer(viewer: WebRTCDesktopViewerT, offer_sdp: str, expected_dtls: return viewer.process_offer(offer_sdp, expected_dtls_fingerprint=expected_dtls) -class _ViewerConnectionMixin(_PanelPart): +class _ViewerConnectionMixin(_ViewerPanelPart): """Methods of ``_WebRTCViewerPanel``; the module docstring says which group.""" # State this group owns; the panel's __init__ sets the starting values. diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py index dcca18dca..179d7702b 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _ViewerPanelPart + import functools import os from typing import TYPE_CHECKING, Any, List, Optional, Sequence, Tuple @@ -22,14 +24,14 @@ _t, ) from je_auto_control.utils.logging.logging_instance import autocontrol_logger -from je_auto_control.gui.remote_desktop.webrtc_panel_common import _PanelPart, start_panel_task +from je_auto_control.gui.remote_desktop.webrtc_panel_common import start_panel_task from je_auto_control.gui.tab_task_controller import CancellationToken if TYPE_CHECKING: # imported lazily at runtime to keep startup cheap from je_auto_control.utils.remote_desktop.file_sync import FolderSyncEngine -class _ViewerFilesMixin(_PanelPart): +class _ViewerFilesMixin(_ViewerPanelPart): """Methods of ``_WebRTCViewerPanel``; the module docstring says which group.""" # State this group owns; the panel's __init__ sets the starting values. diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py index eb363cebe..46e96ee9c 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _ViewerPanelPart + from typing import Optional @@ -31,12 +33,11 @@ fps_for_preset, ) from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _QUALITY_DOT_STYLE, _av_frame_to_qimage, ) -class _ViewerMediaMixin(_PanelPart): +class _ViewerMediaMixin(_ViewerPanelPart): """Methods of ``_WebRTCViewerPanel``; the module docstring says which group.""" # State this group owns; the panel's __init__ sets the starting values. diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py index a2380005e..c40ba7b26 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.webrtc_panel_state import _ViewerPanelPart + from PySide6.QtWidgets import ( QCheckBox, QComboBox, QGridLayout, @@ -27,12 +29,11 @@ BANDWIDTH_PRESETS, ) from je_auto_control.gui.remote_desktop.webrtc_panel_common import ( - _PanelPart, _DEFAULT_SIGNALING_URL, _QUALITY_DOT_STYLE, ) -class _ViewerUiMixin(_PanelPart): +class _ViewerUiMixin(_ViewerPanelPart): """Methods of ``_WebRTCViewerPanel``; the module docstring says which group.""" def _build_ui(self) -> None: diff --git a/pyproject.toml b/pyproject.toml index dc337492c..d8eb7681e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -362,6 +362,7 @@ module = [ "je_auto_control.gui.config_sync_tab", "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", + "je_auto_control.gui.remote_desktop.webrtc_panel_state", "je_auto_control.gui.rbac_users_panel", "je_auto_control.gui.remote_desktop._connect_task", "je_auto_control.gui.remote_desktop._webrtc_types", diff --git a/test/unit_test/headless/test_remote_desktop_optional_codec_ui.py b/test/unit_test/headless/test_remote_desktop_optional_codec_ui.py index ecf16cf0c..7484f00e1 100644 --- a/test/unit_test/headless/test_remote_desktop_optional_codec_ui.py +++ b/test/unit_test/headless/test_remote_desktop_optional_codec_ui.py @@ -31,7 +31,7 @@ def unexpected_call(): for name in ("available_hardware_codecs", "active_hardware_codec"): monkeypatch.setattr(advanced_group, name, None if missing in (name, "both") else unexpected_call) panel = SimpleNamespace(_tr=lambda widget, key: widget, _on_hw_codec_changed=lambda: None) - group = advanced_group.build_advanced_group(panel, include_hw_codec=True) + group = advanced_group.build_advanced_group(panel, hardware_codec=panel) assert not panel._hw_codec_combo.isEnabled() assert panel._hw_codec_combo.count() == 1 assert panel._hw_codec_combo.currentData() == "" @@ -43,7 +43,7 @@ def test_available_codec_helpers_populate_and_select_picker(qapp, monkeypatch): monkeypatch.setattr(advanced_group, "available_hardware_codecs", lambda: ["h264_nvenc", "h264_qsv"]) monkeypatch.setattr(advanced_group, "active_hardware_codec", lambda: "h264_qsv") panel = SimpleNamespace(_tr=lambda widget, key: widget, _on_hw_codec_changed=lambda: None) - group = advanced_group.build_advanced_group(panel, include_hw_codec=True) + group = advanced_group.build_advanced_group(panel, hardware_codec=panel) assert panel._hw_codec_combo.isEnabled() assert panel._hw_codec_combo.count() == 3 assert panel._hw_codec_combo.currentData() == "h264_qsv" @@ -65,3 +65,17 @@ def test_missing_codec_actions_report_failure(qapp, monkeypatch, codec): assert label.text() == expected combo.close() label.close() + + +def test_viewer_advanced_group_needs_no_hardware_controls(qapp, monkeypatch): + def unexpected_probe(): + raise AssertionError("viewer must not enumerate codecs") + + monkeypatch.setattr(advanced_group, "available_hardware_codecs", unexpected_probe) + monkeypatch.setattr(advanced_group, "active_hardware_codec", unexpected_probe) + panel = SimpleNamespace(_tr=lambda widget, key: widget) + group = advanced_group.build_advanced_group(panel) + assert panel._stun_edit.text() == advanced_group.DEFAULT_STUN + assert panel._turn_edit.text() == "" + assert not hasattr(panel, "_hw_codec_combo") + group.close() diff --git a/test/verify/typing_extras_exempt.txt b/test/verify/typing_extras_exempt.txt index 0d53ff6c9..741ff1969 100644 --- a/test/verify/typing_extras_exempt.txt +++ b/test/verify/typing_extras_exempt.txt @@ -12,16 +12,4 @@ # Measure with the versions the `typing-extras` job of `quality.yml` pins. # # Targets: win32, linux, darwin -# Measured entries: 11 - -je_auto_control.gui.remote_desktop.webrtc_host_connection -je_auto_control.gui.remote_desktop.webrtc_host_media -je_auto_control.gui.remote_desktop.webrtc_host_sessions -je_auto_control.gui.remote_desktop.webrtc_host_trust -je_auto_control.gui.remote_desktop.webrtc_host_ui -je_auto_control.gui.remote_desktop.webrtc_panel_common -je_auto_control.gui.remote_desktop.webrtc_viewer_address_book -je_auto_control.gui.remote_desktop.webrtc_viewer_connection -je_auto_control.gui.remote_desktop.webrtc_viewer_files -je_auto_control.gui.remote_desktop.webrtc_viewer_media -je_auto_control.gui.remote_desktop.webrtc_viewer_ui +# Measured entries: 0 From 19e085d87c32ff0b4adf69bf772afa164786c157 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 17:11:45 +0800 Subject: [PATCH 023/161] Reconcile package loading progress with verified behavior --- Progress.md | 2 -- docs/updates/2026-11-b.md | 5 +++++ docs/updates/README.md | 3 ++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Progress.md b/Progress.md index cf12bdf72..fcce67dc1 100644 --- a/Progress.md +++ b/Progress.md @@ -156,8 +156,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **變數範圍**:free-threaded 原生執行緒繼承與同時存取範圍的行為尚未實測。 - **遠端桌面的擁有者模型**:Quick Connect 沒有狀態列,它的連線被取代時視窗只是關掉;主機的 Stop 會停任何擁有者開的 host(刻意的); 只用假的 viewer/host 測過,真的 viewer 被擠掉時會不會觸發 `on_error` 而多跳一個警告框,沒看過。 -- **套件閘門**:`execute_action` 會先驗完所有指令名稱才執行,所以「載入套件」與「用它的指令」寫在同一份清單裡會以 unknown command 失敗,與閘門無關(既有限制)。 - repo 根目錄的舊範例 `AutoControl/keyword/keyword1.json` 載入 `time`,現在預設會被拒絕。 - **`pytest --cov` 沒有重新量過**:進入點搬到 `je_auto_control_pytest` 之後,它是否還少算,未知;規則仍是 `coverage run -m pytest`。 - **快到 750 行上限的檔案**:`utils/usb/passthrough/viewer_client.py`(748)、`gui/remote_desktop/connection_screen.py`(729)、 `utils/mcp_server/server.py`(734)、`utils/mcp_server/http_transport.py`(727)、`utils/agent/backends/anthropic_computer_use.py`(723)——下一次要加東西就得先拆。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 475918717..a9c713e11 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -10,3 +10,8 @@ - **Evidence:** At 3d8c320c, all changed-test suites passed 540 cases with 2 platform skips. Sphinx HTML built with warnings as errors. Isolated builds produced wheel and sdist without modifying the shared environment; all 42 changed package files in the wheel matched source bytes, and the removed MCP bridge was absent. The first no-isolation attempt could not import the unavailable setuptools backend; the isolated build succeeded. - **Limits:** This checkpoint predates U-20261111-12. Final fixed-source full-suite and native acceptance remain in Progress.md; no deployment or shared installation occurred. + +## U-20261111-14 · 2026-11-11 · Reconcile package-loading progress with existing execution support · #snapshot #progress + +- **What:** Removed the stale claim that allowed package loading and use cannot share one action list. Existing validation defers only eligible names after an earlier literal allowed load. The keyword example already uses AC_sleep and no longer imports time. +- **Evidence:** Current package-gate and same-list suites passed 39 cases, covering closed/open gates, call order, unknown/private executors, nested actions, CLI validation and the example. The original change is c96286bf6. No desktop actions ran; this updates progress evidence only. diff --git a/docs/updates/README.md b/docs/updates/README.md index 8f4bb0c45..868859c10 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-14 | 2026-11-11 | Reconcile package-loading progress with existing execution support | #snapshot #progress | [2026-11-b](2026-11-b.md) | | U-20261111-13 | 2026-11-11 | Validate integrated implementation and package artifacts | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-12 | 2026-11-11 | Remove remaining WebRTC Qt typing exemptions | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261111-11 | 2026-11-11 | Enroll EI helpers in the strict typing gate | #done #typing | [2026-11](2026-11.md) | @@ -632,7 +633,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 2 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 3 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | From 582d0fc2836dd8dfe2078a1223aec1ebe4af3fa3 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 17:17:01 +0800 Subject: [PATCH 024/161] Reconcile security progress with verified transport coverage --- Progress.md | 5 ++--- docs/updates/2026-11-b.md | 5 +++++ docs/updates/README.md | 3 ++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Progress.md b/Progress.md index fcce67dc1..af0412c6a 100644 --- a/Progress.md +++ b/Progress.md @@ -139,11 +139,10 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **Intel Mac 安裝要編譯 `cryptography`**:下限拉到 50 之後 `macosx_10_9_x86_64` 沒有 wheel(探測:最新只到 48.0.1), `pip install je_auto_control` 在 Intel Mac 需要 Rust 工具鏈。沒有在 Intel Mac 上實際編過。 - **簽章分離擋不住能寫檔的人**:能執行寫檔指令(shell、檔案類指令)的人仍能換掉公鑰檔本身,保護那個檔是作業系統權限的事; - 私鑰是未加密的 PEM(0600,Windows 上沒驗權限位元),沒有通行碼選項;遷移模式開著時 HMAC 簽章會被接受。 - 強制簽章經 socket/REST/MCP 的端到端沒有跑過,覆蓋的是共用的 `read_executable_action_json` 與指令本身。 + 私鑰支援選用通行碼加密,未設定時仍是明文 PEM(0600,Windows 上沒驗權限位元);遷移模式開著時 HMAC 簽章會被接受。 - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - viewer 的其餘影像檔案型、mobile 與外掛唯讀工具仍需全面盤點 capability;自製工具仍依提示採預設分類。 - - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;SSE、無狀態與 `subscriptions/listen` 路徑、TLS 加 RBAC 沒有測試。 + - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, 限於可辨識的絕對路徑、已存在的相對路徑及 `file:` URL;保留原字串,不代表能限制應用程式自行解讀的路徑或尚不存在的相對路徑。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index a9c713e11..8ef109f86 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -15,3 +15,8 @@ - **What:** Removed the stale claim that allowed package loading and use cannot share one action list. Existing validation defers only eligible names after an earlier literal allowed load. The keyword example already uses AC_sleep and no longer imports time. - **Evidence:** Current package-gate and same-list suites passed 39 cases, covering closed/open gates, call order, unknown/private executors, nested actions, CLI validation and the example. The original change is c96286bf6. No desktop actions ran; this updates progress evidence only. + +## U-20261111-15 · 2026-11-11 · Reconcile signing and RBAC transport verification · #snapshot #security + +- **What:** Corrected stale progress statements: private signing keys support optional passphrases; signature enforcement has socket/REST/MCP end-to-end coverage; RBAC covers SSE, stateless requests, subscriptions and TLS. Remaining real-client, ACL and capability-inventory limits remain in Progress.md. +- **Evidence:** Current signing socket/passphrase/execution-role and MCP transport/sensitive-read suites passed 125 cases. Tests use loopback servers, temporary keys and fake probe tools. No desktop actions, deployed services or real client acceptance ran. diff --git a/docs/updates/README.md b/docs/updates/README.md index 868859c10..54c613b02 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-15 | 2026-11-11 | Reconcile signing and RBAC transport verification | #snapshot #security | [2026-11-b](2026-11-b.md) | | U-20261111-14 | 2026-11-11 | Reconcile package-loading progress with existing execution support | #snapshot #progress | [2026-11-b](2026-11-b.md) | | U-20261111-13 | 2026-11-11 | Validate integrated implementation and package artifacts | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-12 | 2026-11-11 | Remove remaining WebRTC Qt typing exemptions | #done #typing | [2026-11-b](2026-11-b.md) | @@ -633,7 +634,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 3 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 4 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | From d46d5090abc19b9eaa67a02dfe5006aa7d4e9c40 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 17:20:04 +0800 Subject: [PATCH 025/161] Reconcile historical verification and current file budgets --- Progress.md | 4 +--- docs/updates/2026-11-b.md | 5 +++++ docs/updates/README.md | 3 ++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Progress.md b/Progress.md index af0412c6a..a8a464e0a 100644 --- a/Progress.md +++ b/Progress.md @@ -155,9 +155,7 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **變數範圍**:free-threaded 原生執行緒繼承與同時存取範圍的行為尚未實測。 - **遠端桌面的擁有者模型**:Quick Connect 沒有狀態列,它的連線被取代時視窗只是關掉;主機的 Stop 會停任何擁有者開的 host(刻意的); 只用假的 viewer/host 測過,真的 viewer 被擠掉時會不會觸發 `on_error` 而多跳一個警告框,沒看過。 -- **`pytest --cov` 沒有重新量過**:進入點搬到 `je_auto_control_pytest` 之後,它是否還少算,未知;規則仍是 `coverage run -m pytest`。 -- **快到 750 行上限的檔案**:`utils/usb/passthrough/viewer_client.py`(748)、`gui/remote_desktop/connection_screen.py`(729)、 - `utils/mcp_server/server.py`(734)、`utils/mcp_server/http_transport.py`(727)、`utils/agent/backends/anthropic_computer_use.py`(723)——下一次要加東西就得先拆。 +- **快到 750 行上限的檔案**:`utils/mcp_server/server.py`(744)——下一次要加東西就得先檢查預算,超標前拆分。 --- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 8ef109f86..31a9f080c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -20,3 +20,8 @@ - **What:** Corrected stale progress statements: private signing keys support optional passphrases; signature enforcement has socket/REST/MCP end-to-end coverage; RBAC covers SSE, stateless requests, subscriptions and TLS. Remaining real-client, ACL and capability-inventory limits remain in Progress.md. - **Evidence:** Current signing socket/passphrase/execution-role and MCP transport/sensitive-read suites passed 125 cases. Tests use loopback servers, temporary keys and fake probe tools. No desktop actions, deployed services or real client acceptance ran. + +## U-20261111-16 · 2026-11-11 · Reconcile historical coverage comparison and file budgets · #snapshot #progress + +- **What:** Removed the stale claim that the relocated pytest entry point had never been compared. U-20261009-24 and CLAUDE.md record 87.35% versus 87.32% on that historical tree; this is not a fresh comparison or a claim about the current tree. The required coverage command remains unchanged. +- **Evidence:** Recounted the five named modules: viewer_client 552, connection_screen 679, server 744, http_transport 622 and anthropic_computer_use 234 lines. Progress retains the current server budget concern and removes stale pre-split sizes. No runtime code changed. diff --git a/docs/updates/README.md b/docs/updates/README.md index 54c613b02..decb8f289 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-16 | 2026-11-11 | Reconcile historical coverage comparison and file budgets | #snapshot #progress | [2026-11-b](2026-11-b.md) | | U-20261111-15 | 2026-11-11 | Reconcile signing and RBAC transport verification | #snapshot #security | [2026-11-b](2026-11-b.md) | | U-20261111-14 | 2026-11-11 | Reconcile package-loading progress with existing execution support | #snapshot #progress | [2026-11-b](2026-11-b.md) | | U-20261111-13 | 2026-11-11 | Validate integrated implementation and package artifacts | #snapshot #verification | [2026-11-b](2026-11-b.md) | @@ -634,7 +635,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 4 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 5 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | From e304b6a3bbebdcf6f5988b5607eba1cfe53f47bf Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 17:26:18 +0800 Subject: [PATCH 026/161] Keep WebRTC statistics lifecycle off the GUI wait path --- Progress.md | 3 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture.md | 4 + architecture_explore.md | 16 +- .../doc/new_features/v223_features_doc.rst | 9 +- .../Zh/doc/new_features/v223_features_doc.rst | 8 +- docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- .../utils/remote_desktop/webrtc_stats.py | 109 +++++--- .../test_webrtc_lan_advertise_stop.py | 29 +-- .../headless/test_webrtc_stats_lifecycle.py | 232 ++++++++++++++++++ .../headless/test_webrtc_stats_poller.py | 2 +- 14 files changed, 364 insertions(+), 63 deletions(-) create mode 100644 test/unit_test/headless/test_webrtc_stats_lifecycle.py diff --git a/Progress.md b/Progress.md index a8a464e0a..07fe6e476 100644 --- a/Progress.md +++ b/Progress.md @@ -532,7 +532,8 @@ F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 - **F1 的遺留面板釋放**:Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 -- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移。 +- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, + 包含 Quick Connect 的同步啟停與傳輸中取消。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/README.md b/README.md index 2a1cc1e79..f65ac7dbe 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ Cancellation prevents later move/click steps, but cannot interrupt a native call Auto Click, Record and Script Executor own their controls and background tasks. Closing them stops local work; reopening creates fresh inputs. The shared recorder continues after its page closes, and a reopened page reads backend status (unknown when unsupported). This status does not verify native hook health. Ctrl+4 still stops scripts and auto-clicking. +WebRTC statistics polling starts in the background and discards late samples after it stops. + Windows, macOS, X11 and Wayland use different backends. Available features depend on system permissions and optional dependencies; Windows ARM64 has additional limitations. See the installation guide before choosing a deployment target. Wayland NORMAL input runs libei and portal calls in an owned helper process. Timeouts, cancellation and uncertain replies retire that helper without replay or automatic provider fallback. The direct `LibeiBackend` API remains in-process. Helper retirement is not proof that a compositor released input; native acceptance remains pending. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index e515214bf..62dc809bc 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -41,6 +41,8 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, 自动点击、录制与脚本执行分页各自持有控件与后台任务;关闭会停止本页任务,重新打开会建立新的输入框。共享录制器不随分页关闭,重新打开后会读取后端状态,不支持查询时显示未知;此状态不代表原生钩子健康检查。Ctrl+4 仍可停止脚本与自动点击。 +WebRTC 统计轮询在后台启动,停止后会丢弃延迟到达的样本。 + Windows、macOS、X11 与 Wayland 使用不同后端,实际功能取决于系统权限与可选依赖。Windows ARM64 另有限制,部署前请先阅读安装文件。 Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用。超时、取消或回复不确定时会退役该进程,不重播输入或自动切换提供者。直接使用 `LibeiBackend` 仍在调用端进程内执行;子进程退役不代表合成器已释放输入,原生验收仍待执行。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index fdc26b582..a9207f1d0 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -41,6 +41,8 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, 自動點擊、錄製與腳本執行分頁各自持有控制項與背景工作;關閉會停止本頁工作,重開會建立新的輸入欄位。共用錄製器不隨分頁關閉,重開後會讀取後端狀態,不支援查詢時顯示未知;此狀態不代表原生掛鉤健康檢查。Ctrl+4 仍可停止腳本與自動點擊。 +WebRTC 統計輪詢在背景啟動,停止後會捨棄晚到的樣本。 + Windows、macOS、X11 與 Wayland 使用不同後端,實際功能取決於系統權限與選配依賴。Windows ARM64 另有限制,部署前請先閱讀安裝文件。 Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫。逾時、取消或回覆不確定時會退役該程序,不重播輸入或自動切換供應者。直接使用 `LibeiBackend` 仍在呼叫端程序內執行;子程序退役不代表合成器已釋放輸入,原生驗收仍待執行。 diff --git a/architecture.md b/architecture.md index 5db7fbac8..23374714c 100644 --- a/architecture.md +++ b/architecture.md @@ -1,5 +1,9 @@ # AutoControl Architecture +WebRTC statistics owns one submitted polling future. Start does not wait for +the event loop; stop closes admission, cancels pending submission and drops +the callback owner without acquiring a bridge. Late awaited samples are discarded. + WebRTC host and viewer mixins share concrete typed state and slot contracts. Initialization remains in the composed panels. STUN/TURN controls use a common contract; the host supplies a separate optional hardware-codec owner. diff --git a/architecture_explore.md b/architecture_explore.md index 5fba9cc75..1dc29b9f9 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,510 | -| 程式碼總行數 | 230,573 | +| 程式碼總行數 | 230,622 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 30,486 行。 +> 6 個套件、約 30,535 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 15,252 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 15,301 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -801,7 +801,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(15,252 行/72 檔) +#### `utils/remote_desktop/`(15,301 行/72 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -842,7 +842,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 197 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | -| `webrtc_stats.py` | 174 | 把 aiortc 的 `RTCStats` 報告輪詢成精簡 dict。 | +| `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | | `adaptive_bitrate.py` | 148 | 依統計調整主機擷取 FPS。 | | `signaling_client.py` | 164 | 純標準庫的訊令用戶端。 | @@ -1416,7 +1416,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,176 個 `test_*.py`/11,417 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,177 個 `test_*.py`/11,429 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1509,7 +1509,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 145 | 40,154 | | `utils/mcp_server/` | 60 | 22,037 | -| `utils/remote_desktop/` | 72 | 15,252 | +| `utils/remote_desktop/` | 72 | 15,301 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1528,7 +1528,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,498** | **229,828** | +| **總計** | **1,498** | **229,877** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 23e5756bd..76b08b868 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -14,7 +14,7 @@ Image Detection and Report, expose ``menu_actions()`` returning ``[(label_key, handler), ...]``. The menu bar queries the active page and renders its commands. Registry-supplied actions remain supported for embedders. -46 of 48 registered tabs surface their commands this way. **Script Builder** +49 of 51 registered tabs surface their commands this way. **Script Builder** and **Remote Desktop** intentionally keep their interactive panel layouts, and the Actions menu shows a placeholder there. Controls a window-level menu cannot replace stay in place: per-page browse buttons inside stacked trigger forms, @@ -185,3 +185,10 @@ Closing stops page-owned work but does not stop the shared recorder. Reopening reads existing backend capture state; unsupported/custom backends show unknown. The read-only state does not prove hook health or native input acceptance. Hiding preserves page state; closing and reopening creates a fresh page. + +WebRTC statistics +----------------- + +Statistics polling starts without waiting for the network loop. Stopping it +discards late samples and releases the callback owner; a callback already +executing may finish. This does not close the remote session itself. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index d665c5a63..4ae689848 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -12,7 +12,7 @@ Actions 選單 提供 ``menu_actions()`` 方法,回傳 ``[(label_key, handler), ...]``。 選單列查詢當前分頁並呈現其指令;嵌入者仍可透過註冊資料宣告動作。 -48 個已註冊分頁中有 46 個以此方式呈現指令。**Script Builder** 與 +51 個已註冊分頁中有 49 個以此方式呈現指令。**Script Builder** 與 **Remote Desktop** 刻意保留其互動式面板版面,Actions 選單在這兩頁顯示 佔位訊息。視窗層級選單無法取代的控制項則維持原位:堆疊觸發器表單內的 逐頁瀏覽按鈕、隨可見性切換的資料來源瀏覽按鈕,以及有狀態的自動更新 @@ -178,3 +178,9 @@ GUI 執行緒執行,原本接在阻塞呼叫後面的程式碼就放在這裡。 錄製分頁持有播放、載入資料與背景開始/停止/檔案工作。 關閉不會停止共用錄製器,重開後讀取既有後端狀態;不支援查詢的後端顯示未知。 此唯讀狀態不證明原生掛鉤健康或輸入已被接受。隱藏保留狀態,關閉後重開則建立新分頁。 + +WebRTC 統計 +----------- + +統計輪詢啟動時不等待網路迴圈。停止會捨棄晚到樣本並釋放回呼擁有者; +已經開始執行的回呼仍可完成。停止統計本身不會關閉遠端連線。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 31a9f080c..5dc9a1777 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -25,3 +25,9 @@ - **What:** Removed the stale claim that the relocated pytest entry point had never been compared. U-20261009-24 and CLAUDE.md record 87.35% versus 87.32% on that historical tree; this is not a fresh comparison or a claim about the current tree. The required coverage command remains unchanged. - **Evidence:** Recounted the five named modules: viewer_client 552, connection_screen 679, server 744, http_transport 622 and anthropic_computer_use 234 lines. Progress retains the current server budget concern and removes stale pre-split sizes. No runtime code changed. + +## U-20261111-17 · 2026-11-11 · Start and stop WebRTC statistics without waiting · #done #gui + +- **What:** A single future owns polling, with idempotent nonblocking start and terminal stop. Queued submissions are cancelled after stop, failed submissions close their coroutine, and late samples do not deliver. Stopped pollers release bound callback owners, including across the next suspended sample. +- **Evidence:** Implementation passed 122 focused/consumer cases; independent review passed 36 before the final callback-retention regression. Parent reviewed that final delta and passed all 38 integration cases, plus 44 document/quality gates and a warnings-as-errors Sphinx dummy build. Scoped three-target typing, Ruff, Bandit, Pylint error checks and Radon passed. Tests use fake bridges and peers; no native media operations ran. README translations and Sphinx describe the behavior; the Actions-menu counts were remeasured from the registry. +- **Open items:** Remaining F3 operations and native GUI acceptance stay in Progress.md. An already admitted application callback may finish; stop does not preempt it. diff --git a/docs/updates/README.md b/docs/updates/README.md index decb8f289..129fa72e2 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-17 | 2026-11-11 | Start and stop WebRTC statistics without waiting | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-16 | 2026-11-11 | Reconcile historical coverage comparison and file budgets | #snapshot #progress | [2026-11-b](2026-11-b.md) | | U-20261111-15 | 2026-11-11 | Reconcile signing and RBAC transport verification | #snapshot #security | [2026-11-b](2026-11-b.md) | | U-20261111-14 | 2026-11-11 | Reconcile package-loading progress with existing execution support | #snapshot #progress | [2026-11-b](2026-11-b.md) | @@ -635,7 +636,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 5 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 6 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/webrtc_stats.py b/je_auto_control/utils/remote_desktop/webrtc_stats.py index 90e5893de..5165a8076 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_stats.py +++ b/je_auto_control/utils/remote_desktop/webrtc_stats.py @@ -8,6 +8,9 @@ import asyncio import time +import threading +from concurrent.futures import Future +from enum import Enum, auto from dataclasses import asdict, dataclass from typing import Callable, Optional @@ -30,53 +33,89 @@ def to_dict(self) -> dict: return asdict(self) +class _PollState(Enum): + NEW = auto() + SUBMITTING = auto() + RUNNING = auto() + STOPPED = auto() + + class StatsPoller: """Drive a periodic ``getStats()`` poll on the asyncio bridge.""" def __init__(self, pc, callback: Callable[[StatsSnapshot], None], interval_s: float = _DEFAULT_INTERVAL_S) -> None: self._pc = pc - self._callback = callback + self._callback: Optional[Callable[[StatsSnapshot], None]] = callback self._interval = max(0.25, float(interval_s)) - self._task: Optional[asyncio.Task] = None + self._lifecycle_lock = threading.Lock() + self._state = _PollState.NEW + self._future: Optional[Future[None]] = None self._prev_packets_received = 0 self._prev_packets_lost = 0 self._prev_bytes_received = 0 self._prev_frames_decoded = 0 self._prev_sample_time: Optional[float] = None - self._stopped = False + + @property + def _stopped(self) -> bool: + return self._state is _PollState.STOPPED def start(self) -> None: - from je_auto_control.utils.remote_desktop.webrtc_transport import get_bridge - future = get_bridge().submit(self._async_start()) + """Submit polling once without waiting for the bridge to run it. + + Stop is terminal. A submission already in progress is cancelled as + soon as its future arrives; duplicate starts cannot submit another loop. + """ + with self._lifecycle_lock: + if self._state is not _PollState.NEW: + return + self._state = _PollState.SUBMITTING + coroutine = self._loop() try: - future.result(timeout=2.0) - # Not redundant: TimeoutError is not an OSError on Python 3.10, the - # lowest supported version; the overlap only exists from 3.11. - except (RuntimeError, TimeoutError, OSError) as error: # NOSONAR + from je_auto_control.utils.remote_desktop.webrtc_transport import get_bridge + future = get_bridge().submit(coroutine) + except BaseException as error: # reason: release unsubmitted coroutine; only expected bridge errors are logged + coroutine.close() + with self._lifecycle_lock: + if self._state is _PollState.SUBMITTING: + self._state = _PollState.NEW + if not isinstance(error, (RuntimeError, OSError)): + raise autocontrol_logger.warning("stats poller start: %r", error) - - # Must stay a coroutine although it awaits nothing: bridge.submit hands it - # to asyncio.run_coroutine_threadsafe, and the body schedules the loop task. - async def _async_start(self) -> None: # NOSONAR - if self._task is not None: return - self._task = asyncio.ensure_future(self._loop()) + with self._lifecycle_lock: + stopped = self._stopped + if not stopped: + self._state = _PollState.RUNNING + self._future = future + future.add_done_callback(self._finished) + if stopped: + future.cancel() + + def _finished(self, future: Future[None]) -> None: + with self._lifecycle_lock: + self._state = _PollState.STOPPED + self._callback = None + if self._future is future: + self._future = None + if not future.cancelled(): + error = future.exception() + if error is not None: + autocontrol_logger.warning("stats poller: %r", error) def stop(self) -> None: - """Stop polling; safe from any thread, and it never waits. + """Retire this poller without joining, waiting or acquiring a bridge. - It sets a flag and asks the bridge's loop to cancel the poll task - (``call_soon_threadsafe``): no thread is joined, no future is waited - for and no socket is closed, so a GUI slot may call it directly. The - loop finishes a sample that is already in flight on its own time. + Samples finishing after stop are discarded. A callback already admitted + may finish; stop does not preempt application callback code. """ - self._stopped = True - if self._task is None: - return - from je_auto_control.utils.remote_desktop.webrtc_transport import get_bridge - get_bridge().call_soon(self._task.cancel) - self._task = None + with self._lifecycle_lock: + self._state = _PollState.STOPPED + self._callback = None + future, self._future = self._future, None + if future is not None: + future.cancel() async def _loop(self) -> None: # No try/except CancelledError wrapper here — cancellation must @@ -84,16 +123,26 @@ async def _loop(self) -> None: # to cancellation rather than completing normally (S7497). while not self._stopped: await asyncio.sleep(self._interval) + if self._stopped: + return try: snapshot = await self._sample() except (RuntimeError, OSError) as error: autocontrol_logger.debug("stats sample: %r", error) continue + if self._stopped: + return if snapshot is not None: - try: - self._callback(snapshot) - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("stats cb: %r", error) + self._deliver(snapshot) + + def _deliver(self, snapshot: StatsSnapshot) -> None: + """Keep callback ownership out of the polling coroutine's suspended frame.""" + callback = self._callback + if callback is not None and not self._stopped: + try: + callback(snapshot) + except (RuntimeError, OSError) as error: + autocontrol_logger.debug("stats cb: %r", error) async def _sample(self) -> Optional[StatsSnapshot]: if self._pc is None: diff --git a/test/unit_test/headless/test_webrtc_lan_advertise_stop.py b/test/unit_test/headless/test_webrtc_lan_advertise_stop.py index ef23b8f40..58c1d8e96 100644 --- a/test/unit_test/headless/test_webrtc_lan_advertise_stop.py +++ b/test/unit_test/headless/test_webrtc_lan_advertise_stop.py @@ -155,27 +155,16 @@ def test_an_advertiser_that_comes_up_for_a_panel_that_is_gone_is_closed(advertis assert pump_until(lambda: [entry[0] for entry in advertisers.log] == ["build", "stop"]) -def test_a_stats_poller_stop_only_schedules_a_cancel(monkeypatch): - """Why the pollers' ``stop()`` may stay on the GUI thread: no join, no future to wait for.""" - scheduled = [] +def test_a_stats_poller_stop_cancels_its_owned_future_without_a_bridge(monkeypatch): + from concurrent.futures import Future - class _Bridge: - def call_soon(self, callback, *args): - scheduled.append(callback) + def unavailable(): + raise AssertionError("stop must not acquire the shared bridge") - def submit(self, _coroutine): - raise AssertionError("stop() must not wait for the loop") - - class _Task: - def cancel(self): - raise AssertionError("cancelled on the calling thread instead of the loop's") - - monkeypatch.setattr(webrtc_transport, "get_bridge", _Bridge) + monkeypatch.setattr(webrtc_transport, "get_bridge", unavailable) poller = webrtc_stats.StatsPoller(None, lambda _snapshot: None) - poller.stop() # never started: nothing to schedule - assert scheduled == [] - task = _Task() - poller._task = task + future = Future() + poller._future = future poller.stop() - assert scheduled == [task.cancel] - assert poller._task is None + assert future.cancelled() + assert poller._future is None diff --git a/test/unit_test/headless/test_webrtc_stats_lifecycle.py b/test/unit_test/headless/test_webrtc_stats_lifecycle.py new file mode 100644 index 000000000..a7ece0ed1 --- /dev/null +++ b/test/unit_test/headless/test_webrtc_stats_lifecycle.py @@ -0,0 +1,232 @@ +"""Statistics lifecycle uses a queued fake bridge, never native media or a peer.""" +import asyncio +import gc +import weakref +from concurrent.futures import Future +import sys +import threading +from types import SimpleNamespace + +import pytest + +from je_auto_control.utils.remote_desktop import webrtc_stats + + +class PendingFuture(Future): + def result(self, timeout=None): + raise AssertionError("start must not wait for the bridge") + + +class QueuedBridge: + def __init__(self): + self.calls = [] + self.future = PendingFuture() + + def submit(self, coroutine): + self.calls.append(coroutine) + return self.future + + def close(self): + for coroutine in self.calls: + coroutine.close() + + +@pytest.fixture +def bridge(monkeypatch): + queued = QueuedBridge() + monkeypatch.setitem(sys.modules, "je_auto_control.utils.remote_desktop.webrtc_transport", + SimpleNamespace(get_bridge=lambda: queued)) + yield queued + queued.close() + + +def test_start_returns_before_bridge_runs_and_duplicate_start_submits_once(bridge): + poller = webrtc_stats.StatsPoller(None, lambda snapshot: None) + poller.start() + poller.start() + assert len(bridge.calls) == 1 + assert not bridge.future.done() + poller.stop() + assert bridge.future.cancelled() + + +def test_stop_before_start_never_looks_up_bridge(monkeypatch): + def unavailable(): + raise AssertionError("a stopped poller must not acquire a bridge") + monkeypatch.setitem(sys.modules, "je_auto_control.utils.remote_desktop.webrtc_transport", + SimpleNamespace(get_bridge=unavailable)) + poller = webrtc_stats.StatsPoller(None, lambda snapshot: None) + poller.stop() + poller.start() + poller.stop() + + +def test_stop_before_queued_coroutine_runs_prevents_sampling(bridge): + class Peer: + async def getStats(self): + raise AssertionError("stopped queued work must not sample") + poller = webrtc_stats.StatsPoller(Peer(), lambda snapshot: pytest.fail("late sample")) + poller.start() + poller.stop() + asyncio.run(bridge.calls[0]) + assert bridge.future.cancelled() + + +def test_stop_during_submission_does_not_wait_and_cancels_arriving_future(bridge): + entered, finish = threading.Event(), threading.Event() + original = bridge.submit + def submit(coroutine): + entered.set() + assert finish.wait(2) + return original(coroutine) + bridge.submit = submit + poller = webrtc_stats.StatsPoller(None, lambda snapshot: None) + errors = [] + def start(): + try: + poller.start() + except BaseException as error: + errors.append(error) + worker = threading.Thread(target=start) + worker.start() + try: + assert entered.wait(2) + poller.stop() + assert worker.is_alive() + finally: + finish.set() + worker.join(2) + assert not worker.is_alive() and not errors + assert bridge.future.cancelled() + poller.start() + assert len(bridge.calls) == 1 + + +def test_sample_finishing_after_stop_is_not_delivered(monkeypatch): + async def run(): + sampled, finish = asyncio.Event(), asyncio.Event() + class Peer: + async def getStats(self): + sampled.set() + await finish.wait() + return {} + delivered = [] + poller = webrtc_stats.StatsPoller(Peer(), delivered.append) + async def tick(delay): + return None + monkeypatch.setattr(webrtc_stats.asyncio, "sleep", tick) + task = asyncio.create_task(poller._loop()) + await sampled.wait() + poller.stop() + finish.set() + await task + assert delivered == [] + asyncio.run(run()) + + +def test_submission_failure_closes_coroutine_and_reports_error(bridge, monkeypatch): + captured, warnings = [], [] + def submit(coroutine): + captured.append(coroutine) + raise RuntimeError("bridge closed") + bridge.submit = submit + monkeypatch.setattr(webrtc_stats.autocontrol_logger, "warning", lambda *args: warnings.append(args)) + poller = webrtc_stats.StatsPoller(None, lambda snapshot: None) + poller.start() + assert captured[0].cr_frame is None + assert warnings and "bridge closed" in str(warnings) + poller.stop() + + +def test_synchronous_future_completion_is_safe(bridge, monkeypatch): + bridge.future.set_result(None) + warnings = [] + monkeypatch.setattr(webrtc_stats.autocontrol_logger, "warning", lambda *args: warnings.append(args)) + poller = webrtc_stats.StatsPoller(None, lambda snapshot: None) + poller.start() + poller.stop() + assert warnings == [] + + +def test_async_failure_is_observed_without_waiting(bridge, monkeypatch): + warnings = [] + monkeypatch.setattr(webrtc_stats.autocontrol_logger, "warning", lambda *args: warnings.append(args)) + poller = webrtc_stats.StatsPoller(None, lambda snapshot: None) + poller.start() + bridge.future.set_exception(RuntimeError("peer closed")) + assert warnings and "peer closed" in str(warnings) + poller.stop() + + +def test_started_poller_delivers_samples_until_callback_stops_it(bridge, monkeypatch): + delivered = [] + class Peer: + async def getStats(self): + return {} + poller = webrtc_stats.StatsPoller(Peer(), lambda snapshot: (delivered.append(snapshot), poller.stop())) + async def tick(delay): + return None + monkeypatch.setattr(webrtc_stats.asyncio, "sleep", tick) + poller.start() + asyncio.run(bridge.calls[0]) + assert len(delivered) == 1 + assert bridge.future.cancelled() + + +def test_stop_during_initial_interval_does_not_query_peer(bridge, monkeypatch): + class Peer: + async def getStats(self): + raise AssertionError("stop during interval must skip query") + poller = webrtc_stats.StatsPoller(Peer(), lambda snapshot: pytest.fail("late sample")) + async def tick(delay): + poller.stop() + monkeypatch.setattr(webrtc_stats.asyncio, "sleep", tick) + poller.start() + asyncio.run(bridge.calls[0]) + assert bridge.future.cancelled() + + +def test_stop_drops_callback_owner_even_when_bridge_has_not_run(bridge): + class Receiver: + def receive(self, snapshot): + raise AssertionError("stopped callback") + receiver = Receiver() + reference = weakref.ref(receiver) + poller = webrtc_stats.StatsPoller(None, receiver.receive) + poller.start() + del receiver + assert reference() is not None + poller.stop() + gc.collect() + assert reference() is None + + +def test_previous_callback_owner_is_not_retained_during_next_sample(monkeypatch): + async def run(): + second_sample, finish = asyncio.Event(), asyncio.Event() + class Peer: + count = 0 + async def getStats(self): + self.count += 1 + if self.count == 2: + second_sample.set() + await finish.wait() + return {} + class Receiver: + def receive(self, snapshot): + pass + receiver = Receiver() + reference = weakref.ref(receiver) + poller = webrtc_stats.StatsPoller(Peer(), receiver.receive) + async def tick(delay): + return None + monkeypatch.setattr(webrtc_stats.asyncio, "sleep", tick) + task = asyncio.create_task(poller._loop()) + await second_sample.wait() + del receiver + poller.stop() + gc.collect() + assert reference() is None + finish.set() + await task + asyncio.run(run()) diff --git a/test/unit_test/headless/test_webrtc_stats_poller.py b/test/unit_test/headless/test_webrtc_stats_poller.py index a4c274232..2881e5292 100644 --- a/test/unit_test/headless/test_webrtc_stats_poller.py +++ b/test/unit_test/headless/test_webrtc_stats_poller.py @@ -237,4 +237,4 @@ def test_stopping_a_poller_that_never_started_is_harmless(): poller = StatsPoller(_PeerConnection(), lambda snap: None) poller.stop() assert poller._stopped is True - assert poller._task is None + assert poller._future is None From e9f9356e4450beb8d0e2a6bff2417443712ef04d Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 18:01:00 +0800 Subject: [PATCH 027/161] Release remote pages without retaining callback owners --- CHANGELOG.md | 8 + Progress.md | 5 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture.md | 8 +- architecture_explore.md | 34 +- docs/guides/en/setup.md | 2 +- docs/guides/zh-CN/setup.md | 2 +- docs/guides/zh-TW/setup.md | 2 +- .../doc/new_features/v223_features_doc.rst | 5 + .../Zh/doc/new_features/v223_features_doc.rst | 5 + docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- je_auto_control/gui/main_widget.py | 6 +- .../gui/remote_desktop/__init__.py | 3 +- .../gui/remote_desktop/connection_screen.py | 48 +-- .../remote_desktop/folder_sync_controls.py | 6 +- .../gui/remote_desktop/host_panel.py | 10 +- je_auto_control/gui/remote_desktop/tab.py | 2 +- .../gui/remote_desktop/view_approvals.py | 64 +++ .../gui/remote_desktop/view_frames.py | 25 ++ .../gui/remote_desktop/view_lifetime.py | 85 ++++ .../gui/remote_desktop/view_upload.py | 30 ++ .../gui/remote_desktop/viewer_panel.py | 72 ++-- .../remote_desktop/webrtc_host_connection.py | 9 +- .../gui/remote_desktop/webrtc_host_media.py | 8 +- .../remote_desktop/webrtc_host_sessions.py | 19 +- .../gui/remote_desktop/webrtc_panel.py | 33 +- .../gui/remote_desktop/webrtc_panel_state.py | 11 +- .../webrtc_viewer_connection.py | 18 +- .../gui/remote_desktop/webrtc_viewer_media.py | 2 +- je_auto_control/gui/remote_desktop_tab.py | 3 +- pyproject.toml | 5 + test/unit_test/headless/_remote_view_owner.py | 10 + .../headless/test_gui_registry_close.py | 23 +- .../headless/test_remote_view_retirement.py | 379 ++++++++++++++++++ .../headless/test_webrtc_folder_receipts.py | 9 +- .../headless/test_webrtc_folder_reconnect.py | 3 +- 39 files changed, 810 insertions(+), 159 deletions(-) create mode 100644 je_auto_control/gui/remote_desktop/view_approvals.py create mode 100644 je_auto_control/gui/remote_desktop/view_frames.py create mode 100644 je_auto_control/gui/remote_desktop/view_lifetime.py create mode 100644 je_auto_control/gui/remote_desktop/view_upload.py create mode 100644 test/unit_test/headless/_remote_view_owner.py create mode 100644 test/unit_test/headless/test_remote_view_retirement.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 78b704952..aa0a7742b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## [Unreleased] + +- Closing Image Detection, Auto Click, Record, Script Executor or Remote Desktop now + releases its page controls. Hiding still preserves them. Reopening starts fresh + local state; the shared recorder and registry-owned TCP/WebSocket sessions survive + their views. Remote Desktop does not automatically reattach a reopened view, and + its page-owned WebRTC sessions are stopped in the background. + ## [1.2.0] - 2026-11-02 Python 3.11 is now the minimum. Pillow 13.0.0 and dnspython 2.9.0, the releases that fix the advisories diff --git a/Progress.md b/Progress.md index 07fe6e476..d270aa6d3 100644 --- a/Progress.md +++ b/Progress.md @@ -530,10 +530,11 @@ H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深 F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 -- **F1 的遺留面板釋放**:Remote Desktop 在關閉時仍保留 widget;需隨 F3 遷移直接控制項引用、執行中工作與連線生命週期,再啟用銷毀。 - **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, - 包含 Quick Connect 的同步啟停與傳輸中取消。 + 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 +- **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, + 尚未保留失敗資源的明確重試所有權;不能把背景排程等同原生資源已釋放。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/README.md b/README.md index f65ac7dbe..8d928a379 100644 --- a/README.md +++ b/README.md @@ -64,3 +64,5 @@ Managed agent tasks and cross-host transfers include experimental features. See ## License [MIT](LICENSE) © JE-Chen. [Third-party licenses](Third_Party_License.md). + +Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 62dc809bc..dc8ecd9d5 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -64,3 +64,5 @@ Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用 ## 许可 [MIT](../LICENSE) © JE-Chen. [第三方许可](../Third_Party_License.md). + +关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。已进入发送阶段的文件传输不会因关闭页面而中断。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index a9207f1d0..6bbf02fe4 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -64,3 +64,5 @@ Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫 ## License [MIT](../LICENSE) © JE-Chen. [Third-party licenses](../Third_Party_License.md). + +關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 diff --git a/architecture.md b/architecture.md index 23374714c..2c2078654 100644 --- a/architecture.md +++ b/architecture.md @@ -338,6 +338,12 @@ only its token; controller retirement also cleans jobs after the controller has gone. Context/identity are refreshed on dispatch, without prescribing one capability for every task. Each work function authorizes its operation. Qt-free cancellation/progress live in utils/exception/cancellation.py. +Remote Desktop factory pages retire weak callback delivery before destruction. +ViewLifetime gates queued delivery; ViewApprovals wakes pending requests with denial. +Value-only upload tasks and frame conversion do not retain the page. Registry TCP/WS +sessions survive close; page-owned WebRTC cleanup runs through the detached stop queue. +Reopening creates a fresh page without reattaching those sessions. Stop failures are +logged; explicit failed-resource retry ownership remains open in Progress.md. Legacy start_worker retains its API and now rolls back failed thread starts. Remaining panel/backend integration and WebRTC splitting remain open. @@ -588,7 +594,7 @@ safe source strings/references and masks resolved input strings/dynamic keys. | `je_auto_control/wrapper/` | Platform-neutral API (`auto_control_mouse/keyboard/screen/image/record/window.py`); `platform_wrapper.py` picks the backend; `backend_contract.py` types the seam; `window_backends/`. | | `je_auto_control/{windows,osx,linux_with_x11,linux_wayland}/` | Desktop OS backends; only the running OS's backend is imported. | | `je_auto_control/{android,ios}/` | Mobile device control (adb / uiautomator2, WebDriverAgent). | -| `je_auto_control/gui/` | Optional PySide6 GUI (`[gui]` extra): `main_window.py` (menus, navigation dock, theme), `main_widget.py` (the tabbed workspace), `workspace.py` (scroll containers preserving original page identity, vector close buttons), `workspace_settings.py` (validated per-user QSettings, injectable in tests), the Qt-free `TabRegistry` in `tab_registry.py` (open caches panels; close detaches and schedules owned panels for destruction, retaining metadata and legacy forms), `navigation.py`, `theme.py`, `script_builder/`, `remote_desktop/`, `language_wrapper/`. | +| `je_auto_control/gui/` | Optional PySide6 GUI (`[gui]` extra): `main_window.py` (menus, navigation dock, theme), `main_widget.py` (the tabbed workspace), `workspace.py` (scroll containers preserving original page identity, vector close buttons), `workspace_settings.py` (validated per-user QSettings, injectable in tests), the Qt-free `TabRegistry` in `tab_registry.py` (open caches panels; close detaches and schedules owned panels for destruction, retaining metadata and embedder-supplied widgets), `navigation.py`, `theme.py`, `script_builder/`, `remote_desktop/`, `language_wrapper/`. | | `autocontrol-lsp/` | Separate distribution: language server for `AC_*` action JSON, plus a `vscode/` client. | | `native/owner_service/` | Optional Linux owner service in C, not shipped in the wheel. A root guardian (epoch journal, cgroup v2 delegation, client verification, crash recovery) starts a service that authenticates every packet by pidfd, issues leases and runs each helper in its own protected cgroup tree. `build.sh` and an administrator-reviewed manifest build it; `tests/` holds the unprivileged and root acceptance. The Python side is `helper_owner_linux.py`, selected by `owned_channel_factory.py` through a root-owned binding file. | | `native/android_helper/` | Android device-side helper in Kotlin, not shipped in the wheel (stage 2 of 4): `core/` holds `FenceLedger` (the epoch fence and per-command settlement `AndroidCommandLease` requires) and `ProtocolHandler`, tested on the JVM; `app/` is the instrumentation (shell/root-only socket, fence-aware injector), built into an APK by `.github/workflows/android-helper.yml`. Not wired into the runtime yet; protocol in its `README.md`. | diff --git a/architecture_explore.md b/architecture_explore.md index 1dc29b9f9..0cc79e155 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,510 | -| 程式碼總行數 | 230,622 | +| Python 模組總數(含周邊子專案) | 1,514 | +| 程式碼總行數 | 230,812 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1275,8 +1275,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | | `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | -| `main_widget.py` | 317 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的三個分頁與保留的 Remote Desktop 表單在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | -| `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與既有表單;不匯入 Qt。 | +| `main_widget.py` | 317 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的分頁在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | +| `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 203 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | | `workspace.py` | 121 | 可捲動的分頁容器:保留 `widget/currentWidget/indexOf/setCurrentWidget` 的原始頁面身分、移除時保留頁面所有權,並直接繪製隨 palette 變色的向量關閉鈕。 | @@ -1354,7 +1354,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 369 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 144 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 192 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(17 檔) | 8,162 | 見下。 | +| remote_desktop | `remote_desktop/`(17 檔) | 8,353 | 見下。 | | presence | `presence_tab.py` | 164 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 260 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 318 | 管理多個遠端 AutoControl REST 端點。 | @@ -1372,21 +1372,25 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,36 檔/8,162 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,353 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `folder_sync_controls.py` | 70 | Translate the existing folder toggle into owned start, reconnect handoff and explicit baseline reset. | +| `view_lifetime.py` | 85 | Retirable weak delivery from surviving transports to one Qt view. | +| `view_approvals.py` | 64 | Terminal default-deny approval ownership independent of a Qt page. | +| `view_frames.py` | 25 | Frame conversion and optional recording without retaining a remote view. | +| `view_upload.py` | 30 | Value-only legacy viewer uploads owned by the shared GUI task controller. | +| `folder_sync_controls.py` | 72 | Translate the existing folder toggle into owned start, reconnect handoff and explicit baseline reset. | | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | -| `webrtc_panel_state.py` | 156 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | -| `webrtc_panel.py` | 417 | WebRTC 子分頁主體。 | +| `webrtc_panel_state.py` | 165 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | +| `webrtc_panel.py` | 422 | WebRTC 子分頁主體。 | | `webrtc_dialogs.py` | 520 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 104 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 73 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | -| `connection_screen.py` | 679 | Quick Connect —— AnyDesk 風格單畫面入口。 | -| `viewer_panel.py` | 623 | 「控制另一台機器」子分頁。 | +| `connection_screen.py` | 667 | Quick Connect —— AnyDesk 風格單畫面入口。 | +| `viewer_panel.py` | 599 | 「控制另一台機器」子分頁。 | | `webrtc_known_hosts.py` | 346 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | -| `host_panel.py` | 433 | 「分享這台機器」子分頁。 | +| `host_panel.py` | 437 | 「分享這台機器」子分頁。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | | `webrtc_workers.py` | 237 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | | `tab.py` | 179 | 外層容器分頁。 | @@ -1416,7 +1420,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,177 個 `test_*.py`/11,429 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,178 個 `test_*.py`/11,443 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1507,7 +1511,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 145 | 40,154 | +| `gui/` | 149 | 40,344 | | `utils/mcp_server/` | 60 | 22,037 | | `utils/remote_desktop/` | 72 | 15,301 | | `utils/executor/` | 11 | 10,702 | @@ -1528,7 +1532,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,498** | **229,877** | +| **總計** | **1,502** | **230,067** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/setup.md b/docs/guides/en/setup.md index d07f836c2..a3a1d62c9 100644 --- a/docs/guides/en/setup.md +++ b/docs/guides/en/setup.md @@ -21,7 +21,7 @@ Optional extras, installed only when you need them: | `fuzzy` / `locale` | `rapidfuzz` matching, `babel` locale parsing | | `s3` / `audio` | S3 artifact store, system volume control | -Closing a factory-built feature with the tab cross releases its widget, subscriptions and timers on the next Qt event-loop turn; reopening starts a new panel. **View → Tabs** and the embedding `hide_tab` API only hide it and preserve state. `tab_registry.open/close` and `close_tab` expose explicit lifecycle operations. Legacy owner-built forms and Remote Desktop remain reusable on close while their lifecycle migration is pending. +Closing a factory-built feature with the tab cross releases its widget, subscriptions and timers on the next Qt event-loop turn; reopening starts a new panel. **View → Tabs** and the embedding `hide_tab` API only hide it and preserve state. `tab_registry.open/close` and `close_tab` expose explicit lifecycle operations. Core pages and Remote Desktop also release on close. Shared TCP/WebSocket registry sessions remain available to scripts; page-owned WebRTC sessions are stopped in the background. Reopening creates fresh controls without reattaching an existing session. Pending approvals and late page callbacks are rejected. Widgets explicitly supplied by embedders retain their existing ownership contract. **Windows on arm64** installs and runs, minus what upstream cannot ship there: neither `opencv-python` nor `cryptography` publishes a `win_arm64` diff --git a/docs/guides/zh-CN/setup.md b/docs/guides/zh-CN/setup.md index 4bdad58d0..f98ac44ac 100644 --- a/docs/guides/zh-CN/setup.md +++ b/docs/guides/zh-CN/setup.md @@ -21,7 +21,7 @@ pip install je_auto_control[gui] # 加上 PySide6 桌面应用 | `fuzzy` / `locale` | `rapidfuzz` 模糊匹配、`babel` 区域解析 | | `s3` / `audio` | S3 制品存储、系统音量控制 | -使用标签页关闭按钮关闭 factory 创建的功能面板时,下一次 Qt event loop 会释放 widget、订阅与计时器;重新打开会创建新面板。**View → Tabs** 与嵌入用的 `hide_tab` 只隐藏并保留状态。`tab_registry.open/close` 与 `close_tab` 提供明确的生命周期接口。既有的所有者表单与 Remote Desktop 在生命周期迁移完成前,关闭后仍保留以供重用。 +使用标签页关闭按钮关闭 factory 创建的功能面板时,下一次 Qt event loop 会释放 widget、订阅与计时器;重新打开会创建新面板。**View → Tabs** 与嵌入用的 `hide_tab` 只隐藏并保留状态。`tab_registry.open/close` 与 `close_tab` 提供明确的生命周期接口。核心分页与 Remote Desktop 也会在关闭时释放。共享 registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接在后台停止。重新打开会创建新控件,不自动接回现有连接;待处理批准与延迟页面回调会被拒绝。嵌入者直接提供的 widget 保持原有所有权契约。 **Windows arm64** 装得起来也跑得起来,少的是上游在那里发不出来的那些: `opencv-python` 与 `cryptography` 都没发 `win_arm64` wheel。所以 `find_image*`、 diff --git a/docs/guides/zh-TW/setup.md b/docs/guides/zh-TW/setup.md index c1ce11d85..ffe015ffa 100644 --- a/docs/guides/zh-TW/setup.md +++ b/docs/guides/zh-TW/setup.md @@ -21,7 +21,7 @@ pip install je_auto_control[gui] # 加上 PySide6 桌面應用程式 | `fuzzy` / `locale` | `rapidfuzz` 模糊比對、`babel` 地區解析 | | `s3` / `audio` | S3 產出物儲存、系統音量控制 | -以分頁關閉鈕關閉 factory 建立的功能面板時,下一次 Qt event loop 會釋放 widget、訂閱與計時器;重新開啟會建立新面板。**View → Tabs** 與嵌入用的 `hide_tab` 只隱藏並保留狀態。`tab_registry.open/close` 與 `close_tab` 提供明確的生命週期介面。既有的擁有者表單與 Remote Desktop 在生命週期遷移完成前,關閉後仍保留以供重用。 +以分頁關閉鈕關閉 factory 建立的功能面板時,下一次 Qt event loop 會釋放 widget、訂閱與計時器;重新開啟會建立新面板。**View → Tabs** 與嵌入用的 `hide_tab` 只隱藏並保留狀態。`tab_registry.open/close` 與 `close_tab` 提供明確的生命週期介面。核心分頁與 Remote Desktop 也會在關閉時釋放。共用 registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線在背景停止。重開會建立新控制項,不自動接回既有連線;待處理核准與晚到頁面回呼會被拒絕。嵌入者直接提供的 widget 維持其既有所有權契約。 **Windows arm64** 裝得起來也跑得起來,少的是上游在那裡發不出來的那些: `opencv-python` 與 `cryptography` 都沒發 `win_arm64` wheel。所以 `find_image*`、 diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 76b08b868..e25c19138 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -192,3 +192,8 @@ WebRTC statistics Statistics polling starts without waiting for the network loop. Stopping it discards late samples and releases the callback owner; a callback already executing may finish. This does not close the remote session itself. + +Remote Desktop lifetime +----------------------- + +Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index 4ae689848..8c3e3fb52 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -184,3 +184,8 @@ WebRTC 統計 統計輪詢啟動時不等待網路迴圈。停止會捨棄晚到樣本並釋放回呼擁有者; 已經開始執行的回呼仍可完成。停止統計本身不會關閉遠端連線。 + +Remote Desktop 生命週期 +----------------------- + +關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 5dc9a1777..c8d986c78 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -31,3 +31,9 @@ - **What:** A single future owns polling, with idempotent nonblocking start and terminal stop. Queued submissions are cancelled after stop, failed submissions close their coroutine, and late samples do not deliver. Stopped pollers release bound callback owners, including across the next suspended sample. - **Evidence:** Implementation passed 122 focused/consumer cases; independent review passed 36 before the final callback-retention regression. Parent reviewed that final delta and passed all 38 integration cases, plus 44 document/quality gates and a warnings-as-errors Sphinx dummy build. Scoped three-target typing, Ruff, Bandit, Pylint error checks and Radon passed. Tests use fake bridges and peers; no native media operations ran. README translations and Sphinx describe the behavior; the Actions-menu counts were remeasured from the registry. - **Open items:** Remaining F3 operations and native GUI acceptance stay in Progress.md. An already admitted application callback may finish; stop does not preempt it. + +## U-20261111-18 · 2026-11-11 · Release remote pages without retaining callback owners · #done #gui + +- **What:** Factory-owned Remote Desktop pages now release on close and reopen fresh. Weak terminal callback leases reject late delivery, pending approvals default to denial, and value-only upload tasks no longer retain pages. Registry TCP/WS sessions survive page closure. Page-owned WebRTC cleanup is scheduled independently of widget destruction. Embedder-supplied widgets retain their ownership contract. +- **Evidence:** Independent review passed 102 offscreen cases; parent integration passed 123 and the updated close-contract suites passed 24. Final document/quality gates passed 67 cases and Sphinx dummy built with warnings as errors. Three-target remote-module typing and scoped Ruff/Bandit/Radon checks passed. Fixed-source full testing at c3982928 reported 18,002 passed, 160 skipped and one obsolete Record-retention assertion; that assertion now verifies destruction and fresh reopening, with explicit embedder retention coverage. This does not claim a green full suite at the new source. Tests use fake transports and offscreen Qt, without native input, capture or media. +- **Open items:** F3 transfer cancellation, session generations, synchronous Quick Connect operations, failed-stop resource ownership and native acceptance remain in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index 129fa72e2..4bb4b0dc3 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-18 | 2026-11-11 | Release remote pages without retaining callback owners | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-17 | 2026-11-11 | Start and stop WebRTC statistics without waiting | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-16 | 2026-11-11 | Reconcile historical coverage comparison and file budgets | #snapshot #progress | [2026-11-b](2026-11-b.md) | | U-20261111-15 | 2026-11-11 | Reconcile signing and RBAC transport verification | #snapshot #security | [2026-11-b](2026-11-b.md) | @@ -636,7 +637,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 6 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 7 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index 13ea5cba2..2f00e75a2 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -120,7 +120,7 @@ def _add_tab( else: entry = TabEntry(key=key, title_key=title_key, factory=widget, category=category, default_visible=default_visible, actions=actions, - retain_on_close=key == "remote_desktop", + retain_on_close=False, on_build=lambda page: AutoControlGUIWidget._adopt_hidden_tab(self, page)) self._tab_entries.append(entry) if default_visible: @@ -257,11 +257,11 @@ def _on_tab_close_requested(self, index: int) -> None: return def close_tab(self, key: str) -> None: - """Release a feature; keep Remote Desktop reusable. + """Release a feature and its page-owned resources. Unlike ``hide_tab``, closing a feature discards its local UI state and schedules cleanup of subscriptions and timers. Reopening rebuilds it. - Remote Desktop retains live sessions until its lifecycle is migrated. + Remote Desktop keeps registry-owned sessions while retiring its view callbacks. """ self.tab_registry.close(key) diff --git a/je_auto_control/gui/remote_desktop/__init__.py b/je_auto_control/gui/remote_desktop/__init__.py index 11b5d9391..a6282367c 100644 --- a/je_auto_control/gui/remote_desktop/__init__.py +++ b/je_auto_control/gui/remote_desktop/__init__.py @@ -11,11 +11,10 @@ from je_auto_control.gui.remote_desktop.host_panel import _HostPanel from je_auto_control.gui.remote_desktop.tab import RemoteDesktopTab from je_auto_control.gui.remote_desktop.viewer_panel import ( - _FileSendThread, _ViewerPanel, + _ViewerPanel, ) __all__ = [ "RemoteDesktopTab", "QuickConnectScreen", "_HostPanel", "_ViewerPanel", "_FrameDisplay", - "_FileSendThread", ] diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 6f1ba0b71..29db49739 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -17,7 +17,6 @@ """ import functools import secrets -import threading from pathlib import Path from typing import Any, List, Optional @@ -31,10 +30,12 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._weak_call import WeakCall +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime +from je_auto_control.gui.remote_desktop.view_approvals import ApprovalRequest as _ApprovalRequest, ViewApprovals from je_auto_control.gui.remote_desktop._connect_task import connect_viewer from je_auto_control.gui.remote_desktop.connection_recent import _RecentConnectionsMixin from je_auto_control.gui.remote_desktop._helpers import ( - _StatusBadge, _build_verifying_client_context, _t, displaced_notifier, + _StatusBadge, _build_verifying_client_context, _t, wire_remote_input, ) from je_auto_control.gui.remote_desktop.remote_screen_window import ( @@ -76,23 +77,6 @@ _APPROVAL_TIMEOUT_S = 60.0 -class _ApprovalRequest: - """Threading-safe request envelope passed from host thread to GUI. - - The host's accept thread blocks on :attr:`event` while the GUI - thread shows a modal "Allow / View only / Deny" dialog and writes - ``decision``. Falls back to deny if the operator never answers. - """ - - __slots__ = ("pending", "event", "decision") - - def __init__(self, pending: PendingViewer) -> None: - self.pending = pending - self.event = threading.Event() - # One of "full", "view_only", "denied". - self.decision: str = "denied" - - class QuickConnectScreen(_RecentConnectionsMixin, TranslatableMixin, QWidget): """AnyDesk-style single-screen entry point for Remote Desktop.""" @@ -127,6 +111,9 @@ class QuickConnectScreen(_RecentConnectionsMixin, TranslatableMixin, QWidget): def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() + self._view = ViewLifetime(self) + self._approvals = ViewApprovals(self._view.callback("_show_approval_dialog"), _APPROVAL_TIMEOUT_S) + self.destroyed.connect(self._approvals.retire) self._owner = new_owner("quick-connect") self._displaced.connect(self._on_displaced) self._host_id_label = QLabel("---") @@ -190,6 +177,8 @@ def dispose(self) -> None: them. A connect that has not answered is cancelled, and the viewer it may still produce is disconnected. """ + self._view.retire() + self._approvals.retire() release_resources(self, self._cancel_pending_connect, self._close_screen_window) def retranslate(self) -> None: @@ -312,13 +301,13 @@ def _start_hosting(self) -> None: host = RemoteDesktopHost( token=token, bind="127.0.0.1", port=0, fps=10.0, quality=70, - on_pending_viewer=self._host_approval_callback, + on_pending_viewer=self._approvals.request, ) host.start() except (OSError, ValueError, RuntimeError) as error: QMessageBox.warning(self, _t("rd_quick_start_host"), str(error)) return - registry.adopt(SLOT_HOST, host, self._owner, displaced_notifier(self)) + registry.adopt(SLOT_HOST, host, self._owner, self._view.callback("_on_displaced")) self._refresh_status() def _host_approval_callback(self, pending: PendingViewer): @@ -329,14 +318,13 @@ def _host_approval_callback(self, pending: PendingViewer): then block here until the operator clicks (or the timeout fires, in which case we deny). """ - request = _ApprovalRequest(pending) - self._approval_requested.emit(request) - if not request.event.wait(timeout=_APPROVAL_TIMEOUT_S): - return False - return request.decision + return self._approvals.request(pending) def _show_approval_dialog(self, request: _ApprovalRequest) -> None: """GUI thread: ask the operator how to admit ``request.pending``.""" + if request.event.is_set() or self._view.retired: + request.resolve("denied") + return try: address = ":".join(str(part) for part in request.pending.address) transport = request.pending.transport.upper() @@ -460,9 +448,9 @@ def _on_displaced(self, slot: str, _by: str) -> None: self._refresh_status() def _viewer_callbacks(self) -> dict: - return {"on_frame": self._frame_arrived.emit, - "on_error": lambda exc: self._error_arrived.emit(str(exc)), - "on_cursor": self._cursor_moved.emit} + return {"on_frame": self._view.callback("_on_frame"), + "on_error": self._view.error_callback("_on_error"), + "on_cursor": self._view.callback("_on_remote_cursor")} def _begin_connect(self, slot: str, build, on_live) -> None: """Take ``slot``, build the viewer, and connect it off the GUI thread (see ``_connect_task``). @@ -484,7 +472,7 @@ def _begin_connect(self, slot: str, build, on_live) -> None: def _on_viewer_live(self, slot: str, on_live: WeakCall, live_viewer) -> None: """GUI thread: the connect succeeded; register the viewer and show it.""" - registry.adopt(slot, live_viewer, self._owner, displaced_notifier(self)) + registry.adopt(slot, live_viewer, self._owner, self._view.callback("_on_displaced")) on_live() def _cancel_pending_connect(self) -> None: diff --git a/je_auto_control/gui/remote_desktop/folder_sync_controls.py b/je_auto_control/gui/remote_desktop/folder_sync_controls.py index aa3cba0d4..0f19cbe9b 100644 --- a/je_auto_control/gui/remote_desktop/folder_sync_controls.py +++ b/je_auto_control/gui/remote_desktop/folder_sync_controls.py @@ -54,9 +54,11 @@ def _start(owner: Any, factory: Callable[..., FolderSyncEngine]) -> None: try: viewer = owner._require_viewer() checkpoint = history.checkpoint(viewer, path) - engine = factory(viewer, path, lambda: owner._viewer, lambda: owner._sync_engine, checkpoint) + current_viewer = owner._view.getter(lambda page: page._viewer, None) + current_engine = owner._view.getter(lambda page: page._sync_engine, None) + engine = factory(viewer, path, current_viewer, current_engine, checkpoint) owner._sync_engine = engine - bind_folder_receipts(viewer, lambda: owner._viewer, lambda: owner._sync_engine) + bind_folder_receipts(viewer, current_viewer, current_engine) engine.start() history.remember(viewer, path, engine) except (RuntimeError, OSError) as error: diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index 43926303a..6cad410ec 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -14,8 +14,9 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui.remote_desktop._helpers import ( - _CollapsibleSection, _StatusBadge, _t, displaced_notifier, + _CollapsibleSection, _StatusBadge, _t, ) from je_auto_control.gui.remote_desktop.frame_display import _FrameDisplay from je_auto_control.utils.remote_desktop import ( @@ -67,6 +68,7 @@ class _HostPanel(TranslatableMixin, QWidget): def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() + self._view = ViewLifetime(self) self._owner = new_owner("host-tab") self._displaced.connect(self._on_displaced) # Start and Stop both stop a host, which joins its threads. @@ -127,8 +129,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: def dispose(self) -> None: """Release what the tab holds beyond its widgets: its status and preview timers (the host keeps running). - Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. + Called by ``close_tab(key)`` before the widget is deleted; safe to call twice. """ + self._view.retire() + release_resources(self._host_op) release_resources(self) def retranslate(self) -> None: @@ -357,7 +361,7 @@ def _start(self) -> None: self._starting = {"bind": bind, "transport": transport, "token": token} self._pending_key = "gui_op_starting" self._host_op.run( - functools.partial(_replace_host, self._owner, build, displaced_notifier(self)), + functools.partial(_replace_host, self._owner, build, self._view.callback("_on_displaced")), on_done=self._on_started, on_error=self._on_start_failed, discard=functools.partial(_release_host, self._owner)) self._refresh_status() diff --git a/je_auto_control/gui/remote_desktop/tab.py b/je_auto_control/gui/remote_desktop/tab.py index 59c0cd18b..4c5843250 100644 --- a/je_auto_control/gui/remote_desktop/tab.py +++ b/je_auto_control/gui/remote_desktop/tab.py @@ -163,7 +163,7 @@ def _build_sub_panel_list(self) -> List[Tuple[QWidget, str]]: def dispose(self) -> None: """Release what the sub-panels hold beyond their widgets, through each panel's own ``dispose()``. - Called by ``close_tab(key, release=True)``; safe to call twice. + Called by ``close_tab(key)``; safe to call twice. Timers stop, connects and transfers still out are cancelled and the pop-out windows close. A TCP / WebSocket host or session a panel opened is left running -- it belongs to the registry, where scripts diff --git a/je_auto_control/gui/remote_desktop/view_approvals.py b/je_auto_control/gui/remote_desktop/view_approvals.py new file mode 100644 index 000000000..0e5fa4559 --- /dev/null +++ b/je_auto_control/gui/remote_desktop/view_approvals.py @@ -0,0 +1,64 @@ +"""Terminal default-deny approval ownership independent of a Qt page.""" +import threading +from typing import Callable + +from je_auto_control.utils.remote_desktop.host_access import PendingViewer + + +class ApprovalRequest: + """One decision; timeout or retirement cannot be reversed by a late dialog.""" + + def __init__(self, pending: PendingViewer) -> None: + self.pending = pending + self.event = threading.Event() + self._lock = threading.Lock() + self._decision = "denied" + + @property + def decision(self) -> str: + with self._lock: + return self._decision + + @decision.setter + def decision(self, value: str) -> None: + self.resolve(value) + + def resolve(self, value: str) -> None: + with self._lock: + if not self.event.is_set(): + self._decision = value + self.event.set() + + +class ViewApprovals: + """Wake all waiters and deny new requests when their approving view retires.""" + + def __init__(self, notify: Callable[[ApprovalRequest], None], timeout: float) -> None: + self._notify, self._timeout = notify, timeout + self._lock = threading.Lock() + self._pending: set[ApprovalRequest] = set() + self._retired = False + + def request(self, pending: PendingViewer) -> str | bool: + request = ApprovalRequest(pending) + with self._lock: + if self._retired: + return False + self._pending.add(request) + try: + self._notify(request) + completed = request.event.wait(self._timeout) + request.resolve("denied") + with self._lock: + return request.decision if completed and not self._retired else False + finally: + with self._lock: + self._pending.discard(request) + + def retire(self) -> None: + with self._lock: + self._retired = True + pending = tuple(self._pending) + self._pending.clear() + for request in pending: + request.resolve("denied") diff --git a/je_auto_control/gui/remote_desktop/view_frames.py b/je_auto_control/gui/remote_desktop/view_frames.py new file mode 100644 index 000000000..2b3a76d51 --- /dev/null +++ b/je_auto_control/gui/remote_desktop/view_frames.py @@ -0,0 +1,25 @@ +"""Frame conversion and optional recording without retaining a remote view.""" +from typing import Callable, Optional + +from PySide6.QtGui import QImage + +from je_auto_control.gui.remote_desktop._webrtc_types import AvFrameT, SessionRecorderT +from je_auto_control.gui.remote_desktop.webrtc_panel_common import _av_frame_to_qimage +from je_auto_control.utils.logging.logging_instance import autocontrol_logger + + +class ViewFrames: + def __init__(self, deliver: Callable[[QImage], None], + recorder: Optional[Callable[[], Optional[SessionRecorderT]]] = None) -> None: + self._deliver, self._recorder = deliver, recorder + + def __call__(self, frame: AvFrameT) -> None: + recorder = self._recorder() if self._recorder is not None else None + if recorder is not None: + try: + recorder.write_frame(frame) + except (RuntimeError, OSError) as error: + autocontrol_logger.debug("recorder write: %r", error) + image = _av_frame_to_qimage(frame) + if image is not None: + self._deliver(image) diff --git a/je_auto_control/gui/remote_desktop/view_lifetime.py b/je_auto_control/gui/remote_desktop/view_lifetime.py new file mode 100644 index 000000000..662cca03d --- /dev/null +++ b/je_auto_control/gui/remote_desktop/view_lifetime.py @@ -0,0 +1,85 @@ +"""Retirable weak delivery from surviving transports to one Qt view.""" +from __future__ import annotations + +import functools +import threading +import weakref +from typing import Callable, Generic, TypeVar + +from PySide6.QtCore import QObject, Qt, Signal, Slot + +_Owner = TypeVar("_Owner", bound=QObject) +_Value = TypeVar("_Value") + + +class _Relay(QObject): + delivered = Signal(str, object) + + def __init__(self, owner: QObject, deliver: Callable[[str, tuple[object, ...]], None]) -> None: + super().__init__(owner) + self._deliver = deliver + self.delivered.connect(self._dispatch, Qt.ConnectionType.QueuedConnection) + + @Slot(str, object) + def _dispatch(self, method: str, arguments: tuple[object, ...]) -> None: + self._deliver(method, arguments) + + +class ViewLifetime(Generic[_Owner]): + """A backend-held delivery lease that never owns the page or its Qt relay. + + Retirement and producer emission serialize only the short signal emission. + Widget methods run on Qt's thread outside the lock and recheck retirement. + Parent destruction retires the lease before Qt destroys the child relay. + """ + + def __init__(self, owner: _Owner) -> None: + self._owner = weakref.ref(owner) + self._lock = threading.RLock() + self._retired = False + relay = _Relay(owner, self._deliver) + self._relay = weakref.ref(relay) + owner.destroyed.connect(self.retire) + + @property + def retired(self) -> bool: + with self._lock: + return self._retired + + def retire(self) -> None: + """Permanently reject producers and events already queued for this view.""" + with self._lock: + self._retired = True + + def callback(self, method: str) -> Callable[..., None]: + """Create a producer callback containing no bound widget or Qt signal.""" + return functools.partial(self.post, method) + + def error_callback(self, method: str) -> Callable[[Exception], None]: + def error(exc: Exception) -> None: + self.post(method, str(exc)) + return error + + def post(self, method: str, *arguments: object) -> None: + with self._lock: + relay = self._relay() + if self._retired or relay is None: + return + try: + relay.delivered.emit(method, arguments) + except RuntimeError: # reason: the relay may be explicitly deleted without its parent + self._retired = True + + def _deliver(self, method: str, arguments: tuple[object, ...]) -> None: + with self._lock: + owner = None if self._retired else self._owner() + if owner is not None: + getattr(owner, method)(*arguments) + + def getter(self, read: Callable[[_Owner], _Value], default: _Value) -> Callable[[], _Value]: + """Read plain backend state weakly; never use this to query a Qt widget.""" + def get() -> _Value: + with self._lock: + owner = None if self._retired else self._owner() + return default if owner is None else read(owner) + return get diff --git a/je_auto_control/gui/remote_desktop/view_upload.py b/je_auto_control/gui/remote_desktop/view_upload.py new file mode 100644 index 000000000..8aa0dcba4 --- /dev/null +++ b/je_auto_control/gui/remote_desktop/view_upload.py @@ -0,0 +1,30 @@ +"""Value-only legacy viewer uploads owned by the shared GUI task controller.""" +import functools +from typing import TypeVar + +from PySide6.QtCore import QObject + +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime +from je_auto_control.gui.tab_task_controller import CancellationToken, TaskHandle, task_controller +from je_auto_control.utils.remote_desktop.viewer import RemoteDesktopViewer + + +_Owner = TypeVar("_Owner", bound=QObject) + +def _send(viewer: RemoteDesktopViewer, source: str, dest: str, + view: ViewLifetime[_Owner], token: CancellationToken) -> None: + token.raise_if_cancelled() + try: + result = viewer.send_file(source, dest, on_progress=view.callback("_on_file_progress_main")) + except (OSError, RuntimeError) as error: + token.raise_if_cancelled() + view.post("_on_file_complete_main", "", False, str(error), dest) + return + token.raise_if_cancelled() + view.post("_on_file_complete_main", result.transfer_id, bool(result.success), result.error or "", dest) + + +def start_upload(owner: _Owner, viewer: RemoteDesktopViewer, source: str, dest: str, + view: ViewLifetime[_Owner]) -> TaskHandle: + """Snapshot upload arguments; retiring the view does not disconnect its shared viewer.""" + return task_controller().submit(functools.partial(_send, viewer, source, dest, view), owner=owner) diff --git a/je_auto_control/gui/remote_desktop/viewer_panel.py b/je_auto_control/gui/remote_desktop/viewer_panel.py index f157dc108..eead3be56 100644 --- a/je_auto_control/gui/remote_desktop/viewer_panel.py +++ b/je_auto_control/gui/remote_desktop/viewer_panel.py @@ -11,13 +11,14 @@ QVBoxLayout, QWidget, ) -from je_auto_control.gui._daemon_thread import DaemonThread +from je_auto_control.gui._slow_op import StopQueue +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._dispose import release_resources from je_auto_control.gui.remote_desktop._connect_task import connect_viewer from je_auto_control.gui.remote_desktop._helpers import ( _CollapsibleSection, _StatusBadge, _build_insecure_client_context, - _build_verifying_client_context, _t, displaced_notifier, + _build_verifying_client_context, _t, wire_remote_input, ) from je_auto_control.gui.remote_desktop.remote_screen_window import ( @@ -59,6 +60,8 @@ class _ViewerPanel(TranslatableMixin, QWidget): def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() + self._view = ViewLifetime(self) + self._stops = StopQueue(self) # This panel's name in the registry: it only ever reads, drives and # disconnects the viewer it opened itself. self._owner = new_owner("viewer-tab") @@ -238,7 +241,8 @@ def dispose(self) -> None: reach goes -- a connect that has not answered is cancelled and the viewer it may still produce is disconnected. """ - release_resources(self, self._cancel_pending_connect, self._stop_audio_player, + self._view.retire() + release_resources(self, self._cancel_pending_connect, self._retire_audio_player, self._close_screen_window) def _connect(self) -> None: @@ -263,26 +267,22 @@ def _connect(self) -> None: self._cancel_pending_connect() registry.evict(SLOT_VIEWER, by=self._owner) authority = DeferredAuthorization.capture() - clipboard_receiver = ClipboardReceiver(authority, self._clipboard_signal.emit) + clipboard_receiver = ClipboardReceiver(authority, self._view.callback("_on_clipboard_main")) viewer: RemoteDesktopViewer self._early_frame = None # a frame of the session being replaced try: viewer = viewer_cls( host=host, port=port, token=token, - on_frame=self._frame_signal.emit, - on_error=lambda exc: self._error_signal.emit(str(exc)), - on_audio=self._audio_signal.emit, + on_frame=self._view.callback("_on_frame_main"), + on_error=self._view.error_callback("_on_error_main"), + on_audio=self._view.callback("_on_audio_main"), on_clipboard=clipboard_receiver, expected_host_id=expected_id, ssl_context=ssl_context, ) viewer.set_file_receiver(FileReceiver( - on_progress=lambda tid, done, total: - self._file_progress_signal.emit(tid, done, total), - on_complete=lambda tid, ok, err, dst: - self._file_complete_signal.emit( - tid, bool(ok), err or "", dst, - ), + on_progress=self._view.callback("_on_file_progress_main"), + on_complete=self._view.callback("_received_file_complete"), base_dir=default_download_dir(), )) clipboard_receiver.bind(viewer) @@ -315,7 +315,7 @@ def _on_connect_failed(self, error: Exception) -> None: def _on_connected(self, viewer) -> None: """GUI thread: the viewer this panel asked for is connected.""" - registry.adopt(SLOT_VIEWER, viewer, self._owner, displaced_notifier(self)) + registry.adopt(SLOT_VIEWER, viewer, self._owner, self._view.callback("_on_displaced")) self._clipboard_authority, self._connect_authority = self._connect_authority, None self._connected = True self._start_audio_player_if_requested() @@ -367,6 +367,11 @@ def _stop_audio_player(self) -> None: except (OSError, RuntimeError): pass + def _retire_audio_player(self) -> None: + player, self._audio_player = self._audio_player, None + if player is not None: + self._stops.retire(player.stop) + def _own_viewer(self): """The viewer this panel opened, or None once it is gone or replaced.""" return registry.owned(SLOT_VIEWER, self._owner) @@ -499,6 +504,9 @@ def _on_file_progress_main(self, transfer_id: str, .replace("{total}", str(total)) ) + def _received_file_complete(self, transfer_id: str, success: bool, error: str | None, dest: str) -> None: + self._on_file_complete_main(transfer_id, bool(success), error or "", dest) + def _on_file_complete_main(self, transfer_id: str, success: bool, error: str, dest_path: str) -> None: del transfer_id @@ -587,37 +595,5 @@ def _upload_file(self, source_path: str) -> None: viewer = self._own_viewer() if viewer is None: return - thread = _FileSendThread(viewer, source_path, dest, self) - thread.progress.connect(self._on_file_progress_main) - thread.completed.connect(self._on_file_complete_main) - thread.finished.connect(thread.deleteLater) - thread.start() - - -class _FileSendThread(DaemonThread): - """Run send_file off the GUI thread; bridge progress via signals.""" - - progress = Signal(str, int, int) - completed = Signal(str, bool, str, str) - - def __init__(self, viewer: RemoteDesktopViewer, source: str, dest: str, - parent=None) -> None: - super().__init__(parent) - self._viewer = viewer - self._source = source - self._dest = dest - - def run(self) -> None: - def relay(transfer_id, done, total): - self.progress.emit(transfer_id, done, total) - try: - result = self._viewer.send_file( - self._source, self._dest, on_progress=relay, - ) - except (OSError, RuntimeError) as error: - self.completed.emit("", False, str(error), self._dest) - return - self.completed.emit( - result.transfer_id, bool(result.success), - result.error or "", self._dest, - ) + from je_auto_control.gui.remote_desktop.view_upload import start_upload + start_upload(self, viewer, source_path, dest, self._view) diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py index 5bcea73d8..c2d6ec8a2 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py @@ -264,16 +264,17 @@ def _build_multi_host(self, token: str) -> MultiViewerHostT: whitelist_text = self._ip_whitelist_edit.toPlainText().strip() whitelist = [line.strip() for line in whitelist_text.splitlines() if line.strip() and not line.strip().startswith("#")] + state_changed = self._view.callback("_on_state") host = MultiViewerHost( token=token, config=_read_webrtc_config(self), trust_list=self._trust_list, read_only=self._readonly_check.isChecked(), ip_whitelist=whitelist, - on_annotation=self._signals.annotation.emit, - on_session_state=lambda _sid, state: self._signals.state.emit(state), - on_session_authenticated=self._on_session_authed, - on_pending_viewer=self._signals.pending_viewer.emit, + on_annotation=self._view.callback("_on_annotation_event"), + on_session_state=lambda _sid, state: state_changed(state), + on_session_authenticated=self._view.callback("_on_session_authed"), + on_pending_viewer=self._view.callback("_on_pending_viewer"), ) return host diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_media.py b/je_auto_control/gui/remote_desktop/webrtc_host_media.py index 50d693eff..d7a816915 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_media.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_media.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.view_frames import ViewFrames + from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart from typing import Optional @@ -74,7 +76,7 @@ def _on_toggle_accept_viewer_video(self, value: bool) -> None: try: if value: host.set_viewer_video_callback( - self._on_viewer_video_av_frame, + ViewFrames(self._view.callback("_on_viewer_video_image")), ) host.enable_accept_viewer_video() else: @@ -196,7 +198,7 @@ def _maybe_start_adaptive(self) -> None: else: self._adaptive_controller = None self._adaptive_poller = StatsPoller( - pc, self._on_host_stats, interval_s=1.0, + pc, self._view.callback("_on_host_stats"), interval_s=1.0, ) self._adaptive_poller.start() autocontrol_logger.info( @@ -264,7 +266,7 @@ def _on_session_authed(self, session_id: str) -> None: host = self._multi_host._sessions.get(session_id) if host is None: return - host.set_viewer_video_callback(self._on_viewer_video_av_frame) + host.set_viewer_video_callback(ViewFrames(self._view.callback("_on_viewer_video_image"))) def _on_viewer_video_av_frame(self, frame: AvFrameT) -> None: image = _av_frame_to_qimage(frame) diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py index 6c1b0aa81..3c68ee6c7 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py @@ -99,17 +99,14 @@ def _sync_session_pollers(self) -> None: def _make_session_stats_handler(self, session_id: str) -> Callable[[StatsSnapshot], None]: """Closure capturing session_id for the per-session poller.""" - def _handle(snapshot: StatsSnapshot) -> None: - default_webrtc_inspector().record(snapshot) - color = self._quality_color(snapshot) - self._session_cache.set( - session_id, color=color, snapshot=snapshot, - ) - # Re-paint just the dot cell for this session_id (avoid full reflow). - # One read: the GUI thread can clear it between a check and a call. - host = self._multi_host - self._signals.session_count.emit(host.session_count() if host else 0) - return _handle + return functools.partial(self._view.post, "_store_session_stats", session_id) + + def _store_session_stats(self, session_id: str, snapshot: StatsSnapshot) -> None: + default_webrtc_inspector().record(snapshot) + color = self._quality_color(snapshot) + self._session_cache.set(session_id, color=color, snapshot=snapshot) + host = self._multi_host + self._signals.session_count.emit(host.session_count() if host else 0) @staticmethod def _format_quality_tooltip(snapshot: Optional[StatsSnapshot]) -> str: diff --git a/je_auto_control/gui/remote_desktop/webrtc_panel.py b/je_auto_control/gui/remote_desktop/webrtc_panel.py index 361856a9e..535536c1b 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_panel.py +++ b/je_auto_control/gui/remote_desktop/webrtc_panel.py @@ -29,6 +29,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._slow_op import StopQueue +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui.remote_desktop._helpers import ( _t, ) @@ -95,6 +96,7 @@ class _WebRTCHostPanel(_HostUiMixin, _HostTrustMixin, _HostMediaMixin, _HostSess def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() + self._view = ViewLifetime(self) self._multi_host: Optional[MultiViewerHostT] = None self._publish_loop: Optional[HostPublishLoopWorker] = None self._manual_session_id: Optional[str] = None @@ -122,13 +124,13 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: parent=self, ) self._signals = _PanelSignals() - self._signals.state.connect(self._on_state) - self._signals.auth.connect(self._on_auth) - self._signals.pending_viewer.connect(self._on_pending_viewer) - self._signals.session_count.connect(self._on_session_count) - self._signals.viewer_video_frame.connect(self._on_viewer_video_image) - self._signals.annotation.connect(self._on_annotation_event) - self._signals.stats.connect(self._update_host_quality_dot) + self._signals.state.connect(self._view.callback("_on_state")) + self._signals.auth.connect(self._view.callback("_on_auth")) + self._signals.pending_viewer.connect(self._view.callback("_on_pending_viewer")) + self._signals.session_count.connect(self._view.callback("_on_session_count")) + self._signals.viewer_video_frame.connect(self._view.callback("_on_viewer_video_image")) + self._signals.annotation.connect(self._view.callback("_on_annotation_event")) + self._signals.stats.connect(self._view.callback("_update_host_quality_dot")) self._build_ui() self._refresh_trusted_list() self._update_availability() @@ -167,6 +169,7 @@ def dispose(self) -> None: for Stop, together with the signaling loop, the LAN advertiser, the offer or file push still out and the tray icon. """ + self._view.retire() release_resources(self, self._stop_host_if_any, self._hide_tray) def _hide_tray(self) -> None: @@ -241,6 +244,7 @@ class _WebRTCViewerPanel(_ViewerUiMixin, _ViewerFilesMixin, _ViewerAddressBookMi def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() + self._view = ViewLifetime(self) self._viewer: Optional[WebRTCDesktopViewerT] = None self._file_task: Optional[TaskHandle] = None # the upload in progress, off-thread self._offer_worker: Optional[ViewerSignalingWorker] = None @@ -269,13 +273,13 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: # Set by _ensure_screen_window(). self._screen_window: Optional[RemoteScreenWindow] = None self._signals = _PanelSignals() - self._signals.frame.connect(self._on_frame_image) - self._signals.state.connect(self._on_state) - self._signals.auth.connect(self._on_auth) - self._signals.stats.connect(self._on_stats) - self._signals.inbox_listing.connect(self._on_inbox_listing) - self._signals.inbox_op.connect(self._on_inbox_op_result) - self._signals.file_received.connect(self._on_file_received_ui) + self._signals.frame.connect(self._view.callback("_on_frame_image")) + self._signals.state.connect(self._view.callback("_on_state")) + self._signals.auth.connect(self._view.callback("_on_auth")) + self._signals.stats.connect(self._view.callback("_on_stats")) + self._signals.inbox_listing.connect(self._view.callback("_on_inbox_listing")) + self._signals.inbox_op.connect(self._view.callback("_on_inbox_op_result")) + self._signals.file_received.connect(self._view.callback("_on_file_received_ui")) self._build_ui() self._refresh_address_book() self._update_availability() @@ -350,6 +354,7 @@ def dispose(self) -> None: the pending reconnect, the signaling workers, the recording, the folder sync, the upload still out and the pop-out window go with it. """ + self._view.retire() release_resources(self, self._end_session_for_good) def _end_session_for_good(self) -> None: diff --git a/je_auto_control/gui/remote_desktop/webrtc_panel_state.py b/je_auto_control/gui/remote_desktop/webrtc_panel_state.py index ce7dbc110..c8dca4036 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_panel_state.py +++ b/je_auto_control/gui/remote_desktop/webrtc_panel_state.py @@ -4,13 +4,16 @@ from typing import TYPE_CHECKING, Callable, Optional, Sequence from je_auto_control.gui.remote_desktop.webrtc_panel_common import _PanelPart +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime if TYPE_CHECKING: from PySide6.QtCore import QPoint, QTimer from PySide6.QtWidgets import ( QCheckBox, QComboBox, QLabel, QLineEdit, QPushButton, QSpinBox, QTableWidget, QTextEdit, ) - from je_auto_control.gui.remote_desktop._webrtc_types import AvFrameT, MultiViewerHostT, WebRTCDesktopViewerT + from je_auto_control.gui.remote_desktop._webrtc_types import ( + AvFrameT, MultiViewerHostT, WebRTCDesktopViewerT, SessionRecorderT, + ) from je_auto_control.gui.remote_desktop.annotation_overlay import HostAnnotationOverlay from je_auto_control.gui.remote_desktop.viewer_screen_window import ViewerScreenWindow from je_auto_control.gui.remote_desktop.remote_screen_window import RemoteScreenWindow @@ -20,6 +23,7 @@ from je_auto_control.gui.remote_desktop.webrtc_dialogs import AddressBookList, RemoteFilesTable, TrustedViewersList from je_auto_control.utils.remote_desktop.session_quality_cache import SessionQualityCache from je_auto_control.utils.remote_desktop.webrtc_stats import StatsPoller + from je_auto_control.utils.remote_desktop.file_sync import FolderSyncEngine from je_auto_control.utils.remote_desktop.trust_list import TrustList from je_auto_control.utils.remote_desktop.address_book import AddressBook from je_auto_control.utils.remote_desktop.fingerprint import KnownHosts @@ -28,6 +32,7 @@ class _HostPanelPart(_PanelPart): """State initialized by the host panel and slots supplied by its mixins.""" + _view: ViewLifetime[_HostPanelPart] _accept_viewer_video_check: QCheckBox _adaptive_check: QCheckBox _annotation_overlay: Optional[HostAnnotationOverlay] @@ -88,6 +93,10 @@ class _HostPanelPart(_PanelPart): class _ViewerPanelPart(_PanelPart): """State initialized by the viewer panel and slots supplied by its mixins.""" + _view: ViewLifetime[_ViewerPanelPart] + _recorder: Optional[SessionRecorderT] + _sync_engine: Optional[FolderSyncEngine] + _address_book: AddressBook _address_list: AddressBookList _answer_view: QTextEdit diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py index 7c0877638..634bcd4b7 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_connection.py @@ -5,6 +5,8 @@ """ from __future__ import annotations +from je_auto_control.gui.remote_desktop.view_frames import ViewFrames + from je_auto_control.gui.remote_desktop.webrtc_panel_state import _ViewerPanelPart import functools @@ -204,14 +206,16 @@ def _build_viewer(self, token: str) -> WebRTCDesktopViewerT: token=token, config=_read_webrtc_config(self), viewer_id=self._viewer_id, - on_frame=self._on_av_frame, - on_state_change=self._signals.state.emit, - on_auth_result=self._signals.auth.emit, + on_frame=ViewFrames(self._view.callback("_on_frame_image"), + self._view.getter(lambda owner: owner._recorder, None)), + on_state_change=self._view.callback("_on_state"), + on_auth_result=self._view.callback("_on_auth"), ) - bind_folder_receipts(viewer, lambda: self._viewer, lambda: self._sync_engine, - self._on_received_file) - viewer.set_inbox_listing_callback(self._signals.inbox_listing.emit) - viewer.set_inbox_op_result_callback(self._signals.inbox_op.emit) + bind_folder_receipts(viewer, self._view.getter(lambda owner: owner._viewer, None), + self._view.getter(lambda owner: owner._sync_engine, None), + self._view.callback("_on_file_received_ui")) + viewer.set_inbox_listing_callback(self._view.callback("_on_inbox_listing")) + viewer.set_inbox_op_result_callback(self._view.callback("_on_inbox_op_result")) return viewer def _stop_viewer_if_any(self) -> None: diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py index 46e96ee9c..15cf4cd90 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py @@ -228,7 +228,7 @@ def _start_stats_polling(self) -> None: return self._stop_stats_polling() self._stats_poller = StatsPoller( - self._viewer._pc, self._on_viewer_stats_sample, + self._viewer._pc, self._view.callback("_on_viewer_stats_sample"), ) self._stats_poller.start() diff --git a/je_auto_control/gui/remote_desktop_tab.py b/je_auto_control/gui/remote_desktop_tab.py index 328beb48e..6d77b1368 100644 --- a/je_auto_control/gui/remote_desktop_tab.py +++ b/je_auto_control/gui/remote_desktop_tab.py @@ -7,11 +7,10 @@ ``_ViewerPanel``, ``_FrameDisplay`` and ``RemoteDesktopTab`` from here. """ from je_auto_control.gui.remote_desktop import ( - RemoteDesktopTab, _FileSendThread, _FrameDisplay, _HostPanel, + RemoteDesktopTab, _FrameDisplay, _HostPanel, _ViewerPanel, ) __all__ = [ "RemoteDesktopTab", "_HostPanel", "_ViewerPanel", "_FrameDisplay", - "_FileSendThread", ] diff --git a/pyproject.toml b/pyproject.toml index d8eb7681e..eb6b499f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -363,6 +363,11 @@ module = [ "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", "je_auto_control.gui.remote_desktop.webrtc_panel_state", + "je_auto_control.gui.remote_desktop.view_lifetime", + "je_auto_control.gui.remote_desktop.view_approvals", + "je_auto_control.gui.remote_desktop.view_frames", + "je_auto_control.gui.remote_desktop.view_upload", + "je_auto_control.gui.rbac_users_panel", "je_auto_control.gui.remote_desktop._connect_task", "je_auto_control.gui.remote_desktop._webrtc_types", diff --git a/test/unit_test/headless/_remote_view_owner.py b/test/unit_test/headless/_remote_view_owner.py new file mode 100644 index 000000000..90f32e2b3 --- /dev/null +++ b/test/unit_test/headless/_remote_view_owner.py @@ -0,0 +1,10 @@ +"""Data-only Qt owner for folder wiring tests; no desktop resources.""" +from PySide6.QtCore import QObject +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime + + +class RemoteViewOwner(QObject): + def __init__(self, **attributes): + super().__init__() + self.__dict__.update(attributes) + self._view = ViewLifetime(self) diff --git a/test/unit_test/headless/test_gui_registry_close.py b/test/unit_test/headless/test_gui_registry_close.py index 9272c2548..4ca49d2a0 100644 --- a/test/unit_test/headless/test_gui_registry_close.py +++ b/test/unit_test/headless/test_gui_registry_close.py @@ -135,11 +135,28 @@ def test_unknown_key_does_not_build_any_registered_page(workspace): @pytest.mark.parametrize("key", ["record", "remote_desktop"]) -def test_legacy_form_and_remote_session_owner_are_retained_on_close(workspace, key): +def test_owned_core_pages_release_on_close_and_reopen_fresh(workspace, qapp, key): + from shiboken6 import isValid entry = workspace._find_entry(key) first = entry.widget workspace.close_tab(key) - assert entry.built + assert not entry.built assert workspace.tabs.indexOf(first) == -1 + _flush(qapp) + assert not isValid(first) workspace.show_tab(key) - assert entry.widget is first + assert entry.widget is not first + assert isValid(entry.widget) + + +def test_embedder_supplied_widget_keeps_its_close_contract(workspace, qapp): + from PySide6.QtWidgets import QWidget + from shiboken6 import isValid + supplied = QWidget() + workspace._add_tab("embedded", "embedded", supplied) + workspace.show_tab("embedded") + workspace.close_tab("embedded") + _flush(qapp) + assert isValid(supplied) + workspace.show_tab("embedded") + assert workspace._find_entry("embedded").widget is supplied diff --git a/test/unit_test/headless/test_remote_view_retirement.py b/test/unit_test/headless/test_remote_view_retirement.py new file mode 100644 index 000000000..e1fffd1fc --- /dev/null +++ b/test/unit_test/headless/test_remote_view_retirement.py @@ -0,0 +1,379 @@ +"""Remote view retirement with fake transports and offscreen Qt only.""" +import gc +import threading +import weakref +from types import SimpleNamespace + +import pytest +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +from PySide6.QtCore import QEvent # noqa: E402 # reason: optional Qt imports follow importorskip +from PySide6.QtWidgets import QWidget # noqa: E402 # reason: optional Qt imports follow importorskip + +from headless.test_gui_panel_dispose import qapp as qapp # noqa: E402, F401 # reason: shared fake-only fixtures +from je_auto_control.gui.remote_desktop import connection_screen # noqa: E402 # reason: optional Qt imports follow importorskip + + +def test_retired_quick_connect_drops_live_backend_events(qapp, monkeypatch): + received = [] + monkeypatch.setattr(connection_screen.QuickConnectScreen, "_on_error", lambda self, value: received.append(value)) + screen = connection_screen.QuickConnectScreen() + callback = screen._viewer_callbacks()["on_error"] + screen.dispose() + callback(RuntimeError("late")) + qapp.processEvents() + assert received == [] + screen.deleteLater() + + +def test_retired_quick_connect_drops_already_queued_events(qapp, monkeypatch): + received = [] + monkeypatch.setattr(connection_screen.QuickConnectScreen, "_on_error", lambda self, value: received.append(value)) + screen = connection_screen.QuickConnectScreen() + callback = screen._viewer_callbacks()["on_error"] + worker = threading.Thread(target=callback, args=(RuntimeError("queued"),)) + worker.start() + worker.join(2) + screen.dispose() + qapp.processEvents() + assert received == [] + screen.deleteLater() + + +@pytest.mark.parametrize("dispose", [False, True]) +def test_surviving_callbacks_do_not_retain_deleted_quick_view(qapp, dispose): + screen = connection_screen.QuickConnectScreen() + callbacks = screen._viewer_callbacks() + reference = weakref.ref(screen) + if dispose: + screen.dispose() + screen.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + del screen + gc.collect() + assert reference() is None + callbacks["on_error"](RuntimeError("after deletion")) + callbacks["on_frame"](b"not an image") + callbacks["on_cursor"](1, 2) + qapp.processEvents() + + +def test_live_delivery_runs_on_gui_thread_and_retirement_drops_queued(qapp): + from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime + seen = [] + + class Page(QWidget): + def receive(self, value): + seen.append((value, threading.current_thread())) + + page = Page() + lease = ViewLifetime(page) + callback = lease.callback("receive") + producer = threading.Thread(target=callback, args=("live",)) + producer.start() + producer.join(2) + qapp.processEvents() + assert seen == [("live", threading.main_thread())] + callback("queued") + lease.retire() + qapp.processEvents() + assert len(seen) == 1 + page.deleteLater() + + +def test_close_denies_pending_future_and_late_approval(qapp, monkeypatch): + screen = connection_screen.QuickConnectScreen() + pending = SimpleNamespace(address=("fake", 1), transport="tcp") + announced = threading.Event() + requests = [] + original = screen._approvals._notify + + def announce(request): + requests.append(request) + original(request) + announced.set() + + monkeypatch.setattr(screen._approvals, "_notify", announce) + callback = screen._approvals.request + result = [] + worker = threading.Thread(target=lambda: result.append(callback(pending))) + worker.start() + assert announced.wait(2) + screen.dispose() + worker.join(2) + assert not worker.is_alive() and result == [False] + requests[0].decision = "full" + assert requests[0].decision == "denied" + assert callback(pending) is False + qapp.processEvents() # queued request must not construct a dialog + screen.deleteLater() + + +def test_workspace_releases_remote_page_and_preserves_registry_host(qapp, monkeypatch): + from je_auto_control.gui import main_widget + from je_auto_control.gui.remote_desktop import tab + from je_auto_control.utils.remote_desktop.registry import registry, SLOT_HOST + from headless.test_gui_panel_dispose import _Host + monkeypatch.setattr(tab, "_load_webrtc_panels", lambda: (None, None)) + workspace = main_widget.AutoControlGUIWidget() + entry = workspace._find_entry("remote_desktop") + old = entry.widget + host = _Host() + host.start() + registry.adopt(SLOT_HOST, host, old._quick_connect._owner) + workspace.close_tab("remote_desktop") + assert not entry.built + assert registry.host is host and host.is_running + workspace.show_tab("remote_desktop") + assert entry.widget is not old + assert entry.widget._webrtc_viewer_panel is None + workspace.close_tab("remote_desktop") + workspace.deleteLater() + + +def test_retired_tcp_callbacks_do_not_keep_viewer_panel(qapp, monkeypatch): + from je_auto_control.gui.remote_desktop import viewer_panel + from headless.test_gui_panel_dispose import _Viewer + panel = viewer_panel._ViewerPanel() + panel._port.setValue(1234) + panel._token.setText("fake") + # Keep the connect pending without entering any backend. + class Task: + finished = SimpleNamespace(connect=lambda callback: None) + def cancel(self): + return None + monkeypatch.setattr(viewer_panel, "connect_viewer", lambda *a, **k: Task()) + panel._connect() + backend = _Viewer.made[-1] + reference = weakref.ref(panel) + panel.dispose() + panel.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + del panel + gc.collect() + assert reference() is None + backend.kwargs["on_error"](RuntimeError("late")) + backend.kwargs["on_frame"](b"invalid") + backend.kwargs["on_audio"](b"") + qapp.processEvents() + + +def test_blocked_upload_outlives_view_without_holding_it(qapp): + from je_auto_control.gui.remote_desktop import viewer_panel + from je_auto_control.gui.remote_desktop.view_upload import start_upload + entered, finish, done = threading.Event(), threading.Event(), threading.Event() + calls = [] + + class Viewer: + def send_file(self, source, dest, on_progress): + calls.append((source, dest)) + entered.set() + assert finish.wait(3) + on_progress("id", 1, 1) + done.set() + return SimpleNamespace(transfer_id="id", success=True, error=None) + + panel = viewer_panel._ViewerPanel() + reference = weakref.ref(panel) + start_upload(panel, Viewer(), "source", "dest", panel._view) + try: + assert entered.wait(2) + panel.dispose() + panel.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + del panel + gc.collect() + assert reference() is None + finally: + finish.set() + assert done.wait(2) + qapp.processEvents() + assert calls == [("source", "dest")] + + +def test_audio_stop_runs_after_page_deletion_without_blocking_qt(qapp): + from je_auto_control.gui.remote_desktop import viewer_panel + from PySide6.QtCore import QTimer + entered, finish, done = threading.Event(), threading.Event(), threading.Event() + threads = [] + + def stop(): + threads.append(threading.current_thread()) + entered.set() + finish.wait(3) + done.set() + + panel = viewer_panel._ViewerPanel() + panel._audio_player = SimpleNamespace(stop=stop) + ticks = [] + timer = QTimer() + timer.setInterval(0) + timer.timeout.connect(lambda: ticks.append(1)) + timer.start() + try: + panel.dispose() + panel.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + assert entered.wait(2) + qapp.processEvents() + assert ticks and len(threads) == 1 and threads[0] is not threading.main_thread() + finally: + timer.stop() + finish.set() + assert done.wait(2) + + +def test_retirement_serializes_concurrent_producers_with_qt_deletion(qapp): + from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime + calls = [] + + class Page(QWidget): + def receive(self, value): + calls.append(value) + + page = Page() + lease = ViewLifetime(page) + callback = lease.callback("receive") + ready, finish = threading.Event(), threading.Event() + errors = [] + + def producer(): + ready.set() + try: + for value in range(1000): + callback(value) + finish.wait(2) + callback("after deletion") + except Exception as error: + errors.append(error) + + worker = threading.Thread(target=producer) + worker.start() + assert ready.wait(2) + lease.retire() + page.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + finish.set() + worker.join(2) + qapp.processEvents() + assert not worker.is_alive() and not errors and not calls + + +def test_audio_replacement_finishes_old_stop_before_new_start(qapp, monkeypatch): + from je_auto_control.gui.remote_desktop import viewer_panel + events = [] + active = [True] + + def stop_old(): + events.append("old stopped") + active[0] = False + + class NewPlayer: + def start(self): + assert not active[0] + events.append("new started") + active[0] = True + + def stop(self): + active[0] = False + + panel = viewer_panel._ViewerPanel() + panel._audio_available = True + panel._enable_audio.setChecked(True) + panel._audio_player = SimpleNamespace(stop=stop_old) + monkeypatch.setattr(viewer_panel, "AudioPlayer", NewPlayer) + panel._start_audio_player_if_requested() + assert events == ["old stopped", "new started"] + assert isinstance(panel._audio_player, NewPlayer) + panel.dispose() + panel.deleteLater() + + +@pytest.mark.parametrize("kind", ["host", "viewer"]) +def test_webrtc_backend_survives_deleted_view_and_cleanup_starts_after_delete(qapp, monkeypatch, kind): + from pathlib import Path + from je_auto_control.gui import tab_task_controller + from je_auto_control.gui.remote_desktop import webrtc_panel, webrtc_host_connection, webrtc_viewer_connection + from je_auto_control.gui.remote_desktop import view_frames + workers, stopped = [], [] + + def defer_start(owner, worker, **kwargs): + workers.append(worker) + return None + + class Backend: + authenticated = False + _pc = None + + def __init__(self, **kwargs): + self.callbacks = kwargs + + def set_file_received_callback(self, callback): + self.file = callback + + def set_inbox_listing_callback(self, callback): + self.listing = callback + + def set_inbox_op_result_callback(self, callback): + self.operation = callback + + def stop(self): + stopped.append(threading.current_thread()) + + stop_all = stop + + monkeypatch.setattr(tab_task_controller, "start_worker", defer_start) + monkeypatch.setattr(webrtc_host_connection, "MultiViewerHost", Backend) + monkeypatch.setattr(webrtc_viewer_connection, "WebRTCDesktopViewer", Backend) + monkeypatch.setattr(view_frames, "_av_frame_to_qimage", lambda frame: None) + if kind == "host": + panel = webrtc_panel._WebRTCHostPanel() + backend = panel._build_multi_host("token") + panel._multi_host = backend + callbacks = [(backend.callbacks["on_session_state"], ("id", "failed")), + (backend.callbacks["on_session_authenticated"], ("id",)), + (backend.callbacks["on_annotation"], ({},)), + (backend.callbacks["on_pending_viewer"], ("id", "viewer"))] + else: + panel = webrtc_panel._WebRTCViewerPanel() + backend = panel._build_viewer("token") + panel._viewer = backend + callbacks = [(backend.callbacks["on_state_change"], ("failed",)), + (backend.callbacks["on_auth_result"], (True,)), + (backend.callbacks["on_frame"], (object(),)), + (backend.file, (Path("late"),)), + (backend.listing, ([],)), (backend.operation, ("late", False, {}))] + for callback, args in callbacks: + callback(*args) + reference = weakref.ref(panel) + panel.dispose() + assert workers and not stopped + panel.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + del panel + gc.collect() + assert reference() is None + for callback, args in callbacks: + callback(*args) + qapp.processEvents() + for worker in workers: + thread = threading.Thread(target=worker.run) + thread.start() + thread.join(2) + assert not thread.is_alive() + assert len(stopped) == 1 and stopped[0] is not threading.main_thread() + + + + +def test_approval_timeout_cannot_accept_racing_late_allow(): + from je_auto_control.gui.remote_desktop.view_approvals import ViewApprovals + + def notify(request): + def timed_out(timeout): + request.resolve("full") + return False + request.event.wait = timed_out + + approvals = ViewApprovals(notify, 0) + assert approvals.request(SimpleNamespace()) is False diff --git a/test/unit_test/headless/test_webrtc_folder_receipts.py b/test/unit_test/headless/test_webrtc_folder_receipts.py index 95cacf20b..19f5a88cd 100644 --- a/test/unit_test/headless/test_webrtc_folder_receipts.py +++ b/test/unit_test/headless/test_webrtc_folder_receipts.py @@ -5,6 +5,9 @@ import pytest pytest.importorskip('PySide6.QtWidgets', exc_type=ImportError) +from PySide6.QtWidgets import QApplication +from headless.test_gui_panel_dispose import qapp as qapp # noqa: F401 +from headless._remote_view_owner import RemoteViewOwner from headless._webrtc_doubles import Bridge, Channel, FakePeerConnection from headless.test_folder_sync_content import loop from je_auto_control.gui.remote_desktop import webrtc_panel, webrtc_viewer_connection @@ -28,7 +31,9 @@ def native_folder(tmp_path, monkeypatch): notices = [] signals = SimpleNamespace(**{name: SimpleNamespace(emit=lambda *_args: None) for name in ['state', 'auth', 'inbox_listing', 'inbox_op']}) - owner = SimpleNamespace(_viewer_id='controlled', _on_av_frame=lambda _frame: None, _signals=signals, + signals.file_received = SimpleNamespace(emit=notices.append) + owner = RemoteViewOwner(_viewer_id='controlled', _recorder=None, _on_file_received_ui=notices.append, + _on_av_frame=lambda _frame: None, _signals=signals, _on_received_file=notices.append, _viewer=None, _sync_engine=None, watch=watch, store=store, _sync_dir_edit=SimpleNamespace(text=lambda: str(watch)), _sync_btn=SimpleNamespace(setText=lambda _text: None, setChecked=lambda _value: None)) @@ -72,6 +77,7 @@ def test_native_gui_receipt_does_not_echo_and_later_local_bytes_still_send(nativ loop(engine, lambda: deliver(channel), lambda: target.write_bytes(b'local edit'), lambda: None) sent = [message for message in channel.sent if isinstance(message, bytes)] assert sent == [b'local edit'], 'the GUI folder mirror echoed received bytes or consumed a local edit' + QApplication.instance().processEvents() assert notices == [target] @@ -151,6 +157,7 @@ def edited_b(): assert (owner.watch / 'shared.bin').read_bytes() == (watch_b / 'shared.bin').read_bytes() == b'local B' assert [message for message in channel_a.sent if isinstance(message, bytes)] == [b'local A'] assert [message for message in channel_b.sent if isinstance(message, bytes)] == [b'local B'] + QApplication.instance().processEvents() assert notices == [owner.watch / 'shared.bin'] finally: engine_b.stop() diff --git a/test/unit_test/headless/test_webrtc_folder_reconnect.py b/test/unit_test/headless/test_webrtc_folder_reconnect.py index 716cc6114..779d67d99 100644 --- a/test/unit_test/headless/test_webrtc_folder_reconnect.py +++ b/test/unit_test/headless/test_webrtc_folder_reconnect.py @@ -7,6 +7,7 @@ import pytest pytest.importorskip('PySide6.QtWidgets', exc_type=ImportError) +from headless._remote_view_owner import RemoteViewOwner from headless._webrtc_doubles import FakePeerConnection from headless.test_folder_sync_content import loop from headless.test_webrtc_file_commit import bounded_waits as bounded_waits, native_pair as native_pair @@ -27,7 +28,7 @@ def folder_panel(native_pair, tmp_path, monkeypatch): (watch / 'existing.bin').write_bytes(b'initial baseline') button = SimpleNamespace(setChecked=lambda _value: None, setText=lambda _text: None, setEnabled=lambda _value: None) - owner = SimpleNamespace(_viewer=native_pair.viewer, _sync_engine=None, _offer_worker=None, _answer_worker=None, + owner = RemoteViewOwner(_viewer=native_pair.viewer, _sync_engine=None, _offer_worker=None, _answer_worker=None, _recorder=None, _sync_dir_edit=SimpleNamespace(text=lambda: str(watch)), _sync_btn=button, _stop_stats_polling=lambda: None, watch=watch, warnings=[], # The panel's StopQueue runs shutdowns off the GUI thread; here, at once. From 4c625dfe696fff060b18b07defd20555f7251dac Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 18:08:09 +0800 Subject: [PATCH 028/161] Ignore local audit artifacts --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index fa2332aee..50040bd30 100644 --- a/.gitignore +++ b/.gitignore @@ -125,6 +125,7 @@ dmypy.json /.claude # Local test/smoke artifacts +.audit/ .worktrees/ .superpowers/ .test-tmp/ From 51af09d4cf4e02c0b57b372c26198bdacdbcd018 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 18:22:44 +0800 Subject: [PATCH 029/161] Expose an injectable workspace with current execution details --- CHANGELOG.md | 4 + Progress.md | 2 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture.md | 10 +- architecture_explore.md | 25 +- .../doc/new_features/v223_features_doc.rst | 16 + .../Zh/doc/new_features/v223_features_doc.rst | 14 + docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- je_auto_control/gui/diagnostics_tab.py | 11 + .../gui/language_wrapper/english.py | 11 + .../gui/language_wrapper/japanese.py | 11 + .../language_wrapper/simplified_chinese.py | 11 + .../language_wrapper/traditional_chinese.py | 11 + je_auto_control/gui/main_widget.py | 251 +--------------- je_auto_control/gui/main_window.py | 8 + je_auto_control/gui/tab_registry.py | 36 +++ je_auto_control/gui/workspace.py | 280 +++++++++++++++++- je_auto_control/gui/workspace_details.py | 95 ++++++ pyproject.toml | 1 + .../test_gui_engine_state_vlm_audit.py | 2 +- .../headless/test_gui_tab_lifecycle_audit.py | 3 +- .../headless/test_gui_workspace_navigation.py | 3 +- .../test_workspace_execution_details.py | 118 ++++++++ .../headless/test_workspace_shell.py | 208 +++++++++++++ 27 files changed, 883 insertions(+), 263 deletions(-) create mode 100644 je_auto_control/gui/workspace_details.py create mode 100644 test/unit_test/headless/test_workspace_execution_details.py create mode 100644 test/unit_test/headless/test_workspace_shell.py diff --git a/CHANGELOG.md b/CHANGELOG.md index aa0a7742b..fc8cca2cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- Add an injectable WorkspaceShell and collapsible execution details under View. + Diagnostics publishes progress and outcomes; existing embedded-widget imports, + constructors and tab visibility/close behavior remain supported. + - Closing Image Detection, Auto Click, Record, Script Executor or Remote Desktop now releases its page controls. Hiding still preserves them. Reopening starts fresh local state; the shared recorder and registry-owned TCP/WebSocket sessions survive diff --git a/Progress.md b/Progress.md index d270aa6d3..c4effff30 100644 --- a/Progress.md +++ b/Progress.md @@ -530,7 +530,7 @@ H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深 F 還缺: - **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 -- **F2 其餘**:計畫指定的 `WorkspaceShell` 介面、右側可收合詳情,以及各面板的空白/錯誤/permission states 還沒全面交付。 +- **F2 其餘**:Diagnostics 以外面板的執行詳情,以及各面板的空白/錯誤/permission states 尚未全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/README.md b/README.md index 8d928a379..22d832eae 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ Cancellation prevents later move/click steps, but cannot interrupt a native call Auto Click, Record and Script Executor own their controls and background tasks. Closing them stops local work; reopening creates fresh inputs. The shared recorder continues after its page closes, and a reopened page reads backend status (unknown when unsupported). This status does not verify native hook health. Ctrl+4 still stops scripts and auto-clicking. +View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there; other pages explicitly say when details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. + WebRTC statistics polling starts in the background and discards late samples after it stops. Windows, macOS, X11 and Wayland use different backends. Available features depend on system permissions and optional dependencies; Windows ARM64 has additional limitations. See the installation guide before choosing a deployment target. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index dc8ecd9d5..5858d855b 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -41,6 +41,8 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, 自动点击、录制与脚本执行分页各自持有控件与后台任务;关闭会停止本页任务,重新打开会建立新的输入框。共享录制器不随分页关闭,重新打开后会读取后端状态,不支持查询时显示未知;此状态不代表原生钩子健康检查。Ctrl+4 仍可停止脚本与自动点击。 +View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态;其他分页尚未提供时会明确显示。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 + WebRTC 统计轮询在后台启动,停止后会丢弃延迟到达的样本。 Windows、macOS、X11 与 Wayland 使用不同后端,实际功能取决于系统权限与可选依赖。Windows ARM64 另有限制,部署前请先阅读安装文件。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 6bbf02fe4..1b0cbc13d 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -41,6 +41,8 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, 自動點擊、錄製與腳本執行分頁各自持有控制項與背景工作;關閉會停止本頁工作,重開會建立新的輸入欄位。共用錄製器不隨分頁關閉,重開後會讀取後端狀態,不支援查詢時顯示未知;此狀態不代表原生掛鉤健康檢查。Ctrl+4 仍可停止腳本與自動點擊。 +View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態;其他分頁尚未提供時會明確顯示。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 + WebRTC 統計輪詢在背景啟動,停止後會捨棄晚到的樣本。 Windows、macOS、X11 與 Wayland 使用不同後端,實際功能取決於系統權限與選配依賴。Windows ARM64 另有限制,部署前請先閱讀安裝文件。 diff --git a/architecture.md b/architecture.md index 2c2078654..e67f39f38 100644 --- a/architecture.md +++ b/architecture.md @@ -346,6 +346,14 @@ Reopening creates a fresh page without reattaching those sessions. Stop failures logged; explicit failed-resource retry ownership remains open in Progress.md. Legacy start_worker retains its API and now rolls back failed thread starts. Remaining panel/backend integration and WebRTC splitting remain open. +WorkspaceShell accepts one authoritative TabRegistry. Weak close observers preserve +external close callbacks and detach accepted closes before release. Identity-checked +destruction clears cached pages without discarding a reopened replacement. Only the +active page's direct-child ExecutionDetailsSource feeds the collapsible right pane; +queued updates from old sources are rejected. Diagnostics publishes its existing +progress and outcomes, while task and cancellation ownership stay with the page. +AutoControlGUIWidget keeps its constructor and embedding API; MainWindow retains +the navigation dock and owns the translated execution-details View action. Diagnostics now adopts TaskController with a plain-data runner snapshot and READ_SCREEN revalidation. Its run/stop Actions and cached four-language @@ -594,7 +602,7 @@ safe source strings/references and masks resolved input strings/dynamic keys. | `je_auto_control/wrapper/` | Platform-neutral API (`auto_control_mouse/keyboard/screen/image/record/window.py`); `platform_wrapper.py` picks the backend; `backend_contract.py` types the seam; `window_backends/`. | | `je_auto_control/{windows,osx,linux_with_x11,linux_wayland}/` | Desktop OS backends; only the running OS's backend is imported. | | `je_auto_control/{android,ios}/` | Mobile device control (adb / uiautomator2, WebDriverAgent). | -| `je_auto_control/gui/` | Optional PySide6 GUI (`[gui]` extra): `main_window.py` (menus, navigation dock, theme), `main_widget.py` (the tabbed workspace), `workspace.py` (scroll containers preserving original page identity, vector close buttons), `workspace_settings.py` (validated per-user QSettings, injectable in tests), the Qt-free `TabRegistry` in `tab_registry.py` (open caches panels; close detaches and schedules owned panels for destruction, retaining metadata and embedder-supplied widgets), `navigation.py`, `theme.py`, `script_builder/`, `remote_desktop/`, `language_wrapper/`. | +| `je_auto_control/gui/` | Optional PySide6 GUI (`[gui]` extra): `main_window.py` (menus, navigation dock, theme), `main_widget.py` (the configured compatibility subclass), `workspace.py` (injectable WorkspaceShell, identity-preserving scroll containers and vector close buttons), `workspace_details.py` (immutable execution snapshots and a passive details pane), `workspace_settings.py` (validated per-user QSettings, injectable in tests), the Qt-free `TabRegistry` in `tab_registry.py` (open caches panels; close detaches and schedules owned panels for destruction, retaining metadata and embedder-supplied widgets), `navigation.py`, `theme.py`, `script_builder/`, `remote_desktop/`, `language_wrapper/`. | | `autocontrol-lsp/` | Separate distribution: language server for `AC_*` action JSON, plus a `vscode/` client. | | `native/owner_service/` | Optional Linux owner service in C, not shipped in the wheel. A root guardian (epoch journal, cgroup v2 delegation, client verification, crash recovery) starts a service that authenticates every packet by pidfd, issues leases and runs each helper in its own protected cgroup tree. `build.sh` and an administrator-reviewed manifest build it; `tests/` holds the unprivileged and root acceptance. The Python side is `helper_owner_linux.py`, selected by `owned_channel_factory.py` through a root-owned binding file. | | `native/android_helper/` | Android device-side helper in Kotlin, not shipped in the wheel (stage 2 of 4): `core/` holds `FenceLedger` (the epoch fence and per-command settlement `AndroidCommandLease` requires) and `ProtocolHandler`, tested on the JVM; `app/` is the instrumentation (shell/root-only socket, fence-aware injector), built into an APK by `.github/workflows/android-helper.yml`. Not wired into the runtime yet; protocol in its `README.md`. | diff --git a/architecture_explore.md b/architecture_explore.md index 0cc79e155..43ef3821c 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,514 | -| 程式碼總行數 | 230,812 | +| Python 模組總數(含周邊子專案) | 1,515 | +| 程式碼總行數 | 231,047 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1274,12 +1274,13 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | -| `main_window.py` | 442 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | -| `main_widget.py` | 317 | 工作區:擁有 `QTabWidget`,依 `tab_registry.TAB_SPECS` 註冊 49 個分頁,並暴露 show/hide/close/activate/list API 給選單列與導覽面板。只有預設開啟的分頁在啟動時建立,其餘第一次開啟才匯入模組、建立 widget。核心分頁在 `_own_tab_builders` 宣告 `(label_key, handler)` 動作對。 | -| `tab_registry.py` | 198 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | +| `main_window.py` | 450 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | +| `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | +| `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 203 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | -| `workspace.py` | 121 | 可捲動的分頁容器:保留 `widget/currentWidget/indexOf/setCurrentWidget` 的原始頁面身分、移除時保留頁面所有權,並直接繪製隨 palette 變色的向量關閉鈕。 | +| `workspace.py` | 393 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情。 | +| `workspace_details.py` | 95 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 166 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 131 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | @@ -1304,7 +1305,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 7,939 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 7,983 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1354,7 +1355,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 369 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 144 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 192 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(17 檔) | 8,353 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,353 | 見下。 | | presence | `presence_tab.py` | 164 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 260 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 318 | 管理多個遠端 AutoControl REST 端點。 | @@ -1363,7 +1364,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | usb_devices | `usb_devices_tab.py` | 168 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 290 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | -| diagnostics | `diagnostics_tab.py` | 221 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | +| diagnostics | `diagnostics_tab.py` | 232 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1420,7 +1421,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,178 個 `test_*.py`/11,443 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,180 個 `test_*.py`/11,455 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1511,7 +1512,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 149 | 40,344 | +| `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 60 | 22,037 | | `utils/remote_desktop/` | 72 | 15,301 | | `utils/executor/` | 11 | 10,702 | @@ -1532,7 +1533,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,502** | **230,067** | +| **總計** | **1,503** | **230,302** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index e25c19138..b9dd22fc8 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -197,3 +197,19 @@ Remote Desktop lifetime ----------------------- Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. + +Execution details +~~~~~~~~~~~~~~~~~ + +**View → Execution details** (``Ctrl+Shift+D``) expands a scrollable right pane. +It starts collapsed. Diagnostics publishes actual run progress, stop requests, +results and errors; pages without a publisher show an explicit unavailable state. +Switching or closing a page disconnects its updates, including queued old results. +The pane does not start work or own cancellation. Use the page's Actions menu. + +Embedders can construct ``WorkspaceShell(registry, parent)`` from +``je_auto_control.gui.workspace``. The supplied ``TabRegistry`` remains authoritative, +including direct registry closes. ``AutoControlGUIWidget(parent)`` keeps its import +path, default features and show/hide/list APIs. Hiding retains a page; closing an +owned page rebuilds it on reopening. A registry outliving its shell forgets pages +when Qt destroys them. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index 8c3e3fb52..dc633bdb3 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -189,3 +189,17 @@ Remote Desktop 生命週期 ----------------------- 關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 + +執行詳情 +~~~~~~~~ + +**View → 執行詳情** (``Ctrl+Shift+D``)展開可捲動的右側詳情,初始為收合。 +診斷分頁提供實際執行進度、停止要求、結果與錯誤;未提供詳情的分頁會明確顯示。 +切換或關閉分頁會斷開更新,包含已排隊的舊結果。詳情不啟動工作,也不持有取消權限; +操作仍使用分頁的 Actions 選單。 + +嵌入程式可從 ``je_auto_control.gui.workspace`` 建立 ``WorkspaceShell(registry, parent)``。 +傳入的 ``TabRegistry`` 是唯一的分頁資料來源,直接呼叫 registry 關閉也會移除畫面。 +``AutoControlGUIWidget(parent)`` 保留匯入路徑、預設功能與 show/hide/list API。 +隱藏會保留分頁;關閉擁有的分頁後,重開會重新建立。Registry 若比工作區存活更久, +會在 Qt 銷毀頁面時清除該快取。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c8d986c78..4d085091c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -37,3 +37,9 @@ - **What:** Factory-owned Remote Desktop pages now release on close and reopen fresh. Weak terminal callback leases reject late delivery, pending approvals default to denial, and value-only upload tasks no longer retain pages. Registry TCP/WS sessions survive page closure. Page-owned WebRTC cleanup is scheduled independently of widget destruction. Embedder-supplied widgets retain their ownership contract. - **Evidence:** Independent review passed 102 offscreen cases; parent integration passed 123 and the updated close-contract suites passed 24. Final document/quality gates passed 67 cases and Sphinx dummy built with warnings as errors. Three-target remote-module typing and scoped Ruff/Bandit/Radon checks passed. Fixed-source full testing at c3982928 reported 18,002 passed, 160 skipped and one obsolete Record-retention assertion; that assertion now verifies destruction and fresh reopening, with explicit embedder retention coverage. This does not claim a green full suite at the new source. Tests use fake transports and offscreen Qt, without native input, capture or media. - **Open items:** F3 transfer cancellation, session generations, synchronous Quick Connect operations, failed-stop resource ownership and native acceptance remain in Progress.md. + +## U-20261111-19 · 2026-11-11 · Add an injectable workspace and live execution details · #done #gui + +- **What:** WorkspaceShell uses the supplied registry and preserves the embedded AutoControlGUIWidget entry point. Weak close observers honor direct registry closes and refused closes. Page destruction clears only its own cached identity. View exposes collapsible execution details; Diagnostics publishes real progress, stop and terminal states without moving task ownership. Active-source checks reject stale detail signals. All four language catalogues are updated. +- **Evidence:** Implementation passed 216 focused tests and 21 quality gates. Independent review passed 171 tests, verified Qt-free registry import, and found one line-length issue that was corrected. Parent integration passed 90 tests and quality gates plus a warnings-as-errors Sphinx dummy build. Ordinary and real-Qt typing passed all three targets for six changed GUI modules. Ruff, Bandit and Radon passed; raw Pylint error output retains known compiled-Qt import inference failures. Parent viewed standalone 640x420 offscreen renders with 16pt text and confirmed wrapping, vertical scrolling and collapsed width. This is not native or mixed-DPI acceptance. +- **Open items:** Other panel execution/permission states and native acceptance remain in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index 4bb4b0dc3..26db0e387 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-19 | 2026-11-11 | Add an injectable workspace and live execution details | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-18 | 2026-11-11 | Release remote pages without retaining callback owners | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-17 | 2026-11-11 | Start and stop WebRTC statistics without waiting | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-16 | 2026-11-11 | Reconcile historical coverage comparison and file budgets | #snapshot #progress | [2026-11-b](2026-11-b.md) | @@ -637,7 +638,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 7 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 8 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/gui/diagnostics_tab.py b/je_auto_control/gui/diagnostics_tab.py index 6476133e0..9c2a89476 100644 --- a/je_auto_control/gui/diagnostics_tab.py +++ b/je_auto_control/gui/diagnostics_tab.py @@ -13,6 +13,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.diagnostics_capabilities import CapabilityView from je_auto_control.gui.mcp_discovery_view import MCPDiscoveryView +from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsSource, ExecutionPhase from je_auto_control.gui.task_controller import TaskController, TaskHandle, TaskOutcome from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -61,6 +62,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() self._view = _DiagnosticViewState() + self.execution_details = ExecutionDetailsSource(self) self._task_controller = TaskController(self) self._active_task: Optional[TaskHandle] = None self._summary_label = QLabel(_t("diag_summary_idle")) @@ -77,6 +79,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: ) self._build_layout() self._apply_table_headers() + self._render_summary() def _build_layout(self) -> None: # The run command runs from the Actions menu; the tab keeps only @@ -186,6 +189,14 @@ def _render_summary(self) -> None: if self._active_task is not None and self._view.total: progress = _t('diag_progress').format(completed=self._view.completed, total=self._view.total) self._progress_label.setText(progress) + phase: ExecutionPhase + if self._view.kind == 'result': + phase = 'succeeded' if report is not None and report.ok else 'error' + else: + phase = self._view.kind + self.execution_details.publish(ExecutionDetails( + phase, text, self._view.completed, self._view.total if self._active_task is not None else 0, + )) def closeEvent(self, event: QCloseEvent) -> None: """Abandon this run's display and request cleanup without blocking or closing another owner.""" diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index b0c50b603..842d3e54e 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -2070,3 +2070,14 @@ 'mcp_disclosure_page_size': 'Tools per progressive/static page', 'mcp_disclosure_plan': 'Preview MCP server configuration' }) + +english_word_dict.update({'workspace_details_title': 'Execution details', + 'workspace_details_empty': 'Select a feature to see execution details.', + 'workspace_details_unavailable': 'This feature does not publish execution details.', + 'workspace_phase_idle': 'Idle', + 'workspace_phase_running': 'Running', + 'workspace_phase_stopping': 'Stopping', + 'workspace_phase_succeeded': 'Completed', + 'workspace_phase_cancelled': 'Cancelled', + 'workspace_phase_error': 'Error', + 'workspace_phase_unavailable': 'Unavailable'}) diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index d2f1c3e3a..84f87937e 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -1962,3 +1962,14 @@ 'mcp_disclosure_page_size': '段階/固定モードのページ件数', 'mcp_disclosure_plan': 'MCP サーバー設定をプレビュー' }) + +japanese_word_dict.update({'workspace_details_title': '実行の詳細', + 'workspace_details_empty': '機能を選択すると実行の詳細を表示します。', + 'workspace_details_unavailable': 'この機能は実行の詳細を提供していません。', + 'workspace_phase_idle': '待機中', + 'workspace_phase_running': '実行中', + 'workspace_phase_stopping': '停止中', + 'workspace_phase_succeeded': '完了', + 'workspace_phase_cancelled': 'キャンセル済み', + 'workspace_phase_error': 'エラー', + 'workspace_phase_unavailable': '利用不可'}) diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 2f0df06ec..b66f45941 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1904,3 +1904,14 @@ 'mcp_disclosure_page_size': '渐进/固定模式的每页工具数', 'mcp_disclosure_plan': '预览 MCP 服务器设置' }) + +simplified_chinese_word_dict.update({'workspace_details_title': '执行详情', + 'workspace_details_empty': '选择功能以查看执行详情。', + 'workspace_details_unavailable': '此功能尚未提供执行详情。', + 'workspace_phase_idle': '待命', + 'workspace_phase_running': '执行中', + 'workspace_phase_stopping': '停止中', + 'workspace_phase_succeeded': '已完成', + 'workspace_phase_cancelled': '已取消', + 'workspace_phase_error': '错误', + 'workspace_phase_unavailable': '无法使用'}) diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index e67dacc9e..4f088a189 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1912,3 +1912,14 @@ 'mcp_disclosure_page_size': '逐步/固定模式的每頁工具數', 'mcp_disclosure_plan': '預覽 MCP 伺服器設定' }) + +traditional_chinese_word_dict.update({'workspace_details_title': '執行詳情', + 'workspace_details_empty': '選取功能以查看執行詳情。', + 'workspace_details_unavailable': '此功能尚未提供執行詳情。', + 'workspace_phase_idle': '待命', + 'workspace_phase_running': '執行中', + 'workspace_phase_stopping': '停止中', + 'workspace_phase_succeeded': '已完成', + 'workspace_phase_cancelled': '已取消', + 'workspace_phase_error': '錯誤', + 'workspace_phase_unavailable': '無法使用'}) diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index 2f00e75a2..b2d02fb38 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -1,21 +1,14 @@ -"""Workspace widget: owns the tab bar and the registry of every tab it can open.""" -from typing import Any, Dict, List, Optional +"""Configured application workspace preserving the embedded-widget entry point.""" +from typing import Any, Dict from PySide6.QtCore import Signal, QObject from PySide6.QtGui import QKeyEvent, Qt -from PySide6.QtWidgets import ( - QWidget, QVBoxLayout, QLabel, -) +from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel from je_auto_control.gui._tab_task import stop_all_script_runs -from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper -from je_auto_control.gui.tab_registry import ( - TAB_SPECS, MenuActions, TabEntry, TabRegistry, WidgetFactory, lazy_factory, -) -from je_auto_control.gui.workspace import ScrollableTabs +from je_auto_control.gui.tab_registry import TAB_SPECS, TabEntry, TabRegistry, lazy_factory +from je_auto_control.gui.workspace import WorkspaceShell -# Kept under its old name: tests and embedders read ``_tab_entries`` rows as this. _TabEntry = TabEntry @@ -24,52 +17,18 @@ class _WorkerSignals(QObject): error = Signal(str) -# ============================================================================= -# Main Widget -# ============================================================================= -class AutoControlGUIWidget( - TranslatableMixin, - QWidget, -): - """Owns the QTabWidget and exposes show/hide/list APIs for the menu bar.""" +class AutoControlGUIWidget(WorkspaceShell): + """Configure the standard feature registry while preserving embedding APIs.""" - tabs_changed = Signal() - current_tab_changed = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - self._tr_init() - layout = QVBoxLayout() - layout.setContentsMargins(0, 0, 0, 0) - - self._tab_entries: List[TabEntry] = [] - self.tab_registry = TabRegistry(self._tab_entries, on_close=self._detach_closed_tab) - - self.tabs = ScrollableTabs() - self.tabs.setTabsClosable(True) - self.tabs.setDocumentMode(True) - self.tabs.setUsesScrollButtons(True) - # Without this the widest page's minimum size is the window's: the - # Script Builder alone kept the window from going under ~860 px. - self.tabs.setMinimumSize(360, 240) - self.tabs.tabCloseRequested.connect(self._on_tab_close_requested) - - # The window opens on record / script_builder / remote_desktop. Every - # other tab is registered but not built: its module is imported and - # its widget constructed the first time it is opened, from the - # navigation panel or the View menu. + def __init__(self, parent: QWidget | None = None) -> None: + self._tab_entries: list[TabEntry] = [] + super().__init__(TabRegistry(self._tab_entries), parent) own_tabs = self._own_tab_builders() for spec in TAB_SPECS: builder, actions = own_tabs.get(spec.key, (None, ())) self._add_tab(spec.key, spec.title_key, builder or lazy_factory(spec.module, spec.class_name), category=spec.category, default_visible=spec.default_visible, actions=actions) - layout.addWidget(self.tabs) - - self.setLayout(layout) - - self.tabs.currentChanged.connect(self._on_current_tab_changed) - def _own_tab_builders(self) -> Dict[str, Any]: """Remote Desktop keeps its existing optional-dependency fallback.""" @@ -104,196 +63,6 @@ def _build_remote_desktop_tab() -> QWidget: layout.addStretch() return placeholder - # --- tab registry API ---------------------------------------------------- - - def _add_tab( - self, key: str, title_key: str, widget: QWidget | WidgetFactory, - category: str = "core", default_visible: bool = False, - actions: MenuActions = (), - ) -> None: - """Register a tab from a widget, or from a factory called on first open.""" - if isinstance(widget, QWidget): - built = widget - entry = TabEntry(key=key, title_key=title_key, factory=lambda: built, - category=category, default_visible=default_visible, actions=actions, - retain_on_close=True) - else: - entry = TabEntry(key=key, title_key=title_key, factory=widget, - category=category, default_visible=default_visible, actions=actions, - retain_on_close=False, - on_build=lambda page: AutoControlGUIWidget._adopt_hidden_tab(self, page)) - self._tab_entries.append(entry) - if default_visible: - self.tabs.addTab(entry.widget, language_wrapper.translate(title_key, title_key)) - elif isinstance(widget, QWidget): - AutoControlGUIWidget._adopt_hidden_tab(self, entry.widget) - - def _adopt_hidden_tab(self, widget: QWidget) -> None: - # Owned from the start: an unparented hidden tab outlived this - # widget, and one a registry held a listener of (Presence) kept - # its timer running after every window that built it was gone. - if self.tabs.indexOf(widget) == -1: - widget.setParent(self) - widget.hide() - - @staticmethod - def _is_built(entry: Any) -> bool: - return bool(getattr(entry, "built", True)) - - def _built_entries(self) -> List[Any]: - return [entry for entry in self._tab_entries if self._is_built(entry)] - - def _is_open(self, entry: Any) -> bool: - return self._is_built(entry) and self.tabs.indexOf(entry.widget) != -1 - - def _on_current_tab_changed(self, _index: int) -> None: - self.current_tab_changed.emit() - - def current_tab_menu_actions(self) -> list: - """Return ``[(label_key, callable), ...]`` for the active tab. - - Core tabs declare their actions at registration time; feature tabs - may instead expose a ``menu_actions()`` method returning the same - shape. The menu bar renders these under the Actions menu so tabs - stay button-free. - """ - widget = self.tabs.currentWidget() - if widget is None: - return [] - for entry in self._built_entries(): - if entry.widget is widget: - if entry.actions: - return list(entry.actions) - provider = getattr(widget, "menu_actions", None) - if callable(provider): - return list(provider()) - return [] - return [] - - def _find_entry(self, key: str): - for entry in self._tab_entries: - if entry.key == key: - return entry - return None - - def sync_engine_tabs(self) -> None: - """Let every built tab that mirrors an engine re-read its state (after Tools > Start). - - A tab not built yet reads the engine when it is. - """ - for entry in self._tab_entries: - if not AutoControlGUIWidget._is_built(entry): - continue - sync = getattr(entry.widget, "sync_with_engine", None) - if callable(sync): - sync() - - def list_registered_tabs(self) -> list: - """Return metadata for the View → Tabs menu and the navigation panel. - - Reading it builds nothing: a tab never opened is listed as not visible. - """ - return [ - { - "key": entry.key, - "title": language_wrapper.translate(entry.title_key, entry.title_key), - "visible": self._is_open(entry), - "category": entry.category, - } - for entry in self._tab_entries - ] - - def current_tab_key(self) -> Optional[str]: - """Key of the tab on screen, or ``None`` when every tab is closed.""" - widget = self.tabs.currentWidget() - for entry in self._built_entries(): - if entry.widget is widget: - return str(entry.key) - return None - - def show_tab(self, key: str) -> None: - """Open the tab ``key`` (building it if this is its first time) and select it.""" - entry = self._find_entry(key) - if entry is None or self._is_open(entry): - return - target_index = 0 - for candidate in self._tab_entries: - if candidate.key == key: - break - if self._is_open(candidate): - target_index += 1 - title = language_wrapper.translate(entry.title_key, entry.title_key) - page = self.tab_registry.open(key) - self.tabs.insertTab(target_index, page, title) - self.tabs.setCurrentWidget(page) - self.tabs_changed.emit() - - def activate_tab(self, key: str) -> bool: - """Bring the tab ``key`` to the front, opening it first if needed.""" - entry = self._find_entry(key) - if entry is None: - return False - if self._is_open(entry): - self.tabs.setCurrentWidget(entry.widget) - else: - self.show_tab(key) - return True - - def hide_tab(self, key: str) -> None: - """Close the tab ``key``; its widget is kept for the next time it is opened.""" - entry = self._find_entry(key) - if entry is None or not self._is_built(entry): - return - index = self.tabs.indexOf(entry.widget) - if index != -1: - self.tabs.removeTab(index) - self.tabs_changed.emit() - - def _on_tab_close_requested(self, index: int) -> None: - widget = self.tabs.widget(index) - for entry in self._built_entries(): - if entry.widget is widget: - self.close_tab(entry.key) - return - - def close_tab(self, key: str) -> None: - """Release a feature and its page-owned resources. - - Unlike ``hide_tab``, closing a feature discards its local UI state and - schedules cleanup of subscriptions and timers. Reopening rebuilds it. - Remote Desktop keeps registry-owned sessions while retiring its view callbacks. - """ - self.tab_registry.close(key) - - def _detach_closed_tab(self, page: QWidget) -> None: - """Remove a closed page before its deferred Qt destruction.""" - index = self.tabs.indexOf(page) - if index != -1: - self.tabs.removeTab(index) - self.tabs_changed.emit() - - def _translate(self, key: str) -> str: - return language_wrapper.translate(key, key) - - def retranslate(self) -> None: - """Relabel tab titles and propagate into every child tab.""" - self.tabs.retranslate() - for entry in self._built_entries(): - index = self.tabs.indexOf(entry.widget) - if index != -1: - self.tabs.setTabText( - index, language_wrapper.translate(entry.title_key, entry.title_key), - ) - TranslatableMixin.retranslate(self) - # Child class tabs get their own retranslate if they implement one. - for entry in self._built_entries(): - callback = getattr(entry.widget, "retranslate", None) - if callable(callback) and entry.widget is not self: - try: - callback() - except (RuntimeError, AttributeError): - continue - def open_script_file(self, path: str) -> None: """Load a JSON script into the Script Executor tab and focus it.""" if self.activate_tab("script"): diff --git a/je_auto_control/gui/main_window.py b/je_auto_control/gui/main_window.py index eb41f3802..e116a69bc 100644 --- a/je_auto_control/gui/main_window.py +++ b/je_auto_control/gui/main_window.py @@ -140,6 +140,12 @@ def _build_navigation(self) -> None: self._sidebar_action = self._navigation_dock.toggleViewAction() self._sidebar_action.setShortcut(QKeySequence("Ctrl+B")) self.addAction(self._sidebar_action) + self._details_action = QAction(self) + self._details_action.setCheckable(True) + self._details_action.setShortcut(QKeySequence("Ctrl+Shift+D")) + self._details_action.toggled.connect(self.auto_control_gui_widget.set_details_visible) + self.auto_control_gui_widget.details_visibility_changed.connect(self._details_action.setChecked) + self.addAction(self._details_action) self._refresh_navigation() def _refresh_navigation(self) -> None: @@ -203,6 +209,8 @@ def _build_view_menu(self) -> QMenu: menu.addAction(self._search_action) self._sidebar_action.setText(_t("menu_view_sidebar", "Navigation Panel")) menu.addAction(self._sidebar_action) + self._details_action.setText(_t("workspace_details_title", "Execution details")) + menu.addAction(self._details_action) tabs_menu = menu.addMenu(_t("menu_view_tabs", "Tabs")) self._view_menu = tabs_menu self._rebuild_tabs_menu() diff --git a/je_auto_control/gui/tab_registry.py b/je_auto_control/gui/tab_registry.py index e5d67fb14..c7ffe3831 100644 --- a/je_auto_control/gui/tab_registry.py +++ b/je_auto_control/gui/tab_registry.py @@ -11,6 +11,7 @@ """ from __future__ import annotations +import weakref from dataclasses import dataclass, field from importlib import import_module from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple @@ -69,10 +70,23 @@ def widget(self) -> Any: """The tab's widget, building it on first access.""" if self._widget is None: self._widget = self.factory() + self._track_destruction() if self.on_build is not None: self.on_build(self._widget) return self._widget + def _track_destruction(self) -> None: + destroyed = getattr(self._widget, "destroyed", None) + if destroyed is None: + return + entry_ref, page_ref = weakref.ref(self), weakref.ref(self._widget) + + def forget() -> None: + entry = entry_ref() + if entry is not None and entry._widget is page_ref(): + entry._widget = None + destroyed.connect(forget) + def release(self) -> bool: """Drop an owned panel and schedule its Qt cleanup, retaining metadata. @@ -105,6 +119,26 @@ def __init__(self, entries: list[TabEntry], *, on_close: Optional[Callable[[QWidget], None]] = None) -> None: self._entries = entries self._on_close = on_close + self._close_listeners: set[Callable[[QWidget], None]] = set() + + @property + def entries(self) -> tuple[TabEntry, ...]: + """Return registered metadata without building any page.""" + return tuple(self._entries) + + def add(self, entry: TabEntry) -> None: + """Register metadata in this registry's authoritative order.""" + if self._find(entry.key) is not None: + raise AutoControlActionException(f"Duplicate tab: {entry.key}") + self._entries.append(entry) + + def subscribe_close(self, callback: Callable[[QWidget], None]) -> Callable[[], None]: + """Observe accepted closes before release; return an idempotent disconnector.""" + self._close_listeners.add(callback) + + def disconnect() -> None: + self._close_listeners.discard(callback) + return disconnect def _find(self, key: str) -> Optional[TabEntry]: return next((entry for entry in self._entries if entry.key == key), None) @@ -131,6 +165,8 @@ def close(self, key: str) -> None: return if self._on_close is not None: self._on_close(page) + for callback in tuple(self._close_listeners): + callback(page) entry.release() diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index ccf26ad89..83bb643be 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -1,9 +1,14 @@ -"""Scrollable tab pages that preserve the embedded workspace's widget API.""" -from typing import Any +"""Registry-owned tab workspace with scrollable pages and passive execution details.""" +import weakref +from typing import Any, Callable, List, Optional -from PySide6.QtCore import QPointF, Qt +from PySide6.QtCore import QPointF, Qt, QObject, QMetaObject, Signal, Slot from PySide6.QtGui import QPaintEvent, QPainter, QPen -from PySide6.QtWidgets import QAbstractButton, QScrollArea, QTabBar, QTabWidget, QWidget +from PySide6.QtWidgets import QAbstractButton, QScrollArea, QTabBar, QTabWidget, QWidget, QSplitter, QVBoxLayout + +from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.tab_registry import MenuActions, TabEntry, TabRegistry, WidgetFactory +from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsPane, ExecutionDetailsSource from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper @@ -119,3 +124,270 @@ def retranslate(self) -> None: button = self.tabBar().tabButton(index, QTabBar.ButtonPosition.RightSide) if isinstance(button, _CloseButton): button.retranslate() + + +class WorkspaceShell(TranslatableMixin, QWidget): + """Present one supplied tab registry and the active page's execution details.""" + + tabs_changed = Signal() + current_tab_changed = Signal() + details_visibility_changed = Signal(bool) + + def __init__(self, registry: TabRegistry, parent: QWidget | None = None) -> None: + super().__init__(parent) + self._tr_init() + self.tab_registry = registry + self.tabs = ScrollableTabs() + self.tabs.setDocumentMode(True) + self.tabs.setUsesScrollButtons(True) + self.tabs.setMinimumSize(360, 240) + self.tabs.tabCloseRequested.connect(self._on_tab_close_requested) + self.details = ExecutionDetailsPane() + self._details_source: weakref.ReferenceType[ExecutionDetailsSource] | None = None + self._details_connection: QMetaObject.Connection | None = None + self._splitter = QSplitter(Qt.Orientation.Horizontal, self) + self._splitter.addWidget(self.tabs) + self._splitter.addWidget(self.details) + self._splitter.setCollapsible(0, False) + self._splitter.setStretchFactor(0, 1) + self.details.hide() + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.addWidget(self._splitter) + owner = weakref.ref(self) + + def closed(page: QWidget) -> None: + shell = owner() + if shell is not None: + shell._detach_closed_tab(page) + self.destroyed.connect(registry.subscribe_close(closed)) + self.tabs.currentChanged.connect(self._on_current_tab_changed) + for entry in registry.entries: + if entry.default_visible: + self.show_tab(entry.key) + self._bind_details() + + def set_details_visible(self, visible: bool) -> None: + """Expand or collapse execution details without starting any work.""" + self.details.setVisible(visible) + if visible: + self._splitter.setSizes([max(360, self.width() - 260), 260]) + self.details_visibility_changed.emit(visible) + + def _bind_details(self) -> None: + if self._details_connection is not None: + QObject.disconnect(self._details_connection) + self._details_connection = None + self._details_source = None + page = self.tabs.currentWidget() + source = None if page is None else page.findChild( + ExecutionDetailsSource, options=Qt.FindChildOption.FindDirectChildrenOnly, + ) + if source is None: + self.details.display(None, selected=page is not None) + else: + self._details_source = weakref.ref(source) + self._details_connection = source.changed.connect(self._on_details_changed) + self.details.display(source.snapshot, selected=True) + + @Slot(object) + def _on_details_changed(self, snapshot: ExecutionDetails) -> None: + source = None if self._details_source is None else self._details_source() + if source is not None and self.sender() is source: + self.details.display(snapshot, selected=True) + + def _add_tab( + self, key: str, title_key: str, widget: QWidget | WidgetFactory, + category: str = "core", default_visible: bool = False, + actions: MenuActions = (), + ) -> None: + """Register a tab from a widget, or from a factory called on first open.""" + if isinstance(widget, QWidget): + built = widget + entry = TabEntry(key=key, title_key=title_key, factory=lambda: built, + category=category, default_visible=default_visible, actions=actions, + retain_on_close=True) + else: + owner = weakref.ref(self) + + def adopt(page: QWidget) -> None: + shell = owner() + if shell is not None: + shell._adopt_hidden_tab(page) + entry = TabEntry(key=key, title_key=title_key, factory=widget, + category=category, default_visible=default_visible, actions=actions, + retain_on_close=False, + on_build=adopt) + self.tab_registry.add(entry) + if default_visible: + self.tabs.addTab(entry.widget, language_wrapper.translate(title_key, title_key)) + elif isinstance(widget, QWidget): + WorkspaceShell._adopt_hidden_tab(self, entry.widget) + + def _adopt_hidden_tab(self, widget: QWidget) -> None: + # Owned from the start: an unparented hidden tab outlived this + # widget, and one a registry held a listener of (Presence) kept + # its timer running after every window that built it was gone. + if self.tabs.indexOf(widget) == -1: + widget.setParent(self) + widget.hide() + + @staticmethod + def _is_built(entry: Any) -> bool: + return bool(getattr(entry, "built", True)) + + def _built_entries(self) -> List[Any]: + return [entry for entry in self.tab_registry.entries if self._is_built(entry)] + + def _is_open(self, entry: Any) -> bool: + return self._is_built(entry) and self.tabs.indexOf(entry.widget) != -1 + + def _on_current_tab_changed(self, _index: int) -> None: + self._bind_details() + self.current_tab_changed.emit() + + def current_tab_menu_actions(self) -> list[tuple[str, Callable[[], Any]]]: + """Return ``[(label_key, callable), ...]`` for the active tab. + + Core tabs declare their actions at registration time; feature tabs + may instead expose a ``menu_actions()`` method returning the same + shape. The menu bar renders these under the Actions menu so tabs + stay button-free. + """ + widget = self.tabs.currentWidget() + if widget is None: + return [] + for entry in self._built_entries(): + if entry.widget is widget: + if entry.actions: + return list(entry.actions) + provider = getattr(widget, "menu_actions", None) + if callable(provider): + return list(provider()) + return [] + return [] + + def _find_entry(self, key: str) -> TabEntry | None: + for entry in self.tab_registry.entries: + if entry.key == key: + return entry + return None + + def sync_engine_tabs(self) -> None: + """Let every built tab that mirrors an engine re-read its state (after Tools > Start). + + A tab not built yet reads the engine when it is. + """ + for entry in self.tab_registry.entries: + if not WorkspaceShell._is_built(entry): + continue + sync = getattr(entry.widget, "sync_with_engine", None) + if callable(sync): + sync() + + def list_registered_tabs(self) -> list[dict[str, Any]]: + """Return metadata for the View → Tabs menu and the navigation panel. + + Reading it builds nothing: a tab never opened is listed as not visible. + """ + return [ + { + "key": entry.key, + "title": language_wrapper.translate(entry.title_key, entry.title_key), + "visible": self._is_open(entry), + "category": entry.category, + } + for entry in self.tab_registry.entries + ] + + def current_tab_key(self) -> Optional[str]: + """Key of the tab on screen, or ``None`` when every tab is closed.""" + widget = self.tabs.currentWidget() + for entry in self._built_entries(): + if entry.widget is widget: + return str(entry.key) + return None + + def show_tab(self, key: str) -> None: + """Open the tab ``key`` (building it if this is its first time) and select it.""" + entry = self._find_entry(key) + if entry is None or self._is_open(entry): + return + target_index = 0 + for candidate in self.tab_registry.entries: + if candidate.key == key: + break + if self._is_open(candidate): + target_index += 1 + title = language_wrapper.translate(entry.title_key, entry.title_key) + page = self.tab_registry.open(key) + self.tabs.insertTab(target_index, page, title) + self.tabs.setCurrentWidget(page) + self.tabs_changed.emit() + + def activate_tab(self, key: str) -> bool: + """Bring the tab ``key`` to the front, opening it first if needed.""" + entry = self._find_entry(key) + if entry is None: + return False + if self._is_open(entry): + self.tabs.setCurrentWidget(entry.widget) + else: + self.show_tab(key) + return True + + def hide_tab(self, key: str) -> None: + """Close the tab ``key``; its widget is kept for the next time it is opened.""" + entry = self._find_entry(key) + if entry is None or not self._is_built(entry): + return + index = self.tabs.indexOf(entry.widget) + if index != -1: + self.tabs.removeTab(index) + self.tabs_changed.emit() + + def _on_tab_close_requested(self, index: int) -> None: + widget = self.tabs.widget(index) + for entry in self._built_entries(): + if entry.widget is widget: + self.close_tab(entry.key) + return + + def close_tab(self, key: str) -> None: + """Release a feature and its page-owned resources. + + Unlike ``hide_tab``, closing a feature discards its local UI state and + schedules cleanup of subscriptions and timers. Reopening rebuilds it. + Remote Desktop keeps registry-owned sessions while retiring its view callbacks. + """ + self.tab_registry.close(key) + + def _detach_closed_tab(self, page: QWidget) -> None: + """Remove a closed page before its deferred Qt destruction.""" + index = self.tabs.indexOf(page) + if index != -1: + self.tabs.removeTab(index) + self.tabs_changed.emit() + + def _translate(self, key: str) -> str: + return language_wrapper.translate(key, key) + + def retranslate(self) -> None: + """Relabel tab titles and propagate into every child tab.""" + self.tabs.retranslate() + self.details.retranslate() + for entry in self._built_entries(): + index = self.tabs.indexOf(entry.widget) + if index != -1: + self.tabs.setTabText( + index, language_wrapper.translate(entry.title_key, entry.title_key), + ) + TranslatableMixin.retranslate(self) + # Child class tabs get their own retranslate if they implement one. + for entry in self._built_entries(): + callback = getattr(entry.widget, "retranslate", None) + if callable(callback) and entry.widget is not self: + try: + callback() + except (RuntimeError, AttributeError): + continue diff --git a/je_auto_control/gui/workspace_details.py b/je_auto_control/gui/workspace_details.py new file mode 100644 index 000000000..f4a38ffbb --- /dev/null +++ b/je_auto_control/gui/workspace_details.py @@ -0,0 +1,95 @@ +"""Immutable execution snapshots and a passive, scrollable workspace detail view.""" +from dataclasses import dataclass +from typing import Literal + +from PySide6.QtCore import QObject, Qt, Signal +from PySide6.QtWidgets import QLabel, QProgressBar, QScrollArea, QVBoxLayout, QWidget + +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper + + +ExecutionPhase = Literal['idle', 'running', 'stopping', 'succeeded', 'cancelled', 'error', 'unavailable'] + + +@dataclass(frozen=True) +class ExecutionDetails: + """Display data only; the producing page retains task and cancellation ownership.""" + + phase: ExecutionPhase = 'idle' + summary: str = '' + completed: int = 0 + total: int = 0 + + +class ExecutionDetailsSource(QObject): + """A page-owned snapshot publisher updated on the GUI thread.""" + + changed = Signal(object) + + def __init__(self, parent: QWidget) -> None: + super().__init__(parent) + self._snapshot = ExecutionDetails() + + @property + def snapshot(self) -> ExecutionDetails: + """Return the latest immutable snapshot without starting work.""" + return self._snapshot + + def publish(self, snapshot: ExecutionDetails) -> None: + """Replace the cached display state and notify the active view.""" + self._snapshot = snapshot + self.changed.emit(snapshot) + + +class ExecutionDetailsPane(QScrollArea): + """Render one snapshot without retaining a page, task, exception or result.""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setWidgetResizable(True) + self.setMinimumWidth(0) + content = QWidget() + layout = QVBoxLayout(content) + self.title = QLabel() + self.state = QLabel() + self.summary = QLabel() + for label in (self.title, self.state, self.summary): + label.setTextFormat(Qt.TextFormat.PlainText) + label.setWordWrap(True) + label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + layout.addWidget(label) + self.progress = QProgressBar() + layout.addWidget(self.progress) + layout.addStretch() + self.setWidget(content) + self._snapshot: ExecutionDetails | None = None + self._selected = False + self.retranslate() + + @property + def snapshot(self) -> ExecutionDetails | None: + """Return the data currently displayed, or None for an empty/unpublished page.""" + return self._snapshot + + def display(self, snapshot: ExecutionDetails | None, *, selected: bool) -> None: + """Show a snapshot, or the distinct no-page/no-publisher state.""" + self._snapshot, self._selected = snapshot, selected + self.retranslate() + + def retranslate(self) -> None: + """Refresh display labels while preserving the current execution data.""" + translate = language_wrapper.translate + self.title.setText(translate('workspace_details_title', 'Execution details')) + snapshot = self._snapshot + if snapshot is None: + key = 'workspace_details_unavailable' if self._selected else 'workspace_details_empty' + self.state.setText(translate(key, key)) + self.summary.clear() + self.progress.hide() + return + key = 'workspace_phase_' + snapshot.phase + self.state.setText(translate(key, key)) + self.summary.setText(snapshot.summary) + self.progress.setVisible(snapshot.total > 0) + self.progress.setRange(0, max(0, snapshot.total)) + self.progress.setValue(max(0, min(snapshot.completed, snapshot.total))) diff --git a/pyproject.toml b/pyproject.toml index eb6b499f7..5762fe595 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -362,6 +362,7 @@ module = [ "je_auto_control.gui.config_sync_tab", "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", + "je_auto_control.gui.workspace_details", "je_auto_control.gui.remote_desktop.webrtc_panel_state", "je_auto_control.gui.remote_desktop.view_lifetime", "je_auto_control.gui.remote_desktop.view_approvals", diff --git a/test/unit_test/headless/test_gui_engine_state_vlm_audit.py b/test/unit_test/headless/test_gui_engine_state_vlm_audit.py index a5be15300..8e81f033a 100644 --- a/test/unit_test/headless/test_gui_engine_state_vlm_audit.py +++ b/test/unit_test/headless/test_gui_engine_state_vlm_audit.py @@ -76,7 +76,7 @@ def test_tools_start_resyncs_every_engine_tab(): synced = [] entries = [types.SimpleNamespace(widget=types.SimpleNamespace(sync_with_engine=lambda: synced.append(1))), types.SimpleNamespace(widget=types.SimpleNamespace())] - AutoControlGUIWidget.sync_engine_tabs(types.SimpleNamespace(_tab_entries=entries)) + AutoControlGUIWidget.sync_engine_tabs(types.SimpleNamespace(tab_registry=types.SimpleNamespace(entries=entries))) assert synced == [1] diff --git a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py index 33d710cc2..a2c783324 100644 --- a/test/unit_test/headless/test_gui_tab_lifecycle_audit.py +++ b/test/unit_test/headless/test_gui_tab_lifecycle_audit.py @@ -240,7 +240,8 @@ def test_a_hidden_tab_is_owned_and_stays_hidden(qapp): class _Owner(QWidget): def __init__(self): super().__init__() - self._tab_entries = [] + from je_auto_control.gui.tab_registry import TabRegistry + self.tab_registry = TabRegistry([]) self.tabs = QTabWidget(self) owner, page = _Owner(), QWidget() diff --git a/test/unit_test/headless/test_gui_workspace_navigation.py b/test/unit_test/headless/test_gui_workspace_navigation.py index f117272e1..b9149b3ea 100644 --- a/test/unit_test/headless/test_gui_workspace_navigation.py +++ b/test/unit_test/headless/test_gui_workspace_navigation.py @@ -222,7 +222,8 @@ def test_switching_theme_keeps_the_text_size(window): def test_rebuilding_the_menus_for_a_language_switch_adds_no_shortcut(window): assert window["actions_after"] == window["actions_before"] assert window["placeholder"] - assert window["view_menu"] == ["Search Features...", "Navigation Panel", "Tabs", "Theme", "Text Size"] + assert window["view_menu"] == ["Search Features...", "Navigation Panel", "Execution details", + "Tabs", "Theme", "Text Size"] def test_the_window_shrinks_to_a_small_screen_with_both_panes_usable(window): diff --git a/test/unit_test/headless/test_workspace_execution_details.py b/test/unit_test/headless/test_workspace_execution_details.py new file mode 100644 index 000000000..8bb55a161 --- /dev/null +++ b/test/unit_test/headless/test_workspace_execution_details.py @@ -0,0 +1,118 @@ +"""Real Diagnostics actions publish execution details without native diagnostic work.""" +import os +import threading +import time +import types + +import pytest + +os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') + + +@pytest.fixture(scope='module') +def app(): + widgets = pytest.importorskip('PySide6.QtWidgets', exc_type=ImportError) + return widgets.QApplication.instance() or widgets.QApplication([]) + + +def pump(app, predicate): + deadline = time.monotonic() + 3 + while time.monotonic() < deadline: + app.processEvents() + if predicate(): + return + threading.Event().wait(.001) + assert predicate() + + +@pytest.fixture +def shell(app): + from PySide6.QtCore import QEvent + from je_auto_control.gui.diagnostics_tab import DiagnosticsTab + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + widget = WorkspaceShell(TabRegistry([TabEntry('diag', 'tab_diagnostics', DiagnosticsTab)])) + widget.activate_tab('diag') + yield widget + widget.close_tab('diag') + widget.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +@pytest.mark.parametrize('outcome', ['succeeded', 'error', 'cancelled']) +def test_diagnostics_progress_and_terminal_states_come_from_real_actions(shell, app, monkeypatch, outcome): + from je_auto_control.gui import diagnostics_tab + from je_auto_control.utils.diagnostics.diagnostics import Check, DiagnosticsReport + from je_auto_control.utils.exception.cancellation import current_cancellation_token + started, release = threading.Event(), threading.Event() + + def run(): + token = current_cancellation_token() + token.report(1, 3) + started.set() + release.wait(2) + token.checkpoint() + if outcome == 'error': + raise RuntimeError('controlled failure') + return DiagnosticsReport([Check('fake', True, 'info', 'done')]) + + monkeypatch.setattr(diagnostics_tab, 'run_diagnostics', run) + page = shell.tabs.currentWidget() + actions = dict(page.menu_actions()) + assert shell.details.snapshot.phase == 'idle' + actions['diag_run']() + try: + assert started.wait(1) + pump(app, lambda: shell.details.snapshot.completed == 1) + assert shell.details.snapshot.phase == 'running' + assert shell.details.snapshot.total == 3 + if outcome == 'cancelled': + actions['diag_stop']() + assert shell.details.snapshot.phase == 'stopping' + finally: + release.set() + pump(app, lambda: page._active_task is None) + assert shell.details.snapshot.phase == outcome + if outcome == 'error': + assert 'controlled failure' in shell.details.snapshot.summary + + +def test_view_toggle_survives_language_rebuild_and_refreshes_all_languages(app, monkeypatch, tmp_path): + from PySide6.QtCore import QEvent, QSettings + from je_auto_control.gui import main_widget, main_window, workspace_details + from je_auto_control.gui.language_wrapper.multi_language_wrapper import LanguageWrapper + from je_auto_control.gui.workspace_details import ExecutionDetails + language = LanguageWrapper() + monkeypatch.setattr(main_window, 'language_wrapper', language) + monkeypatch.setattr(workspace_details, 'language_wrapper', language) + monkeypatch.setattr(main_window, 'sys', types.SimpleNamespace(platform='test')) + monkeypatch.setattr(main_widget, 'TAB_SPECS', ()) + settings = QSettings(str(tmp_path / 'workspace.ini'), QSettings.Format.IniFormat) + window = main_window.AutoControlGUIUI(settings=settings) + try: + shell = window.auto_control_gui_widget + action = window._details_action + assert action.shortcut().toString() == 'Ctrl+Shift+D' + assert shell.details.isHidden() + action.trigger() + assert not shell.details.isHidden() + shell.details.display(ExecutionDetails('running', 'values stay intact', 2, 5), selected=True) + initial_actions = len(window.actions()) + labels = set() + for name in language.available_languages: + language.reset_language(name) + labels.add(action.text()) + assert action.isChecked() + assert window._details_action is action + assert len(window.actions()) == initial_actions + assert shell.details.summary.text() == 'values stay intact' + assert len(labels) == 4 + shell.set_details_visible(False) + assert not action.isChecked() + window._apply_font_pt(20) + window.resize(640, 420) + assert shell.minimumSizeHint().width() <= 640 + finally: + window.close() + window.deleteLater() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) diff --git a/test/unit_test/headless/test_workspace_shell.py b/test/unit_test/headless/test_workspace_shell.py new file mode 100644 index 000000000..ae01719b1 --- /dev/null +++ b/test/unit_test/headless/test_workspace_shell.py @@ -0,0 +1,208 @@ +"""The injected workspace registry and detail subscriptions preserve page ownership.""" +import gc +import os +import weakref + +import pytest + +os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') + + +@pytest.fixture(scope='module') +def app(): + widgets = pytest.importorskip('PySide6.QtWidgets', exc_type=ImportError) + return widgets.QApplication.instance() or widgets.QApplication([]) + + +def flush(app): + from PySide6.QtCore import QEvent + app.processEvents() + app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +@pytest.fixture +def shell(app): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + from je_auto_control.gui.workspace_details import ExecutionDetailsSource + + def page(): + widget = QWidget() + ExecutionDetailsSource(widget) + return widget + + registry = TabRegistry([TabEntry('one', 'one', page), TabEntry('two', 'two', page), + TabEntry('plain', 'plain', QWidget)]) + widget = WorkspaceShell(registry) + yield widget + widget.deleteLater() + flush(app) + + +def source(shell): + from je_auto_control.gui.workspace_details import ExecutionDetailsSource + return shell.tabs.currentWidget().findChild(ExecutionDetailsSource) + + +def test_supplied_registry_is_authoritative_and_hidden_pages_stay_lazy(shell): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.tab_registry import TabEntry + assert not any(entry.built for entry in shell.tab_registry.entries) + shell.tab_registry.add(TabEntry('later', 'later', QWidget)) + assert [entry['key'] for entry in shell.list_registered_tabs()] == ['one', 'two', 'plain', 'later'] + shell.activate_tab('two') + assert shell.tabs.currentWidget() is shell.tab_registry.open('two') + assert [entry.key for entry in shell.tab_registry.entries if entry.built] == ['two'] + + +def test_external_close_detaches_and_reopen_has_fresh_details(shell, app): + from shiboken6 import isValid + from je_auto_control.gui.workspace_details import ExecutionDetails + shell.activate_tab('one') + first = shell.tabs.currentWidget() + source(shell).publish(ExecutionDetails('running', 'first operation', 1, 5)) + assert shell.details.snapshot.summary == 'first operation' + shell.tab_registry.close('one') + assert shell.tabs.count() == 0 + assert shell.details.snapshot is None + flush(app) + assert not isValid(first) + shell.activate_tab('one') + assert shell.tabs.currentWidget() is not first + assert shell.details.snapshot.phase == 'idle' + + +def test_hide_preserves_page_but_disconnects_its_details(shell): + from je_auto_control.gui.workspace_details import ExecutionDetails + shell.activate_tab('one') + page = shell.tabs.currentWidget() + publisher = source(shell) + shell.hide_tab('one') + publisher.publish(ExecutionDetails('error', 'hidden result')) + assert shell.details.snapshot is None + shell.activate_tab('one') + assert shell.tabs.currentWidget() is page + assert shell.details.snapshot.summary == 'hidden result' + + +def test_queued_old_details_cannot_replace_selected_page(shell, app): + from PySide6.QtCore import QObject, Qt + from je_auto_control.gui.workspace_details import ExecutionDetails + shell.activate_tab('one') + old = source(shell) + QObject.disconnect(shell._details_connection) + shell._details_connection = old.changed.connect(shell._on_details_changed, Qt.ConnectionType.QueuedConnection) + old.publish(ExecutionDetails('error', 'stale')) + shell.activate_tab('two') + source(shell).publish(ExecutionDetails('succeeded', 'current')) + flush(app) + assert shell.details.snapshot.summary == 'current' + + +def test_refused_close_preserves_details_and_constructor_callback(app): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + from je_auto_control.gui.workspace_details import ExecutionDetailsSource + + class Unsaved(QWidget): + def __init__(self): + super().__init__() + ExecutionDetailsSource(self) + + def closeEvent(self, event): + event.ignore() + + closed = [] + registry = TabRegistry([TabEntry('one', 'one', Unsaved)], on_close=closed.append) + widget = WorkspaceShell(registry) + widget.activate_tab('one') + snapshot = widget.details.snapshot + registry.close('one') + assert widget.tabs.count() == 1 + assert widget.details.snapshot is snapshot + assert closed == [] + widget.deleteLater() + flush(app) + + +def test_registry_does_not_retain_destroyed_shell(app): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + registry = TabRegistry([TabEntry('one', 'one', QWidget)]) + widget = WorkspaceShell(registry) + widget._add_tab('added', 'added', QWidget) + widget.activate_tab('one') + page = widget.tabs.currentWidget() + reference = weakref.ref(widget) + widget.deleteLater() + flush(app) + del widget + gc.collect() + assert reference() is None + assert not registry._close_listeners + assert not registry.entries[0].built + replacement = WorkspaceShell(registry) + replacement.activate_tab('one') + assert replacement.tabs.currentWidget() is not page + replacement.deleteLater() + flush(app) + + +def test_old_deferred_destruction_cannot_forget_replacement(shell, app): + shell.activate_tab('one') + first = shell.tabs.currentWidget() + shell.close_tab('one') + shell.activate_tab('one') + second = shell.tabs.currentWidget() + assert second is not first + flush(app) + assert shell.tab_registry.open('one') is second + + +def test_accepted_close_notifies_existing_callback_before_releasing(app): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + events = [] + + class Page(QWidget): + def dispose(self): + events.append(('dispose', widget.tabs.count())) + + registry = TabRegistry([TabEntry('one', 'one', Page)], on_close=lambda page: events.append(('callback', page))) + widget = WorkspaceShell(registry) + widget.activate_tab('one') + page = widget.tabs.currentWidget() + registry.close('one') + assert events == [('callback', page), ('dispose', 0)] + widget.deleteLater() + flush(app) + + +def test_unpublished_page_has_distinct_empty_state_and_plain_text(shell): + from PySide6.QtCore import Qt + from je_auto_control.gui.workspace_details import ExecutionDetails + empty = shell.details.state.text() + shell.activate_tab('plain') + assert shell.details.state.text() != empty + shell.activate_tab('one') + source(shell).publish(ExecutionDetails('error', '')) + assert shell.details.summary.textFormat() == Qt.TextFormat.PlainText + assert shell.details.summary.text() == '' + + +def test_collapsed_details_do_not_expand_minimum_width(shell, app): + shell.resize(640, 420) + shell.show() + shell.activate_tab('one') + shell.set_details_visible(True) + flush(app) + assert not shell.details.isHidden() + shell.set_details_visible(False) + flush(app) + assert shell.details.isHidden() + assert shell.minimumSizeHint().width() <= 640 + assert shell.tabs.width() <= shell.width() From b8f7df713a845038ee2c2c8cdf520c9f49715bfa Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 18:25:08 +0800 Subject: [PATCH 030/161] Enforce reviewed MCP capabilities through refreshed invocation --- CHANGELOG.md | 4 + Progress.md | 3 +- README.md | 4 + README/README_zh-CN.md | 4 + README/README_zh-TW.md | 4 + architecture.md | 10 + architecture_explore.md | 33 +- .../Eng/doc/mcp_server/mcp_server_doc.rst | 71 +--- .../Zh/doc/mcp_server/mcp_server_doc.rst | 22 +- docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- je_auto_control/utils/mcp_server/_authz.py | 26 +- .../utils/mcp_server/_call_authority.py | 8 +- .../utils/mcp_server/_disclosure_server.py | 11 +- je_auto_control/utils/mcp_server/discovery.py | 5 +- je_auto_control/utils/mcp_server/server.py | 5 +- .../utils/mcp_server/tools/__init__.py | 27 +- .../utils/mcp_server/tools/_base.py | 4 + .../utils/mcp_server/tools/_factories.py | 6 +- .../mcp_server/tools/_handlers_operations.py | 7 +- .../utils/mcp_server/tools/_readonly.py | 32 ++ je_auto_control/utils/rbac/policy.py | 32 +- .../utils/rbac/tool_classification.py | 391 ++++++++++++++++++ pyproject.toml | 2 + .../headless/test_mcp_disclosure_policy.py | 4 +- .../headless/test_mcp_discovery_index.py | 14 +- .../test_mcp_plugin_read_only_declaration.py | 12 +- .../headless/test_mcp_readonly_authority.py | 142 +++++++ .../headless/test_mcp_stop_execution.py | 4 +- .../headless/test_rbac_mcp_transports.py | 18 +- .../headless/test_rbac_reviewed_tools.py | 255 ++++++++++++ .../headless/test_rbac_server_wiring.py | 14 +- .../headless/test_rbac_user_admin.py | 6 +- 33 files changed, 1018 insertions(+), 171 deletions(-) create mode 100644 je_auto_control/utils/mcp_server/tools/_readonly.py create mode 100644 je_auto_control/utils/rbac/tool_classification.py create mode 100644 test/unit_test/headless/test_mcp_readonly_authority.py create mode 100644 test/unit_test/headless/test_rbac_reviewed_tools.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fc8cca2cb..0f6f5eb01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ their views. Remote Desktop does not automatically reattach a reopened view, and its page-owned WebRTC sessions are stopped in the background. +- MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. + +- Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. + ## [1.2.0] - 2026-11-02 Python 3.11 is now the minimum. Pillow 13.0.0 and dnspython 2.9.0, the releases that fix the advisories diff --git a/Progress.md b/Progress.md index c4effff30..e2a36c0e6 100644 --- a/Progress.md +++ b/Progress.md @@ -141,7 +141,8 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **簽章分離擋不住能寫檔的人**:能執行寫檔指令(shell、檔案類指令)的人仍能換掉公鑰檔本身,保護那個檔是作業系統權限的事; 私鑰支援選用通行碼加密,未設定時仍是明文 PEM(0600,Windows 上沒驗權限位元);遷移模式開著時 HMAC 簽章會被接受。 - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - - viewer 的其餘影像檔案型、mobile 與外掛唯讀工具仍需全面盤點 capability;自製工具仍依提示採預設分類。 + - `ac_list_plugins` 的外掛 factory,以及 `ac_web_list_commands`/`ac_web_current_url` 的實際相依版本初始化契約尚待審查;目前不列入唯讀目錄,完整目錄仍要求 `read_data`。本機 sibling 原始碼不代表部署版本驗收。 + - `ac_diagnose` 的預設 audit-log 初始化可能建立固定目錄及 SQLite schema;全域零寫入診斷與外部 SDK 初始化副作用仍未驗證。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, diff --git a/README.md b/README.md index 22d832eae..6e2b555c4 100644 --- a/README.md +++ b/README.md @@ -68,3 +68,7 @@ Managed agent tasks and cross-host transfers include experimental features. See [MIT](LICENSE) © JE-Chen. [Third-party licenses](Third_Party_License.md). Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. + +MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. + +Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 5858d855b..8bac8f054 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -68,3 +68,7 @@ Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用 [MIT](../LICENSE) © JE-Chen. [第三方许可](../Third_Party_License.md). 关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。已进入发送阶段的文件传输不会因关闭页面而中断。 + +MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 + +主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 1b0cbc13d..799f7da7d 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -68,3 +68,7 @@ Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫 [MIT](../LICENSE) © JE-Chen. [Third-party licenses](../Third_Party_License.md). 關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 + +MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 + +主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 diff --git a/architecture.md b/architecture.md index e67f39f38..e004998f8 100644 --- a/architecture.md +++ b/architecture.md @@ -684,6 +684,16 @@ TCP client authentication marks rejection terminal before writing AUTH_FAIL. Adm reaping therefore releases its client slot before an immediate retry can arrive, while the separate handshake semaphore bounds outstanding cleanup and authentication threads. +MCP capability policy uses an explicit reviewed screen/caller-data catalogue in +`utils/rbac/tool_classification.py`; unknown read-only hints require read_data. +Canonical aliases and stronger overrides share base and argument requirements at +admission and refreshed direct/nested invocation. The readonly variant builder +applies equally to default, explicit and dynamically registered catalogues. It +excludes executable selectors/unreviewed external initializers and rejects capture +or VLM branches before handlers. Failure artifacts require writable host/tool +ownership and refreshed drive authority. CI annotation formatting returns data +without writing into the MCP stdio stream. External initializer review remains open. + Delayed work captures registration authority through `utils/rbac/deferred.py`. Schedulers, triggers, hotkeys, watchdogs, webhooks, e-mail watchers and observers bind that owner at dispatch, independently of the worker's ambient context. diff --git a/architecture_explore.md b/architecture_explore.md index 43ef3821c..2cfb6203b 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,515 | -| 程式碼總行數 | 231,047 | +| Python 模組總數(含周邊子專案) | 1,517 | +| 程式碼總行數 | 231,497 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -516,7 +516,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,754 行。 +> 14 個套件、約 52,801 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -530,7 +530,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,037 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,084 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 660 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,050 行。 +> 13 個套件、約 4,453 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -674,7 +674,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/governance/` | 243 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | -| `utils/rbac/` | 1,303 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 敏感讀取獨立於唯讀提示要求 operator | +| `utils/rbac/` | 1,706 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | @@ -743,7 +743,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,037 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,084 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -761,9 +761,9 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers_journal.py` | 75 | 日誌擷取與查閱 adapter:進度、合作式取消及保留執行資料的受控失敗。 | | `_tool_notifications.py` | 44 | Publish tool-list changes to the live HTTP session streams owned by one transport. | | `disclosure.py` | 213 | Session-local availability and bounded opaque cursors; disclosure never grants execution authority. | -| `_disclosure_server.py` | 161 | Bind tool availability to transport lifetimes while retaining the existing dispatcher gates. | +| `_disclosure_server.py` | 170 | Bind tool availability to transport lifetimes while retaining the existing dispatcher gates. | | `stdio.py` | 23 | Lazy stdio entry point with optional host-configured tool availability. | -| `discovery.py` | 140 | Bounded, authority-filtered tool summaries and detached schemas from one registry snapshot. | +| `discovery.py` | 141 | Bounded, authority-filtered tool summaries and detached schemas from one registry snapshot. | | `tools/_discovery.py` | 70 | Small discovery tools query the active server registry instead of constructing another catalogue. | | `tools/_capabilities.py` | 29 | 唯讀能力 MCP schema 與共用 headless adapter;拒絕外部 context/授權資料。 | | `tools/_diagnostics.py` | 51 | 主動唯讀診斷 MCP;共用 report、request-owned 取消與進度,拒絕外部 token/授權資料。 | @@ -776,8 +776,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers_mobile_executor.py` | 135 | 10 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_vision_executor.py` | 564 | 70 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_locators.py` | 436 | 同一種 adapter,定位主題:無障礙樹、智慧等待、自我修復、螢幕觀察、座標空間、視覺與 OCR、影像去重、元件倉庫、A/B 定位。 | -| `tools/_handlers_operations.py` | 655 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | -| `server.py` | 744 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、工具與 resource/prompt 處理器;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | +| `tools/_handlers_operations.py` | 656 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | +| `server.py` | 745 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、工具與 resource/prompt 處理器;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | | `http_transport.py` | 622 | MCP 的 HTTP 傳輸;宣告 2026-07-28 的請求走 `_http_stateless.py` 的標頭規則,不發 session。 | | `_http_stateless.py` | 185 | MCP 2026-07-28 在 Streamable HTTP 上的規則:`MCP-Protocol-Version`/`Mcp-Method`/`Mcp-Name` 必須與 body 相符(`=?base64?…?=` 先解碼),不符是 400+`HeaderMismatch`;版本與中繼資料錯誤 400、未知方法 404。純函式,由 `http_transport.py` 回覆。 | | `http_sessions.py` | 301 | MCP 的 HTTP 傳輸用的 session 身分:`Mcp-Session-Id` 註冊表,以及每個 session 那條常駐的 server→client SSE 串流。 | @@ -792,7 +792,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `prompts.py` | 220 | MCP prompt 目錄。 | | `fake_backend.py` | 187 | CI/無頭測試用的記憶體內假後端。 | | `plugin_watcher.py` | 169 | 檔案變更時熱重載外掛工具的背景 watcher。 | -| `tools/_base.py` | 225 | 工具註冊表的共用型別與輔助;JSON 相容的 MCPToolResult 分離受控失敗旗標與資料。 | +| `tools/_base.py` | 229 | 工具註冊表的共用型別與輔助;JSON 相容的 MCPToolResult 分離受控失敗旗標與資料。 | +| `tools/_readonly.py` | 32 | Read-only registry variants with enforced argument restrictions. 預設/外部/動態目錄共用篩選及呼叫限制。 | | `tools/_validation.py` | 124 | MCP 工具用到的 JSON Schema 子集驗證器。 | | `tools/plugin_tools.py` | 147 | 把外掛載入的 `AC_*` callable 包成 `MCPTool`。 | | `log_bridge.py` | 118 | 把 Python logging 記錄橋接成 MCP `notifications/message`;2026-07-28 的請求只收到自己設了 `logLevel` 時產生的記錄。 | @@ -1421,7 +1422,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,180 個 `test_*.py`/11,455 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,182 個 `test_*.py`/11,482 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1513,7 +1514,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | | `gui/` | 150 | 40,579 | -| `utils/mcp_server/` | 60 | 22,037 | +| `utils/mcp_server/` | 61 | 22,084 | | `utils/remote_desktop/` | 72 | 15,301 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | @@ -1532,8 +1533,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,002 | 102,291 | -| **總計** | **1,503** | **230,302** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,003 | 102,694 | +| **總計** | **1,505** | **230,752** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst b/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst index 4b9fbdbed..f64e220aa 100644 --- a/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst +++ b/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst @@ -331,7 +331,7 @@ share one file. Without a store, live MCP tool sessions use an operator principa host-management tools require an authenticated administrator. The stdio transport has no bearer token and uses the same operator ceiling for its live tool sessions. -- A tool defaults to ``read_screen`` for ``readOnlyHint`` and ``drive_input`` +- A tool defaults to ``read_data`` for ``readOnlyHint`` and ``drive_input`` otherwise, with explicit capability overrides. Sensitive reads require ``drive_input`` (operator/admin): clipboard and history, local document/data/SQL readers, dotenv and reference resolution, JWT/OTP generation, persistent-store @@ -347,50 +347,22 @@ bearer token and uses the same operator ceiling for its live tool sessions. ``ac_load_plugins`` need ``manage_hosts`` (``admin``); ``ac_user_add`` / ``_remove`` / ``_set_role`` / ``_rotate_token`` / ``_list`` need ``manage_users`` (``admin``). -- Read-only is not the same as harmless to show: the read-only tools that - return the host's data rather than the state of its screen need - ``read_data``, which ``operator`` and ``admin`` hold and ``viewer`` does - not. They are the clipboard tools (``ac_get_clipboard`` and its - ``_csv`` / ``_files`` / ``_html`` / ``_image`` / ``_rtf`` variants, - ``ac_clipboard_formats``, ``ac_assert_clipboard``, ``ac_clip_history_list`` - / ``_search``); the file readers (``ac_load_dotenv``, ``ac_load_data``, - ``ac_read_action_file``, ``ac_read_document``, ``ac_read_presentation``, - ``ac_read_workbook``, ``ac_extract_pdf_text``, ``ac_assert_pdf_text``, - ``ac_assert_file``, ``ac_build_provenance``, ``ac_verify_provenance``); the - database and store readers (``ac_sql_query``, ``ac_assert_db``, - ``ac_get_asset``, ``ac_list_assets``, ``ac_cas_get``, ``ac_outbox_pending``, - ``ac_checkpoint_status``, ``ac_memory_recall``, ``ac_memory_recent``, - ``ac_s3_list``); references and tokens (``ac_resolve_ref``, - ``ac_resolve_refs``, ``ac_generate_otp``, ``ac_jwt_encode``, - ``ac_jwt_decode``); and the process list, network and microphone probes - (``ac_list_processes``, ``ac_assert_process``, ``ac_wait_for_process``, - ``ac_assert_http``, ``ac_wait_for_port``, ``ac_assert_audio``). The list is - ``DATA_TOOLS`` in ``je_auto_control.utils.rbac.policy``. A ``viewer`` keeps - every other read-only tool: screen size, windows, pixels, image and text - location, accessibility reads, waits. -- The rule behind that list: a tool that returns **records or configuration - the host keeps** needs ``read_data``; a tool that only observes the live - screen needs ``read_screen``. So ``read_data`` also covers run history and - what is computed from it (``ac_list_run_history``, ``ac_flaky_report``, - ``ac_rank_tests``, ``ac_select_tests``, ``ac_shard_suite``); agent traces - and the cost ledger (``ac_trace_export``, ``ac_trace_summary``, - ``ac_costs_list``, ``ac_costs_summary``); action journals - (``ac_journal_read``, ``ac_journal_runs``); the self-healing log, its - statistics, stored revisions and datasets (``ac_self_heal_log_list``, - ``ac_heal_stats``, ``ac_self_heal_revision_list``, - ``ac_self_heal_evaluate``); locator strategy history, repairs and saved - libraries (``ac_ab_report``, ``ac_ab_best_strategy``, ``ac_repair_pending``, - ``ac_repair_resolved``, ``ac_element_list``, ``ac_skill_list``, - ``ac_skill_search``); stored policy and state (``ac_usb_acl_list``, - ``ac_lease_active``, ``ac_quarantine_list``, ``ac_pending_artifacts``); - and a connected device's clipboard - (``ac_android_get_clipboard``, ``ac_ios_get_clipboard``). These were - ``read_screen`` before, so **a viewer token can no longer call them**; - ``operator`` and ``admin`` are unaffected. -- What a call costs is not a capability. ``ac_vlm_locate`` and - ``ac_self_heal_locate`` read the screen and stay ``read_screen`` although a - call may be billed by a model provider; limit spend with the rate limiter - or by not configuring a VLM backend for a server viewers reach. +- MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data + tools use ``read_screen``; stored files, device data and unknown tools require + ``read_data``. Aliases share canonical policy and stronger overrides take precedence. + Optional image sources, environment-backed config fields and file open plans require + ``read_data``. Anchor locators permit live accessibility/OCR; image templates require + ``read_data`` and VLM requests require ``drive_input``. Read-only invocation rejects + capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB + executables. MCP CI annotations return formatted lines without writing to stdout. + Unreviewed plugin and WebRunner initialization tools are omitted from read-only + catalogues and require dependency-specific review. +- Host read-only mode applies the same restrictions to explicitly supplied registries + and later registrations. Both admission and refreshed invocation check mixed + arguments. Configured MCP failure screenshots require a writable tool and a refreshed + caller with drive authority; readonly calls and viewers never trigger them. This does + not promise that every dependency or diagnostic read has no initialization side + effects. - The REST API follows the same rule: ``GET /history`` and ``GET /usb/acl`` need ``read_data`` like ``ac_list_run_history`` and ``ac_usb_acl_list``, so a viewer token reads neither the run history nor the USB ACL there either @@ -402,11 +374,6 @@ bearer token and uses the same operator ceiling for its live tool sessions. and ``resources/read`` and ``resources/subscribe`` refuse the rest with ``-32003``. A resource URI the server does not recognise (one from a custom provider) is treated as stored data and needs ``read_data``. -- Tools that report the live state of this process rather than a stored - record -- ``ac_list_executions``, ``ac_scheduler_list_jobs``, - ``ac_trigger_list``, ``ac_hotkey_list``, ``ac_observe_list``, - ``ac_watchdog_list``, ``ac_journal_status``, the USB device lists -- stay - ``read_screen``. - ``tools/list`` returns only the tools the caller may call, and ``tools/call`` on any other answers JSON-RPC error ``-32003`` (``Forbidden: ...``, ``data.required_capability``) without running it. @@ -830,7 +797,7 @@ under RBAC. A plugin opts one of its callables out by setting the attribute The tool is then registered with ``readOnlyHint`` true. It is listed and runs on a read-only server in all three tool modes (``full``, ``progressive`` -- once enabled -- and ``static``, when the profile names -it), and under RBAC it needs only ``read_screen``, so a ``viewer`` may call +it), and under RBAC it needs ``read_data``, so a ``viewer`` may not call it. Only the read-only hint is taken from the plugin; the tool is not marked idempotent. @@ -839,7 +806,7 @@ marked idempotent. The declaration is **trusted, not verified**. It is the plugin author's word: the server cannot tell what arbitrary Python does, and a callable that declares itself read-only and then writes files or sends input will - do so on a read-only server and for a viewer. Declaring it does not + do so on a read-only server for an authorized caller. Declaring it does not sandbox it. Review a plugin before giving it a directory a read-only or viewer-facing server watches. Each time such a tool is registered the server logs a warning naming it (``plugin tool 'plugin_ac_queue_depth' is diff --git a/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst b/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst index de8a19075..ec843a664 100644 --- a/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst +++ b/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst @@ -300,7 +300,7 @@ Bearer token 也可從 ``JE_AUTOCONTROL_MCP_TOKEN`` 環境變數讀取。 同一個檔案。未設定存放檔的有效工具 session 會使用 operator 身分;主機管理工具需要 已驗證的管理員。stdio 傳輸沒有 bearer token,其有效工具 session 也受相同 operator 範圍約束。 -- 工具預設依 ``readOnlyHint`` 使用 ``read_screen``,否則為 ``drive_input``,另有明確 +- 工具預設依 ``readOnlyHint`` 使用 ``read_data``,否則為 ``drive_input``,另有明確 的 capability 覆寫。敏感讀取需要 ``drive_input`` (operator/admin):剪貼簿與歷史、 本機文件/資料/SQL、dotenv 與參照解析、JWT/OTP 產生、持久存放區讀取、對外 HTTP/port/S3 檢查、麥克風擷取與外部 VLM 請求。斷言容器的 spec 可能讀取相同資源, @@ -324,12 +324,11 @@ Bearer token 也可從 ``JE_AUTOCONTROL_MCP_TOKEN`` 環境變數讀取。 具名儲存區(``ac_sql_query``、``ac_assert_db``、``ac_get_asset``、``ac_list_assets``、 ``ac_cas_get``、``ac_outbox_pending``、``ac_checkpoint_status``、``ac_memory_recall``、 ``ac_memory_recent``、``ac_s3_list``);參照與 token(``ac_resolve_ref``、 - ``ac_resolve_refs``、``ac_generate_otp``、``ac_jwt_encode``、``ac_jwt_decode``); + ``ac_resolve_refs``、``ac_generate_otp``、``ac_jwt_encode``); 以及行程清單、網路與麥克風探測(``ac_list_processes``、``ac_assert_process``、 ``ac_wait_for_process``、``ac_assert_http``、``ac_wait_for_port``、 ``ac_assert_audio``)。完整清單是 ``je_auto_control.utils.rbac.policy`` 的 - ``DATA_TOOLS``。其餘唯讀工具 ``viewer`` 都保留:螢幕尺寸、視窗、像素、影像與文字 - 定位、無障礙讀取、等待。 + ``DATA_TOOLS``。 - 這份清單背後的規則:回傳\ **主機保存的紀錄或設定**\ 的工具需要 ``read_data``; 只觀察目前畫面的工具需要 ``read_screen``。所以 ``read_data`` 也包含執行歷史與由它 算出來的結果(``ac_list_run_history``、``ac_flaky_report``、``ac_rank_tests``、 @@ -345,9 +344,6 @@ Bearer token 也可從 ``JE_AUTOCONTROL_MCP_TOKEN`` 環境變數讀取。 以及連線裝置的剪貼簿(``ac_android_get_clipboard``、 ``ac_ios_get_clipboard``)。這些以前是 ``read_screen``,所以\ **viewer 的 token 現在不能呼叫它們**\ ;``operator`` 與 ``admin`` 不受影響。 -- 一次呼叫要花多少錢不是一種能力。``ac_vlm_locate`` 與 ``ac_self_heal_locate`` 讀的是 - 畫面,雖然呼叫可能被模型供應商計費,仍然是 ``read_screen``;要限制花費,請用 - rate limiter,或不要在 viewer 連得到的伺服器上設定 VLM 後端。 - REST API 依同一條規則:``GET /history`` 與 ``GET /usb/acl`` 和 ``ac_list_run_history``、``ac_usb_acl_list`` 一樣需要 ``read_data``,所以 viewer 的 token 在那裡也讀不到執行歷史與 USB ACL(見維運章節的 REST 表格)。 @@ -356,10 +352,6 @@ Bearer token 也可從 ``JE_AUTOCONTROL_MCP_TOKEN`` 環境變數讀取。 與即時畫面需要 ``read_screen``\ 。\ ``resources/list`` 只列出呼叫者讀得到的, ``resources/read`` 與 ``resources/subscribe`` 對其餘的回 ``-32003``\ 。伺服器不認得的 resource URI(自訂 provider 的)視為已儲存的資料,需要 ``read_data``\ 。 -- 回報這個行程目前狀態、而不是保存紀錄的工具——``ac_list_executions``、 - ``ac_scheduler_list_jobs``、``ac_trigger_list``、``ac_hotkey_list``、 - ``ac_observe_list``、``ac_watchdog_list``、``ac_journal_status``、USB 裝置清單—— - 維持 ``read_screen``。 - ``tools/list`` 只回呼叫者可以呼叫的工具;對其他工具 ``tools/call`` 會回 JSON-RPC 錯誤 ``-32003``\ (``Forbidden: ...``、``data.required_capability``),且不會執行。 - 接受動作清單的工具(``ac_execute_actions`` 等)在清單含有呼叫者角色沒有的指令時 @@ -700,14 +692,14 @@ Plugin Hot-Reload 這個工具就會以 ``readOnlyHint`` 為 true 註冊。唯讀伺服器在三種工具模式下都會列出並執行它 (``full``、``progressive`` —— 啟用之後 —— 以及 profile 有列它的 ``static``),在 RBAC 下 -只需要 ``read_screen``,所以 ``viewer`` 可以呼叫。從 plugin 取用的只有唯讀這一項; +需要 ``read_data``,所以 ``viewer`` 不能呼叫。從 plugin 取用的只有唯讀這一項; 工具不會被標成 idempotent。 .. warning:: 這個宣告是\ **被信任的,不是被驗證的**。它只是 plugin 作者的說法:伺服器無從得知 任意的 Python 程式做了什麼,一個宣告自己唯讀、實際上卻寫檔或送出輸入的 callable, - 在唯讀伺服器上、對 viewer 也照樣會那樣做。宣告不會把它關進沙箱。把 plugin 放進 + 在唯讀伺服器上、對有權限的呼叫者也照樣會那樣做。宣告不會把它關進沙箱。把 plugin 放進 唯讀或給 viewer 用的伺服器所監看的目錄之前,請先審查它。每次註冊這樣的工具, 伺服器都會記一筆指名它的 warning(``plugin tool 'plugin_ac_queue_depth' is registered read-only because its plugin declared mcp_read_only=True; the @@ -767,3 +759,7 @@ CI runner 也能走完所有 MCP 工具: 受管任務、觸發範本及技能驗證持續檢查來源根目錄政策。撤銷、遺失或損壞的政策紀錄會阻止後續操作。MCP 客戶端根目錄與非同步更新依連線階段隔離,過期回覆不能恢復已終止的授權。主機固定政策在更換前保留;客戶端政策在來源結束時撤銷。HTTP 客戶端根目錄不再改寫共用資源提供者的工作目錄。服務停止會取消所有實際執行中的 worker,包含尚未取得 lease 的模型初始化;尚未啟動的派送保留供服務重啟。 舊式 MCP 包裝及平行/本機 DAG worker 保留來源限制的交集。工具 context 的綁定不會自行建立紀錄,由受管任務分派延後解析。 + +MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 ``read_screen``;檔案、裝置資料及未知工具需要 ``read_data``。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 ``read_data``。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 ``read_data``,VLM 請求需要 ``drive_input``。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 + +主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 4d085091c..c2d20c595 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -43,3 +43,9 @@ - **What:** WorkspaceShell uses the supplied registry and preserves the embedded AutoControlGUIWidget entry point. Weak close observers honor direct registry closes and refused closes. Page destruction clears only its own cached identity. View exposes collapsible execution details; Diagnostics publishes real progress, stop and terminal states without moving task ownership. Active-source checks reject stale detail signals. All four language catalogues are updated. - **Evidence:** Implementation passed 216 focused tests and 21 quality gates. Independent review passed 171 tests, verified Qt-free registry import, and found one line-length issue that was corrected. Parent integration passed 90 tests and quality gates plus a warnings-as-errors Sphinx dummy build. Ordinary and real-Qt typing passed all three targets for six changed GUI modules. Ruff, Bandit and Radon passed; raw Pylint error output retains known compiled-Qt import inference failures. Parent viewed standalone 640x420 offscreen renders with 16pt text and confirmed wrapping, vertical scrolling and collapsed width. This is not native or mixed-DPI acceptance. - **Open items:** Other panel execution/permission states and native acceptance remain in Progress.md. + +## U-20261111-20 · 2026-11-11 · Enforce reviewed MCP capabilities at every invocation · #done #security + +- **What:** Source review covered all 373 formerly viewer-visible descriptors. Explicit canonical policy preserves reviewed screen/caller-data tools and stronger overrides, gates mixed file/environment/VLM/capture arguments, and restricts unknown read-only hints. Default, explicit and dynamically registered readonly catalogues share the same filtering and invocation guard. Fresh invocation authority and failure-artifact capture revalidate current grants. MCP CI annotations return formatted data without stdout pollution. Measured catalogues contain 820 full, 461 readonly and 289 viewer-visible tools. +- **Evidence:** Broad MCP/RBAC testing passed 1,147 cases with four obsolete policy assertions; after migration, all 56 affected cases passed. Independent review reproduced and verified fixes for error-artifact capture, explicit-registry readonly bypass and argument authority after revocation. Its selected run passed 429 before a stale fixture was corrected, then all 112 follow-up cases. Parent integration passed 484 cases and quality gates plus a warnings-as-errors Sphinx dummy build. Three-target typing, Ruff, Bandit, complexity and strict Sphinx passed. Tests use fake handlers and loopback transports, without native input, capture or device calls. +- **Open items:** Three external initializer contracts, diagnostic SQLite initialization effects and real-client acceptance remain in Progress.md. This does not claim globally zero filesystem mutation or a sandbox for trusted host Python plugins. diff --git a/docs/updates/README.md b/docs/updates/README.md index 26db0e387..230a730a7 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-20 | 2026-11-11 | Enforce reviewed MCP capabilities at every invocation | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-19 | 2026-11-11 | Add an injectable workspace and live execution details | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-18 | 2026-11-11 | Release remote pages without retaining callback owners | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-17 | 2026-11-11 | Start and stop WebRTC statistics without waiting | #done #gui | [2026-11-b](2026-11-b.md) | @@ -638,7 +639,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 8 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 9 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/mcp_server/_authz.py b/je_auto_control/utils/mcp_server/_authz.py index 8c30fa352..81da0fc6e 100644 --- a/je_auto_control/utils/mcp_server/_authz.py +++ b/je_auto_control/utils/mcp_server/_authz.py @@ -14,16 +14,17 @@ token does not identify an administrator. Authenticated roles remain opt-in. """ import hmac -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from je_auto_control.utils.mcp_server._protocol import _MCPError from je_auto_control.utils.mcp_server.audit import AuditLogger from je_auto_control.utils.mcp_server.tools import MCPTool from je_auto_control.utils.rbac.authorization import ( - AuthorizationContext, current_authorization, resolve_token, + AuthorizationContext, AuthorizationError, current_authorization, resolve_token, ) -from je_auto_control.utils.rbac.policy import capability_for_tool, denied_command_in +from je_auto_control.utils.rbac.policy import capabilities_for_tool_call, capability_for_tool, denied_command_in from je_auto_control.utils.rbac.users import Capability, UserStore +from je_auto_control.utils.rbac.deferred import DeferredAuthorization #: JSON-RPC error code of a call refused for the caller's role. FORBIDDEN_CODE = -32003 @@ -72,6 +73,20 @@ def _tool_capability(tool: MCPTool) -> str: return capability_for_tool(tool.name, tool.annotations.read_only) +def capture_error_artifact(tool: MCPTool, read_only: bool, + capture: Callable[[str], Optional[str]]) -> Optional[str]: + """Capture only with writable tool ownership and current caller authority.""" + if read_only or tool.enforce_readonly_arguments: + return None + try: + with DeferredAuthorization.capture().context_scope() as caller: + if caller is not None and not caller.allows(Capability.DRIVE_INPUT): + return None + return capture(tool.name) + except (AuthorizationError, OSError, ValueError): + return None + + def visible_tools(tools: List[MCPTool]) -> List[MCPTool]: """The tools the current caller may call; all of them outside an RBAC scope.""" caller = current_authorization() @@ -92,9 +107,10 @@ def authorize_tool_call(tool: MCPTool, arguments: Dict[str, Any], caller = current_authorization() if caller is None: return - needed: Optional[str] = _tool_capability(tool) + needed = next((capability for capability in capabilities_for_tool_call( + tool.name, tool.annotations.read_only, arguments) if not caller.allows(capability)), None) reason = f"tool {tool.name!r}" - if caller.allows(str(needed)): + if needed is None: denied = denied_command_in(arguments, caller) if denied is None: return diff --git a/je_auto_control/utils/mcp_server/_call_authority.py b/je_auto_control/utils/mcp_server/_call_authority.py index ae45de329..901ee527d 100644 --- a/je_auto_control/utils/mcp_server/_call_authority.py +++ b/je_auto_control/utils/mcp_server/_call_authority.py @@ -6,7 +6,7 @@ from je_auto_control.utils.rbac.authorization import AuthorizationContext, AuthorizationError, current_authorization from je_auto_control.utils.rbac.deferred import DeferredAuthorization -from je_auto_control.utils.rbac.policy import capability_for_tool, denied_command_in +from je_auto_control.utils.rbac.policy import capabilities_for_tool_call, denied_command_in @contextmanager @@ -23,9 +23,9 @@ def invocation_authority(tool: Any, arguments: dict, context: Any) -> Iterator[N def _require(identity: AuthorizationContext, tool: Any, arguments: dict) -> None: - needed = capability_for_tool(tool.name, tool.annotations.read_only) - if not identity.allows(needed): - raise AuthorizationError(f"{tool.name} requires {needed}", capability=needed) + for needed in capabilities_for_tool_call(tool.name, tool.annotations.read_only, arguments): + if not identity.allows(needed): + raise AuthorizationError(f"{tool.name} requires {needed}", capability=needed) denied = denied_command_in(arguments, identity) if denied is not None: raise AuthorizationError(f"{denied[0]} requires {denied[1]}", capability=denied[1]) diff --git a/je_auto_control/utils/mcp_server/_disclosure_server.py b/je_auto_control/utils/mcp_server/_disclosure_server.py index 4439c075b..f068d5aad 100644 --- a/je_auto_control/utils/mcp_server/_disclosure_server.py +++ b/je_auto_control/utils/mcp_server/_disclosure_server.py @@ -10,6 +10,7 @@ from je_auto_control.utils.mcp_server.disclosure import CORE_TOOLS, ToolView, validate_tool_profile from je_auto_control.utils.mcp_server._protocol import _MCPError from je_auto_control.utils.mcp_server.tools._base import MCPTool, read_only_env_flag +from je_auto_control.utils.mcp_server.tools._readonly import readonly_tools from je_auto_control.utils.rbac.authorization import AuthorizationContext, current_authorization from je_auto_control.utils.rbac.deferred import DeferredAuthorization @@ -110,6 +111,14 @@ def _accepted_tool_view(self) -> ToolView: raise _MCPError(-32602, str(error)) from error return view + def _tool_for_invocation(self, tool: MCPTool) -> MCPTool: + if not self._read_only_tools: + return tool + variants = readonly_tools([tool]) + if not variants: + raise _MCPError(-32602, f"Tool unavailable in read-only mode: {tool.name}") + return variants[0] + def _require_disclosed_tool(self, name: str, view: ToolView | None = None, tool: MCPTool | None = None) -> None: if self._disclosure_mode == "full" and not self._read_only_tools: return @@ -124,7 +133,7 @@ def _require_disclosed_tool(self, name: str, view: ToolView | None = None, tool: def _core_tool_available(self, tool: MCPTool | None) -> bool: return (tool is not None and tool.name in CORE_TOOLS - and (not self._read_only_tools or tool.annotations.read_only)) + and (not self._read_only_tools or bool(readonly_tools([tool])))) def _handle_tools_list(self, params: dict[str, Any] | None = None) -> dict[str, Any]: """List one availability snapshot, preserving full-mode and stateless response compatibility.""" diff --git a/je_auto_control/utils/mcp_server/discovery.py b/je_auto_control/utils/mcp_server/discovery.py index fa7723aa0..1d6cf3eb5 100644 --- a/je_auto_control/utils/mcp_server/discovery.py +++ b/je_auto_control/utils/mcp_server/discovery.py @@ -11,6 +11,7 @@ from je_auto_control.utils.rbac.deferred import DeferredAuthorization from je_auto_control.utils.rbac.policy import capability_for_tool from je_auto_control.utils.mcp_server.tools._base import MCPTool +from je_auto_control.utils.mcp_server.tools._readonly import readonly_tools if TYPE_CHECKING: import threading @@ -136,5 +137,5 @@ def tool_index(self) -> ToolIndex: def _filtered_tool_index(self, read_only: bool) -> ToolIndex: with self._tools_lock: - return ToolIndex(tool for tool in self._tools.values() - if not read_only or tool.annotations.read_only) + tools = list(self._tools.values()) + return ToolIndex(readonly_tools(tools) if read_only else tools) diff --git a/je_auto_control/utils/mcp_server/server.py b/je_auto_control/utils/mcp_server/server.py index 56223ee9f..7610164c6 100644 --- a/je_auto_control/utils/mcp_server/server.py +++ b/je_auto_control/utils/mcp_server/server.py @@ -20,7 +20,7 @@ from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.logging.secret_scope import secret_log_scope from je_auto_control.utils.mcp_server._authz import ( - authorize_resource, authorize_tool_call, visible_resources, + authorize_resource, authorize_tool_call, capture_error_artifact, visible_resources, ) from je_auto_control.utils.mcp_server.audit import AuditLogger from je_auto_control.utils.mcp_server._disclosure_server import DisclosureServerMixin @@ -638,6 +638,7 @@ def _prepare_tool_call( tool = self._tools.get(name) if tool is None: raise _MCPError(-32602, f"Unknown tool: {name}") + tool = self._tool_for_invocation(tool) authorize_tool_call(tool, arguments, self._audit) # RBAC; a no-op without a user self._require_disclosed_tool(name, tool_view, tool) violation = (validate_arguments(tool.input_schema, arguments) @@ -683,7 +684,7 @@ def _handle_tools_call(self, msg_id: Any, # left the call unanswered (stdio) or dropped the connection (HTTP). except Exception as error: # noqa: BLE001 # reason: a tool's failure of any type must answer the call with isError autocontrol_logger.warning("MCP tool %s failed: %r", name, error) - artifact = _capture_error_screenshot(name) + artifact = capture_error_artifact(tool, self._read_only_tools, _capture_error_screenshot) self._audit.record( tool=name, arguments=arguments, status="error", duration_seconds=time.monotonic() - started_at, diff --git a/je_auto_control/utils/mcp_server/tools/__init__.py b/je_auto_control/utils/mcp_server/tools/__init__.py index ec67ad437..cc3da55fc 100644 --- a/je_auto_control/utils/mcp_server/tools/__init__.py +++ b/je_auto_control/utils/mcp_server/tools/__init__.py @@ -9,6 +9,8 @@ from dataclasses import replace from typing import Callable, Dict, List, Optional +from je_auto_control.utils.rbac.tool_classification import TOOL_ALIASES + from je_auto_control.utils.mcp_server.tools._base import ( MCPContent, MCPTool, MCPToolAnnotations, MCPToolDescriptor, MCPToolResult, read_only_env_flag, ) @@ -20,27 +22,7 @@ # Short, model-friendly aliases for the most-used tools. Each alias is # registered as an additional MCPTool entry pointing at the same handler. -_DEFAULT_ALIASES: Dict[str, str] = { - "click": "ac_click_mouse", - "move_mouse": "ac_set_mouse_position", - "mouse_pos": "ac_get_mouse_position", - "scroll": "ac_mouse_scroll", - "type": "ac_type_text", - "press": "ac_press_key", - "hotkey": "ac_hotkey", - "screenshot": "ac_screenshot", - "screen_size": "ac_screen_size", - "find_image": "ac_locate_image_center", - "find_text": "ac_locate_text", - "click_text": "ac_click_text", - "drag": "ac_drag", - "list_windows": "ac_list_windows", - "focus_window": "ac_focus_window", - "wait_image": "ac_wait_for_image", - "wait_pixel": "ac_wait_for_pixel", - "diff_screens": "ac_diff_screenshots", - "shell": "ac_shell", -} +_DEFAULT_ALIASES = TOOL_ALIASES #: The canonical tools behind the aliases: the handful most sessions need. @@ -99,7 +81,8 @@ def build_default_tool_registry(read_only: Optional[bool] = None, tools.extend(tool if tool.category else replace(tool, category=category) for tool in factory()) if enforce_read_only: - tools = [tool for tool in tools if tool.annotations.read_only] + from je_auto_control.utils.mcp_server.tools._readonly import readonly_tools + tools = readonly_tools(tools) if _aliases_enabled(aliases): tools.extend(_make_aliases(tools)) return tools diff --git a/je_auto_control/utils/mcp_server/tools/_base.py b/je_auto_control/utils/mcp_server/tools/_base.py index cdba272fa..099ce8647 100644 --- a/je_auto_control/utils/mcp_server/tools/_base.py +++ b/je_auto_control/utils/mcp_server/tools/_base.py @@ -145,6 +145,7 @@ class MCPTool: annotations: MCPToolAnnotations = MCPToolAnnotations() output_schema: Optional[Dict[str, Any]] = None category: str = "" + enforce_readonly_arguments: bool = False def descriptor(self) -> MCPToolDescriptor: """Return the typed form of :meth:`to_descriptor`.""" @@ -183,6 +184,9 @@ def invoke(self, arguments: Dict[str, Any], ctx: Any = None) -> Any: A source path policy follows managed submissions through legacy wrappers. Task-aware dispatch resolves this lazily carried policy's private metadata. """ + if self.enforce_readonly_arguments: + from je_auto_control.utils.mcp_server.tools._readonly import check_readonly_arguments + check_readonly_arguments(self.name, arguments) from je_auto_control.utils.script_vars.execution import execution_scope from je_auto_control.utils.agent_runtime.origin_policy import source_policy_scope from je_auto_control.utils.mcp_server._call_authority import invocation_authority diff --git a/je_auto_control/utils/mcp_server/tools/_factories.py b/je_auto_control/utils/mcp_server/tools/_factories.py index 94361eac9..4779ef46f 100644 --- a/je_auto_control/utils/mcp_server/tools/_factories.py +++ b/je_auto_control/utils/mcp_server/tools/_factories.py @@ -3537,9 +3537,9 @@ def ci_annotation_tools() -> List[MCPTool]: return [ MCPTool( name="ac_ci_annotations", - description=("Emit GitHub Actions workflow annotations from result " - "dicts ({level, message, file?, line?, title?}) so " - "failures show inline in a PR. Returns the {lines}."), + description=("Format GitHub Actions workflow annotations from result " + "dicts ({level, message, file?, line?, title?}). " + "Returns {lines} without writing to stdout."), input_schema=schema({ "annotations": {"type": "array", "items": {"type": "object"}}}, diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_operations.py b/je_auto_control/utils/mcp_server/tools/_handlers_operations.py index b4258e5d0..a36d89285 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_operations.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_operations.py @@ -176,9 +176,10 @@ def checkpoint_clear(run_id, db): return {"cleared": CheckpointStore(db).clear(run_id)} -def ci_annotations(annotations): - from je_auto_control.utils.ci_annotations import emit_annotations - return {"lines": emit_annotations(annotations)} +def ci_annotations(annotations: List[Dict[str, Any]]) -> Dict[str, List[str]]: + """Return formatted annotations without writing into the MCP transport.""" + from je_auto_control.utils.ci_annotations import format_annotation + return {"lines": [format_annotation(item) for item in annotations]} def scan_secrets(data): diff --git a/je_auto_control/utils/mcp_server/tools/_readonly.py b/je_auto_control/utils/mcp_server/tools/_readonly.py new file mode 100644 index 000000000..f0e2471f1 --- /dev/null +++ b/je_auto_control/utils/mcp_server/tools/_readonly.py @@ -0,0 +1,32 @@ +"""Read-only registry variants with enforced argument restrictions.""" +import copy +from collections.abc import Mapping +from dataclasses import replace + +from je_auto_control.utils.mcp_server.tools._base import MCPTool +from je_auto_control.utils.rbac.tool_classification import UNREVIEWED_EXTERNAL_TOOLS, argument_capability +from je_auto_control.utils.rbac.users import Capability + + +def check_readonly_arguments(name: str, arguments: Mapping[str, object]) -> None: + """Reject known mutating argument branches even without schema validation.""" + if arguments.get("capture_on_fail") or argument_capability(name, arguments) == Capability.DRIVE_INPUT: + from je_auto_control.utils.exception.exceptions import AutoControlActionException + raise AutoControlActionException("read-only tool refuses mutating arguments") + + +def readonly_tools(tools: list[MCPTool]) -> list[MCPTool]: + """Exclude executable selectors and forbid optional capture writes.""" + result: list[MCPTool] = [] + for tool in tools: + properties = tool.input_schema.get("properties", {}) + if not tool.annotations.read_only or "adb_path" in properties: + continue + if tool.name in UNREVIEWED_EXTERNAL_TOOLS: + continue + if "capture_on_fail" in properties: + schema = copy.deepcopy(tool.input_schema) + schema["properties"]["capture_on_fail"]["enum"] = [False] + tool = replace(tool, input_schema=schema) + result.append(replace(tool, enforce_readonly_arguments=True)) + return result diff --git a/je_auto_control/utils/rbac/policy.py b/je_auto_control/utils/rbac/policy.py index 4afc6e57f..19d2334cc 100644 --- a/je_auto_control/utils/rbac/policy.py +++ b/je_auto_control/utils/rbac/policy.py @@ -7,8 +7,9 @@ than open. A ``GET`` route that returns records or configuration the host keeps needs ``read_data`` like the MCP tool reading the same thing; one that observes live state needs ``read_screen``. -* **MCP tools** default to ``read_screen`` for a read-only annotation and - ``drive_input`` otherwise. Named overrides separate non-mutating sensitive +* **MCP tools** default to ``read_data`` for a read-only annotation and + ``drive_input`` otherwise. Only reviewed screen/caller-data tools grant + ``read_screen``. Named overrides separate non-mutating sensitive reads (clipboard, local data, credentials, network and audio) from screen observation, hand the host's records to ``read_data``, manage users, and protect administration of the host itself. @@ -26,6 +27,7 @@ """ from __future__ import annotations +from collections.abc import Mapping from typing import Any, Dict, Iterator, Optional, Tuple from je_auto_control.utils.rbac.authorization import ( @@ -185,13 +187,9 @@ #: says a tool changes nothing; it does not say that what it returns is #: something a viewer of the desktop was meant to see. #: -#: The rule: a tool that returns records or configuration the host keeps -- -#: history, traces, cost ledgers, healing logs, journals, saved libraries, ACL -#: contents -- is listed here; a tool that only observes the live screen (or -#: computes on what the caller sent) is not. What a tool costs to run is a -#: separate question this table does not answer: ``ac_vlm_locate`` and -#: ``ac_self_heal_locate`` read the screen and stay ``read_screen`` although a -#: call may be billed by a model provider. +#: These explicit data classifications remain stable when annotations change. +#: Other read-only tools also default to READ_DATA unless their canonical name +#: has a reviewed screen classification. Effectful overrides take precedence. DATA_TOOLS = frozenset({ # the clipboard and its history, a connected device's included "ac_get_clipboard", "ac_get_clipboard_csv", "ac_get_clipboard_files", @@ -365,10 +363,24 @@ def capability_for_route(method: str, path: str) -> str: def capability_for_tool(name: str, read_only: bool) -> str: """The capability the MCP tool ``name`` needs, given its read-only hint.""" + from je_auto_control.utils.rbac.tool_classification import ( + MIXED_ARGUMENT_TOOLS, SCREEN_SOURCE_TOOLS, SCREEN_TOOLS, canonical_tool_name, + ) + name = canonical_tool_name(name) listed = TOOL_CAPABILITIES.get(name) if listed is not None: return listed - return _READ if read_only else _DRIVE + if not read_only: + return _DRIVE + return _READ if name in SCREEN_TOOLS or name in SCREEN_SOURCE_TOOLS or name in MIXED_ARGUMENT_TOOLS else _DATA + + +def capabilities_for_tool_call(name: str, read_only: bool, arguments: Mapping[str, object]) -> tuple[str, ...]: + """Use one base and argument policy at admission and refreshed invocation.""" + from je_auto_control.utils.rbac.tool_classification import argument_capability + base = capability_for_tool(name, read_only) + extra = argument_capability(name, arguments) + return (base,) if extra is None or extra == base else (base, extra) def capability_for_command(name: str) -> str: diff --git a/je_auto_control/utils/rbac/tool_classification.py b/je_auto_control/utils/rbac/tool_classification.py new file mode 100644 index 000000000..040ff63ea --- /dev/null +++ b/je_auto_control/utils/rbac/tool_classification.py @@ -0,0 +1,391 @@ +"""Reviewed MCP screen capabilities and canonical tool aliases. + +Read-only hints describe effects, not permission to read host data. Only +reviewed screen and caller-data operations belong here. Unknown tools require +READ_DATA; trusted host registration can still replace a named handler. +""" +from collections.abc import Callable, Mapping +import json + +TOOL_ALIASES: dict[str, str] = { + "click": "ac_click_mouse", + "move_mouse": "ac_set_mouse_position", + "mouse_pos": "ac_get_mouse_position", + "scroll": "ac_mouse_scroll", + "type": "ac_type_text", + "press": "ac_press_key", + "hotkey": "ac_hotkey", + "screenshot": "ac_screenshot", + "screen_size": "ac_screen_size", + "find_image": "ac_locate_image_center", + "find_text": "ac_locate_text", + "click_text": "ac_click_text", + "drag": "ac_drag", + "list_windows": "ac_list_windows", + "focus_window": "ac_focus_window", + "wait_image": "ac_wait_for_image", + "wait_pixel": "ac_wait_for_pixel", + "diff_screens": "ac_diff_screenshots", + "shell": "ac_shell", +} + +# Reviewed adapters observe the live desktop or compute only from caller data. +SCREEN_TOOLS = frozenset({ + "ac_a11y_dump", + "ac_a11y_find", + "ac_a11y_find_all", + "ac_a11y_focused", + "ac_a11y_list", + "ac_ab_significance", + "ac_adaptive_timeout", + "ac_adjust_delays", + "ac_apply_json_patch", + "ac_apply_unified", + "ac_apply_vex", + "ac_assert_pixel", + "ac_assert_session_active", + "ac_assert_text", + "ac_assert_window", + "ac_assign_stable_ids", + "ac_associate_fields", + "ac_audit_accessibility", + "ac_audit_contrast", + "ac_audit_focus_order", + "ac_baggage_format", + "ac_baggage_parse", + "ac_best_candidate", + "ac_bidi_check", + "ac_build_critic_record", + "ac_build_multipart", + "ac_build_timeline", + "ac_burn_alerts", + "ac_canonical_log", + "ac_canonicalize_url", + "ac_cascade_rects", + "ac_categorical_drift", + "ac_cell_by_header", + "ac_cell_changes", + "ac_cell_for_point", + "ac_check_accepted_values", + "ac_check_catalog", + "ac_check_compatibility", + "ac_check_foreign_key", + "ac_check_licenses", + "ac_check_overflow", + "ac_check_postcondition", + "ac_check_row_count", + "ac_check_unique_key", + "ac_checksum_digit", + "ac_checksum_validate", + "ac_ci_annotations", + "ac_classify_effect", + "ac_classify_formats", + "ac_classify_lines", + "ac_classify_lock_transitions", + "ac_classify_widget", + "ac_client_point", + "ac_cofailure_pairs", + "ac_collation_compare", + "ac_collation_sort", + "ac_colors_collide", + "ac_column_gutters", + "ac_compare_field_value", + "ac_confusable_compare", + "ac_confusable_scan", + "ac_consensus_element", + "ac_consensus_point", + "ac_control_expand_state", + "ac_control_get_state", + "ac_control_get_value", + "ac_control_range", + "ac_control_text_attributes", + "ac_cookie_header", + "ac_critical_steps", + "ac_cua_command", + "ac_decision_table", + "ac_decode_body", + "ac_decode_conversion_mode", + "ac_dedupe_moves", + "ac_delta_observation", + "ac_describe_stats", + "ac_detect_anomalies", + "ac_detect_borderless_table", + "ac_detect_drift", + "ac_detect_lists", + "ac_detect_pii", + "ac_diff_formats", + "ac_diff_json", + "ac_diff_rows", + "ac_diff_runs", + "ac_dominant_hue_regions", + "ac_dominant_pair", + "ac_effect_near_point", + "ac_enumerate_monitors", + "ac_evaluate_flag", + "ac_evaluate_slo", + "ac_evaluate_trajectory", + "ac_ewma", + "ac_explain_config", + "ac_extract_fields", + "ac_failure_clusters", + "ac_failure_signature", + "ac_find_color_region", + "ac_find_control_text", + "ac_find_grid", + "ac_find_lines", + "ac_find_rectangles", + "ac_find_separators", + "ac_find_shapes", + "ac_find_text_lines", + "ac_find_text_regions", + "ac_flag_enabled", + "ac_flow_order", + "ac_foreground_window", + "ac_foreground_window_pid", + "ac_format_currency", + "ac_format_date", + "ac_format_decimal", + "ac_format_list", + "ac_format_message", + "ac_fuse_elements", + "ac_fuzzy_best_match", + "ac_fuzzy_dedupe", + "ac_fuzzy_ratio", + "ac_get_client_rect", + "ac_get_control_text", + "ac_get_element_properties", + "ac_get_mouse_position", + "ac_get_pixel", + "ac_get_selected_text", + "ac_get_selection", + "ac_get_visible_text", + "ac_gettext_ngettext", + "ac_gettext_translate", + "ac_grade_contrast", + "ac_grid_cell", + "ac_grid_cells", + "ac_grid_rects", + "ac_group_failures", + "ac_group_paragraphs", + "ac_guard_text", + "ac_http_replay", + "ac_humanize_role", + "ac_idle_point", + "ac_idle_seconds", + "ac_ime_state", + "ac_infer_schema", + "ac_is_composing", + "ac_json_extract", + "ac_json_query", + "ac_jwt_decode", + "ac_label_color", + "ac_legacy_info", + "ac_list_action_commands", + "ac_list_monitors", + "ac_list_views", + "ac_list_windows", + "ac_locate_chain", + "ac_locate_text", + "ac_make_json_patch", + "ac_mask_rows", + "ac_match_elements", + "ac_match_json", + "ac_match_labels_to_widgets", + "ac_mcp_tool_schema", + "ac_mcp_tool_search", + "ac_mcp_tools_disable", + "ac_mcp_tools_enable", + "ac_mcp_tools_state", + "ac_merge_patch", + "ac_merge_results", + "ac_merge_sleeps", + "ac_mine_actions", + "ac_monitor_at_point", + "ac_near_duplicates", + "ac_next_url", + "ac_normalize_ext", + "ac_normalize_text", + "ac_normalize_url", + "ac_observation_index", + "ac_ocr_read_structure", + "ac_outline", + "ac_parse_cache_control", + "ac_parse_decimal", + "ac_parse_dotenv", + "ac_parse_link_header", + "ac_parse_multipart", + "ac_parse_number", + "ac_parse_problem", + "ac_parse_quality_values", + "ac_parse_set_cookie", + "ac_parse_sse", + "ac_percentiles", + "ac_place_labels", + "ac_plan_file_drop", + "ac_plan_keep_awake", + "ac_plan_lock_session", + "ac_plan_repair", + "ac_plan_retry_delays", + "ac_point_for_cell", + "ac_populate_table", + "ac_profile_rows", + "ac_propose_elements", + "ac_pseudo_localize", + "ac_rank_changes", + "ac_read_table", + "ac_readability_report", + "ac_reading_order", + "ac_redact_config", + "ac_redact_pii", + "ac_redact_secret_text", + "ac_region_contrast", + "ac_resolve_config", + "ac_resolve_pointer", + "ac_retry_after", + "ac_retry_delay", + "ac_rrule_next", + "ac_rrule_occurrences", + "ac_scale_coordinates", + "ac_scan_secrets", + "ac_scan_vulns", + "ac_score_candidates", + "ac_score_step", + "ac_screen_diff", + "ac_screen_size", + "ac_search_documents", + "ac_segment_hsv", + "ac_serialize_observation", + "ac_settle_point", + "ac_simhash", + "ac_simulate_cvd", + "ac_slugify", + "ac_sma", + "ac_soft_assert", + "ac_spans_to_otlp", + "ac_store_validators", + "ac_sync_entry_merge", + "ac_sync_peer_state", + "ac_tab_order", + "ac_table_cell", + "ac_table_headers", + "ac_tag_kinds", + "ac_text_similarity", + "ac_three_way_merge", + "ac_tile_rect", + "ac_timeout_stats", + "ac_to_model", + "ac_to_physical", + "ac_trace_extract", + "ac_trace_inject", + "ac_trim_actions", + "ac_ts_downsample", + "ac_ts_rate", + "ac_unified_diff", + "ac_urls_equal", + "ac_validate_action", + "ac_validate_json", + "ac_validate_rows", + "ac_verify_field_value", + "ac_vote_centers", + "ac_wait_color", + "ac_wait_for_composition_commit", + "ac_wait_for_focus_change", + "ac_wait_for_pixel", + "ac_wait_for_window", + "ac_wait_pixel_changes", + "ac_wait_region_idle", + "ac_wait_screen_stable", + "ac_wait_text_gone", + "ac_wait_until_app_idle", + "ac_wait_window_title", + "ac_walk_tree", + "ac_wcag_audit", + "ac_window_interaction_state", + "ac_window_pid", + "ac_window_rect", + "ac_windows_for_pid", + "ac_xy_cut", +}) + +# Each of these exact adapters captures the screen when source is None and +# passes a supplied source to an image loader otherwise. +SCREEN_SOURCE_TOOLS = frozenset({ + "ac_image_histogram", "ac_image_quality", "ac_quality_gate", + "ac_salient_regions", "ac_most_salient", "ac_read_barcodes", +}) + +CAPTURE_ASSERTIONS = frozenset({ + "ac_assert_text", "ac_assert_image", "ac_assert_pixel", "ac_assert_window", + "ac_assert_clipboard", "ac_assert_process", +}) + + +def canonical_tool_name(name: str) -> str: + """Resolve only the aliases declared by the trusted built-in registry.""" + return TOOL_ALIASES.get(name, name) + + +UNREVIEWED_EXTERNAL_TOOLS = frozenset({"ac_list_plugins", "ac_web_list_commands", "ac_web_current_url"}) + +ANCHOR_TOOLS = frozenset({"ac_anchor_locate", "ac_anchor_locate_all"}) +ANDROID_READ_TOOLS = frozenset({ + "ac_android_list_devices", "ac_android_device_info", "ac_android_screen_info", + "ac_android_app_state", "ac_android_wait_for_app", +}) + + +def _anchor_capability(arguments: Mapping[str, object]) -> str | None: + from je_auto_control.utils.rbac.users import Capability + locators = [arguments.get(key) for key in ("anchor", "target")] + kinds = [value.get("kind") if isinstance(value, dict) else None for value in locators] + if "vlm" in kinds: + return Capability.DRIVE_INPUT + if any(kind not in ("ocr", "a11y") for kind in kinds): + return Capability.READ_DATA + return None + + +def _config_capability(arguments: Mapping[str, object]) -> str | None: + from je_auto_control.utils.rbac.users import Capability + spec, config = arguments.get("schema"), arguments.get("config") + try: + spec = json.loads(spec) if isinstance(spec, str) else spec + config = json.loads(config) if isinstance(config, str) else config + except (ValueError, TypeError): + return Capability.READ_DATA + if not isinstance(spec, dict) or not isinstance(config, dict): + return Capability.READ_DATA + for name, field in spec.items(): + if not isinstance(field, dict) or (field.get("env") and name not in config): + return Capability.READ_DATA + return None + + +def _open_capability(arguments: Mapping[str, object]) -> str | None: + from je_auto_control.utils.rbac.users import Capability + from je_auto_control.utils.shell_open.shell_open import _scheme + target = arguments.get("target") + if isinstance(target, str) and _scheme(target.strip()) is not None: + return None + return Capability.READ_DATA + + +MIXED_ARGUMENT_TOOLS: dict[str, Callable[[Mapping[str, object]], str | None]] = { + **dict.fromkeys(ANCHOR_TOOLS, _anchor_capability), + "ac_validate_config": _config_capability, + "ac_plan_open": _open_capability, +} + + +def argument_capability(name: str, arguments: Mapping[str, object]) -> str | None: + """Additional authority needed by known mixed-effect tool arguments.""" + from je_auto_control.utils.rbac.users import Capability + name = canonical_tool_name(name) + if name in CAPTURE_ASSERTIONS and arguments.get("capture_on_fail", False): + return Capability.DRIVE_INPUT + if name in ANDROID_READ_TOOLS and arguments.get("adb_path"): + return Capability.DRIVE_INPUT + if name in SCREEN_SOURCE_TOOLS and arguments.get("source") is not None: + return Capability.READ_DATA + check = MIXED_ARGUMENT_TOOLS.get(name) + return check(arguments) if check is not None else None diff --git a/pyproject.toml b/pyproject.toml index 5762fe595..0198d697f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -415,6 +415,8 @@ module = [ "je_auto_control.utils.config_sync.store", "je_auto_control.utils.config_sync.versions", "je_auto_control.utils.generate_report.report_path", + "je_auto_control.utils.rbac.tool_classification", + "je_auto_control.utils.mcp_server.tools._readonly", "je_auto_control.utils.mcp_server.tools._handlers_accessibility_executor", "je_auto_control.utils.mcp_server.tools._handlers_automation_executor", "je_auto_control.utils.mcp_server.tools._handlers_data_executor", diff --git a/test/unit_test/headless/test_mcp_disclosure_policy.py b/test/unit_test/headless/test_mcp_disclosure_policy.py index fb8c80edf..ce52a80e8 100644 --- a/test/unit_test/headless/test_mcp_disclosure_policy.py +++ b/test/unit_test/headless/test_mcp_disclosure_policy.py @@ -24,7 +24,7 @@ def inspect(ctx): return {"role": current_authorization().role, "session": ctx.session_id, "same_policy": ctx.path_policy is policy} - server = MCPServer(tools=[MCPTool("fixture", "Inspect authority", {}, inspect, + server = MCPServer(tools=[MCPTool("ac_screen_size", "Inspect authority", {}, inspect, MCPToolAnnotations(read_only=True))]) server.argument_policy = ArgumentPolicy(PathPolicy(use_client_roots=True)) replies = [] @@ -33,7 +33,7 @@ def inspect(ctx): policy = server._active_argument_policy.path_policy policy.set_client_roots([tmp_path]) assert server.handle_line(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", - "params": {"name": "fixture"}})) is None + "params": {"name": "ac_screen_size"}})) is None server._join_workers() value = json.loads(json.loads(replies[0])["result"]["content"][0]["text"]) assert value == {"role": "viewer", "session": server._agent_session + ":first", "same_policy": True} diff --git a/test/unit_test/headless/test_mcp_discovery_index.py b/test/unit_test/headless/test_mcp_discovery_index.py index 71899d52f..c69a2cb41 100644 --- a/test/unit_test/headless/test_mcp_discovery_index.py +++ b/test/unit_test/headless/test_mcp_discovery_index.py @@ -10,7 +10,7 @@ def catalog(): return [ - MCPTool("ac_read", "Read a document", {"type": "object"}, lambda: None, + MCPTool("ac_screen_size", "Read document screen size", {"type": "object"}, lambda: None, MCPToolAnnotations(read_only=True)), MCPTool("ac_click", "Click a document", {"type": "object"}, lambda: None), MCPTool("ac_agent_target", "Register host target", {"type": "object"}, lambda: None), @@ -21,7 +21,7 @@ def test_search_returns_summary_not_full_schema(): from je_auto_control.utils.mcp_server.discovery import ToolIndex index = ToolIndex(catalog()) results = index.search("document") - assert {item["name"] for item in results} == {"ac_read", "ac_click"} + assert {item["name"] for item in results} == {"ac_screen_size", "ac_click"} assert all("inputSchema" not in item and "capability" in item and "category" in item for item in results) @@ -29,7 +29,7 @@ def test_only_authorized_tools_are_indexed(): from je_auto_control.utils.mcp_server.discovery import ToolIndex index = ToolIndex(catalog()) with authorization_scope(AuthorizationContext("reader", "viewer")): - assert [item["name"] for item in index.search("")] == ["ac_read"] + assert [item["name"] for item in index.search("")] == ["ac_screen_size"] with pytest.raises(ToolDiscoveryError, match="not available"): index.get_schema("ac_click") with authorization_scope(AuthorizationContext("driver", "operator")): @@ -41,11 +41,11 @@ def test_schema_lookup_is_single_tool_and_detached(): tools = catalog() index = ToolIndex(tools) tools[0].input_schema["changed"] = True - descriptor = index.get_schema("ac_read") - assert descriptor["name"] == "ac_read" + descriptor = index.get_schema("ac_screen_size") + assert descriptor["name"] == "ac_screen_size" assert "changed" not in descriptor["inputSchema"] descriptor["inputSchema"]["corrupt"] = True - assert "corrupt" not in index.get_schema("ac_read")["inputSchema"] + assert "corrupt" not in index.get_schema("ac_screen_size")["inputSchema"] assert index.snapshot_id == ToolIndex(catalog()).snapshot_id assert index.snapshot_id != ToolIndex(tools).snapshot_id @@ -103,7 +103,7 @@ def test_queries_refresh_a_store_backed_role(tmp_path): with pytest.raises(AuthorizationError): index.search("") with pytest.raises(AuthorizationError): - index.get_schema("ac_read") + index.get_schema("ac_screen_size") def test_schema_discovery_does_not_bypass_the_argument_root_policy(tmp_path): diff --git a/test/unit_test/headless/test_mcp_plugin_read_only_declaration.py b/test/unit_test/headless/test_mcp_plugin_read_only_declaration.py index babd6f20d..bc9752c25 100644 --- a/test/unit_test/headless/test_mcp_plugin_read_only_declaration.py +++ b/test/unit_test/headless/test_mcp_plugin_read_only_declaration.py @@ -207,7 +207,7 @@ def test_a_server_that_is_not_read_only_offers_both(): @pytest.mark.parametrize("mode", _MODES) -def test_a_viewer_may_call_the_declared_tool_and_only_that_one(mode): +def test_a_viewer_cannot_call_plugins_based_on_read_only_declaration(mode): plugin = _Plugin() server = MCPServer(tools=[]) register_plugin_tools(server, plugin.commands) @@ -215,18 +215,18 @@ def test_a_viewer_may_call_the_declared_tool_and_only_that_one(mode): _enable(server, mode, _PEEK) listed = _listed(server) peek, poke = _call(server, _PEEK), _call(server, _POKE) - assert _PEEK in listed + assert _PEEK not in listed assert _POKE not in listed - assert peek["result"]["isError"] is False + assert "error" in peek assert "error" in poke - assert plugin.ran == ["peek"] + assert plugin.ran == [] -def test_the_declared_tool_needs_read_screen_and_a_role_without_it_is_refused(): +def test_the_declared_tool_needs_read_data_and_a_role_without_it_is_refused(): plugin = _Plugin() tools = [make_plugin_tool(name, handler) for name, handler in plugin.commands.items()] peek = tools[0] - assert capability_for_tool(peek.name, peek.annotations.read_only) == Capability.READ_SCREEN + assert capability_for_tool(peek.name, peek.annotations.read_only) == Capability.READ_DATA with authorization_scope(AuthorizationContext("nobody", "no-such-role")): assert visible_tools(tools) == [] with authorization_scope(AuthorizationContext("op", Role.OPERATOR)): diff --git a/test/unit_test/headless/test_mcp_readonly_authority.py b/test/unit_test/headless/test_mcp_readonly_authority.py new file mode 100644 index 000000000..f12c785f7 --- /dev/null +++ b/test/unit_test/headless/test_mcp_readonly_authority.py @@ -0,0 +1,142 @@ +"""Host readonly ceilings and refreshed authority protect late invocation effects.""" +from dataclasses import replace +import json + +import pytest + +from je_auto_control.utils.mcp_server.server import MCPServer +from je_auto_control.utils.mcp_server.tools import build_default_tool_registry +from je_auto_control.utils.rbac import AuthorizationContext, Role, authorization_scope +from je_auto_control.utils.rbac.authorization import AuthorizationError, resolve_token +from je_auto_control.utils.rbac.users import UserStore + + +def call(server, name, arguments, role=Role.OPERATOR): + identity = AuthorizationContext(role, role) if role is not None else None + with authorization_scope(identity): + return json.loads(server.handle_line(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": name, "arguments": arguments}}))) + + +@pytest.fixture(scope="module") +def registry(): + return {tool.name: tool for tool in build_default_tool_registry(read_only=False)} + + +@pytest.mark.parametrize("dynamic", [False, True]) +@pytest.mark.parametrize("name", ["ac_android_list_devices", "ac_web_current_url", "ac_list_plugins"]) +def test_host_readonly_excludes_unsafe_descriptors_and_late_registration(registry, dynamic, name): + calls = [] + tool = replace(registry[name], handler=lambda **args: calls.append(args)) + server = MCPServer(tools=[] if dynamic else [tool]) + server.configure_tool_disclosure("full", read_only=True) + if dynamic: + server.register_tool(tool) + assert name not in server.tool_index().names() + assert "error" in call(server, name, {}) + assert calls == [] + + +@pytest.mark.parametrize("name, safe, unsafe", [ + ("ac_assert_text", {"text": "x"}, {"text": "x", "capture_on_fail": True}), + ("ac_anchor_locate", {"anchor": {"kind": "a11y"}, "target": {"kind": "ocr"}}, + {"anchor": {"kind": "a11y"}, "target": {"kind": "vlm"}}), +]) +def test_explicit_full_registry_gets_readonly_argument_variants(registry, name, safe, unsafe): + calls = [] + original = replace(registry[name], handler=lambda **args: calls.append(args)) + server = MCPServer(tools=[original]) + server.configure_tool_disclosure("full", read_only=True) + assert call(server, name, safe)["result"]["isError"] is False + assert call(server, name, unsafe)["result"]["isError"] is True + assert calls == [safe] + assert not original.enforce_readonly_arguments + if name == "ac_assert_text": + assert server.tool_index().get_schema(name)["inputSchema"]["properties"]["capture_on_fail"]["enum"] == [False] + assert "enum" not in original.input_schema["properties"]["capture_on_fail"] + + +@pytest.mark.parametrize("readonly, variant, role, expected", [ + (False, False, Role.VIEWER, []), (False, False, Role.OPERATOR, ["ac_screen_size"]), + (True, False, Role.OPERATOR, []), (True, False, None, []), (False, True, Role.OPERATOR, []), +]) +def test_failure_artifacts_require_writable_tool_and_caller(registry, monkeypatch, readonly, variant, role, expected): + captures = [] + monkeypatch.setenv("JE_AUTOCONTROL_MCP_ERROR_SHOTS", "must-not-be-used-directly") + monkeypatch.setattr("je_auto_control.utils.mcp_server.server._capture_error_screenshot", + lambda name: captures.append(name)) + def fail(): + raise RuntimeError("fake handler failure") + tool = replace(registry["ac_screen_size"], handler=fail, enforce_readonly_arguments=variant) + server = MCPServer(tools=[tool]) + server.configure_tool_disclosure("full", read_only=readonly) + assert call(server, tool.name, {}, role)["result"]["isError"] is True + assert captures == expected + + +def test_readonly_vlm_rejection_never_captures_error_artifact(registry, monkeypatch): + captures, calls = [], [] + monkeypatch.setattr("je_auto_control.utils.mcp_server.server._capture_error_screenshot", + lambda name: captures.append(name)) + tool = replace(registry["ac_anchor_locate"], handler=lambda **args: calls.append(args)) + server = MCPServer(tools=[tool]) + server.configure_tool_disclosure("full", read_only=True) + args = {"anchor": {"kind": "vlm"}, "target": {"kind": "ocr"}} + assert call(server, tool.name, args)["result"]["isError"] is True + assert captures == calls == [] + + +@pytest.mark.parametrize("name, args", [ + ("ac_image_histogram", {"source": "private.png"}), + ("ac_assert_text", {"text": "x", "capture_on_fail": True}), + ("ac_anchor_locate", {"anchor": {"kind": "vlm"}, "target": {"kind": "ocr"}}), +]) +def test_direct_and_nested_invocations_require_argument_authority(registry, name, args): + calls = [] + target = replace(registry[name], handler=lambda **values: calls.append(values)) + outer = replace(registry["ac_screen_size"], handler=lambda: target.invoke(args)) + with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): + with pytest.raises(AuthorizationError): + target.invoke(args) + with pytest.raises(AuthorizationError): + outer.invoke({}) + assert calls == [] + + +@pytest.mark.parametrize("revoke", ["viewer", "missing", "invalid"]) +def test_revocation_after_prepare_blocks_argument_dispatch_and_failure_capture(registry, monkeypatch, tmp_path, revoke): + store = UserStore(tmp_path / "users.json") + token = store.add_user(user_id="owner", display_name="owner", role=Role.OPERATOR) + identity = resolve_token(store, token) + calls, captures = [], [] + tool = replace(registry["ac_image_histogram"], handler=lambda **args: calls.append(args)) + server = MCPServer(tools=[tool]) + build = server._build_call_context + def change_role(*args, **kwargs): + context = build(*args, **kwargs) + if revoke == "viewer": + store.set_role("owner", Role.VIEWER) + elif revoke == "missing": + store.path.unlink() + else: + store.path.write_text("invalid", encoding="utf-8") + return context + monkeypatch.setattr(server, "_build_call_context", change_role) + monkeypatch.setattr("je_auto_control.utils.mcp_server.server._capture_error_screenshot", + lambda name: captures.append(name)) + with authorization_scope(identity): + response = json.loads(server.handle_line(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": tool.name, "arguments": {"source": "private.png"}}}))) + assert response["result"]["isError"] is True + assert calls == captures == [] + + +def test_host_readonly_preserves_safe_alias_after_dynamic_registration(registry): + calls = [] + server = MCPServer(tools=[]) + server.configure_tool_disclosure("full", read_only=True) + tool = replace(registry["mouse_pos"], handler=lambda **args: calls.append(args)) + server.register_tool(tool) + assert "mouse_pos" in server.tool_index().names() + assert call(server, "mouse_pos", {}, Role.VIEWER)["result"]["isError"] is False + assert calls == [{}] diff --git a/test/unit_test/headless/test_mcp_stop_execution.py b/test/unit_test/headless/test_mcp_stop_execution.py index 8f32bdd5c..82ebe5a41 100644 --- a/test/unit_test/headless/test_mcp_stop_execution.py +++ b/test/unit_test/headless/test_mcp_stop_execution.py @@ -30,11 +30,11 @@ def test_both_tools_are_registered_with_their_annotations(): assert listing.input_schema["properties"] == {} -def test_stopping_needs_drive_input_and_listing_only_read_screen(): +def test_stopping_needs_drive_input_and_listing_needs_read_data(): tools = _tools(read_only=False) stop, listing = tools["ac_stop_execution"], tools["ac_list_executions"] assert capability_for_tool(stop.name, stop.annotations.read_only) == Capability.DRIVE_INPUT - assert capability_for_tool(listing.name, listing.annotations.read_only) == Capability.READ_SCREEN + assert capability_for_tool(listing.name, listing.annotations.read_only) == Capability.READ_DATA def test_a_read_only_server_lists_runs_but_cannot_stop_them(): diff --git a/test/unit_test/headless/test_rbac_mcp_transports.py b/test/unit_test/headless/test_rbac_mcp_transports.py index b4f962ec2..1ace77331 100644 --- a/test/unit_test/headless/test_rbac_mcp_transports.py +++ b/test/unit_test/headless/test_rbac_mcp_transports.py @@ -29,7 +29,7 @@ ) _SSE = "application/json, text/event-stream" -_ALL = ["peek", "poke", "ac_load_plugins"] +_ALL = ["ac_screen_size", "poke", "ac_load_plugins"] _VISIBLE = {Role.VIEWER: _ALL[:1], Role.OPERATOR: _ALL[:2], Role.ADMIN: _ALL} @@ -66,7 +66,7 @@ def handler(**_arguments): started = [] def start(**kwargs): - tools = [tool("peek", READ_ONLY), tool("poke", DESTRUCTIVE), + tools = [tool("ac_screen_size", READ_ONLY), tool("poke", DESTRUCTIVE), tool("ac_load_plugins", DESTRUCTIVE)] server = HttpMCPServer( mcp=MCPServer(tools=tools, audit_logger=AuditLogger(path=str(audit_path))), @@ -201,7 +201,7 @@ def test_session_requests_are_authorised_one_by_one(serve, users): users.tokens[Role.OPERATOR], own) assert status == 200 assert json.loads(raw)["error"]["code"] == -32003 - assert _exchange(server, _call("peek"), None, session)[0] == 401 + assert _exchange(server, _call("ac_screen_size"), None, session)[0] == 401 assert server.calls == [("ac_load_plugins", "admin-user")] @@ -258,7 +258,7 @@ def test_stateless_lists_and_runs_only_what_the_role_grants(serve, users, role): assert status == 200 assert "Mcp-Session-Id" not in headers assert [tool["name"] for tool in json.loads(raw)["result"]["tools"]] == _VISIBLE[role] - for name in ("peek", "ac_load_plugins"): + for name in ("ac_screen_size", "ac_load_plugins"): body = _stateless("tools/call", {"name": name, "arguments": {}}) _status, _headers, raw = _exchange(server, body, token, _stateless_headers("tools/call", name)) @@ -267,19 +267,19 @@ def test_stateless_lists_and_runs_only_what_the_role_grants(serve, users, role): assert reply["result"]["isError"] is False else: assert reply["error"]["code"] == -32003 - expected = [name for name in ("peek", "ac_load_plugins") if name in _VISIBLE[role]] + expected = [name for name in ("ac_screen_size", "ac_load_plugins") if name in _VISIBLE[role]] assert server.calls == [(name, f"{role}-user") for name in expected] def test_stateless_sse_reply_is_authorised_too(serve, users): server = serve() - body = _stateless("tools/call", {"name": "peek", "arguments": {}}) - headers = {**_stateless_headers("tools/call", "peek"), "Accept": _SSE} + body = _stateless("tools/call", {"name": "ac_screen_size", "arguments": {}}) + headers = {**_stateless_headers("tools/call", "ac_screen_size"), "Accept": _SSE} status, _headers, raw = _exchange(server, body, users.tokens[Role.VIEWER], headers) assert status == 200 assert _events(raw)[-1]["result"]["isError"] is False assert _exchange(server, body, "wrong", headers)[0] == 401 - assert server.calls == [("peek", "viewer-user")] + assert server.calls == [("ac_screen_size", "viewer-user")] # --- subscriptions/listen --------------------------------------------------- @@ -335,7 +335,7 @@ def test_a_viewer_may_listen_and_gets_only_the_change_signal(serve, users): _status, _headers, raw = _exchange(server, _stateless("tools/list"), users.tokens[Role.VIEWER], _stateless_headers("tools/list")) - assert [tool["name"] for tool in json.loads(raw)["result"]["tools"]] == ["peek"] + assert [tool["name"] for tool in json.loads(raw)["result"]["tools"]] == ["ac_screen_size"] # --- TLS -------------------------------------------------------------------- diff --git a/test/unit_test/headless/test_rbac_reviewed_tools.py b/test/unit_test/headless/test_rbac_reviewed_tools.py new file mode 100644 index 000000000..b09cff4ca --- /dev/null +++ b/test/unit_test/headless/test_rbac_reviewed_tools.py @@ -0,0 +1,255 @@ +"""Reviewed screen authority stays separate from tool behavior hints.""" +from dataclasses import replace +import json + +import pytest + +from je_auto_control.utils.exception.exceptions import AutoControlActionException +from je_auto_control.utils.mcp_server.server import MCPServer +from je_auto_control.utils.mcp_server.tools import build_default_tool_registry, make_plugin_tool +from je_auto_control.utils.mcp_server.tools._base import MCPTool, READ_ONLY, schema +from je_auto_control.utils.rbac import AuthorizationContext, Role, authorization_scope +from je_auto_control.utils.rbac.policy import capability_for_tool +from je_auto_control.utils.rbac.tool_classification import SCREEN_SOURCE_TOOLS, SCREEN_TOOLS, TOOL_ALIASES +from je_auto_control.utils.rbac.users import Capability + + +def rpc(server, method, params=None, role=Role.VIEWER): + with authorization_scope(AuthorizationContext(role, role)): + return json.loads(server.handle_line(json.dumps({ + "jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}, + }))) + + +@pytest.fixture(scope="module") +def registry(): + return {tool.name: tool for tool in build_default_tool_registry(read_only=False)} + + +def marker(tool): + calls = [] + def invoke(**arguments): + calls.append(arguments) + return "allowed" + return MCPServer(tools=[replace(tool, handler=invoke)]), calls + + +@pytest.mark.parametrize("name", [ + "ac_image_hash", "ac_dedupe_images", "ac_diff_screenshots", "diff_screens", + "ac_locate_image_center", "find_image", "ac_wait_for_image", "wait_image", + "ac_assert_image", "ac_assert_video_changes", "ac_wait_for_file", + "ac_android_list_devices", + "ac_android_device_info", "ac_android_screen_info", "ac_android_app_state", + "ac_android_wait_for_app", "ac_ios_device_info", "ac_ios_screen_info", + "ac_ios_app_state", "ac_ios_wait_for_app", "ac_ios_find_element", "ac_ios_dump_source", +]) +def test_data_tools_are_hidden_and_refused_before_validation_or_handler(registry, name): + server, calls = marker(registry[name]) + assert rpc(server, "tools/list")["result"]["tools"] == [] + reply = rpc(server, "tools/call", {"name": name, "arguments": {}}) + assert reply["error"]["data"]["required_capability"] == Capability.READ_DATA + assert calls == [] + + +@pytest.mark.parametrize("name", sorted(SCREEN_SOURCE_TOOLS)) +def test_optional_source_preserves_live_screen_but_not_host_file_reads(registry, name): + server, calls = marker(registry[name]) + assert rpc(server, "tools/list")["result"]["tools"][0]["name"] == name + assert "result" in rpc(server, "tools/call", {"name": name, "arguments": {}}) + assert calls == [{}] + reply = rpc(server, "tools/call", {"name": name, "arguments": {"source": "private.png"}}) + assert reply["error"]["data"]["required_capability"] == Capability.READ_DATA + assert calls == [{}] + assert "result" in rpc(server, "tools/call", { + "name": name, "arguments": {"source": "private.png"}}, role=Role.OPERATOR) + assert calls[-1] == {"source": "private.png"} + + +def test_alias_policy_has_one_canonical_source(registry): + for short, canonical in TOOL_ALIASES.items(): + assert capability_for_tool(short, registry[short].annotations.read_only) == capability_for_tool( + canonical, registry[canonical].annotations.read_only) + assert SCREEN_TOOLS <= registry.keys() + + +def test_unreviewed_read_hint_does_not_grant_viewer_authority(): + tool = MCPTool("future_read", "future", schema({}), lambda: "private", READ_ONLY) + server, calls = marker(tool) + assert rpc(server, "tools/list")["result"]["tools"] == [] + assert "error" in rpc(server, "tools/call", {"name": tool.name, "arguments": {}}) + assert not calls + assert "result" in rpc(server, "tools/call", {"name": tool.name, "arguments": {}}, role=Role.OPERATOR) + + +def test_plugin_read_hint_and_builtin_looking_name_are_not_grants(): + def read_data(): + return "private" + read_data.mcp_read_only = True + tool = make_plugin_tool("ac_screen_size", read_data) + server, calls = marker(tool) + assert tool.name.startswith("plugin_") + assert rpc(server, "tools/list")["result"]["tools"] == [] + assert "error" in rpc(server, "tools/call", {"name": tool.name, "arguments": {}}) + assert not calls + + +def test_readonly_catalogue_excludes_caller_selected_executables(registry): + readonly = {tool.name: tool for tool in build_default_tool_registry(read_only=True)} + unsafe = {name for name, tool in registry.items() if "adb_path" in tool.input_schema.get("properties", {})} + assert {"ac_android_list_devices", "ac_android_device_info", "ac_android_screen_info", + "ac_android_app_state", "ac_android_wait_for_app"} <= unsafe + assert not unsafe.intersection(readonly) + server = MCPServer(tools=readonly.values()) + reply = rpc(server, "tools/call", {"name": "ac_android_list_devices", + "arguments": {"adb_path": "must-never-run.exe"}}, role=Role.OPERATOR) + assert "error" in reply + full, calls = marker(registry["ac_android_list_devices"]) + assert "result" in rpc(full, "tools/call", {"name": "ac_android_list_devices", + "arguments": {"adb_path": "must-never-run.exe"}}, role=Role.OPERATOR) + assert calls == [{"adb_path": "must-never-run.exe"}] + + +@pytest.mark.parametrize("name", ["ac_assert_text", "ac_assert_image", "ac_assert_pixel", "ac_assert_window"]) +def test_readonly_capture_guard_applies_even_without_schema_validation(name): + readonly = {tool.name: tool for tool in build_default_tool_registry(read_only=True)} + calls = [] + tool = replace(readonly[name], handler=lambda **args: calls.append(args)) + assert tool.input_schema["properties"]["capture_on_fail"]["enum"] == [False] + with pytest.raises(AutoControlActionException, match="read-only"): + tool.invoke({"capture_on_fail": True}) + assert calls == [] + tool.invoke({"capture_on_fail": False}) + assert calls == [{"capture_on_fail": False}] + + +def test_viewer_cannot_request_capture_artifact_in_full_registry(registry): + server, calls = marker(registry["ac_assert_text"]) + reply = rpc(server, "tools/call", {"name": "ac_assert_text", "arguments": { + "text": "known", "capture_on_fail": True}}) + assert reply["error"]["data"]["required_capability"] == Capability.DRIVE_INPUT + assert calls == [] + + +@pytest.mark.parametrize("name", sorted(SCREEN_TOOLS)) +def test_reviewed_screen_names_reach_marker_for_viewer(registry, name): + # Schema-independent dispatch probe; the real handler is never executed. + server, calls = marker(replace(registry[name], input_schema=schema({}))) + assert rpc(server, "tools/list")["result"]["tools"][0]["name"] == name + assert "result" in rpc(server, "tools/call", {"name": name, "arguments": {}}) + assert calls == [{}] + + +@pytest.mark.parametrize("name", ["ac_anchor_locate", "ac_anchor_locate_all"]) +@pytest.mark.parametrize("field", ["anchor", "target"]) +@pytest.mark.parametrize("kind, capability", [("image", Capability.READ_DATA), ("vlm", Capability.DRIVE_INPUT)]) +def test_anchor_authority_checks_each_locator_before_handler(registry, name, field, kind, capability): + server, calls = marker(registry[name]) + args = {"anchor": {"kind": "a11y", "name": "label"}, "target": {"kind": "ocr", "text": "value"}} + assert "result" in rpc(server, "tools/call", {"name": name, "arguments": args}) + assert calls == [args] + changed = {**args, field: {"kind": kind}} + denied = rpc(server, "tools/call", {"name": name, "arguments": changed}) + assert denied["error"]["data"]["required_capability"] == capability + assert calls == [args] + + +@pytest.mark.parametrize("name", ["ac_anchor_locate", "ac_anchor_locate_all"]) +def test_readonly_anchors_reject_vlm_even_without_schema_validation(name): + readonly = {tool.name: tool for tool in build_default_tool_registry(read_only=True)} + calls = [] + tool = replace(readonly[name], handler=lambda **args: calls.append(args)) + safe = {"anchor": {"kind": "a11y"}, "target": {"kind": "ocr"}} + tool.invoke(safe) + for field in ("anchor", "target"): + with pytest.raises(AutoControlActionException, match="read-only"): + tool.invoke({**safe, field: {"kind": "vlm"}}) + assert calls == [safe] + + +def test_configuration_env_lookup_requires_data_authority(registry, monkeypatch): + monkeypatch.setenv("AUTOCONTROL_RBAC_TEST_SECRET", "must-not-leak") + server = MCPServer(tools=[registry["ac_validate_config"]]) + args = {"schema": {"key": {"env": "AUTOCONTROL_RBAC_TEST_SECRET"}}, "config": {}} + denied = rpc(server, "tools/call", {"name": "ac_validate_config", "arguments": args}) + assert denied["error"]["data"]["required_capability"] == Capability.READ_DATA + assert "must-not-leak" not in str(denied) + args["config"] = {"key": "caller-value"} + allowed = rpc(server, "tools/call", {"name": "ac_validate_config", "arguments": args}) + assert "result" in allowed + assert "caller-value" in str(allowed) + assert "must-not-leak" not in str(allowed) + + +@pytest.mark.parametrize("schema_value", [{"key": {"env": "SECRET"}}, '{"key": {"env": "SECRET"}}']) +def test_config_guard_handles_both_adapter_input_forms(schema_value): + from je_auto_control.utils.rbac.tool_classification import argument_capability + assert argument_capability("ac_validate_config", {"schema": schema_value, "config": {}}) == Capability.READ_DATA + assert argument_capability("ac_validate_config", { + "schema": schema_value, "config": '{"key": "caller"}'}) is None + + +@pytest.mark.parametrize("target", ["https://example.invalid/path", "mailto:user@example.invalid"]) +def test_url_open_plan_remains_viewer_visible(registry, target): + server, calls = marker(registry["ac_plan_open"]) + assert "result" in rpc(server, "tools/call", {"name": "ac_plan_open", "arguments": {"target": target}}) + assert calls == [{"target": target}] + + +@pytest.mark.parametrize("target", ["~/private", "relative/file", "C:\\private"]) +def test_file_open_plan_requires_host_data_authority(registry, target): + server, calls = marker(registry["ac_plan_open"]) + denied = rpc(server, "tools/call", {"name": "ac_plan_open", "arguments": {"target": target}}) + assert denied["error"]["data"]["required_capability"] == Capability.READ_DATA + assert calls == [] + + +def test_annotation_formatting_preserves_stdio_protocol(monkeypatch): + import io + readonly = {tool.name: tool for tool in build_default_tool_registry(read_only=True)} + server = MCPServer(tools=[readonly["ac_ci_annotations"]]) + request = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { + "name": "ac_ci_annotations", "arguments": {"annotations": [{"message": "line\nnext"}]}}} + output = io.StringIO() + monkeypatch.setattr("sys.stdout", output) + with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): + server.serve_stdio(stdin=io.StringIO(json.dumps(request) + "\n")) + lines = output.getvalue().splitlines() + assert len(lines) == 1 + reply = json.loads(lines[0]) + assert reply["id"] == 1 + content = json.loads(reply["result"]["content"][0]["text"]) + assert content == {"lines": ["::error::line%0Anext"]} + + +@pytest.mark.parametrize("name", ["ac_web_current_url", "ac_web_list_commands", "ac_list_plugins"]) +def test_external_initialization_unknowns_do_not_gain_viewer_authority(registry, name): + server, calls = marker(registry[name]) + denied = rpc(server, "tools/call", {"name": name, "arguments": {}}) + assert denied["error"]["data"]["required_capability"] == Capability.READ_DATA + assert calls == [] + + +def test_unknown_external_initialization_is_excluded_from_readonly(): + readonly = {tool.name for tool in build_default_tool_registry(read_only=True)} + assert not {"ac_list_plugins", "ac_web_list_commands", "ac_web_current_url"}.intersection(readonly) + + +@pytest.mark.parametrize("name", ["ac_android_list_devices", "ac_android_device_info", "ac_android_screen_info", + "ac_android_app_state", "ac_android_wait_for_app"]) +def test_android_executable_override_requires_drive_authority(name): + from je_auto_control.utils.rbac.tool_classification import argument_capability + assert argument_capability(name, {}) is None + assert argument_capability(name, {"adb_path": "sentinel-never-executed"}) == Capability.DRIVE_INPUT + + +def test_readonly_capture_schema_guard_also_applies_to_custom_names(): + from je_auto_control.utils.mcp_server.tools._readonly import readonly_tools + calls = [] + tool = MCPTool("custom_assert", "custom", schema({"capture_on_fail": {"type": "boolean"}}), + lambda **args: calls.append(args), READ_ONLY) + readonly = readonly_tools([tool])[0] + with pytest.raises(AutoControlActionException, match="read-only"): + readonly.invoke({"capture_on_fail": "truthy"}) + assert calls == [] + readonly.invoke({"capture_on_fail": False}) + assert calls == [{"capture_on_fail": False}] diff --git a/test/unit_test/headless/test_rbac_server_wiring.py b/test/unit_test/headless/test_rbac_server_wiring.py index 03cd8907e..acd74dcf2 100644 --- a/test/unit_test/headless/test_rbac_server_wiring.py +++ b/test/unit_test/headless/test_rbac_server_wiring.py @@ -294,7 +294,7 @@ def test_policy_tables_name_things_that_exist(): def test_only_admin_holds_the_signing_capability(): - assert capability_for_tool("anything", read_only=True) == Capability.READ_SCREEN + assert capability_for_tool("anything", read_only=True) == Capability.READ_DATA assert capability_for_tool("anything", read_only=False) == Capability.DRIVE_INPUT holders = [role for role in Role.all() if AuthorizationContext("u", role).allows(Capability.SIGN_ACTIONS)] @@ -329,7 +329,7 @@ def handler(**arguments): return MCPTool(name=name, description=name, annotations=annotations, handler=handler, input_schema=schema({"actions": {"type": "array"}})) - tools = [tool("peek", READ_ONLY), tool("poke", DESTRUCTIVE), + tools = [tool("ac_screen_size", READ_ONLY), tool("peek", READ_ONLY), tool("poke", DESTRUCTIVE), tool("ac_load_plugins", DESTRUCTIVE)] audit_path = tmp_path / "mcp_audit.jsonl" started = [] @@ -365,12 +365,12 @@ def _audit_entries(server): def test_mcp_tool_list_matches_what_each_role_may_call(mcp_http, users): server = mcp_http(user_store=users) - expected = {Role.VIEWER: ["peek"], Role.OPERATOR: ["peek", "poke"], - Role.ADMIN: ["peek", "poke", "ac_load_plugins"]} + expected = {Role.VIEWER: ["ac_screen_size"], Role.OPERATOR: ["ac_screen_size", "peek", "poke"], + Role.ADMIN: ["ac_screen_size", "peek", "poke", "ac_load_plugins"]} for role, names in expected.items(): token = users.tokens[role] assert _tool_names(server, token) == names - for name in ("peek", "poke", "ac_load_plugins"): + for name in ("ac_screen_size", "peek", "poke", "ac_load_plugins"): _status, body = _rpc(server, "tools/call", {"name": name, "arguments": {}}, token) assert ("result" in body) is (name in names), (role, name, body) @@ -422,12 +422,12 @@ def test_mcp_rbac_refuses_the_shared_token_and_unknown_roles(mcp_http, users): def test_mcp_unconfigured_rbac_keeps_shared_token(mcp_http): server = mcp_http(auth_token="shared-secret") assert _rpc(server, "tools/list")[0] == 401 - assert _tool_names(server, "shared-secret") == ["peek", "poke"] + assert _tool_names(server, "shared-secret") == ["ac_screen_size", "peek", "poke"] _status, body = _rpc(server, "tools/call", {"name": "ac_load_plugins", "arguments": {}}, "shared-secret") assert "result" in body assert "user_id" not in _audit_entries(server)[0] - assert _tool_names(mcp_http(), None) == ["peek", "poke"] + assert _tool_names(mcp_http(), None) == ["ac_screen_size", "peek", "poke"] def test_default_registry_offers_a_viewer_only_read_only_tools(users): diff --git a/test/unit_test/headless/test_rbac_user_admin.py b/test/unit_test/headless/test_rbac_user_admin.py index 21da7e510..515d242ae 100644 --- a/test/unit_test/headless/test_rbac_user_admin.py +++ b/test/unit_test/headless/test_rbac_user_admin.py @@ -418,12 +418,12 @@ def test_data_tools_need_more_than_read_screen(users): "ac_lease_active", "ac_element_list", "ac_skill_list", "ac_skill_search", "ac_repair_pending", "ac_repair_resolved", "ac_quarantine_list", "ac_pending_artifacts", - "ac_android_get_clipboard", "ac_ios_get_clipboard", + "ac_android_get_clipboard", "ac_ios_get_clipboard", "ac_locate_image_center", + "ac_list_executions", "ac_scheduler_list_jobs", ) _LIVE_SCREEN_TOOLS = ( "ac_vlm_locate", "ac_self_heal_locate", # they read the screen; cost is not a capability - "ac_locate_text", "ac_locate_image_center", "ac_a11y_list", "ac_element_find", - "ac_list_executions", "ac_scheduler_list_jobs", + "ac_locate_text", "ac_a11y_list", "ac_element_find", ) From 7fd75d799d59beaf250caea31cd0307eaa683161 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 18:36:40 +0800 Subject: [PATCH 031/161] Record fixed-source typing and distribution verification --- docs/updates/2026-11-b.md | 5 +++++ docs/updates/README.md | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c2d20c595..c15c54a3a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -49,3 +49,8 @@ - **What:** Source review covered all 373 formerly viewer-visible descriptors. Explicit canonical policy preserves reviewed screen/caller-data tools and stronger overrides, gates mixed file/environment/VLM/capture arguments, and restricts unknown read-only hints. Default, explicit and dynamically registered readonly catalogues share the same filtering and invocation guard. Fresh invocation authority and failure-artifact capture revalidate current grants. MCP CI annotations return formatted data without stdout pollution. Measured catalogues contain 820 full, 461 readonly and 289 viewer-visible tools. - **Evidence:** Broad MCP/RBAC testing passed 1,147 cases with four obsolete policy assertions; after migration, all 56 affected cases passed. Independent review reproduced and verified fixes for error-artifact capture, explicit-registry readonly bypass and argument authority after revocation. Its selected run passed 429 before a stale fixture was corrected, then all 112 follow-up cases. Parent integration passed 484 cases and quality gates plus a warnings-as-errors Sphinx dummy build. Three-target typing, Ruff, Bandit, complexity and strict Sphinx passed. Tests use fake handlers and loopback transports, without native input, capture or device calls. - **Open items:** Three external initializer contracts, diagnostic SQLite initialization effects and real-client acceptance remain in Progress.md. This does not claim globally zero filesystem mutation or a sandbox for trusted host Python plugins. + +## U-20261111-21 · 2026-11-11 · Verify integrated types, HTML and distribution source bytes · #snapshot #verification + +- **Evidence:** At b8f7df713a845038ee2c2c8cdf520c9f49715bfa, full ordinary and real-dependency typing passed win32, linux and darwin with zero failing modules. Sphinx HTML built with warnings as errors; four rendered English/Chinese workspace and MCP pages were parsed. Isolated wheel and sdist builds succeeded without modifying the shared environment. Every one of the 1,498 tracked package Python files, including the top-level pytest plugin, matched both archives byte-for-byte, with no missing or unexpected package Python members. The removed executor bridge was absent. +- **Limits:** Full pytest is separately running on that fixed source and has no terminal result yet. Python-byte comparison does not verify every non-Python asset. Native, device, browser, memory, mixed-DPI and long-duration acceptance remain in Progress.md; no deployment or push occurred. diff --git a/docs/updates/README.md b/docs/updates/README.md index 230a730a7..1c0e74edb 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-21 | 2026-11-11 | Verify integrated types, HTML and distribution source bytes | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-20 | 2026-11-11 | Enforce reviewed MCP capabilities at every invocation | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-19 | 2026-11-11 | Add an injectable workspace and live execution details | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261111-18 | 2026-11-11 | Release remote pages without retaining callback owners | #done #gui | [2026-11-b](2026-11-b.md) | @@ -639,7 +640,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 9 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 10 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | From e08c8094faf999ac41c5fb80818edb00898d5577 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 18:55:17 +0800 Subject: [PATCH 032/161] Measure image-file evidence with retained Windows handles --- CHANGELOG.md | 3 + Progress.md | 3 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture.md | 7 + architecture_explore.md | 29 +- docs/process_memory_contract.md | 43 +++ .../doc/new_features/v223_features_doc.rst | 10 + .../Zh/doc/new_features/v223_features_doc.rst | 8 + docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- .../utils/process_memory/windows.py | 41 +-- .../utils/process_memory/windows_facts.py | 55 +++ .../utils/process_memory/windows_image.py | 246 +++++++++++++ .../process_memory/windows_image_native.py | 62 ++++ .../utils/process_memory/windows_native.py | 24 +- .../headless/test_process_memory_image.py | 347 ++++++++++++++++++ 18 files changed, 840 insertions(+), 53 deletions(-) create mode 100644 je_auto_control/utils/process_memory/windows_facts.py create mode 100644 je_auto_control/utils/process_memory/windows_image.py create mode 100644 je_auto_control/utils/process_memory/windows_image_native.py create mode 100644 test/unit_test/headless/test_process_memory_image.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f6f5eb01..543080899 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] +- Add internal bounded Windows image-file measurements with retained read-only leases + and retryable cleanup. These observations do not grant loaded-code or fixture attestation. + - Add an injectable WorkspaceShell and collapsible execution details under View. Diagnostics publishes progress and outcomes; existing embedded-widget imports, constructors and tab visibility/close behavior remain supported. diff --git a/Progress.md b/Progress.md index e2a36c0e6..f91e2cbf0 100644 --- a/Progress.md +++ b/Progress.md @@ -636,7 +636,8 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報資訊,不能充當 OS 出生身分或可信 resolver。 typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 handle 的注入測試; 應用身分仍須由明確受審的 attestor 提供,沒有預設信任或由期望身分反填的實作。 -仍缺可信 executable/version attestor、ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime grant/helper +仍缺實際載入映像與啟動關係綁定、受審 runtime/固定程式碼交付、可信 executable/version attestor、 +ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 diff --git a/README.md b/README.md index 6e2b555c4..a5cfa29fd 100644 --- a/README.md +++ b/README.md @@ -72,3 +72,5 @@ Closing Remote Desktop releases its page. Reopening creates fresh controls witho MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. + +Internal Windows process-memory preparation can now measure a selected process image file through retained read-only handles, with bounded hashing and retryable cleanup. This is observed file evidence, not loaded-code or fixture attestation; native acceptance and public memory tools remain unavailable. See [the contract](docs/process_memory_contract.md). diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 8bac8f054..4e5eb8bb3 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -72,3 +72,5 @@ Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用 MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 + +内部 Windows 进程内存准备工作新增映像文件测量,通过保留的只读 handle 执行有界哈希并保留失败清理供重试。这只是观察到的文件证据,不是已加载代码或 fixture 的身份证明;原生验收及公开内存工具仍未提供。详见[契约](../docs/process_memory_contract.md)。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 799f7da7d..b22fc4478 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -72,3 +72,5 @@ Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫 MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 + +內部 Windows 行程記憶體準備工作新增映像檔量測,透過保留的唯讀 handle 執行有界雜湊並保留失敗清理供重試。這只是觀測到的檔案證據,不是已載入程式碼或 fixture 的身分證明;原生驗收及公開記憶體工具仍未提供。詳見[契約](../docs/process_memory_contract.md)。 diff --git a/architecture.md b/architecture.md index e004998f8..56046197b 100644 --- a/architecture.md +++ b/architecture.md @@ -46,6 +46,13 @@ The internal Windows provider owns read/query handles and measures native proces facts before asking an explicit reviewed attestor for application identity. Its bindings are tested through injected calls; trusted attestation and native acceptance remain separate requirements. +WindowsImageObserver separately owns a query/synchronize process handle and an +image-file handle opened with read-only sharing. It measures file ID, size and +SHA-256 from that same handle under caller byte/deadline/checkpoint limits, checking +process and file metadata between chunks. Successful observations retain leases +until close; failed cleanup remains owned for explicit retry. Shared native facts +live in windows_facts.py. ObservedImageFile describes the file opened from the +reported image path, not loaded code or a trusted fixture launch. The package facade resolves each public export from its existing source module. Concrete typing declarations generate runtime binding tables, checked by diff --git a/architecture_explore.md b/architecture_explore.md index 2cfb6203b..e50ff8811 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -18,7 +18,7 @@ CI 以 `python scripts/generate_facade_exports.py --check` 檢查一致性。六 ## 1. 專案定位與規模 `test/fixtures/process_memory_fixture.py` 由子程序持有固定 payload 與 sequence 緩衝區, -以有界管線提供已知語意狀態及更新。bootstrap 僅自報資訊,原生身分核對與記憶體讀回仍待實作。 +以有界管線提供已知語意狀態及更新。bootstrap 僅自報資訊,原生身分綁定與實際讀回驗收仍未完成。 `je_auto_control` 是一套跨平台 GUI 自動化框架,涵蓋 Windows(Win32 API)、macOS(pyobjc/Quartz)、 Linux X11(python-Xlib)與 Linux Wayland(libei / ydotool),並延伸到 Android(ADB / uiautomator2)與 @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,517 | -| 程式碼總行數 | 231,497 | +| Python 模組總數(含周邊子專案) | 1,520 | +| 程式碼總行數 | 231,839 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,517 行。 +> 15 個套件、約 4,859 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -340,7 +340,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 193 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | -| `utils/process_memory/` | 721 | 內部受審 probe 的有界語意觀察、typed Windows provider 與失敗 handle 回收;可信應用身分與 runtime 整合待完成 | +| `utils/process_memory/` | 1,063 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測與失敗 handle 回收;檔案證據不等於載入程式碼身分,可信啟動及 runtime 整合待完成 | | `utils/shell_process/` | 279 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -731,6 +731,19 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 上表以子套件為單位;以下把行數最大的幾個子系統展開到檔案層。 +#### `utils/process_memory/`(1,063 行/8 檔) + +| 檔案 | 行數 | 職責 | +| --- | ---: | --- | +| `__init__.py` | 1 | Internal reviewed process observations; no native provider or public command registration. | +| `models.py` | 181 | Closed identities, reviewed probes and safe semantic observation results. | +| `reader.py` | 253 | Adapter-owned semantic observations with bounded reads and retained cleanup ownership. | +| `windows.py` | 162 | Owned Windows read handles with measured native facts and reviewed application attestation. | +| `windows_facts.py` | 55 | Measure native birth, session and architecture through a retained process handle. | +| `windows_image.py` | 246 | Observe an image file while retaining its process and deny-write/delete file leases. | +| `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | +| `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | + #### `utils/executor/`(10,702 行)— 執行核心 | 檔案 | 行數 | 職責 | @@ -1422,7 +1435,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,182 個 `test_*.py`/11,482 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,183 個 `test_*.py`/11,503 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1533,8 +1546,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,003 | 102,694 | -| **總計** | **1,505** | **230,752** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,036 | +| **總計** | **1,508** | **231,094** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index 6170902fd..a6b61ba65 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -68,6 +68,49 @@ and measures facts again after attestation. A path string, fixture nonce, self-r digest or a callback that merely echoes an expected identity is not an attestation. The production attestor and trusted fixture bootstrap matching remain unimplemented. +### Observed image-file evidence + +`windows_image.py` adds a separate one-shot `WindowsImageObserver`. It acquires +only a query/synchronize process handle, measures birth/session/architecture from +that retained relationship, and queries its current image filename. The file is +opened with `GENERIC_READ`, `OPEN_EXISTING` and only `FILE_SHARE_READ`; a successful +lease excludes ordinary write/delete opens and conflicting writable mappings. +File type, volume plus 128-bit file ID, timestamps, attributes and size are measured +from that same file handle. SHA-256 is computed from its actual bytes. Native facts, +image filename and file metadata are rechecked around the bounded read sequence. + +The caller must provide a byte ceiling, timeout and live checkpoint. The finite +artifact ceiling is 64 MiB and the read buffer is at most 64 KiB; these are resource +bounds, not measured performance targets. Checkpoints run between acquisition +phases and file chunks, not every individual metadata syscall, and cannot interrupt +a blocked native call. The observer is not an authorization service. Native ABI +errors become closed failure reasons; checkpoint and cancellation exceptions +propagate unchanged. + +A successful `observe` returns `ObservedImageFile`, with private identity and digest +fields omitted from representations. It retains both leases until explicit `close`. +Failure/cancellation retires the observer and attempts cleanup. Failed handles stay +owned, `pending_cleanup` remains true, and `close` retries only those handles. The +caller must retain the observer until cleanup succeeds. An observer cannot be +reused for another acquisition, including after retirement. + +This is current image-file evidence, **not loaded-image or launch attestation**. +The queried pathname could refer to different current backing bytes from those +originally loaded. It does not prove Python fixture source or imported runtime +code. No `ProcessIdentity` is minted from this evidence, no expected identity/digest +is accepted as a measurement, and no public tool is added. Owned launch/source +delivery, loaded-image binding, trusted runtime dependencies, fixture attestor and +per-launch resolver remain unimplemented. Injected tests exercise the actual +acquisition code with fake native buffers; native acceptance remains paused. + +The ABI and file semantics follow Microsoft's +[QueryFullProcessImageNameW](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-queryfullprocessimagenamew), +[CreateFileW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew), +[GetFileInformationByHandleEx](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfileinformationbyhandleex) +and [FILE_ID_INFO](https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_info) +contracts. Image-name length validation uses Windows UTF-16 code units, including +non-BMP and unpaired-surrogate filenames, rather than Python code-point counts. + Each native read is limited to 1 MiB and one committed, readable, unguarded region. The semantic reader splits reviewed ranges at region boundaries under its smaller per-probe budget. Failed or short reads publish no bytes; post-read region and native diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index b9dd22fc8..7e77006f9 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -213,3 +213,13 @@ including direct registry closes. ``AutoControlGUIWidget(parent)`` keeps its imp path, default features and show/hide/list APIs. Hiding retains a page; closing an owned page rebuilds it on reopening. A registry outliving its shell forgets pages when Qt destroys them. + +Internal Windows image-file observations +-------------------------------------------------------------------------------- + +The internal process-memory foundation can measure the selected process's current +image file using retained query/read-only leases, bounded hashing and retryable +cleanup. Native process facts and file metadata are rechecked. This produces +observed file evidence, not loaded-code, fixture or launch attestation. No public +memory command is added. Native acceptance and runtime authorization integration +remain pending; injected tests do not establish those guarantees. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index dc633bdb3..8e79d5751 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -203,3 +203,11 @@ Remote Desktop 生命週期 ``AutoControlGUIWidget(parent)`` 保留匯入路徑、預設功能與 show/hide/list API。 隱藏會保留分頁;關閉擁有的分頁後,重開會重新建立。Registry 若比工作區存活更久, 會在 Qt 銷毀頁面時清除該快取。 + +內部 Windows 映像檔觀測 +-------------------------------------------------------------------------------- + +行程記憶體的內部基礎可透過保留的查詢/唯讀 handle 量測指定行程目前的映像檔, +使用有界雜湊並保留失敗清理供重試,同時重新核對原生行程事實及檔案 metadata。 +結果是觀測到的檔案證據,不是已載入程式碼、fixture 或啟動身分的證明。 +沒有新增公開記憶體指令。原生驗收與 runtime 授權整合仍待完成,注入測試不代表這些保證。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c15c54a3a..d8ed59fae 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -54,3 +54,9 @@ - **Evidence:** At b8f7df713a845038ee2c2c8cdf520c9f49715bfa, full ordinary and real-dependency typing passed win32, linux and darwin with zero failing modules. Sphinx HTML built with warnings as errors; four rendered English/Chinese workspace and MCP pages were parsed. Isolated wheel and sdist builds succeeded without modifying the shared environment. Every one of the 1,498 tracked package Python files, including the top-level pytest plugin, matched both archives byte-for-byte, with no missing or unexpected package Python members. The removed executor bridge was absent. - **Limits:** Full pytest is separately running on that fixed source and has no terminal result yet. Python-byte comparison does not verify every non-Python asset. Native, device, browser, memory, mixed-DPI and long-duration acceptance remain in Progress.md; no deployment or push occurred. + +## U-20261111-22 · 2026-11-11 · Measure image-file evidence through retained Windows handles · #done #memory + +- **What:** Added typed query/file calls and a one-shot image-file observer. It measures bytes, file identity and size from its owned read-only handle, rechecks retained process facts and file metadata, enforces finite caller bounds, and retains failed closes for retry. Shared native process facts were extracted without changing provider imports. No expected identity or digest is copied into measured results. +- **Evidence:** Implementation passed 172 focused cases plus 21 quality gates. Independent review passed 197 original/new memory and fixture-protocol cases plus a fake last-access drift probe. UTF-16 length and native-error cleanup findings were fixed. Parent integration passed 239 cases and quality gates plus a warnings-as-errors Sphinx dummy build. All eight package modules passed typing on three targets; Ruff, Bandit, Radon, changed-module Pylint and strict Sphinx passed. Whole-package Pylint retains two existing reader inference findings. Native observer calls used injected functions; existing fixture tests used hidden Python IPC only. +- **Open items:** This measures a file, not loaded code. Trusted launch/image binding, reviewed runtime/source delivery, attestor/resolver, runtime integration and native acceptance remain in Progress.md. No new native image or memory observation ran. diff --git a/docs/updates/README.md b/docs/updates/README.md index 1c0e74edb..4913ded92 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-22 | 2026-11-11 | Measure image-file evidence through retained Windows handles | #done #memory | [2026-11-b](2026-11-b.md) | | U-20261111-21 | 2026-11-11 | Verify integrated types, HTML and distribution source bytes | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-20 | 2026-11-11 | Enforce reviewed MCP capabilities at every invocation | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-19 | 2026-11-11 | Add an injectable workspace and live execution details | #done #gui | [2026-11-b](2026-11-b.md) | @@ -640,7 +641,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 10 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 11 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/process_memory/windows.py b/je_auto_control/utils/process_memory/windows.py index 3823a9f6e..0d9e74f69 100644 --- a/je_auto_control/utils/process_memory/windows.py +++ b/je_auto_control/utils/process_memory/windows.py @@ -2,30 +2,18 @@ from __future__ import annotations import ctypes -from dataclasses import dataclass, field import threading from typing import Callable, NoReturn from .models import FailureReason, MemoryObservationError, MemoryRegion, ProcessIdentity -from .windows_native import FileTime, Kernel, MemoryInfo32, MemoryInfo64, SIZE, U16, U32, bind, load +from .windows_native import Kernel, MemoryInfo32, MemoryInfo64, SIZE, bind, load +from .windows_facts import NativeProcessFacts as NativeProcessFacts, measure_process _ACCESS = 0x00100000 | 0x0400 | 0x0010 -_ARCHITECTURES = {0x014C: ("x86", 32), 0x8664: ("x64", 64), 0xAA64: ("arm64", 64)} _READABLE = frozenset({0x02, 0x04, 0x08, 0x20, 0x40, 0x80}) _MAX_READ = 1 << 20 -@dataclass(frozen=True) -class NativeProcessFacts: - """Measured retained-process facts for a host-reviewed application attestor.""" - - pid: int = field(repr=False) - birth: int = field(repr=False) - session_id: int = field(repr=False) - architecture: str - pointer_bits: int - - Attestor = Callable[[NativeProcessFacts], ProcessIdentity] @@ -64,31 +52,8 @@ def _alive(self, handle: int) -> None: if self._kernel.WaitForSingleObject(handle, 0) != 258: _fail(FailureReason.TARGET_CHANGED) - def _architecture(self, handle: int) -> tuple[str, int]: - process_machine, native_machine = U16(), U16() - if not self._kernel.IsWow64Process2(handle, ctypes.byref(process_machine), ctypes.byref(native_machine)): - self._error(FailureReason.UNSUPPORTED) - architecture = _ARCHITECTURES.get(process_machine.value or native_machine.value) - if architecture is None or architecture[1] > self._caller_bits: - _fail(FailureReason.UNSUPPORTED) - return architecture - def _facts(self) -> NativeProcessFacts: - handle = self._owned() - self._alive(handle) - pid = self._kernel.GetProcessId(handle) - times = [FileTime() for _ in range(4)] - if not pid or not self._kernel.GetProcessTimes(handle, *[ctypes.byref(item) for item in times]): - self._error(FailureReason.TARGET_CHANGED) - session = U32() - if not self._kernel.ProcessIdToSessionId(pid, ctypes.byref(session)): - self._error(FailureReason.TARGET_CHANGED) - architecture = self._architecture(handle) - birth = times[0].low | (times[0].high << 32) - if not birth: - _fail(FailureReason.TARGET_CHANGED) - self._alive(handle) - return NativeProcessFacts(pid, birth, session.value, *architecture) + return measure_process(self._kernel, self._owned(), self._last_error, self._caller_bits) def identity(self) -> ProcessIdentity: """Measure native facts, then ask the reviewed owner to attest application identity.""" diff --git a/je_auto_control/utils/process_memory/windows_facts.py b/je_auto_control/utils/process_memory/windows_facts.py new file mode 100644 index 000000000..f0aaef406 --- /dev/null +++ b/je_auto_control/utils/process_memory/windows_facts.py @@ -0,0 +1,55 @@ +"""Measure native birth, session and architecture through a retained process handle.""" +from __future__ import annotations + +import ctypes +from dataclasses import dataclass, field +from typing import Callable + +from .models import FailureReason, MemoryObservationError +from .windows_native import FileTime, ProcessKernel, U16, U32 + +_ARCHITECTURES = {0x014C: ("x86", 32), 0x8664: ("x64", 64), 0xAA64: ("arm64", 64)} + + +@dataclass(frozen=True) +class NativeProcessFacts: + """Measured retained-process facts for a host-reviewed application attestor.""" + + pid: int = field(repr=False) + birth: int = field(repr=False) + session_id: int = field(repr=False) + architecture: str + pointer_bits: int + + +def _check(result: int, error: Callable[[], int], reason: FailureReason) -> None: + if not result: + raise MemoryObservationError(FailureReason.ACCESS_DENIED if error() == 5 else reason) + + +def _architecture(kernel: ProcessKernel, handle: int, error: Callable[[], int], bits: int) -> tuple[str, int]: + process, native = U16(), U16() + _check(kernel.IsWow64Process2(handle, ctypes.byref(process), ctypes.byref(native)), error, + FailureReason.UNSUPPORTED) + architecture = _ARCHITECTURES.get(process.value or native.value) + if architecture is None or architecture[1] > bits: + raise MemoryObservationError(FailureReason.UNSUPPORTED) + return architecture + + +def measure_process(kernel: ProcessKernel, handle: int, error: Callable[[], int], bits: int) -> NativeProcessFacts: + """Return actual native facts; a path, expected identity or bootstrap is never consulted.""" + if kernel.WaitForSingleObject(handle, 0) != 258: + raise MemoryObservationError(FailureReason.TARGET_CHANGED) + pid = kernel.GetProcessId(handle) + times = [FileTime() for _ in range(4)] + _check(pid, error, FailureReason.TARGET_CHANGED) + _check(kernel.GetProcessTimes(handle, *[ctypes.byref(item) for item in times]), error, + FailureReason.TARGET_CHANGED) + session = U32() + _check(kernel.ProcessIdToSessionId(pid, ctypes.byref(session)), error, FailureReason.TARGET_CHANGED) + architecture = _architecture(kernel, handle, error, bits) + birth = times[0].low | (times[0].high << 32) + if not birth or kernel.WaitForSingleObject(handle, 0) != 258: + raise MemoryObservationError(FailureReason.TARGET_CHANGED) + return NativeProcessFacts(pid, birth, session.value, *architecture) diff --git a/je_auto_control/utils/process_memory/windows_image.py b/je_auto_control/utils/process_memory/windows_image.py new file mode 100644 index 000000000..0999a6c23 --- /dev/null +++ b/je_auto_control/utils/process_memory/windows_image.py @@ -0,0 +1,246 @@ +"""Observe an image file while retaining its process and deny-write/delete file leases.""" +from __future__ import annotations + +import ctypes +from dataclasses import dataclass, field +from enum import Enum +import hashlib +import math +import threading +import time +from typing import Callable, NoReturn, TypeVar + +from .models import FailureReason, MemoryObservationError +from .windows_facts import NativeProcessFacts, measure_process +from .windows_image_native import FileBasicInfo, FileIdInfo, I64, ImageKernel, bind, load +from .windows_native import U32 + +_QUERY_ACCESS = 0x00100000 | 0x1000 +_PATH_CHARACTERS = 32768 +_CHUNK_BYTES = 65536 +_MAX_IMAGE_BYTES = 64 * 1024 * 1024 + + +@dataclass(frozen=True) +class ObservedImageFile: + """Measured current image-file evidence, never proof of loaded code or a launch.""" + + process: NativeProcessFacts = field(repr=False) + volume: int = field(repr=False) + file_id: bytes = field(repr=False) + size: int + sha256: str = field(repr=False) + + +@dataclass(frozen=True) +class _FileFacts: + volume: int + file_id: bytes + size: int + created: int + written: int + changed: int + attributes: int + + +class _State(Enum): + NEW = "new" + ACTIVE = "active" + RETIRED = "retired" + + +_Result = TypeVar("_Result") + + +def _native(call: Callable[[], _Result], reason: FailureReason) -> _Result: + try: + return call() + except MemoryObservationError: + raise + except Exception as error: # reason: ABI/provider errors must not expose filenames, handles or addresses + denied = isinstance(error, OSError) and getattr(error, "winerror", None) == 5 + raise MemoryObservationError(FailureReason.ACCESS_DENIED if denied else reason) from None + + +def _fail(reason: FailureReason) -> NoReturn: + raise MemoryObservationError(reason) + + +def _bounds(pid: int, max_bytes: int, timeout: float) -> None: + if type(pid) is not int or not 0 < pid <= 0xFFFFFFFF: + _fail(FailureReason.UNSUPPORTED) + if type(max_bytes) is not int or not 0 < max_bytes <= _MAX_IMAGE_BYTES: + _fail(FailureReason.BUDGET_EXCEEDED) + if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0: + _fail(FailureReason.DEADLINE_EXCEEDED) + + +class WindowsImageObserver: + """One acquisition owner; successful evidence keeps leases until explicit close. + + Failures and cancellation retire the owner and attempt all cleanup. Failed + closes remain owned for another close call. This object cannot be reused for + another process. Callers must retain it while pending_cleanup is true. + """ + + def __init__(self, *, kernel: ImageKernel | None = None, + last_error: Callable[[], int] | None = None, + caller_bits: int | None = None, clock: Callable[[], float] = time.monotonic) -> None: + bits = ctypes.sizeof(ctypes.c_void_p) * 8 if caller_bits is None else caller_bits + if type(bits) is not int or bits not in (32, 64): + _fail(FailureReason.UNSUPPORTED) + if kernel is None: + if bits != ctypes.sizeof(ctypes.c_void_p) * 8: + _fail(FailureReason.UNSUPPORTED) + kernel, last_error = load() + else: + if last_error is None: + _fail(FailureReason.UNSUPPORTED) + bind(kernel) + self._kernel, self._error, self._bits, self._clock = kernel, last_error, bits, clock + self._state = _State.NEW + self._handles: list[int] = [] + self._lock = threading.RLock() + + @property + def pending_cleanup(self) -> bool: + """Whether retirement left any failed handle owned for explicit retry.""" + with self._lock: + return self._state is _State.RETIRED and bool(self._handles) + + def _check(self, deadline: float, checkpoint: Callable[[], None]) -> None: + checkpoint() + if self._state is not _State.ACTIVE: + _fail(FailureReason.TARGET_CHANGED) + now = self._clock() + if not math.isfinite(deadline) or not math.isfinite(now) or now >= deadline: + _fail(FailureReason.DEADLINE_EXCEEDED) + + def _require(self, result: int, reason: FailureReason) -> None: + if not result: + _fail(FailureReason.ACCESS_DENIED if _native(self._error, reason) == 5 else reason) + + def _process(self, pid: int) -> int: + handle = _native(lambda: self._kernel.OpenProcess(_QUERY_ACCESS, False, pid), FailureReason.TARGET_CHANGED) + self._require(handle, FailureReason.TARGET_CHANGED) + self._handles.append(handle) + return handle + + def _path(self, process: int) -> str: + buffer, length = ctypes.create_unicode_buffer(_PATH_CHARACTERS), U32(_PATH_CHARACTERS) + self._require(_native(lambda: self._kernel.QueryFullProcessImageNameW( + process, 0, buffer, ctypes.byref(length)), FailureReason.UNSUPPORTED), FailureReason.UNSUPPORTED) + if not 0 < length.value < _PATH_CHARACTERS: + _fail(FailureReason.UNSUPPORTED) + value = buffer.value + if len(value.encode("utf-16-le", "surrogatepass")) // 2 != length.value or buffer[length.value] != "\0": + _fail(FailureReason.UNSUPPORTED) + return value + + def _file(self, path: str) -> int: + handle = _native(lambda: self._kernel.CreateFileW(path, 0x80000000, 1, None, 3, 0, None), + FailureReason.UNSUPPORTED) + if not handle or handle in (-1, (1 << self._bits) - 1): + code = _native(self._error, FailureReason.UNSUPPORTED) + _fail(FailureReason.ACCESS_DENIED if code == 5 else FailureReason.UNSUPPORTED) + self._handles.append(handle) + if _native(lambda: self._kernel.GetFileType(handle), FailureReason.UNSUPPORTED) != 1: + _fail(FailureReason.UNSUPPORTED) + return handle + + def _file_facts(self, handle: int) -> _FileFacts: + identity, basic, size = FileIdInfo(), FileBasicInfo(), I64() + self._require(_native(lambda: self._kernel.GetFileInformationByHandleEx( + handle, 18, ctypes.byref(identity), ctypes.sizeof(identity)), FailureReason.UNSUPPORTED), + FailureReason.UNSUPPORTED) + self._require(_native(lambda: self._kernel.GetFileInformationByHandleEx( + handle, 0, ctypes.byref(basic), ctypes.sizeof(basic)), FailureReason.UNSUPPORTED), + FailureReason.UNSUPPORTED) + self._require(_native(lambda: self._kernel.GetFileSizeEx(handle, ctypes.byref(size)), + FailureReason.UNSUPPORTED), FailureReason.UNSUPPORTED) + if size.value <= 0 or basic.attributes & 0x10: + _fail(FailureReason.UNSUPPORTED) + return _FileFacts(identity.volume, bytes(identity.identifier), size.value, + basic.created, basic.written, basic.changed, basic.attributes) + + def _read(self, handle: int, size: int) -> bytes: + buffer, count = ctypes.create_string_buffer(size), U32() + self._require(_native(lambda: self._kernel.ReadFile(handle, buffer, size, ctypes.byref(count), None), + FailureReason.PARTIAL_READ), FailureReason.PARTIAL_READ) + if count.value != size: + _fail(FailureReason.PARTIAL_READ) + return buffer.raw + + def _facts(self, process: int) -> NativeProcessFacts: + return _native(lambda: measure_process(self._kernel, process, self._error, self._bits), + FailureReason.TARGET_CHANGED) + + def _unchanged(self, process: int, image: int, path: str, + facts: NativeProcessFacts, file: _FileFacts) -> None: + actual = self._facts(process) + if actual != facts or self._path(process) != path or self._file_facts(image) != file: + _fail(FailureReason.TARGET_CHANGED) + + def _measure(self, pid: int, max_bytes: int, deadline: float, + checkpoint: Callable[[], None]) -> ObservedImageFile: + self._check(deadline, checkpoint) + process = self._process(pid) + self._check(deadline, checkpoint) + facts = self._facts(process) + if facts.pid != pid: + _fail(FailureReason.TARGET_CHANGED) + path = self._path(process) + self._check(deadline, checkpoint) + image = self._file(path) + self._check(deadline, checkpoint) + file = self._file_facts(image) + if file.size > max_bytes: + _fail(FailureReason.BUDGET_EXCEEDED) + digest, remaining = hashlib.sha256(), file.size + self._unchanged(process, image, path, facts, file) + while remaining: + self._check(deadline, checkpoint) + size = min(remaining, _CHUNK_BYTES) + digest.update(self._read(image, size)) + self._check(deadline, checkpoint) + self._unchanged(process, image, path, facts, file) + remaining -= size + self._check(deadline, checkpoint) + return ObservedImageFile(facts, file.volume, file.file_id, file.size, digest.hexdigest()) + + def observe(self, pid: int, *, max_bytes: int, timeout: float, + checkpoint: Callable[[], None]) -> ObservedImageFile: + """Measure one current image file under finite caller bounds; retain successful leases. + + Checkpoints detect cancellation/revocation and deadline overruns between + acquisition phases and file chunks, not every individual native call. + They cannot interrupt a blocked OS call. No attestation is + issued, even if a caller recognizes the measured digest. + """ + with self._lock: + if self._state is not _State.NEW: + _fail(FailureReason.TARGET_CHANGED) + _bounds(pid, max_bytes, timeout) + self._state = _State.ACTIVE + try: + return self._measure(pid, max_bytes, self._clock() + timeout, checkpoint) + except BaseException: + try: + self.close() + except MemoryObservationError: + pass + raise + + def close(self) -> None: + """Retire permanently, trying every owned handle and retaining failed closes.""" + with self._lock: + self._state = _State.RETIRED + for handle in tuple(reversed(self._handles)): + try: + closed = _native(lambda: self._kernel.CloseHandle(handle), FailureReason.CLEANUP_FAILED) + except MemoryObservationError: + closed = 0 + if closed: + self._handles.remove(handle) + if self._handles: + _fail(FailureReason.CLEANUP_FAILED) diff --git a/je_auto_control/utils/process_memory/windows_image_native.py b/je_auto_control/utils/process_memory/windows_image_native.py new file mode 100644 index 000000000..e444e2a81 --- /dev/null +++ b/je_auto_control/utils/process_memory/windows_image_native.py @@ -0,0 +1,62 @@ +"""Typed process-image filename and read-only file acquisition calls.""" +from __future__ import annotations + +import ctypes +import sys +from typing import Callable, Protocol, cast + +from .models import FailureReason, MemoryObservationError +from .windows_native import BOOL, PTR, U32, U64, NativeFunction, ProcessKernel, bind_process + +I64 = ctypes.c_int64 + + +class FileIdInfo(ctypes.Structure): + """FILE_ID_INFO combines a volume serial number with a 128-bit file identity.""" + + _fields_ = [("volume", U64), ("identifier", ctypes.c_ubyte * 16)] + + +class FileBasicInfo(ctypes.Structure): + """FILE_BASIC_INFO timestamps and attributes, including native trailing alignment.""" + + _fields_ = [("created", I64), ("accessed", I64), ("written", I64), + ("changed", I64), ("attributes", U32)] + + +class ImageKernel(ProcessKernel, Protocol): + """Native file reads and identity queries; no write, launch or memory-read calls.""" + + QueryFullProcessImageNameW: NativeFunction + CreateFileW: NativeFunction + GetFileType: NativeFunction + GetFileInformationByHandleEx: NativeFunction + GetFileSizeEx: NativeFunction + ReadFile: NativeFunction + + +def bind(kernel: ImageKernel) -> None: + """Install explicit Unicode, fixed-width integer and pointer argument types.""" + bind_process(kernel) + signatures: tuple[tuple[NativeFunction, list[object], object], ...] = ( + (kernel.QueryFullProcessImageNameW, [PTR, U32, ctypes.POINTER(ctypes.c_wchar), ctypes.POINTER(U32)], BOOL), + (kernel.CreateFileW, [ctypes.c_wchar_p, U32, U32, PTR, U32, U32, PTR], PTR), + (kernel.GetFileType, [PTR], U32), + (kernel.GetFileInformationByHandleEx, [PTR, ctypes.c_int32, PTR, U32], BOOL), + (kernel.GetFileSizeEx, [PTR, ctypes.POINTER(I64)], BOOL), + (kernel.ReadFile, [PTR, PTR, U32, ctypes.POINTER(U32), PTR], BOOL), + ) + for function, arguments, result in signatures: + function.argtypes, function.restype = arguments, result + + +def load() -> tuple[ImageKernel, Callable[[], int]]: + """Load private signatures only on explicit observer construction on Windows.""" + if sys.platform != "win32": + raise MemoryObservationError(FailureReason.UNSUPPORTED) + try: + kernel = cast(ImageKernel, ctypes.WinDLL("kernel32", use_last_error=True)) + bind(kernel) + except (OSError, AttributeError): + raise MemoryObservationError(FailureReason.UNSUPPORTED) from None + return kernel, ctypes.get_last_error diff --git a/je_auto_control/utils/process_memory/windows_native.py b/je_auto_control/utils/process_memory/windows_native.py index 68fad6a30..62cbe6100 100644 --- a/je_auto_control/utils/process_memory/windows_native.py +++ b/je_auto_control/utils/process_memory/windows_native.py @@ -45,8 +45,8 @@ class NativeFunction(Protocol): def __call__(self, *arguments: object) -> int: ... -class Kernel(Protocol): - """Only process identity, liveness, memory queries and handle release are exposed.""" +class ProcessKernel(Protocol): + """Process identity, liveness and handle acquisition/release calls.""" OpenProcess: NativeFunction CloseHandle: NativeFunction @@ -55,11 +55,16 @@ class Kernel(Protocol): ProcessIdToSessionId: NativeFunction IsWow64Process2: NativeFunction WaitForSingleObject: NativeFunction + + +class Kernel(ProcessKernel, Protocol): + """Process facts plus bounded memory query/read calls.""" + VirtualQueryEx: NativeFunction ReadProcessMemory: NativeFunction -def bind(kernel: Kernel) -> None: +def bind_process(kernel: ProcessKernel) -> None: """Install fixed-width DWORD/BOOL and pointer-sized address/length signatures.""" signatures: tuple[tuple[NativeFunction, list[object], object], ...] = ( (kernel.OpenProcess, [U32, BOOL, U32], PTR), @@ -69,14 +74,23 @@ def bind(kernel: Kernel) -> None: (kernel.ProcessIdToSessionId, [U32, ctypes.POINTER(U32)], BOOL), (kernel.IsWow64Process2, [PTR, ctypes.POINTER(U16), ctypes.POINTER(U16)], BOOL), (kernel.WaitForSingleObject, [PTR, U32], U32), - (kernel.VirtualQueryEx, [PTR, PTR, PTR, SIZE], SIZE), - (kernel.ReadProcessMemory, [PTR, PTR, PTR, SIZE, ctypes.POINTER(SIZE)], BOOL), ) for function, arguments, result in signatures: function.argtypes = arguments function.restype = result +def bind(kernel: Kernel) -> None: + """Bind process facts and memory calls without changing shared DLL prototypes.""" + bind_process(kernel) + signatures: tuple[tuple[NativeFunction, list[object], object], ...] = ( + (kernel.VirtualQueryEx, [PTR, PTR, PTR, SIZE], SIZE), + (kernel.ReadProcessMemory, [PTR, PTR, PTR, SIZE, ctypes.POINTER(SIZE)], BOOL), + ) + for function, arguments, result in signatures: + function.argtypes, function.restype = arguments, result + + def load() -> tuple[Kernel, Callable[[], int]]: """Load on explicit provider construction; imports never touch native resources.""" if sys.platform != "win32": diff --git a/test/unit_test/headless/test_process_memory_image.py b/test/unit_test/headless/test_process_memory_image.py new file mode 100644 index 000000000..dea7d43a8 --- /dev/null +++ b/test/unit_test/headless/test_process_memory_image.py @@ -0,0 +1,347 @@ +"""Exercise image acquisition through fake native buffers without loading Windows APIs.""" +import ctypes +import hashlib + +import pytest + +from je_auto_control.utils.process_memory.models import MemoryObservationError +from je_auto_control.utils.process_memory.windows_image import WindowsImageObserver +from je_auto_control.utils.process_memory.windows_image_native import FileBasicInfo, FileIdInfo, I64 +from je_auto_control.utils.process_memory.windows_native import PTR, U32 +from headless.test_process_memory_windows import Function, Kernel + + +class ImageKernel(Kernel): + def __init__(self): + super().__init__() + self.image_path = "C:\\owned\\python.exe" + self.data, self.position = b"measured image bytes", 0 + self.volume, self.file_id, self.changed = 9, b"f" * 16, 11 + self.file_handle, self.file_type = 92, 1 + self.short, self.read_success = False, True + self.failed_closes = set() + self.after_file_read = lambda: None + self.path_failure, self.info_failure, self.size_override = False, False, None + for name, implementation in { + "QueryFullProcessImageNameW": self.image_name, + "CreateFileW": lambda *args: self.file_handle, + "GetFileType": lambda *args: self.file_type, + "GetFileInformationByHandleEx": self.file_info, + "GetFileSizeEx": self.file_size, + "ReadFile": self.file_read, + "CloseHandle": lambda handle: handle not in self.failed_closes, + }.items(): + setattr(self, name, Function(implementation)) + + def image_name(self, process, flags, buffer, length): + buffer.value = self.image_path + length._obj.value = len(self.image_path.encode("utf-16-le", "surrogatepass")) // 2 + return not self.path_failure + + def file_info(self, handle, kind, buffer, size): + if kind == 18: + buffer._obj.volume = self.volume + buffer._obj.identifier[:] = self.file_id + else: + buffer._obj.created, buffer._obj.written = 1, 2 + buffer._obj.changed, buffer._obj.attributes = self.changed, 0x20 + return not self.info_failure + + def file_size(self, handle, size): + size._obj.value = len(self.data) if self.size_override is None else self.size_override + return True + + def file_read(self, handle, buffer, size, count, overlapped): + amount = size - 1 if self.short else size + raw = self.data[self.position:self.position + amount] + ctypes.memmove(buffer, raw, len(raw)) + count._obj.value = len(raw) + self.position += len(raw) + self.after_file_read() + return self.read_success + + +def observer(kernel, **options): + return WindowsImageObserver(kernel=kernel, last_error=lambda: kernel.error, **options) + + +def measure(owner, **options): + return owner.observe(42, max_bytes=1 << 20, timeout=5, checkpoint=lambda: None, **options) + + +def test_measures_actual_file_and_keeps_deny_write_delete_leases_until_close(): + kernel = ImageKernel() + owner = observer(kernel) + result = measure(owner) + assert result.process.pid == 42 and result.process.birth == kernel.birth + assert (result.volume, result.file_id, result.size) == (9, b"f" * 16, len(kernel.data)) + assert result.sha256 == hashlib.sha256(kernel.data).hexdigest() + assert kernel.OpenProcess.calls == [(0x101000, False, 42)] + assert kernel.CreateFileW.calls == [(kernel.image_path, 0x80000000, 1, None, 3, 0, None)] + assert not kernel.CloseHandle.calls and not owner.pending_cleanup + assert not kernel.ReadProcessMemory.calls + assert kernel.image_path not in repr(result) and result.sha256 not in repr(result) + assert "42" not in repr(result) and "ffff" not in repr(result) + owner.close() + owner.close() + assert kernel.CloseHandle.calls == [(92,), (91,)] + with pytest.raises(MemoryObservationError, match="target_changed"): + measure(owner) + + +def test_native_abi_is_fixed_width_and_does_not_request_write_calls(): + kernel = ImageKernel() + observer(kernel) + assert ctypes.sizeof(FileIdInfo) == 24 + assert ctypes.sizeof(FileBasicInfo) == 40 + assert FileBasicInfo.attributes.offset == 32 + assert ctypes.sizeof(I64) == 8 + assert kernel.CreateFileW.restype is PTR + assert kernel.ReadFile.argtypes == [PTR, PTR, U32, ctypes.POINTER(U32), PTR] + assert kernel.QueryFullProcessImageNameW.argtypes[-1] is ctypes.POINTER(U32) + + +@pytest.mark.parametrize("field,value", [ + ("pid", 43), ("birth", 88), ("session", 8), ("machine", 0x014C), + ("wait", 0), ("image_path", "C:\\replacement.exe"), ("file_id", b"g" * 16), + ("volume", 10), ("changed", 12), ("size_override", 100), +]) +def test_changes_during_read_publish_no_evidence_and_close_every_handle(field, value): + kernel = ImageKernel() + kernel.after_file_read = lambda: setattr(kernel, field, value) + owner = observer(kernel) + with pytest.raises(MemoryObservationError, match="target_changed"): + measure(owner) + assert kernel.CloseHandle.calls == [(92,), (91,)] + assert not owner.pending_cleanup + + +@pytest.mark.parametrize("attribute,value,reason,closed", [ + ("open_value", 0, "target_changed", []), + ("path_failure", True, "unsupported", [(91,)]), + ("file_handle", -1, "unsupported", [(91,)]), + ("file_handle", 0xFFFFFFFFFFFFFFFF, "unsupported", [(91,)]), + ("file_type", 3, "unsupported", [(92,), (91,)]), + ("info_failure", True, "unsupported", [(92,), (91,)]), + ("size_override", -1, "unsupported", [(92,), (91,)]), + ("size_override", (1 << 20) + 1, "budget_exceeded", [(92,), (91,)]), + ("short", True, "partial_read", [(92,), (91,)]), + ("read_success", False, "partial_read", [(92,), (91,)]), +]) +def test_acquisition_and_read_failures_keep_closed_reason(attribute, value, reason, closed): + kernel = ImageKernel() + setattr(kernel, attribute, value) + owner = observer(kernel) + with pytest.raises(MemoryObservationError, match=reason): + measure(owner) + assert kernel.CloseHandle.calls == closed + + +def test_access_denial_is_distinct_and_does_not_read_file(): + kernel = ImageKernel() + kernel.error, kernel.file_handle = 5, -1 + with pytest.raises(MemoryObservationError, match="access_denied"): + measure(observer(kernel)) + assert not kernel.ReadFile.calls + + +def test_failed_close_tries_other_handles_and_retains_only_failed_ownership(): + kernel = ImageKernel() + owner = observer(kernel) + measure(owner) + kernel.failed_closes.add(92) + with pytest.raises(MemoryObservationError, match="cleanup_failed"): + owner.close() + assert owner.pending_cleanup and kernel.CloseHandle.calls == [(92,), (91,)] + kernel.failed_closes.clear() + owner.close() + assert not owner.pending_cleanup and kernel.CloseHandle.calls[-1] == (92,) + assert kernel.CloseHandle.calls.count((91,)) == 1 + + +def test_failure_and_cancellation_do_not_orphan_failed_cleanup(): + kernel = ImageKernel() + kernel.failed_closes.add(92) + owner = observer(kernel) + + class Cancelled(Exception): + pass + + def checkpoint(): + if kernel.ReadFile.calls: + raise Cancelled("cancelled") + + with pytest.raises(Cancelled): + owner.observe(42, max_bytes=100, timeout=5, checkpoint=checkpoint) + assert owner.pending_cleanup + assert kernel.CloseHandle.calls == [(92,), (91,)] + kernel.failed_closes.clear() + owner.close() + assert not owner.pending_cleanup + + +def test_deadline_after_read_returns_no_evidence_and_retires(): + kernel = ImageKernel() + now = [1.0] + kernel.after_file_read = lambda: now.__setitem__(0, 7.0) + owner = observer(kernel, clock=lambda: now[0]) + with pytest.raises(MemoryObservationError, match="deadline_exceeded"): + measure(owner) + assert kernel.CloseHandle.calls == [(92,), (91,)] + + +@pytest.mark.parametrize("pid,limit,timeout", [(True, 10, 1), (0, 10, 1), (1 << 32, 10, 1), + (42, True, 1), (42, 1 << 30, 1), (42, 10, float("inf")), + (42, 10, float("nan")), (42, 10, 0)]) +def test_invalid_bounds_make_no_native_calls(pid, limit, timeout): + kernel = ImageKernel() + with pytest.raises(MemoryObservationError): + observer(kernel).observe(pid, max_bytes=limit, timeout=timeout, checkpoint=lambda: None) + assert not kernel.OpenProcess.calls + + +def test_multi_chunk_hash_is_measured_and_no_expected_digest_is_accepted(): + kernel = ImageKernel() + kernel.data = b"a" * 65536 + b"different final chunk" + owner = observer(kernel) + result = measure(owner) + assert result.sha256 == hashlib.sha256(kernel.data).hexdigest() + assert [call[2] for call in kernel.ReadFile.calls] == [65536, 21] + owner.close() + + +def test_reentrant_retirement_at_checkpoint_cannot_publish_evidence(): + kernel = ImageKernel() + owner = observer(kernel) + + def retire(): + if kernel.ReadFile.calls: + owner.close() + + with pytest.raises(MemoryObservationError, match="target_changed"): + owner.observe(42, max_bytes=100, timeout=5, checkpoint=retire) + assert kernel.CloseHandle.calls == [(92,), (91,)] + + +def test_pid_mismatch_before_file_open_fails_closed(): + kernel = ImageKernel() + kernel.pid = 43 + with pytest.raises(MemoryObservationError, match="target_changed"): + measure(observer(kernel)) + assert not kernel.CreateFileW.calls + + +def test_32bit_owner_refuses_64bit_target_without_file_read(): + kernel = ImageKernel() + with pytest.raises(MemoryObservationError, match="unsupported"): + measure(observer(kernel, caller_bits=32)) + assert not kernel.CreateFileW.calls and kernel.CloseHandle.calls == [(91,)] + + + +@pytest.mark.parametrize("path", ["C:\\owned\\\U0001f680.exe", "C:\\owned\\\ud800.exe"]) +def test_image_name_lengths_use_windows_utf16_units(path): + kernel = ImageKernel() + kernel.image_path = path + owner = observer(kernel) + result = measure(owner) + assert result.size == len(kernel.data) + assert kernel.CreateFileW.calls[0][0] == path + owner.close() + + +def test_retirement_before_first_acquisition_is_terminal(): + kernel = ImageKernel() + owner = observer(kernel) + owner.close() + with pytest.raises(MemoryObservationError, match="target_changed"): + measure(owner) + assert not kernel.OpenProcess.calls + + +def test_successive_observers_measure_changed_bytes_instead_of_reusing_identity_digest(): + digests = [] + for contents in (b"one", b"two"): + kernel = ImageKernel() + kernel.data = contents + owner = observer(kernel) + digests.append(measure(owner).sha256) + owner.close() + assert digests == [hashlib.sha256(value).hexdigest() for value in (b"one", b"two")] + + +def test_both_failed_closes_remain_owned_after_acquisition_failure(): + kernel = ImageKernel() + kernel.info_failure = True + kernel.failed_closes.update((91, 92)) + owner = observer(kernel) + with pytest.raises(MemoryObservationError, match="unsupported"): + measure(owner) + assert owner.pending_cleanup and kernel.CloseHandle.calls == [(92,), (91,)] + kernel.failed_closes.clear() + owner.close() + assert kernel.CloseHandle.calls == [(92,), (91,), (92,), (91,)] + + +def test_import_never_loads_kernel_or_registers_public_tools(monkeypatch): + import importlib + import je_auto_control.utils.process_memory.windows_image_native as native + + def forbidden(*args, **kwargs): + raise AssertionError("native loader must not run during import") + + monkeypatch.setattr(ctypes, "WinDLL", forbidden, raising=False) + importlib.reload(native) + importlib.reload(importlib.import_module("je_auto_control.utils.process_memory.windows_image")) + + +def test_unknown_architecture_is_unsupported_before_file_acquisition(): + kernel = ImageKernel() + kernel.machine = 0xFFFF + with pytest.raises(MemoryObservationError, match="unsupported"): + measure(observer(kernel)) + assert not kernel.CreateFileW.calls and not kernel.ReadFile.calls + + +@pytest.mark.parametrize("operation,reason", [("CreateFileW", "unsupported"), ("ReadFile", "partial_read"), + ("GetProcessTimes", "target_changed"), + ("GetFileInformationByHandleEx", "unsupported")]) +def test_native_exceptions_are_closed_and_never_expose_private_data(operation, reason): + kernel = ImageKernel() + + def fail(*args): + raise OSError("private-path-address-123") + + getattr(kernel, operation).implementation = fail + owner = observer(kernel) + with pytest.raises(MemoryObservationError) as error: + measure(owner) + assert str(error.value) == reason + assert "private" not in repr(error.value) + assert not owner.pending_cleanup + + +def test_close_exceptions_try_every_handle_and_preserve_checkpoint_exception(): + kernel = ImageKernel() + owner = observer(kernel) + + def close(handle): + if handle == 92: + raise RuntimeError("private-file-path") + return True + + kernel.CloseHandle.implementation = close + + class Cancelled(Exception): + pass + + def checkpoint(): + if kernel.ReadFile.calls: + raise Cancelled("checkpoint cancellation") + + with pytest.raises(Cancelled, match="checkpoint cancellation"): + owner.observe(42, max_bytes=100, timeout=5, checkpoint=checkpoint) + assert kernel.CloseHandle.calls == [(92,), (91,)] and owner.pending_cleanup + kernel.CloseHandle.implementation = lambda handle: True + owner.close() + assert not owner.pending_cleanup From d83fba07c319cf959281a571f5bfc91735d1ed51 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 19:13:23 +0800 Subject: [PATCH 033/161] Retain unfinished WebRTC software teardown and original peer ownership --- CHANGELOG.md | 6 + Progress.md | 6 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 28 +-- .../operations_layer/operations_layer_doc.rst | 26 +++ .../operations_layer/operations_layer_doc.rst | 20 ++ docs/updates/2026-11-b.md | 11 + docs/updates/README.md | 4 +- .../utils/remote_desktop/file_sync.py | 9 + .../utils/remote_desktop/multi_viewer.py | 124 +++++++--- .../utils/remote_desktop/webrtc_host.py | 140 ++++++------ .../utils/remote_desktop/webrtc_host_auth.py | 28 ++- .../remote_desktop/webrtc_peer_cleanup.py | 88 ++++++++ .../utils/remote_desktop/webrtc_retirement.py | 183 +++++++++++++++ .../utils/remote_desktop/webrtc_viewer.py | 119 +++++----- pyproject.toml | 2 + .../test_remote_desktop_multi_viewer.py | 84 ++++++- .../headless/test_webrtc_host_auth.py | 7 + .../headless/test_webrtc_host_session.py | 11 +- .../headless/test_webrtc_stop_ownership.py | 213 ++++++++++++++++++ .../headless/test_webrtc_viewer_session.py | 11 +- 23 files changed, 923 insertions(+), 203 deletions(-) create mode 100644 je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py create mode 100644 je_auto_control/utils/remote_desktop/webrtc_retirement.py create mode 100644 test/unit_test/headless/test_webrtc_stop_ownership.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 543080899..cad9592ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- WebRTC stop now reports pending or failed software cleanup, retains failed resources, + and blocks peer replacement until cleanup succeeds. Retrying a pending stop reuses + the original future. Multi-viewer teardown retains failed sessions and their capture + source; FolderSync exposes actual worker completion through `stop_confirmed()`. + Native device retirement and durable GUI recovery remain separate work. + - Add internal bounded Windows image-file measurements with retained read-only leases and retryable cleanup. These observations do not grant loaded-code or fixture attestation. diff --git a/Progress.md b/Progress.md index f91e2cbf0..a614f6595 100644 --- a/Progress.md +++ b/Progress.md @@ -535,7 +535,11 @@ F 還缺: - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, - 尚未保留失敗資源的明確重試所有權;不能把背景排程等同原生資源已釋放。 + 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, + 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 + 音訊、錄影與 LAN 廣播後端仍有吞掉清理錯誤或清掉失敗資源參照的路徑;錄影須分開記錄 flush 結果與容器關閉, + 不可重播可能已部分完成的 flush。`webrtc_file_tasks` 的 `asyncio.to_thread` 傳送器仍缺實際工作執行緒完成確認, + 取消並等候非同步包裝任務不代表傳送器已停止。上述缺口已用假資源重現,未執行原生/裝置/網路驗收。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/README.md b/README.md index a5cfa29fd..e990e1f3f 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,8 @@ Managed agent tasks and cross-host transfers include experimental features. See Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. +WebRTC host/viewer `stop()` waits up to three seconds for software teardown. `PeerStopPending` retains the same running attempt; explicit retry waits on it. `PeerStopFailed` retains failed resources for explicit retry, and restarting is blocked until cleanup succeeds. Multi-viewer hosts retain failed sessions and their shared source. `FolderSyncEngine.stop_confirmed()` returns `False` while the original worker remains alive. These outcomes do not prove native device release; recovery after page destruction still needs durable ownership and retry integration. + MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 4e5eb8bb3..a51ade63b 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -69,6 +69,8 @@ Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用 关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。已进入发送阶段的文件传输不会因关闭页面而中断。 +WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStopPending` 保留同一个尚未完成的操作;显式重试只会继续等待。`PeerStopFailed` 保留清理失败的资源供显式重试,成功前禁止重新启动。Multi-viewer host 保留失败的 session 与共享来源。`FolderSyncEngine.stop_confirmed()` 在原工作线程仍存活时返回 `False`。这些结果不代表原生设备已释放;页面销毁后的恢复仍需持久资源保管与重试整合。 + MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index b22fc4478..950c88dfd 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -69,6 +69,8 @@ Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫 關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 +WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStopPending` 保留同一個尚未完成的操作;明確重試只會繼續等待。`PeerStopFailed` 保留清理失敗的資源供明確重試,成功前禁止重新啟動。Multi-viewer host 保留失敗的 session 與共用來源。`FolderSyncEngine.stop_confirmed()` 在原工作執行緒仍存活時回傳 `False`。這些結果不代表原生裝置已釋放;頁面銷毀後的復原仍需持久資源保管與重試整合。 + MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 diff --git a/architecture_explore.md b/architecture_explore.md index e50ff8811..a98759251 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,520 | -| 程式碼總行數 | 231,839 | +| Python 模組總數(含周邊子專案) | 1,522 | +| 程式碼總行數 | 232,184 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 30,535 行。 +> 6 個套件、約 30,880 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 15,301 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 15,646 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -815,7 +815,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(15,301 行/72 檔) +#### `utils/remote_desktop/`(15,646 行/74 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -824,15 +824,17 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `webrtc_host.py` | 747 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | -| `webrtc_viewer.py` | 698 | WebRTC 檢視端:接收視訊並送出輸入。 | +| `webrtc_host.py` | 735 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | +| `webrtc_viewer.py` | 695 | WebRTC 檢視端:接收視訊並送出輸入。 | +| `webrtc_retirement.py` | 183 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | +| `webrtc_peer_cleanup.py` | 88 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | | `host.py` | 686 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | | `viewer.py` | 743 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 564 | `AC_remote_*` 指令使用的行程級單例。 | | `webrtc_transport.py` | 421 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | -| `multi_viewer.py` | 357 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | +| `multi_viewer.py` | 421 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 323 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | @@ -851,7 +853,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_file_write.py` | 209 | Bounded observable DataChannel writes preserve caller cancellation and serialize file producers. | | `webrtc_file_tasks.py` | 117 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | | `webrtc_files.py` | 416 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | -| `webrtc_host_auth.py` | 239 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | +| `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | | `lan_discovery.py` | 204 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 197 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | @@ -867,7 +869,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `totp.py` | 159 | RFC 6238 TOTP(零外部相依)。 | | `file_receipts.py` | 29 | Immutable local publication receipts keep received bytes distinct from later edits to their target path. | | `clipboard_delivery.py` | 62 | Deliver clipboard data under its captured local authority and concrete connection owner. Once-bound ClipboardReceiver weakly pins the origin; queued deliveries keep the concrete peer alive without a registration self-cycle. | -| `file_sync.py` | 379 | 內容摘要鏡像、固定接收收據、離線重試、停止工作擁有權與不可變交接基準。 | +| `file_sync.py` | 388 | 內容摘要鏡像、固定接收收據、離線重試、停止工作擁有權與不可變交接基準。 | | `transport.py` | 126 | 可插拔的型別化訊息傳輸。 | | `host_access.py` | 112 | TCP 主機的檢視端核准與存取控制:`PendingViewer`、權限字串、分享碼的 TOTP 候選值、IP 白名單。`host` 與 `host_client` 共用,所以獨立成模組。 | | `protocol.py` | 98 | 長度前綴的 TCP 框架。 | @@ -1435,7 +1437,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,183 個 `test_*.py`/11,503 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,184 個 `test_*.py`/11,515 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1528,7 +1530,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 61 | 22,084 | -| `utils/remote_desktop/` | 72 | 15,301 | +| `utils/remote_desktop/` | 74 | 15,646 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1547,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,036 | -| **總計** | **1,508** | **231,094** | +| **總計** | **1,510** | **231,439** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 920ce91ef..158b1a6c0 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -742,3 +742,29 @@ Executor commands:: GUI: *Export Config* / *Import Config* buttons on the REST API tab, both with file dialogs and overwrite-confirmation dialogs. + +WebRTC software stop ownership +---------------------------------------------------------------------- + +``WebRTCDesktopHost.stop()`` and ``WebRTCDesktopViewer.stop()`` wait up to three +seconds. ``PeerStopPending`` (from ``utils.remote_desktop.webrtc_retirement``) +means the same retained future is still running; retrying waits on that future +without submitting another coroutine. ``PeerStopFailed`` means a terminal failure; +explicit retry attempts remaining resources. Both are ``RuntimeError`` compatible. +Public and asynchronous restart paths refuse unfinished retirement. Delayed auth +shutdown and peer callbacks remain bound to the original peer generation. + +Independent cleanup steps still run after an ordinary resource error. Failed child +references remain owned, and owned frame tasks must actually finish before the +software stop completes. ``MultiViewerHost`` retains failed child sessions and the +shared screen source until their stop calls succeed; source failure blocks new +sessions. ``FolderSyncEngine.stop_confirmed()`` requests cancellation, waits at most +two seconds and returns whether that exact worker has exited. ``False`` retains the +worker for later observation; it is not permission to start an overlapping worker. + +These are software completion contracts, not proof that every underlying native +resource has retired. Media helpers may still suppress internal device errors. +Cancelling a file-request coroutine does not join its ``asyncio.to_thread`` sender; +that worker still depends on cooperative cancellation. +Durable ownership and explicit retry after GUI page destruction are not yet supplied +by these backend changes; callers must retain an owner when stop raises. diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index 494f9afb9..bb34b98d6 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -673,3 +673,23 @@ Executor 指令:: GUI:REST API 分頁的 *Export Config* / *Import Config* 兩顆按鈕, 都帶檔案對話框與覆寫確認。 + +WebRTC 軟體停止資源保管 +---------------------------------------------------------------------- + +``WebRTCDesktopHost.stop()`` 與 ``WebRTCDesktopViewer.stop()`` 最多等待三秒。 +``utils.remote_desktop.webrtc_retirement`` 的 ``PeerStopPending`` 表示同一個保留的 +future 仍在執行;重試只會等待該 future,不另送 coroutine。``PeerStopFailed`` 表示 +操作已失敗;明確重試會處理剩餘資源。兩者都相容於 ``RuntimeError``。公開及非同步 +重新啟動入口會拒絕尚未完成的清理;延遲驗證關閉與 peer 回呼綁定原連線世代。 + +一般資源錯誤不妨礙其他獨立清理步驟。失敗的子資源保留引用,影格工作必須真正 +結束才算軟體停止完成。``MultiViewerHost`` 保留失敗的 session 與共用畫面來源, +直到停止呼叫成功;來源停止失敗期間禁止新增 session。 +``FolderSyncEngine.stop_confirmed()`` 請求取消、最多等待兩秒,再回報同一個工作 +執行緒是否已退出。``False`` 表示仍保留工作供後續觀測,不代表可啟動重疊工作。 + +以上只承諾軟體操作完成,不證明所有底層原生資源已退出。媒體輔助類別仍可能吞掉 +內部裝置錯誤。取消檔案請求 coroutine 不等於等待其 ``asyncio.to_thread`` 傳送工作 +退出;該工作仍依賴合作式取消。本次後端變更尚未提供 GUI 頁面銷毀後的持久保管與明確重試;停止 +拋出例外時,呼叫端必須保留擁有者。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d8ed59fae..e2e9390b4 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -60,3 +60,14 @@ - **What:** Added typed query/file calls and a one-shot image-file observer. It measures bytes, file identity and size from its owned read-only handle, rechecks retained process facts and file metadata, enforces finite caller bounds, and retains failed closes for retry. Shared native process facts were extracted without changing provider imports. No expected identity or digest is copied into measured results. - **Evidence:** Implementation passed 172 focused cases plus 21 quality gates. Independent review passed 197 original/new memory and fixture-protocol cases plus a fake last-access drift probe. UTF-16 length and native-error cleanup findings were fixed. Parent integration passed 239 cases and quality gates plus a warnings-as-errors Sphinx dummy build. All eight package modules passed typing on three targets; Ruff, Bandit, Radon, changed-module Pylint and strict Sphinx passed. Whole-package Pylint retains two existing reader inference findings. Native observer calls used injected functions; existing fixture tests used hidden Python IPC only. - **Open items:** This measures a file, not loaded code. Trusted launch/image binding, reviewed runtime/source delivery, attestor/resolver, runtime integration and native acceptance remain in Progress.md. No new native image or memory observation ran. + +## U-20261111-23 · 2026-11-11 · Retain unfinished WebRTC software teardown · #done #remote + +- **What:** Host/viewer stop retains one running future and failed resources, denies input at stop admission, and prevents old callbacks from retiring a replacement peer. Independent cleanup continues after ordinary failures, and frame-task completion is observed. MultiViewer keeps original children and source while offer creation or retirement remains unfinished. FolderSync exposes original-worker completion separately from requesting stop. +- **Evidence:** Author scope and quality checks passed 184 cases, adjacent regressions passed 325, and final changed paths passed 105. Independent review verified the final offer-admission and submission-error changes with 65 cases after its broader review. Parent integration passed 200 host/viewer/auth/coordinator/ownership cases, 49 document/quality gates and a warnings-as-errors Sphinx dummy build. Seven production modules passed strict typing, file budgets and complexity checks; strict HTML and dummy Sphinx builds passed in the author checkout. All runtime checks used fake resources or offscreen Qt. +- **Open items:** Durable GUI cleanup ownership, original-authority Diagnostics retries, consumer migration, media finalization and real sender-worker exit remain in Progress.md. Software completion does not prove native resource release. + +## U-20261111-24 · 2026-11-11 · Record fixed-source full-suite failures and coverage · #snapshot #verification + +- **Evidence:** The full coverage run on fixed source b8f7df713a845038ee2c2c8cdf520c9f49715bfa terminated with 18,390 passed, 16 failed, 160 skipped and 16 subtests passed in 2,625.27 seconds. Coverage report returned 87.78% and exit 0. The pytest process returned exit 1. +- **Failures:** Five capability/diagnostic/REST policy cases, five queued registry-view notification cases and six FolderSync GUI-double cases require correction and scoped verification. The fixed source excludes subsequent image-file measurement and WebRTC retirement changes. This is not an all-green integration result; native and long-duration acceptance remain unperformed. diff --git a/docs/updates/README.md b/docs/updates/README.md index 4913ded92..496f3474d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,8 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-24 | 2026-11-11 | Record fixed-source full-suite failures and coverage | #snapshot #verification | [2026-11-b](2026-11-b.md) | +| U-20261111-23 | 2026-11-11 | Retain unfinished WebRTC software teardown | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-22 | 2026-11-11 | Measure image-file evidence through retained Windows handles | #done #memory | [2026-11-b](2026-11-b.md) | | U-20261111-21 | 2026-11-11 | Verify integrated types, HTML and distribution source bytes | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-20 | 2026-11-11 | Enforce reviewed MCP capabilities at every invocation | #done #security | [2026-11-b](2026-11-b.md) | @@ -641,7 +643,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 11 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 13 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/file_sync.py b/je_auto_control/utils/remote_desktop/file_sync.py index e1b3d6ef7..2b2e55aa2 100644 --- a/je_auto_control/utils/remote_desktop/file_sync.py +++ b/je_auto_control/utils/remote_desktop/file_sync.py @@ -157,6 +157,15 @@ def stop(self) -> None: if thread is not None and thread is not threading.current_thread(): thread.join(timeout=2.0) + def stop_confirmed(self) -> bool: + """Request stop and observe whether this exact worker has actually exited.""" + with self._lifecycle_lock: + self.request_stop() + thread = self._thread + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout=2.0) + return thread is None or not thread.is_alive() + @property def stop_requested(self) -> bool: """Expose the current run's cancellation request to an owning synchronous sender.""" diff --git a/je_auto_control/utils/remote_desktop/multi_viewer.py b/je_auto_control/utils/remote_desktop/multi_viewer.py index 9c5455e7f..01f902384 100644 --- a/je_auto_control/utils/remote_desktop/multi_viewer.py +++ b/je_auto_control/utils/remote_desktop/multi_viewer.py @@ -9,6 +9,7 @@ from __future__ import annotations import secrets +from functools import partial import threading from datetime import datetime, timezone from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple @@ -24,6 +25,7 @@ from je_auto_control.utils.remote_desktop.input_dispatch import dispatcher_at from je_auto_control.utils.remote_desktop.permissions import SessionPermissions from je_auto_control.utils.remote_desktop.trust_list import TrustList +from je_auto_control.utils.remote_desktop.webrtc_retirement import CleanupAttempt, PeerLifecycleError, PeerStopPending from je_auto_control.utils.remote_desktop.webrtc_host import WebRTCDesktopHost from je_auto_control.utils.remote_desktop.webrtc_transport import ( ScreenVideoTrack, WebRTCConfig, @@ -98,6 +100,11 @@ def __init__(self, *, token: str, self._on_pending_viewer = on_pending_viewer self._sessions: Dict[str, WebRTCDesktopHost] = {} self._session_meta: Dict[str, dict] = {} + self._session_tokens: Dict[str, object] = {} + self._retiring: Dict[str, WebRTCDesktopHost] = {} + self._creating: set[WebRTCDesktopHost] = set() + self._source_stopping = False + self._source_failed = False self._source: Optional[_ScreenSource] = None self._lock = threading.Lock() @@ -118,9 +125,15 @@ def _annotate(self, data: dict) -> None: def create_session_offer(self) -> Tuple[str, str]: """Mint a new session: returns ``(session_id, offer_sdp)``.""" with self._lock: + if self._retiring or self._source_stopping or self._source_failed: + raise PeerStopPending("finish retiring previous sessions before creating another") if self._source is None: self._source = _ScreenSource(self._config) session_id = secrets.token_hex(8) + if session_id in self._sessions: + raise PeerLifecycleError("session identity collision") + token = object() + self._session_tokens[session_id] = token host = WebRTCDesktopHost( token=self._token, config=self._config, @@ -130,18 +143,27 @@ def create_session_offer(self) -> Tuple[str, str]: ip_whitelist=self._ip_whitelist, on_annotation=self._annotate if self._on_annotation is not None else None, external_video_track=self._source.subscribe(), - on_state_change=self._wrap_state_callback(session_id), - on_authenticated=self._wrap_auth_callback(session_id), - on_pending_viewer=self._wrap_pending_callback(session_id), + on_state_change=self._wrap_state_callback(session_id, token), + on_authenticated=self._wrap_auth_callback(session_id, token), + on_pending_viewer=self._wrap_pending_callback(session_id, token), ) self._sessions[session_id] = host + self._creating.add(host) try: offer = host.create_offer(peer_label=f"viewer-{session_id[:6]}") except BaseException: - # The caller never learns this session_id, so nobody else could - # stop it: it would hold its screen-source subscription forever. - self.stop_session(session_id) + with self._lock: + self._creating.discard(host) + self._stop_owned_session(session_id, host) + self._maybe_release_source() raise + with self._lock: + self._creating.discard(host) + retiring = self._retiring.get(session_id) is host + if retiring: + self._stop_owned_session(session_id, host) + self._maybe_release_source() + raise PeerLifecycleError("session stopped during offer creation") return session_id, offer def accept_session_answer(self, session_id: str, answer_sdp: str) -> None: @@ -150,34 +172,56 @@ def accept_session_answer(self, session_id: str, answer_sdp: str) -> None: def stop_session(self, session_id: str) -> None: with self._lock: - host = self._sessions.pop(session_id, None) - self._session_meta.pop(session_id, None) + host = self._sessions.get(session_id) if host is not None: - try: - host.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("stop session %s: %r", session_id, error) + self._stop_owned_session(session_id, host) self._maybe_release_source() + def _stop_owned_session(self, session_id: str, host: WebRTCDesktopHost) -> None: + with self._lock: + if self._sessions.get(session_id) is not host: + return + self._retiring[session_id] = host + if host in self._creating: + raise PeerStopPending("session offer creation is still running") + host.stop() + with self._lock: + if self._sessions.get(session_id) is host: + self._sessions.pop(session_id) + self._session_meta.pop(session_id, None) + self._session_tokens.pop(session_id, None) + if self._retiring.get(session_id) is host: + self._retiring.pop(session_id) + def stop_all(self) -> None: with self._lock: sessions = list(self._sessions.items()) - self._sessions.clear() - self._session_meta.clear() + self._retiring.update(sessions) + attempt = CleanupAttempt() for session_id, host in sessions: - try: - host.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("stop_all %s: %r", session_id, error) - self._maybe_release_source() + attempt.run(partial(self._stop_owned_session, session_id, host), "session") + attempt.run(self._maybe_release_source, "screen source") + attempt.finish() def _maybe_release_source(self) -> None: with self._lock: if self._sessions or self._source is None: return + if self._source_stopping: + raise PeerStopPending("screen source stop is still running") source = self._source - self._source = None - source.stop() + self._source_stopping = True + self._source_failed = True + try: + source.stop() + except BaseException: + with self._lock: + self._source_stopping = False + raise + with self._lock: + if self._source is source: + self._source = None + self._source_stopping = self._source_failed = False # --- per-session controls ----------------------------------------------- @@ -289,6 +333,8 @@ def session_pc(self, session_id: str): def _require_session(self, session_id: str) -> WebRTCDesktopHost: with self._lock: + if session_id in self._retiring: + raise PeerStopPending("session is retiring") host = self._sessions.get(session_id) if host is None: raise KeyError(f"unknown session_id: {session_id}") @@ -296,11 +342,13 @@ def _require_session(self, session_id: str) -> WebRTCDesktopHost: # --- callback wrappers -------------------------------------------------- - def _wrap_state_callback(self, session_id: str): + def _wrap_state_callback(self, session_id: str, token: object = None): cb = self._on_session_state def _emit(state: str) -> None: + if token is not None and self._session_tokens.get(session_id) is not token: + return if state in _FINAL_STATES: - self._prune_later(session_id) + self._prune_later(session_id, token) if cb is None: return try: @@ -309,7 +357,7 @@ def _emit(state: str) -> None: autocontrol_logger.debug("session state cb: %r", error) return _emit - def _prune_later(self, session_id: str) -> None: + def _prune_later(self, session_id: str, token: object = None) -> None: """Drop a session whose peer connection ended, off the loop thread. A peer that fails, closes, or misses the auth deadline is stopped @@ -318,13 +366,26 @@ def _prune_later(self, session_id: str) -> None: on with nobody watching. ``stop_session`` blocks on the bridge, and this is called from the loop thread, hence the thread. """ - threading.Thread(target=self.stop_session, args=(session_id,), - name="webrtc-prune", daemon=True).start() + with self._lock: + if token is not None and self._session_tokens.get(session_id) is not token: + return + host = self._sessions.get(session_id) + if host is None: + return + def retire() -> None: + try: + self._stop_owned_session(session_id, host) + self._maybe_release_source() + except (RuntimeError, OSError): + autocontrol_logger.warning("session retirement remains pending") + threading.Thread(target=retire, name="webrtc-prune", daemon=True).start() - def _wrap_auth_callback(self, session_id: str): + def _wrap_auth_callback(self, session_id: str, token: object = None): cb = self._on_session_authenticated def _emit() -> None: with self._lock: + if token is not None and self._session_tokens.get(session_id) is not token: + return meta = self._session_meta.setdefault(session_id, {}) meta["connected_at"] = datetime.now(timezone.utc).isoformat() if cb is None: @@ -335,13 +396,16 @@ def _emit() -> None: autocontrol_logger.debug("session auth cb: %r", error) return _emit - def _wrap_pending_callback(self, session_id: str): + def _wrap_pending_callback(self, session_id: str, token: object = None): cb = self._on_pending_viewer if cb is None: return None def _emit() -> None: - host = self._sessions.get(session_id) - viewer_id = host.pending_viewer_id if host is not None else None + with self._lock: + if token is not None and self._session_tokens.get(session_id) is not token: + return + host = self._sessions.get(session_id) + viewer_id = host.pending_viewer_id if host is not None else None try: cb(session_id, viewer_id) except (RuntimeError, OSError) as error: diff --git a/je_auto_control/utils/remote_desktop/webrtc_host.py b/je_auto_control/utils/remote_desktop/webrtc_host.py index 4ae939153..1025c5daa 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host.py @@ -17,8 +17,12 @@ import asyncio import json import threading -from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Tuple +from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional, Tuple +from je_auto_control.utils.remote_desktop.webrtc_peer_cleanup import stop_host +from je_auto_control.utils.remote_desktop.webrtc_retirement import ( + PeerRetirement, stop_resource, +) from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.audit_log import default_audit_log @@ -30,7 +34,7 @@ abort_file_receiver, bind_file_receiver, close_file_receiver, ) from je_auto_control.utils.remote_desktop.webrtc_file_tasks import ( - cancel_file_requests, file_request_failure, start_file_request, + file_request_failure, start_file_request, ) from je_auto_control.utils.remote_desktop.webrtc_file_write import _on_bridge_thread from je_auto_control.utils.remote_desktop.permissions import SessionPermissions @@ -143,6 +147,7 @@ def __init__(self, *, token: str, # NOSONAR python:S107 # loop doesn't garbage-collect them mid-flight (S7502). Tasks # remove themselves from this set in their done callback. self._background_tasks: set = set() + self._retirement = PeerRetirement() self._closed = threading.Event() self._lock = threading.Lock() @@ -150,8 +155,10 @@ def __init__(self, *, token: str, # NOSONAR python:S107 def create_offer(self, peer_label: str = "remote viewer") -> str: """Build the PC, generate SDP offer (with ICE candidates baked in).""" + self._retirement.require_startable() if not self._offer_consent(peer_label): raise PermissionError("offer rejected by consent callback") + self._retirement.admit_start() future = get_bridge().submit(self._async_create_offer()) return future.result(timeout=_OFFER_TIMEOUT_S) @@ -163,15 +170,12 @@ def accept_answer(self, answer_sdp: str) -> None: future.result(timeout=_ANSWER_TIMEOUT_S) def stop(self) -> None: - """Tear down the PeerConnection and capture executor.""" - if self._pc is None: + """Wait for software teardown; retain and report unfinished attempts.""" + if self._pc is None and not self._retirement.unsettled: return self._closed.set() - future = get_bridge().submit(self._async_stop()) - try: - future.result(timeout=3.0) - except (asyncio.TimeoutError, OSError, RuntimeError) as error: - autocontrol_logger.warning("webrtc host stop: %r", error) + self._authenticated = self._has_pending_viewer = False + self._retirement.stop(get_bridge().submit, self._async_stop) @property def authenticated(self) -> bool: @@ -184,8 +188,14 @@ def connection_state(self) -> str: # --- async internals ---------------------------------------------------- async def _async_create_offer(self) -> str: + async with self._retirement.starting(): + return await self._create_offer() + + async def _create_offer(self) -> str: if self._pc is not None: - await self._pc.close() + await self._stop_peer() + self._retirement.require_startable() + self._closed.clear() self._pc = RTCPeerConnection( configuration=self._config.to_rtc_configuration(), ) @@ -229,53 +239,27 @@ async def _async_create_offer(self) -> str: return self._pc.localDescription.sdp async def _async_accept_answer(self, answer_sdp: str) -> None: - if self._pc is None: - raise RuntimeError("call create_offer() first") - answer = RTCSessionDescription(sdp=answer_sdp, type="answer") - await self._pc.setRemoteDescription(answer) - loop = asyncio.get_running_loop() - self._auth_deadline_handle = loop.call_later( - _AUTH_GRACE_S, self._enforce_auth_deadline, - ) + async with self._retirement.starting(): + if self._pc is None: + raise RuntimeError("call create_offer() first") + answer = RTCSessionDescription(sdp=answer_sdp, type="answer") + await self._pc.setRemoteDescription(answer) + peer = self._pc + loop = asyncio.get_running_loop() + self._auth_deadline_handle = loop.call_later( + _AUTH_GRACE_S, lambda: self._for_peer(peer, self._enforce_auth_deadline), + ) - @staticmethod - def _stop_quietly(obj, label: str) -> None: - """Call ``obj.stop()``, swallowing teardown errors with a debug log.""" - if obj is None: - return - try: - obj.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("%s stop: %r", label, error) + _stop_quietly = staticmethod(stop_resource) - async def _async_stop(self) -> None: - self._closed.set() - close_file_receiver(self._files_receiver, self._files_channel) - await cancel_file_requests(self._background_tasks) - self._stop_quietly(self._host_voice_track, "host voice") - self._host_voice_track = None - self._stop_quietly(self._opus_audio_receiver, "opus receiver") - self._opus_audio_receiver = None - if self._viewer_video_task is not None: - self._viewer_video_task.cancel() - self._viewer_video_task = None - self._stop_quietly(self._mic_receiver, "mic receiver") - self._mic_receiver = None - if self._video_track is not None and self._external_video_track is None: - # Only stop tracks we created; relayed/external tracks belong to the owner. - self._video_track.stop() - self._video_track = None - if self._pc is not None: - await self._pc.close() - self._pc = None - self._control_channel = None - self._mic_channel = None - self._files_channel = self._files_receiver = None - self._release_usb_claims() - self._authenticated = False - if self._auth_deadline_handle is not None: - self._auth_deadline_handle.cancel() - self._auth_deadline_handle = None + def _async_stop(self) -> Coroutine[Any, Any, None]: + return self._stop_generation(self._pc) + + async def _stop_generation(self, peer: object) -> None: + await self._retirement.retire(peer, lambda: self._pc, self._stop_peer) + + async def _stop_peer(self) -> None: + await stop_host(self) def _spawn_bg(self, coro) -> "asyncio.Task": """Schedule ``coro`` and pin a strong ref while it runs (S7502).""" @@ -289,6 +273,8 @@ def _spawn_bg(self, coro) -> "asyncio.Task": def _wire_viewer_video_handler(self, pc: RTCPeerConnection) -> None: @pc.on("track") def _on_track(track) -> None: + if self._pc is not pc or self._closed.is_set(): + return if track.kind == "video": autocontrol_logger.info("webrtc host: receiving viewer video") self._viewer_video_task = self._spawn_bg( @@ -448,13 +434,11 @@ def _enabled() -> bool: ) def _release_usb_claims(self) -> None: - usb_host, self._usb_host = self._usb_host, None - if usb_host is None: - return - try: + usb_host = self._usb_host + if usb_host is not None: usb_host.close() - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("usb claims release: %r", error) + if self._usb_host is usb_host: + self._usb_host = None def set_file_received_callback(self, callback) -> None: """Register a sync callback ``cb(path: Path)`` for completed transfers.""" @@ -505,7 +489,8 @@ def _on_open() -> None: @channel.on("message") def _on_message(message) -> None: - self._handle_ctrl_message(message) + if self._control_channel is channel: + self._handle_ctrl_message(message) @channel.on("close") def _on_close() -> None: @@ -514,6 +499,8 @@ def _on_close() -> None: abort_file_receiver(self._files_receiver, self._files_channel) def _handle_ctrl_message(self, message: Any) -> None: + if self._closed.is_set(): + return data = self._parse_ctrl_envelope(message) if data is None: return @@ -590,20 +577,21 @@ def _safe_audit_log(self, event_type: str) -> None: pass async def _async_apply_renegotiate_answer(self, sdp: str) -> None: - if self._pc is None: - return - try: - await self._pc.setRemoteDescription( - RTCSessionDescription(sdp=sdp, type="answer"), - ) - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("apply renegotiate answer: %r", error) - return - # Viewer may have just attached a fresh track. If our consume - # task has died (because the previous track stopped), spawn a - # new one against the same receiver. - self._maybe_resubscribe_viewer_video() - self._maybe_resubscribe_viewer_audio() + async with self._retirement.starting(): + if self._pc is None: + return + try: + await self._pc.setRemoteDescription( + RTCSessionDescription(sdp=sdp, type="answer"), + ) + except (RuntimeError, OSError) as error: + autocontrol_logger.warning("apply renegotiate answer: %r", error) + return + # Viewer may have just attached a fresh track. If our consume + # task has died (because the previous track stopped), spawn a + # new one against the same receiver. + self._maybe_resubscribe_viewer_video() + self._maybe_resubscribe_viewer_audio() def _ensure_files_receiver(self) -> "FileTransferReceiver": """Return the inbox receiver, creating it on first use.""" diff --git a/je_auto_control/utils/remote_desktop/webrtc_host_auth.py b/je_auto_control/utils/remote_desktop/webrtc_host_auth.py index 637ddaaa0..94ce3ce65 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host_auth.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host_auth.py @@ -11,6 +11,7 @@ import asyncio import hmac +from threading import Event from typing import ( TYPE_CHECKING, Any, Callable, Coroutine, List, Mapping, Optional, ) @@ -34,13 +35,17 @@ class ViewerAuthMixin: Requires the host to provide ``_token``, ``_trust_list``, ``_ip_whitelist``, ``_authenticated``, ``_pending_viewer_id``, - ``_send_ctrl``, ``_spawn_bg`` and ``_async_stop``. + ``_send_ctrl``, ``_spawn_bg``, ``_async_stop``, ``_stop_generation``, + ``_pc`` and ``_closed``. """ if TYPE_CHECKING: # Declared, never defined: the host class this is mixed into owns # every one of these. The block is stripped at runtime, so nothing # here can shadow what the host actually binds. + _pc: Any + _stop_generation: Callable[[object], Coroutine[Any, Any, None]] + _closed: Event _token: str _trust_list: Optional["TrustList"] _ip_whitelist: List[str] @@ -102,7 +107,8 @@ def _reject_auth(self, data: Mapping[str, Any]) -> None: ) except (RuntimeError, OSError) as error: autocontrol_logger.debug("audit log auth_fail: %r", error) - get_bridge().call_soon(self._schedule_close_after_fail) + peer = self._pc + get_bridge().call_soon(lambda: self._for_peer(peer, self._schedule_close_after_fail)) def _auto_approve_via_trust(self) -> bool: # The emptiness check is what `_is_trusted_viewer` does first anyway; @@ -172,11 +178,13 @@ def pending_viewer_id(self) -> Optional[str]: def approve_pending_viewer(self) -> None: """Thread-safe accept; call from GUI when user clicks Accept.""" - get_bridge().call_soon(self._approve_pending_viewer) + peer = self._pc + get_bridge().call_soon(lambda: self._for_peer(peer, self._approve_pending_viewer)) def reject_pending_viewer(self) -> None: """Thread-safe reject; call from GUI when user clicks Reject.""" - get_bridge().call_soon(self._reject_pending_viewer) + peer = self._pc + get_bridge().call_soon(lambda: self._for_peer(peer, self._reject_pending_viewer)) def _approve_pending_viewer(self) -> None: # Only a viewer that presented the token and is waiting on the user @@ -189,6 +197,8 @@ def _approve_pending_viewer(self) -> None: def _grant(self) -> None: """Authenticate the viewer. Callers have verified its token.""" + if self._closed.is_set(): + return self._has_pending_viewer = False self._authenticated = True self._send_ctrl({ @@ -217,15 +227,21 @@ def _grant(self) -> None: def _reject_pending_viewer(self) -> None: self._has_pending_viewer = False self._send_ctrl({"type": "auth_fail"}) - get_bridge().call_soon(self._schedule_close_after_fail) + peer = self._pc + get_bridge().call_soon(lambda: self._for_peer(peer, self._schedule_close_after_fail)) @property def has_pending_viewer(self) -> bool: return self._has_pending_viewer + def _for_peer(self, peer: object, action: Callable[[], None]) -> None: + if self._pc is peer: + action() + def _schedule_close_after_fail(self) -> None: + peer = self._pc loop = asyncio.get_event_loop() - loop.call_later(0.5, lambda: self._spawn_bg(self._async_stop())) + loop.call_later(0.5, lambda: self._spawn_bg(self._stop_generation(peer))) def _enforce_auth_deadline(self) -> None: # A viewer with the right token that is waiting on the user's diff --git a/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py b/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py new file mode 100644 index 000000000..dd7de7ec8 --- /dev/null +++ b/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py @@ -0,0 +1,88 @@ +"""Software cleanup of a serialized peer generation, retaining failed resources.""" +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, Any, Coroutine + +from je_auto_control.utils.remote_desktop.webrtc_file_receive import close_file_receiver +from je_auto_control.utils.remote_desktop.webrtc_file_tasks import cancel_file_requests +from je_auto_control.utils.remote_desktop.webrtc_retirement import CleanupAttempt + +if TYPE_CHECKING: + from je_auto_control.utils.remote_desktop.webrtc_host import WebRTCDesktopHost + from je_auto_control.utils.remote_desktop.webrtc_viewer import WebRTCDesktopViewer + + +async def _wait_steps(*steps: Coroutine[Any, Any, object]) -> None: + results = await asyncio.gather(*steps, return_exceptions=True) + for result in results: + if isinstance(result, BaseException): + raise result + + +async def _cancel_task(task: asyncio.Task[Any]) -> None: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + +async def _close_peer(owner: WebRTCDesktopHost | WebRTCDesktopViewer, + attempt: CleanupAttempt) -> None: + peer = owner._pc + if attempt.run(lambda: close_file_receiver(owner._files_receiver, owner._files_channel), "files"): + owner._files_receiver = owner._files_channel = None + if peer is not None and await attempt.wait(peer.close, "peer"): + if owner._pc is peer: + owner._pc = None + if owner._pc is None: + owner._control_channel = owner._mic_channel = None + + +async def _host_tasks(owner: WebRTCDesktopHost, attempt: CleanupAttempt) -> None: + if owner._viewer_video_task is not None: + task = owner._viewer_video_task + if await attempt.wait(lambda: _cancel_task(task), "viewer video task") or task.done(): + owner._viewer_video_task = None + + +async def _viewer_tasks(owner: WebRTCDesktopViewer, attempt: CleanupAttempt) -> None: + if owner._receive_task is not None: + task = owner._receive_task + if await attempt.wait(lambda: _cancel_task(task), "receive task") or task.done(): + owner._receive_task = None + + +async def stop_host(owner: WebRTCDesktopHost) -> None: + owner._closed.set() + owner._authenticated = owner._has_pending_viewer = False + attempt = CleanupAttempt() + owner._host_voice_track = attempt.stop(owner._host_voice_track, "host voice") + owner._opus_audio_receiver = attempt.stop(owner._opus_audio_receiver, "opus receiver") + owner._mic_receiver = attempt.stop(owner._mic_receiver, "mic receiver") + if owner._external_video_track is None: + owner._video_track = attempt.stop(owner._video_track, "screen track") + else: + owner._video_track = None + attempt.run(owner._release_usb_claims, "USB claims") + if owner._auth_deadline_handle is not None: + owner._auth_deadline_handle.cancel() + owner._auth_deadline_handle = None + await _wait_steps( + _close_peer(owner, attempt), _host_tasks(owner, attempt), + attempt.wait(lambda: cancel_file_requests(owner._background_tasks), "file requests"), + ) + attempt.finish() + + +async def stop_viewer(owner: WebRTCDesktopViewer) -> None: + owner._closed.set() + owner._authenticated = False + attempt = CleanupAttempt() + owner._host_voice_receiver = attempt.stop(owner._host_voice_receiver, "host voice") + owner._opus_audio_track = attempt.stop(owner._opus_audio_track, "opus mic track") + owner._viewer_screen_track = attempt.stop(owner._viewer_screen_track, "screen track") + owner._mic_sender = attempt.stop(owner._mic_sender, "mic sender") + await _wait_steps(_close_peer(owner, attempt), _viewer_tasks(owner, attempt)) + attempt.finish() diff --git a/je_auto_control/utils/remote_desktop/webrtc_retirement.py b/je_auto_control/utils/remote_desktop/webrtc_retirement.py new file mode 100644 index 000000000..b90c6ee43 --- /dev/null +++ b/je_auto_control/utils/remote_desktop/webrtc_retirement.py @@ -0,0 +1,183 @@ +"""Serialize peer generations and retain unfinished software stop attempts. + +Completion here acknowledges the stop coroutine, not native device retirement. +""" +from __future__ import annotations + +import asyncio +from concurrent.futures import Future, TimeoutError +from contextlib import asynccontextmanager +import threading +from typing import AsyncIterator, Callable, Coroutine, Any, Protocol, TypeVar + +from je_auto_control.utils.exception.exceptions import AutoControlException +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption + + +_STOP_TIMEOUT_S = 3.0 + + +class PeerLifecycleError(AutoControlException, RuntimeError): + """A peer ownership transition could not be completed.""" + + +class PeerStopPending(PeerLifecycleError): + """The original stop attempt is still running; its owner must be retained.""" + + +class PeerStopFailed(PeerLifecycleError): + """A stop attempt failed; the remaining resources still need explicit retry.""" + + +class Stoppable(Protocol): + def stop(self) -> None: ... + + +Resource = TypeVar("Resource", bound=Stoppable) + + +class CleanupAttempt: + """Attempt independent cleanup steps and retain each unsuccessful resource.""" + + def __init__(self) -> None: + self.failed: list[str] = [] + self.pending: list[str] = [] + + def run(self, action: Callable[[], None], label: str) -> bool: + try: + action() + except PeerStopPending: + self.pending.append(label) + return False + except Exception as error: # reason: Preserve cancellation; ordinary failures retain the resource for retry. + raise_caused_run_interruption(error) + self.failed.append(label) + return False + return True + + async def wait(self, action: Callable[[], Coroutine[Any, Any, None]], label: str) -> bool: + try: + await action() + except PeerStopPending: + self.pending.append(label) + return False + except Exception as error: # reason: Independent resources still need cleanup after an ordinary step failure. + raise_caused_run_interruption(error) + self.failed.append(label) + return False + return True + + def stop(self, resource: Resource | None, label: str) -> Resource | None: + if resource is not None and not self.run(resource.stop, label): + return resource + return None + + def finish(self) -> None: + if self.failed: + raise PeerStopFailed("unfinished cleanup: " + ", ".join(self.failed)) + if self.pending: + raise PeerStopPending("pending cleanup: " + ", ".join(self.pending)) + + +def stop_resource(resource: Stoppable | None, label: str) -> None: + """Return only after the resource's stop call succeeds; preserve its error.""" + if resource is not None: + resource.stop() + + +class PeerRetirement: + """One stop future per attempt, with exclusive async generation changes.""" + + def __init__(self) -> None: + self._mutex = threading.Lock() + self._serial = asyncio.Lock() + self._future: Future[None] | None = None + self.unsettled = False + self._failed = False + + def require_startable(self) -> None: + if self._failed: + raise PeerStopFailed("retry the previous peer stop before restarting") + with self._mutex: + future = self._future + if future is not None: + if not future.done(): + raise PeerStopPending("previous peer stop is still running") + if future.exception() is not None: + raise PeerStopFailed("retry the previous peer stop before restarting") + + def admit_start(self) -> None: + """Own a queued startup before handing its coroutine to the bridge.""" + self.require_startable() + self.unsettled = True + + @asynccontextmanager + async def starting(self) -> AsyncIterator[None]: + self.require_startable() + async with self._serial: + self.require_startable() + self.unsettled = True + try: + yield + except BaseException: # reason: Mark failed ownership even when startup is explicitly interrupted. + self._failed = True + raise + + async def retire(self, expected: object, current: Callable[[], object], + operation: Callable[[], Coroutine[Any, Any, None]]) -> None: + async with self._serial: + if current() is not expected: + return + self.unsettled = True + self._failed = True + await operation() + self._failed = False + self.unsettled = False + + def stop(self, submit: Callable[[Coroutine[Any, Any, None]], Future[None]], + operation: Callable[[], Coroutine[Any, Any, None]], + timeout: float | None = None) -> None: + with self._mutex: + if self._future is None or self._future.done(): + launch = True + future = Future[None]() + self._future = future + else: + launch = False + future = self._future + try: + if launch: + self._submit(submit, operation, future) + future.result(timeout=_STOP_TIMEOUT_S if timeout is None else timeout) + except TimeoutError as error: + raise_caused_run_interruption(error) + if not future.done(): + raise PeerStopPending("peer stop is still running") from error + raise PeerStopFailed("peer stop failed") from error + except Exception as error: # reason: Normalize transport failures without converting cancellation to success. + raise_caused_run_interruption(error) + raise PeerStopFailed("peer stop failed") from error + + @staticmethod + def _submit(submit: Callable[[Coroutine[Any, Any, None]], Future[None]], + operation: Callable[[], Coroutine[Any, Any, None]], + retained: Future[None]) -> None: + coroutine = None + try: + coroutine = operation() + actual = submit(coroutine) + except BaseException as error: # reason: Publish submission failure to every waiter, preserving its identity. + if coroutine is not None: + coroutine.close() + retained.set_exception(error) + raise + + def completed(result: Future[None]) -> None: + try: + result.result() + except BaseException as error: # reason: Relay every terminal outcome to the retained future. + retained.set_exception(error) + else: + retained.set_result(None) + + actual.add_done_callback(completed) diff --git a/je_auto_control/utils/remote_desktop/webrtc_viewer.py b/je_auto_control/utils/remote_desktop/webrtc_viewer.py index 5bca91b1c..2ee6c355d 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_viewer.py +++ b/je_auto_control/utils/remote_desktop/webrtc_viewer.py @@ -9,8 +9,12 @@ import asyncio import json import threading -from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional +from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional +from je_auto_control.utils.remote_desktop.webrtc_peer_cleanup import stop_viewer +from je_auto_control.utils.remote_desktop.webrtc_retirement import ( + PeerRetirement, stop_resource, +) from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.webrtc_file_callbacks import ( @@ -92,6 +96,7 @@ def __init__(self, *, token: str, self._authenticated = False self._read_only = False self._host_fingerprint: Optional[str] = None + self._retirement = PeerRetirement() self._closed = threading.Event() # Pin fire-and-forget asyncio tasks so they aren't reaped before # they finish (S7502). Tasks self-discard via a done callback. @@ -128,6 +133,8 @@ def process_offer(self, offer_sdp: str, verify_dtls_fingerprint, ) verify_dtls_fingerprint(offer_sdp, expected_dtls_fingerprint) + self._retirement.require_startable() + self._retirement.admit_start() future = get_bridge().submit(self._async_process_offer(offer_sdp)) return future.result(timeout=_OFFER_TIMEOUT_S) @@ -273,28 +280,29 @@ def _inplace_detach_track(self, *, kind: str) -> None: async def _async_handle_renegotiate(self, offer_sdp: str) -> None: """Apply a host-initiated renegotiation offer.""" - if self._pc is None: - return - try: - await self._pc.setRemoteDescription( - RTCSessionDescription(sdp=offer_sdp, type="offer"), - ) - if self._config.share_my_screen and self._viewer_screen_track is None: - self._attach_viewer_screen_track() - if (self._config.share_my_audio_opus - and self._opus_audio_track is None): - self._attach_opus_audio_track() - answer = await self._pc.createAnswer() - await self._pc.setLocalDescription(answer) - await wait_for_ice_gathering(self._pc) - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("renegotiate handle: %r", error) - return - self._send({ - "type": "renegotiate_answer", - "sdp": self._pc.localDescription.sdp, - }) - autocontrol_logger.info("webrtc viewer: sent renegotiate answer") + async with self._retirement.starting(): + if self._pc is None: + return + try: + await self._pc.setRemoteDescription( + RTCSessionDescription(sdp=offer_sdp, type="offer"), + ) + if self._config.share_my_screen and self._viewer_screen_track is None: + self._attach_viewer_screen_track() + if (self._config.share_my_audio_opus + and self._opus_audio_track is None): + self._attach_opus_audio_track() + answer = await self._pc.createAnswer() + await self._pc.setLocalDescription(answer) + await wait_for_ice_gathering(self._pc) + except (RuntimeError, OSError) as error: + autocontrol_logger.warning("renegotiate handle: %r", error) + return + self._send({ + "type": "renegotiate_answer", + "sdp": self._pc.localDescription.sdp, + }) + autocontrol_logger.info("webrtc viewer: sent renegotiate answer") def _wire_files_channel(self, channel) -> None: from je_auto_control.utils.remote_desktop.webrtc_files import FileTransferReceiver @@ -326,14 +334,12 @@ def _on_viewer_file_done(self, path) -> None: self._file_callbacks.published(path) def stop(self) -> None: - if self._pc is None: + """Wait for software teardown; retain and report unfinished attempts.""" + if self._pc is None and not self._retirement.unsettled: return self._closed.set() - future = get_bridge().submit(self._async_stop()) - try: - future.result(timeout=3.0) - except (asyncio.TimeoutError, OSError, RuntimeError) as error: - autocontrol_logger.warning("webrtc viewer stop: %r", error) + self._authenticated = False + self._retirement.stop(get_bridge().submit, self._async_stop) @property def connection_identity(self) -> object: @@ -362,12 +368,17 @@ def connection_state(self) -> str: # --- async internals ---------------------------------------------------- async def _async_process_offer(self, offer_sdp: str) -> str: + async with self._retirement.starting(): + return await self._process_offer(offer_sdp) + + async def _process_offer(self, offer_sdp: str) -> str: if self._pc is not None: # The whole previous session goes, not only its peer connection: # tracks, receivers and the authenticated flag outlived it. - await self._async_stop() + await self._stop_peer() # stop() set this and nothing cleared it, so a reused viewer's video # loop ended at once and showed no frames. + self._retirement.require_startable() self._closed.clear() self._pc = RTCPeerConnection( configuration=self._config.to_rtc_configuration(), @@ -440,37 +451,16 @@ def _attach_opus_audio_track(self) -> None: target.sender.replaceTrack(track) target.direction = "sendonly" - @staticmethod - def _stop_quietly(obj, label: str) -> None: - """Call ``obj.stop()``, swallowing teardown errors with a debug log.""" - if obj is None: - return - try: - obj.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("%s stop: %r", label, error) + _stop_quietly = staticmethod(stop_resource) - async def _async_stop(self) -> None: - self._closed.set() - close_file_receiver(self._files_receiver, self._files_channel) - self._stop_quietly(self._host_voice_receiver, "host voice") - self._host_voice_receiver = None - self._stop_quietly(self._opus_audio_track, "opus mic track") - self._opus_audio_track = None - self._stop_quietly(self._viewer_screen_track, "viewer screen track") - self._viewer_screen_track = None - self._stop_quietly(self._mic_sender, "mic sender") - self._mic_sender = None - if self._receive_task is not None: - self._receive_task.cancel() - self._receive_task = None - if self._pc is not None: - await self._pc.close() - self._pc = None - self._control_channel = None - self._mic_channel = None - self._files_channel = self._files_receiver = None - self._authenticated = False + def _async_stop(self) -> Coroutine[Any, Any, None]: + return self._stop_generation(self._pc) + + async def _stop_generation(self, peer: object) -> None: + await self._retirement.retire(peer, lambda: self._pc, self._stop_peer) + + async def _stop_peer(self) -> None: + await stop_viewer(self) # --- wiring ------------------------------------------------------------- @@ -496,6 +486,8 @@ async def _on_state() -> None: @pc.on("track") def _on_track(track) -> None: + if self._pc is not pc or self._closed.is_set(): + return autocontrol_logger.info("webrtc viewer: got %s track", track.kind) if track.kind == "video": self._receive_task = asyncio.ensure_future( @@ -506,6 +498,8 @@ def _on_track(track) -> None: @pc.on("datachannel") def _on_datachannel(channel) -> None: + if self._pc is not pc or self._closed.is_set(): + return self._attach_datachannel(channel) def _attach_datachannel(self, channel) -> None: @@ -534,7 +528,8 @@ def _on_open() -> None: @channel.on("message") def _on_message(message) -> None: - self._handle_ctrl_message(message) + if self._control_channel is channel: + self._handle_ctrl_message(message) @channel.on("close") def _on_close() -> None: @@ -594,6 +589,8 @@ def _send_auth(self) -> None: self._send(payload) def _handle_ctrl_message(self, message: Any) -> None: + if self._closed.is_set(): + return if not isinstance(message, str): return try: diff --git a/pyproject.toml b/pyproject.toml index 0198d697f..ebea2395c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -354,6 +354,8 @@ ignore_missing_imports = true # as a whole is named with `.*` as well, so a file added to it is covered the # day it is written. Nothing here loosens a setting from `[tool.mypy]`. module = [ + "je_auto_control.utils.remote_desktop.webrtc_retirement", + "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", "je_auto_control.android.apps", "je_auto_control.android.input", "je_auto_control.android.screen", diff --git a/test/unit_test/headless/test_remote_desktop_multi_viewer.py b/test/unit_test/headless/test_remote_desktop_multi_viewer.py index 8d8a2936a..77d92babd 100644 --- a/test/unit_test/headless/test_remote_desktop_multi_viewer.py +++ b/test/unit_test/headless/test_remote_desktop_multi_viewer.py @@ -26,6 +26,8 @@ """ from __future__ import annotations +from je_auto_control.utils.remote_desktop.webrtc_retirement import PeerStopFailed, PeerStopPending + import pytest from headless._webrtc_doubles import Track @@ -228,14 +230,20 @@ def test_stopping_an_unknown_session_is_a_no_op(): assert host.session_count() == 1 -def test_a_session_that_fails_to_stop_is_still_forgotten(): - # The PeerConnection may already be dead when the GUI asks to close the - # tab; the session must leave the table anyway, or the capture it holds - # a reference to never gets released. +def test_a_session_that_fails_to_stop_is_retained_until_retry(): host = _host() session_id, _ = host.create_session_offer() track = host.screen_track() - _FakeHost.instances[0].raise_on.add("stop") + child = _FakeHost.instances[0] + child.raise_on.add("stop") + with pytest.raises(RuntimeError): + host.stop_session(session_id) + assert host.session_count() == 1 + assert host.screen_track() is track + assert not track.stopped + with pytest.raises(PeerStopPending): + host.create_session_offer() + child.raise_on.clear() host.stop_session(session_id) assert host.session_count() == 0 assert track.stopped @@ -257,9 +265,10 @@ def test_a_session_that_fails_to_stop_does_not_strand_the_others(): host.create_session_offer() host.create_session_offer() _FakeHost.instances[0].raise_on.add("stop") - host.stop_all() + with pytest.raises(PeerStopFailed): + host.stop_all() assert _FakeHost.instances[1].stopped - assert host.screen_track() is None, "the capture is still released" + assert host.screen_track() is not None, "failed child retains its shared capture" def test_a_new_session_after_stop_all_builds_a_fresh_capture(): @@ -523,14 +532,14 @@ def test_a_pending_viewer_is_reported_with_the_id_read_at_fire_time(monkeypatch) assert seen == [(session_id, "viewer-9")] -def test_a_pending_viewer_from_a_session_that_just_left_reports_none(): +def test_a_pending_viewer_from_a_session_that_just_left_is_ignored(): seen = [] host = _host(on_pending_viewer=lambda sid, vid: seen.append((sid, vid))) session_id, _ = host.create_session_offer() wrapper = _FakeHost.instances[0].kwargs["on_pending_viewer"] host.stop_session(session_id) wrapper() - assert seen == [(session_id, None)] + assert seen == [] def test_no_pending_callback_means_no_wrapper_is_installed(): @@ -557,3 +566,60 @@ def _boom(*_args): wrapper("connected") else: wrapper() + + +def test_failed_source_is_retained_and_retry_does_not_admit_new_sessions(monkeypatch): + host = _host() + host.create_session_offer() + source = host._source + def fail(): + raise OSError("capture stop failed") + monkeypatch.setattr(source, "stop", fail) + with pytest.raises(PeerStopFailed): + host.stop_all() + assert host.session_count() == 0 + assert host._source is source + with pytest.raises(PeerStopPending): + host.create_session_offer() + monkeypatch.setattr(source, "stop", lambda: None) + host.stop_all() + assert host._source is None + + +def test_retired_callbacks_cannot_prune_or_authenticate_reused_session_id(monkeypatch): + monkeypatch.setattr(mv.secrets, "token_hex", lambda _: "same-session") + observed = [] + host = _host(on_pending_viewer=lambda *args: observed.append(args)) + session_id, _ = host.create_session_offer() + old = _FakeHost.instances[-1] + host.stop_session(session_id) + host.create_session_offer() + replacement = _FakeHost.instances[-1] + replacement.pending_viewer_id = "new viewer" + old.kwargs["on_state_change"]("failed") + old.kwargs["on_authenticated"]() + old.kwargs["on_pending_viewer"]() + assert host._sessions[session_id] is replacement + assert not replacement.stopped + assert session_id not in host._session_meta + assert observed == [] + + +def test_stop_during_offer_creation_retains_source_until_original_child_finishes(monkeypatch): + host = _host() + observed = [] + def create(child, peer_label): + source = host._source + with pytest.raises(PeerStopPending): + host.stop_all() + assert host._source is source + assert not source._track.stopped + assert host.session_count() == 1 + observed.append(child) + return "offer completed after stop requested" + monkeypatch.setattr(_FakeHost, "create_offer", create) + with pytest.raises(RuntimeError, match="stopped during offer creation"): + host.create_session_offer() + assert observed[0].stopped + assert host.session_count() == 0 + assert host._source is None diff --git a/test/unit_test/headless/test_webrtc_host_auth.py b/test/unit_test/headless/test_webrtc_host_auth.py index 1778f2bc0..211be72df 100644 --- a/test/unit_test/headless/test_webrtc_host_auth.py +++ b/test/unit_test/headless/test_webrtc_host_auth.py @@ -21,6 +21,7 @@ `~/.je_auto_control`. """ import asyncio +from threading import Event import pytest @@ -54,6 +55,8 @@ class _Host(ViewerAuthMixin): def __init__(self, *, token="secret", trust_list=None, ip_whitelist=None, remote_ip=None, permissions=None, on_pending_viewer=None): + self._pc = object() + self._closed = Event() self._token = token self._trust_list = trust_list self._ip_whitelist = list(ip_whitelist or []) @@ -80,6 +83,10 @@ def _spawn_bg(self, coroutine): async def _async_stop(self): self.stopped += 1 + async def _stop_generation(self, peer): + if self._pc is peer: + await self._async_stop() + def types_sent(self): return [message["type"] for message in self.sent] diff --git a/test/unit_test/headless/test_webrtc_host_session.py b/test/unit_test/headless/test_webrtc_host_session.py index aeeb82646..68c8d501c 100644 --- a/test/unit_test/headless/test_webrtc_host_session.py +++ b/test/unit_test/headless/test_webrtc_host_session.py @@ -28,6 +28,8 @@ import asyncio +from je_auto_control.utils.remote_desktop.webrtc_retirement import PeerStopFailed + import pytest from headless._webrtc_doubles import ( @@ -545,7 +547,9 @@ def test_a_teardown_failure_does_not_abort_the_rest_of_the_teardown(): receiver = Stoppable() host._host_voice_track = voice host._opus_audio_receiver = receiver - asyncio.run(host._async_stop()) + with pytest.raises(PeerStopFailed, match="host voice"): + asyncio.run(host._async_stop()) + assert host._host_voice_track is voice assert receiver.stopped, "teardown continued past the failure" @@ -553,8 +557,9 @@ def test_stop_quietly_ignores_a_collaborator_that_was_never_built(): WebRTCDesktopHost._stop_quietly(None, "nothing") -def test_a_stop_that_times_out_is_reported_rather_than_raised(monkeypatch): +def test_a_completed_stop_with_timeout_error_is_reported_as_failure(monkeypatch): monkeypatch.setattr(host_module, "get_bridge", HangingBridge) host = _host() host._pc = object() - host.stop() # the GUI's close button must not raise + with pytest.raises(PeerStopFailed): + host.stop() diff --git a/test/unit_test/headless/test_webrtc_stop_ownership.py b/test/unit_test/headless/test_webrtc_stop_ownership.py new file mode 100644 index 000000000..6c7c81b3f --- /dev/null +++ b/test/unit_test/headless/test_webrtc_stop_ownership.py @@ -0,0 +1,213 @@ +"""Real peer owners retain fake pending resources across explicit stop retries.""" +import asyncio +from concurrent.futures import Future + +import pytest + +from headless._webrtc_doubles import Bridge, FakePeerConnection, Stoppable +from je_auto_control.utils.remote_desktop import webrtc_host, webrtc_viewer, webrtc_retirement +from je_auto_control.utils.remote_desktop.webrtc_retirement import PeerStopFailed, PeerStopPending +from je_auto_control.utils.remote_desktop.file_sync import FolderSyncEngine + + +@pytest.fixture(params=[webrtc_host.WebRTCDesktopHost, webrtc_viewer.WebRTCDesktopViewer]) +def owner(request, monkeypatch): + monkeypatch.setattr(webrtc_retirement, "_STOP_TIMEOUT_S", 0) + return request.param(token="test-token") + + +class DeferredBridge: + def __init__(self): + self.calls = [] + self.future = Future() + + def submit(self, coroutine): + self.calls.append(coroutine) + return self.future + + def complete(self): + try: + result = asyncio.run(self.calls[0]) + except BaseException as error: + self.future.set_exception(error) + else: + self.future.set_result(result) + + +def bind_bridge(monkeypatch, bridge): + for module in (webrtc_host, webrtc_viewer): + monkeypatch.setattr(module, "get_bridge", lambda: bridge) + + +def test_pending_stop_reuses_one_future_and_blocks_public_and_async_restart(owner, monkeypatch): + bridge = DeferredBridge() + bind_bridge(monkeypatch, bridge) + peer = FakePeerConnection() + owner._pc = peer + owner._authenticated = True + try: + for _ in range(2): + with pytest.raises(PeerStopPending): + owner.stop() + assert len(bridge.calls) == 1 + assert owner._pc is peer + assert not owner.authenticated + assert owner._closed.is_set() + if isinstance(owner, webrtc_host.WebRTCDesktopHost): + with pytest.raises(PeerStopPending): + owner.create_offer() + restart = owner._async_create_offer() + else: + with pytest.raises(PeerStopPending): + owner.process_offer("v=0") + restart = owner._async_process_offer("v=0") + with pytest.raises(PeerStopPending): + asyncio.run(restart) + finally: + bridge.complete() + owner.stop() + assert peer.closed + assert owner._pc is None + assert len(bridge.calls) == 1 + + +def test_failed_media_stays_owned_while_peer_closes_then_explicit_retry_succeeds(owner, monkeypatch): + bind_bridge(monkeypatch, Bridge()) + peer = FakePeerConnection() + owner._pc = peer + failed = Stoppable(error=OSError("sensitive device details")) + attr = "_host_voice_track" if isinstance(owner, webrtc_host.WebRTCDesktopHost) else "_host_voice_receiver" + setattr(owner, attr, failed) + with pytest.raises(PeerStopFailed) as caught: + owner.stop() + assert "sensitive" not in str(caught.value) + assert peer.closed + assert getattr(owner, attr) is failed + with pytest.raises(PeerStopFailed): + owner._retirement.require_startable() + failed._error = None + owner.stop() + assert failed.stopped + assert getattr(owner, attr) is None + owner._retirement.require_startable() + + +def test_queued_stop_targets_original_peer_identity(owner): + original, replacement = FakePeerConnection(), FakePeerConnection() + owner._pc = original + queued = owner._async_stop() + owner._pc = replacement + asyncio.run(queued) + assert owner._pc is replacement + assert not replacement.closed + + +def test_delayed_auth_failure_cannot_close_replacement(monkeypatch): + async def drive(): + host = webrtc_host.WebRTCDesktopHost(token="test-token") + host._pc = FakePeerConnection() + callbacks = [] + loop = asyncio.get_running_loop() + monkeypatch.setattr(loop, "call_later", lambda delay, callback: callbacks.append(callback)) + host._schedule_close_after_fail() + replacement = FakePeerConnection() + host._pc = replacement + callbacks[0]() + await asyncio.gather(*host._background_tasks) + assert host._pc is replacement + assert not replacement.closed + asyncio.run(drive()) + + +def test_stop_waits_for_cancel_resistant_frame_task(): + async def drive(): + viewer = webrtc_viewer.WebRTCDesktopViewer(token="test-token") + peer = FakePeerConnection() + viewer._pc = peer + entered, cancelled, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + async def frames(): + entered.set() + try: + await asyncio.Future() + except asyncio.CancelledError: + cancelled.set() + await release.wait() + task = asyncio.create_task(frames()) + viewer._receive_task = task + await entered.wait() + stop = asyncio.create_task(viewer._async_stop()) + await cancelled.wait() + assert not stop.done() + assert peer.closed + assert viewer._receive_task is task + with pytest.raises(PeerStopFailed): + await viewer._async_process_offer("v=0") + release.set() + await stop + assert viewer._receive_task is None + asyncio.run(drive()) + + +def test_folder_sync_confirmation_observes_original_worker(tmp_path): + engine = FolderSyncEngine(watch_dir=tmp_path, sender=lambda *_: None) + class Worker: + alive = True + def join(self, timeout): + assert timeout == 2.0 + def is_alive(self): + return self.alive + worker = Worker() + engine._thread = worker + assert not engine.stop_confirmed() + assert engine.stop_requested + assert engine._thread is worker + worker.alive = False + assert engine.stop_confirmed() + + +def test_stop_preserves_explicit_interruption_identity(owner, monkeypatch): + from je_auto_control.utils.exception.control_signals import OperationCancelledError + bind_bridge(monkeypatch, Bridge()) + signal = OperationCancelledError("test-stop") + wrapped = RuntimeError("wrapped cancellation") + wrapped.__cause__ = signal + resource = Stoppable(error=wrapped) + attr = "_host_voice_track" if isinstance(owner, webrtc_host.WebRTCDesktopHost) else "_host_voice_receiver" + setattr(owner, attr, resource) + owner._pc = FakePeerConnection() + with pytest.raises(OperationCancelledError) as caught: + owner.stop() + assert caught.value is signal + assert getattr(owner, attr) is resource + + +def test_failed_frame_task_is_reported_once_and_completed_ownership_is_released(): + async def drive(): + viewer = webrtc_viewer.WebRTCDesktopViewer(token="test-token") + async def failed(): + raise RuntimeError("frame processing failed") + task = asyncio.create_task(failed()) + await asyncio.wait({task}) + viewer._receive_task = task + with pytest.raises(PeerStopFailed, match="receive task"): + await viewer._async_stop() + assert task.done() + assert viewer._receive_task is None + await viewer._async_stop() + viewer._retirement.require_startable() + asyncio.run(drive()) + + +def test_bridge_submission_failure_remains_retryable(owner, monkeypatch): + class UnavailableBridge: + def submit(self, _coroutine): + raise OSError("bridge unavailable") + bind_bridge(monkeypatch, UnavailableBridge()) + peer = FakePeerConnection() + owner._pc = peer + with pytest.raises(PeerStopFailed): + owner.stop() + assert owner._pc is peer + bind_bridge(monkeypatch, Bridge()) + owner.stop() + assert peer.closed diff --git a/test/unit_test/headless/test_webrtc_viewer_session.py b/test/unit_test/headless/test_webrtc_viewer_session.py index d34688b2a..4152db871 100644 --- a/test/unit_test/headless/test_webrtc_viewer_session.py +++ b/test/unit_test/headless/test_webrtc_viewer_session.py @@ -28,6 +28,8 @@ import asyncio +from je_auto_control.utils.remote_desktop.webrtc_retirement import PeerStopFailed + import pytest from headless._webrtc_doubles import ( @@ -456,14 +458,17 @@ def test_a_teardown_failure_does_not_abort_the_rest_of_the_teardown(): rest = Stoppable() viewer._host_voice_receiver = failing viewer._opus_audio_track = rest - asyncio.run(viewer._async_stop()) + with pytest.raises(PeerStopFailed, match="host voice"): + asyncio.run(viewer._async_stop()) + assert viewer._host_voice_receiver is failing assert rest.stopped -def test_a_stop_that_times_out_is_reported_rather_than_raised(monkeypatch): +def test_a_completed_stop_with_timeout_error_is_reported_as_failure(monkeypatch): monkeypatch.setattr(viewer_module, "get_bridge", HangingBridge) viewer = _viewer() viewer._pc = object() - viewer.stop() + with pytest.raises(PeerStopFailed): + viewer.stop() From e51a0e0fd26e4a443551eb15e5fab635f6644d6b Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 19:14:07 +0800 Subject: [PATCH 034/161] Align remote GUI tests with queued page ownership --- docs/updates/2026-11-b.md | 6 ++++++ docs/updates/README.md | 3 ++- .../headless/test_remote_registry_owners_gui.py | 12 ++++++------ test/unit_test/headless/test_webrtc_folder_io.py | 14 ++++++++++++-- 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index e2e9390b4..42a852070 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -71,3 +71,9 @@ - **Evidence:** The full coverage run on fixed source b8f7df713a845038ee2c2c8cdf520c9f49715bfa terminated with 18,390 passed, 16 failed, 160 skipped and 16 subtests passed in 2,625.27 seconds. Coverage report returned 87.78% and exit 0. The pytest process returned exit 1. - **Failures:** Five capability/diagnostic/REST policy cases, five queued registry-view notification cases and six FolderSync GUI-double cases require correction and scoped verification. The fixed source excludes subsequent image-file measurement and WebRTC retirement changes. This is not an all-green integration result; native and long-duration acceptance remain unperformed. + +## U-20261111-25 · 2026-11-11 · Align remote GUI tests with queued page ownership · #done #tests + +- **What:** Registry tests wait for queued view notifications before checking the same displacement and share-text results. FolderSync GUI doubles now own a real QObject-backed ViewLifetime and retire it during cleanup. Production guards remain unchanged. +- **Evidence:** The assigned fixed-source failures reproduced as 11 failed and 28 passed. After correction, the affected suites passed all 39 cases; the separate folder/page-retirement run passed 33. Parent integration independently passed all 39 affected cases. Ruff and diff checks passed. Tests use fake transports and offscreen Qt. +- **Limits:** This resolves 11 of the 16 fixed-source full-suite failures. The five policy-related failures are being corrected separately; no new complete suite result is claimed. diff --git a/docs/updates/README.md b/docs/updates/README.md index 496f3474d..d6dd685a4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-25 | 2026-11-11 | Align remote GUI tests with queued page ownership | #done #tests | [2026-11-b](2026-11-b.md) | | U-20261111-24 | 2026-11-11 | Record fixed-source full-suite failures and coverage | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-23 | 2026-11-11 | Retain unfinished WebRTC software teardown | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-22 | 2026-11-11 | Measure image-file evidence through retained Windows handles | #done #memory | [2026-11-b](2026-11-b.md) | @@ -643,7 +644,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 13 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 14 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/test/unit_test/headless/test_remote_registry_owners_gui.py b/test/unit_test/headless/test_remote_registry_owners_gui.py index e3a2ff5f5..66e656b87 100644 --- a/test/unit_test/headless/test_remote_registry_owners_gui.py +++ b/test/unit_test/headless/test_remote_registry_owners_gui.py @@ -24,7 +24,7 @@ from je_auto_control.utils.remote_desktop.registry import ( # noqa: E402 SCRIPT_OWNER, SLOT_HOST, SLOT_VIEWER, SLOT_WS_VIEWER, registry, ) -from headless._qt_settle import deleting, settle, settle_op # noqa: E402 +from headless._qt_settle import deleting, pump_until, settle, settle_op # noqa: E402 class _Viewer: @@ -256,7 +256,7 @@ def test_a_script_connect_closes_the_panels_session(monkeypatch): _script_connect(monkeypatch) tab = _tab() registry.connect_viewer("desk", 5555, "tok") - assert _idle(tab) + assert pump_until(lambda: _idle(tab)) assert tab._status.text() == _t("rd_viewer_displaced") assert registry.viewer_status()["owner"] == SCRIPT_OWNER tab._disconnect() @@ -266,7 +266,7 @@ def test_a_script_connect_closes_the_panels_session(monkeypatch): def test_a_script_disconnect_closes_the_panels_session(): screen = _quick() registry.disconnect_viewer() - assert _idle(screen) + assert pump_until(lambda: _idle(screen)) assert screen._viewer_badge.text() == _t("rd_quick_disconnected") @@ -345,7 +345,7 @@ def test_quick_connect_hosting_replaces_the_host_tabs_host_and_tells_it(qapp): screen._start_hosting() assert not first.is_running assert registry.owner_of(SLOT_HOST) == screen._owner - assert tab._shared is None # no share text for a host it does not run + assert pump_until(lambda: tab._shared is None) # no share text for a host it does not run tab._copy_share_text() assert qapp.messages == [_t("rd_host_copy_share_unavailable")] assert registry.host.is_running @@ -359,13 +359,13 @@ def test_stop_stops_the_host_on_show_and_tells_its_owner(): screen._stop_hosting() assert not running.is_running assert registry.host is None - assert tab._shared is None + assert pump_until(lambda: tab._shared is None) def test_a_script_stopping_the_host_clears_the_panels_share_text(): tab = _host_tab() registry.stop_host() - assert tab._shared is None + assert pump_until(lambda: tab._shared is None) assert registry.host_status()["running"] is False diff --git a/test/unit_test/headless/test_webrtc_folder_io.py b/test/unit_test/headless/test_webrtc_folder_io.py index 1db677d59..f75367c4f 100644 --- a/test/unit_test/headless/test_webrtc_folder_io.py +++ b/test/unit_test/headless/test_webrtc_folder_io.py @@ -8,9 +8,11 @@ import pytest pytest.importorskip('PySide6.QtWidgets', exc_type=ImportError) +from PySide6.QtCore import QObject from headless.test_webrtc_file_delivery import bridge as bridge from je_auto_control.gui.remote_desktop import webrtc_panel, webrtc_viewer_files from je_auto_control.gui.remote_desktop.folder_sync_io import make_folder_engine +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.utils.rbac import ( AuthorizationContext, Role, UserStore, authorization_scope, current_authorization, ) @@ -122,8 +124,14 @@ def accepted(sent, _total): finished.set() viewer = Viewer() - owner = SimpleNamespace(_viewer=viewer, _sync_engine=None, _sync_dir_edit=SimpleNamespace(text=lambda: str(watch)), - _sync_btn=Button(), _require_viewer=lambda: viewer) + owner = QObject() if via_gui else SimpleNamespace() + owner._viewer = viewer + owner._sync_engine = None + owner._sync_dir_edit = SimpleNamespace(text=lambda: str(watch)) + owner._sync_btn = Button() + owner._require_viewer = lambda: viewer + if via_gui: + owner._view = ViewLifetime(owner) context = AuthorizationContext('owner', Role.OPERATOR, store_path=str(store.path)) factory = make_folder_engine @@ -158,6 +166,8 @@ def fast_factory(*args): assert failures == [] finally: engine.stop() + if via_gui: + owner._view.retire() def test_owner_replaced_after_scan_can_stop_without_reentering_a_nonrecursive_lock(tmp_path): From 4ffb9a972ecb0caad70f445b3129c09fc22cecc5 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 19:22:49 +0800 Subject: [PATCH 035/161] Require data authority for matched REST and executor reads --- CHANGELOG.md | 5 ++ Progress.md | 1 + README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 12 ++--- .../Eng/doc/mcp_server/mcp_server_doc.rst | 10 ++-- .../operations_layer/operations_layer_doc.rst | 52 +++++++++--------- .../Zh/doc/mcp_server/mcp_server_doc.rst | 7 +-- .../operations_layer/operations_layer_doc.rst | 43 +++++++-------- docs/updates/2026-11-b.md | 6 +++ docs/updates/README.md | 3 +- je_auto_control/utils/rbac/policy.py | 34 +++++++----- .../headless/test_capability_data_parity.py | 54 +++++++++++++++++++ .../headless/test_capability_surfaces.py | 10 ++-- .../headless/test_diagnostics_cancellable.py | 6 +-- .../headless/test_rest_read_data_routes.py | 52 +++++++++--------- 17 files changed, 191 insertions(+), 110 deletions(-) create mode 100644 test/unit_test/headless/test_capability_data_parity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index cad9592ff..e5c477eb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- Align audited REST host-data routes and registered status/diagnostic commands with + MCP `read_data` authority. Viewer requests are refused before providers execute; + operator/admin diagnostics and cancellation remain supported. Dashboard panels + report the missing capability without widening viewer access. + - WebRTC stop now reports pending or failed software cleanup, retains failed resources, and blocks peer replacement until cleanup succeeds. Retrying a pending stop reuses the original future. Multi-viewer teardown retains failed sessions and their capture diff --git a/Progress.md b/Progress.md index a614f6595..9e857d53b 100644 --- a/Progress.md +++ b/Progress.md @@ -143,6 +143,7 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - `ac_list_plugins` 的外掛 factory,以及 `ac_web_list_commands`/`ac_web_current_url` 的實際相依版本初始化契約尚待審查;目前不列入唯讀目錄,完整目錄仍要求 `read_data`。本機 sibling 原始碼不代表部署版本驗收。 - `ac_diagnose` 的預設 audit-log 初始化可能建立固定目錄及 SQLite schema;全域零寫入診斷與外部 SDK 初始化副作用仍未驗證。 + - 尚需審查未列入 `COMMAND_CAPABILITIES` 的 executor 指令與 REST-only USB device/event、inspector 路由的資料權限;未列指令目前仍依賴提交入口授權,不能把已核對的 MCP/REST/指令配對視為完整分類。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, diff --git a/README.md b/README.md index e990e1f3f..0275a8631 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,8 @@ WebRTC host/viewer `stop()` waits up to three seconds for software teardown. `Pe MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. +REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. Dashboard panels report missing capabilities independently. + Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. Internal Windows process-memory preparation can now measure a selected process image file through retained read-only handles, with bounded hashing and retryable cleanup. This is observed file evidence, not loaded-code or fixture attestation; native acceptance and public memory tools remain unavailable. See [the contract](docs/process_memory_contract.md). diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index a51ade63b..1eab19e9d 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -73,6 +73,8 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStop MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 +REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。Dashboard 各面板分别显示缺少的权限。 + 主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 内部 Windows 进程内存准备工作新增映像文件测量,通过保留的只读 handle 执行有界哈希并保留失败清理供重试。这只是观察到的文件证据,不是已加载代码或 fixture 的身份证明;原生验收及公开内存工具仍未提供。详见[契约](../docs/process_memory_contract.md)。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 950c88dfd..a816d3a06 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -73,6 +73,8 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStop MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 +REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。Dashboard 各面板分別顯示缺少的權限。 + 主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 內部 Windows 行程記憶體準備工作新增映像檔量測,透過保留的唯讀 handle 執行有界雜湊並保留失敗清理供重試。這只是觀測到的檔案證據,不是已載入程式碼或 fixture 的身分證明;原生驗收及公開記憶體工具仍未提供。詳見[契約](../docs/process_memory_contract.md)。 diff --git a/architecture_explore.md b/architecture_explore.md index a98759251..28148dc0a 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,522 | -| 程式碼總行數 | 232,184 | +| 程式碼總行數 | 232,190 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,453 行。 +> 13 個套件、約 4,459 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -674,7 +674,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/governance/` | 243 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | -| `utils/rbac/` | 1,706 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | +| `utils/rbac/` | 1,712 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | @@ -1437,7 +1437,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,184 個 `test_*.py`/11,515 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,185 個 `test_*.py`/11,516 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1548,8 +1548,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,036 | -| **總計** | **1,510** | **231,439** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,042 | +| **總計** | **1,510** | **231,445** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst b/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst index f64e220aa..bc9eec125 100644 --- a/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst +++ b/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst @@ -363,10 +363,12 @@ bearer token and uses the same operator ceiling for its live tool sessions. caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. -- The REST API follows the same rule: ``GET /history`` and ``GET /usb/acl`` - need ``read_data`` like ``ac_list_run_history`` and ``ac_usb_acl_list``, so - a viewer token reads neither the run history nor the USB ACL there either - (see the REST table in the operations chapter). +- The audited REST routes follow the same source policy: history, USB ACL, jobs, + sessions, USB passthrough status and loopback/remote inventories require + ``read_data``. Diagnostics and passive backend metadata also require data + authority. The corresponding registered AC status/diagnostic commands enforce + it before providers run; readonly descriptions do not grant viewer access. + See the endpoint table and command scope in the operations chapter. - Resources follow the same rule. ``autocontrol://history`` (the last 100 run-history rows) and the action files under ``autocontrol://files/`` need ``read_data``; ``autocontrol://commands`` and the live screen feed need diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 158b1a6c0..88cf9dbb7 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -241,16 +241,14 @@ rotated token or a changed role applies to the next request. - Endpoints * - ``read_screen`` - viewer, operator, admin - - the ``GET`` routes that observe live state: ``/screenshot``, - ``/mouse_position``, ``/screen_size``, ``/windows``, ``/sessions``, - ``/commands``, ``/jobs``, ``/inspector/recent``, ``/inspector/summary``, - ``/usb/devices``, ``/usb/events``, ``/usb/passthrough/status``, - ``/usb/loopback/devices``, ``/usb/remote/devices``, ``/diagnose``, - ``/metrics``, ``/openapi.json`` + - ``GET /screenshot``, ``/mouse_position``, ``/screen_size``, ``/windows``, + ``/commands``, ``/inspector/recent``, ``/inspector/summary``, + ``/usb/devices``, ``/usb/events``, ``/metrics``, ``/openapi.json`` * - ``read_data`` - operator, admin - - ``GET /history``, ``GET /usb/acl``; the MCP tools that return the - host's data rather than its screen (see the MCP chapter) + - ``GET /history``, ``/usb/acl``, ``/jobs``, ``/sessions``, + ``/usb/passthrough/status``, ``/usb/loopback/devices``, + ``/usb/remote/devices``, ``/diagnose``; matching MCP host-data reads * - ``drive_input`` - operator, admin - ``POST /execute``, ``/execute_file``, ``/usb/loopback/open``, @@ -275,24 +273,26 @@ A role that lacks the capability gets ``403`` The same value is published per operation as ``x-required-capability`` in ``/openapi.json``. -**Stored records need** ``read_data`` **on REST as on MCP.** A route that -returns records or configuration the host keeps needs ``read_data``; a route -that observes live state needs ``read_screen``. ``GET /history`` (the run -history, as the MCP tool ``ac_list_run_history``) and ``GET /usb/acl`` (the -stored USB ACL, as ``ac_usb_acl_list``) needed only ``read_screen`` before, so -**a viewer token is now answered 403 on those two routes**; ``operator`` and -``admin`` are unaffected, and so is a server without a user store (the shared -token is not restricted by any role). Every other ``GET`` keeps its -capability: each one that has an MCP counterpart (``/jobs`` and -``ac_scheduler_list_jobs``, ``/sessions`` and ``ac_remote_host_status``, -``/usb/passthrough/status``, the USB device lists...) already needed what its -tool needs. A test pairs each route with the read-only MCP tools whose -handler reads the same source and fails when the two disagree. - -The built-in dashboard calls neither route. With a token whose role lacks a -panel's capability -- the audit panel needs ``read_audit`` -- that panel now -says ``not available to role '': needs the '' capability`` -instead of ``HTTP 403 on ``, and the other panels keep refreshing. +**Audited host-data reads require** ``read_data`` **across surfaces.** Besides +history and the USB ACL, this includes scheduler job paths, remote-session records, +USB passthrough configuration and loopback/remote device inventories. Their REST +routes now match the MCP tools reading the same sources. ``/diagnose`` also requires +``read_data``: its checks inspect the host environment and can actively capture. +A viewer receives 403 before a provider runs; operator/admin and shared-token +servers without a user store retain their existing access. + +The registered commands ``AC_probe_capabilities``, ``AC_diagnose``, +``AC_remote_host_status``, ``AC_remote_viewer_status``, ``AC_usb_passthrough_status``, +``AC_usb_loopback_list`` and ``AC_usb_remote_list`` enforce the same data authority. +Passive capability probing still reads environment/PATH and cached backend metadata; +being non-mutating does not make that metadata viewer-authorized. Direct trusted SDK +calls outside an authorization scope retain their existing behavior. This audit does +not classify all unlisted executor commands: those still rely on their entry surface. + +Dashboard panels retain their functionality and independently display missing +capabilities. Diagnostics and sessions require ``read_data``; audit requires +``read_audit``. Refused panels clear their rows while other panels keep refreshing. +The source-pairing regression continues to reject REST/MCP policy disagreements. Being allowed to ``POST /execute`` is being allowed to run actions, not every command. Signing an action file (``sign_actions``), reading the audit log diff --git a/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst b/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst index ec843a664..87c8529d4 100644 --- a/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst +++ b/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst @@ -344,9 +344,10 @@ Bearer token 也可從 ``JE_AUTOCONTROL_MCP_TOKEN`` 環境變數讀取。 以及連線裝置的剪貼簿(``ac_android_get_clipboard``、 ``ac_ios_get_clipboard``)。這些以前是 ``read_screen``,所以\ **viewer 的 token 現在不能呼叫它們**\ ;``operator`` 與 ``admin`` 不受影響。 -- REST API 依同一條規則:``GET /history`` 與 ``GET /usb/acl`` 和 - ``ac_list_run_history``、``ac_usb_acl_list`` 一樣需要 ``read_data``,所以 viewer 的 - token 在那裡也讀不到執行歷史與 USB ACL(見維運章節的 REST 表格)。 +- 已審查的 REST 路由依相同來源權限:歷史、USB ACL、排程、session、USB passthrough + 狀態及 loopback/remote 清單需要 ``read_data``。診斷與被動後端中繼資料也需要 + 資料權限。對應已註冊的 AC 狀態/診斷指令會在執行提供者前檢查;唯讀標記不授予 + viewer 存取權。端點表格與指令審查範圍見維運章節。 - resource 適用同一條規則。\ ``autocontrol://history``\ (最近 100 筆執行歷史)與 ``autocontrol://files/`` 底下的動作檔需要 ``read_data``\ ;\ ``autocontrol://commands`` 與即時畫面需要 ``read_screen``\ 。\ ``resources/list`` 只列出呼叫者讀得到的, diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index bb34b98d6..6fff6a019 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -210,15 +210,14 @@ token 控制項。Python 伺服器的 ``token`` 屬性仍保留設定的共用 t - 端點 * - ``read_screen`` - viewer、operator、admin - - 觀察目前狀態的 ``GET`` 路由:``/screenshot``、``/mouse_position``、 - ``/screen_size``、``/windows``、``/sessions``、``/commands``、``/jobs``、 - ``/inspector/recent``、``/inspector/summary``、``/usb/devices``、 - ``/usb/events``、``/usb/passthrough/status``、``/usb/loopback/devices``、 - ``/usb/remote/devices``、``/diagnose``、``/metrics``、``/openapi.json`` + - ``GET /screenshot``、``/mouse_position``、``/screen_size``、``/windows``、 + ``/commands``、``/inspector/recent``、``/inspector/summary``、 + ``/usb/devices``、``/usb/events``、``/metrics``、``/openapi.json`` * - ``read_data`` - operator、admin - - ``GET /history``、``GET /usb/acl``;以及回傳主機資料而非畫面的 MCP 工具 - (見 MCP 章節) + - ``GET /history``、``/usb/acl``、``/jobs``、``/sessions``、 + ``/usb/passthrough/status``、``/usb/loopback/devices``、 + ``/usb/remote/devices``、``/diagnose``,及對應的 MCP 主機資料讀取 * - ``drive_input`` - operator、admin - ``POST /execute``、``/execute_file``、``/usb/loopback/open``、 @@ -242,20 +241,22 @@ token 控制項。Python 伺服器的 ``token`` 屬性仍保留設定的共用 t ``{"error": "forbidden", "required_capability": "...", "role": "..."}``。 同一個值也以 ``x-required-capability`` 列在 ``/openapi.json`` 的每個 operation 上。 -**保存的紀錄在 REST 與 MCP 都需要** ``read_data``\ **。** 回傳主機保存的紀錄或設定的 -路由需要 ``read_data``;觀察目前狀態的路由需要 ``read_screen``。``GET /history``\ -(執行歷史,與 MCP 工具 ``ac_list_run_history`` 相同)與 ``GET /usb/acl``\ (保存的 -USB ACL,與 ``ac_usb_acl_list`` 相同)以前只需要 ``read_screen``,所以\ **viewer 的 -token 現在在這兩個路由會得到 403**\ ;``operator`` 與 ``admin`` 不受影響,沒有使用者 -存放檔的伺服器也不受影響(共用 token 不受任何角色限制)。其餘 ``GET`` 的能力不變: -有對應 MCP 工具的路由(``/jobs`` 與 ``ac_scheduler_list_jobs``、``/sessions`` 與 -``ac_remote_host_status``、``/usb/passthrough/status``、USB 裝置清單……)原本就與工具 -一致。有一個測試會把每個路由與讀取同一個來源的唯讀 MCP 工具配對,兩者不一致時失敗。 - -內建的 dashboard 不會呼叫這兩個路由。token 的角色缺少某個面板需要的能力時——稽核 -面板需要 ``read_audit``——該面板現在顯示 -``not available to role '<角色>': needs the '<能力>' capability``,而不是 -``HTTP 403 on <路徑>``;其他面板照常更新。 +**已審查的主機資料讀取在各入口都需要** ``read_data``。除了歷史與 USB ACL, +還包括排程指令路徑、遠端 session 紀錄、USB passthrough 設定及 loopback/remote +裝置清單。對應 REST 路由與讀取相同來源的 MCP 工具現在一致。``/diagnose`` 也需要 +``read_data``:檢查會讀取主機環境,並可能主動擷取畫面。viewer 在提供者執行前 +收到 403;operator/admin 及未使用使用者存放檔的共用 token 伺服器維持原存取權。 + +已註冊的 ``AC_probe_capabilities``、``AC_diagnose``、``AC_remote_host_status``、 +``AC_remote_viewer_status``、``AC_usb_passthrough_status``、``AC_usb_loopback_list`` +與 ``AC_usb_remote_list`` 也要求相同資料權限。被動能力探測仍讀取環境/PATH 與 +快取的後端中繼資料;不修改狀態不代表 viewer 有權讀取。授權 scope 外的可信 SDK +直接呼叫維持原行為。本次審查沒有涵蓋所有未列入表格的 executor 指令;那些指令 +仍依賴接收請求入口的權限。 + +Dashboard 保留功能,各面板分別顯示缺少的權限。診斷與 session 需要 ``read_data``, +稽核需要 ``read_audit``;被拒面板清除舊資料,其他面板持續更新。來源配對測試仍會 +拒絕 REST 與 MCP 的權限不一致。 可以 ``POST /execute`` 代表可以執行動作,不代表可以執行每一個指令。替動作檔簽章 (``sign_actions``)、讀取稽核紀錄(``read_audit``),以及管理主機本身的指令—— diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 42a852070..660f50183 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -77,3 +77,9 @@ - **What:** Registry tests wait for queued view notifications before checking the same displacement and share-text results. FolderSync GUI doubles now own a real QObject-backed ViewLifetime and retire it during cleanup. Production guards remain unchanged. - **Evidence:** The assigned fixed-source failures reproduced as 11 failed and 28 passed. After correction, the affected suites passed all 39 cases; the separate folder/page-retirement run passed 33. Parent integration independently passed all 39 affected cases. Ruff and diff checks passed. Tests use fake transports and offscreen Qt. - **Limits:** This resolves 11 of the 16 fixed-source full-suite failures. The five policy-related failures are being corrected separately; no new complete suite result is claimed. + +## U-20261111-26 · 2026-11-11 · Enforce host-data authority across REST and executor reads · #done #security + +- **What:** Six REST routes and seven registered executor commands now require read_data for audited host records, device inventories, capability metadata and diagnostics. MCP policy and stronger overrides remain unchanged. Viewer denial occurs before providers run; operator access and cancellable diagnostics remain available. Dashboard panels keep their capability-specific refusal behavior. +- **Evidence:** All five assigned full-suite failures reproduced. New fake-provider checks demonstrated seven executor bypasses before the fix, then proved denial through executor, direct MCP and JSON-RPC. The unchanged REST source-pairing assertion passes; loopback tests cover all eight data routes. Author verification passed 459 cases, Mypy, Ruff and strict Sphinx. Parent source review confirmed command registrations and policy scope; integration passed 60 affected cases, 49 document/quality gates and warnings-as-errors Sphinx. +- **Open items:** Unlisted executor commands, REST-only device/event/inspector classifications and diagnostic initialization side effects remain in Progress.md. All 16 prior full-suite failures now have passing scoped corrections; a new whole-suite result is not claimed. diff --git a/docs/updates/README.md b/docs/updates/README.md index d6dd685a4..194d0e149 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-26 | 2026-11-11 | Enforce host-data authority across REST and executor reads | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-25 | 2026-11-11 | Align remote GUI tests with queued page ownership | #done #tests | [2026-11-b](2026-11-b.md) | | U-20261111-24 | 2026-11-11 | Record fixed-source full-suite failures and coverage | #snapshot #verification | [2026-11-b](2026-11-b.md) | | U-20261111-23 | 2026-11-11 | Retain unfinished WebRTC software teardown | #done #remote | [2026-11-b](2026-11-b.md) | @@ -644,7 +645,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 14 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 15 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/rbac/policy.py b/je_auto_control/utils/rbac/policy.py index 19d2334cc..122656e3f 100644 --- a/je_auto_control/utils/rbac/policy.py +++ b/je_auto_control/utils/rbac/policy.py @@ -5,8 +5,9 @@ * **REST routes** are listed one by one. A route missing from the list needs ``manage_hosts``, so a route added without a decision is admin-only rather than open. A ``GET`` route that returns records or configuration the host - keeps needs ``read_data`` like the MCP tool reading the same thing; one - that observes live state needs ``read_screen``. + keeps needs ``read_data`` like the MCP tool reading the same thing. Reviewed + desktop observations may use ``read_screen``. Live host records and + device status still need data authority. * **MCP tools** default to ``read_data`` for a read-only annotation and ``drive_input`` otherwise. Only reviewed screen/caller-data tools grant ``read_screen``. Named overrides separate non-mutating sensitive @@ -15,8 +16,8 @@ protect administration of the host itself. * **``AC_*`` commands** reach the executor through anything that runs an action list (``POST /execute``, ``ac_execute_actions``, an action file). - Being allowed to run actions is ``drive_input``; the commands named here - need more, and are checked both where the list is submitted and again by + Running submitted actions requires ``drive_input``; the commands named here + have explicit requirements, checked where the list is submitted and again by the executor, which is what covers a list read from a file. The roles are not a sandbox. An operator drives the real keyboard and can @@ -50,23 +51,23 @@ ("POST", "/agent/shutdown"): _HOSTS, ("POST", "/agent/recover_target"): _HOSTS, ("GET", "/metrics"): _READ, - ("GET", "/jobs"): _READ, + ("GET", "/jobs"): _DATA, ("GET", "/history"): _DATA, # run history, as ac_list_run_history ("GET", "/screenshot"): _READ, ("GET", "/mouse_position"): _READ, ("GET", "/screen_size"): _READ, ("GET", "/windows"): _READ, - ("GET", "/sessions"): _READ, + ("GET", "/sessions"): _DATA, ("GET", "/commands"): _READ, ("GET", "/inspector/recent"): _READ, ("GET", "/inspector/summary"): _READ, ("GET", "/usb/devices"): _READ, ("GET", "/usb/events"): _READ, - ("GET", "/usb/passthrough/status"): _READ, + ("GET", "/usb/passthrough/status"): _DATA, ("GET", "/usb/acl"): _DATA, # the stored ACL, as ac_usb_acl_list - ("GET", "/usb/loopback/devices"): _READ, - ("GET", "/usb/remote/devices"): _READ, - ("GET", "/diagnose"): _READ, + ("GET", "/usb/loopback/devices"): _DATA, + ("GET", "/usb/remote/devices"): _DATA, + ("GET", "/diagnose"): _DATA, ("GET", "/openapi.json"): _READ, ("GET", "/audit/list"): _AUDIT, ("GET", "/audit/verify"): _AUDIT, @@ -93,15 +94,20 @@ DATA_ROUTES = frozenset( route for route, needed in REST_ROUTE_CAPABILITIES.items() if needed == _DATA) -#: Commands that need more than ``drive_input``. Every other command is -#: covered by the capability of the surface that submitted the action list. +#: Explicit command requirements, including audited host-data reads. Unlisted +#: commands still rely on the capability of the surface submitting the action list. COMMAND_CAPABILITIES: Dict[str, str] = { "AC_agent_target": _HOSTS, "AC_agent_target_recover": _HOSTS, "AC_agent_runtime_stop": _HOSTS, "AC_agent_runtime_start": _HOSTS, - "AC_probe_capabilities": _READ, - "AC_diagnose": _READ, + "AC_probe_capabilities": _DATA, + "AC_diagnose": _DATA, + "AC_remote_host_status": _DATA, + "AC_remote_viewer_status": _DATA, + "AC_usb_passthrough_status": _DATA, + "AC_usb_loopback_list": _DATA, + "AC_usb_remote_list": _DATA, "AC_mcp_tool_search": _READ, "AC_mcp_tool_schema": _READ, "AC_history_capture": _DRIVE, diff --git a/test/unit_test/headless/test_capability_data_parity.py b/test/unit_test/headless/test_capability_data_parity.py new file mode 100644 index 000000000..c4ce55cfb --- /dev/null +++ b/test/unit_test/headless/test_capability_data_parity.py @@ -0,0 +1,54 @@ +"""Audited host-data reads deny viewer callers before handlers on every callable surface.""" +from dataclasses import replace +import json + +import pytest + +import je_auto_control as ac +from je_auto_control.utils.mcp_server.audit import AuditLogger +from je_auto_control.utils.mcp_server.server import MCPServer +from je_auto_control.utils.mcp_server.tools import build_default_tool_registry +from je_auto_control.utils.rbac import AuthorizationContext, AuthorizationError, Capability, Role, authorization_scope +from je_auto_control.utils.rbac.policy import capability_for_command, capability_for_tool + + +_READS = ( + ("AC_probe_capabilities", "ac_probe_capabilities"), + ("AC_diagnose", "ac_diagnose"), + ("AC_remote_host_status", "ac_remote_host_status"), + ("AC_remote_viewer_status", "ac_remote_viewer_status"), + ("AC_usb_passthrough_status", "ac_usb_passthrough_status"), + ("AC_usb_loopback_list", "ac_usb_loopback_list"), + ("AC_usb_remote_list", "ac_usb_remote_list"), +) + + +@pytest.mark.parametrize("command,name", _READS) +def test_host_data_requires_data_authority_before_executor_or_mcp_handler(command, name, monkeypatch, tmp_path): + calls = [] + def read(): + calls.append(name) + return {"controlled": True} + monkeypatch.setitem(ac.executor.event_dict, command, read) + original = next(tool for tool in build_default_tool_registry(read_only=True) if tool.name == name) + tool = replace(original, handler=read) + server = MCPServer(tools=[tool], audit_logger=AuditLogger(str(tmp_path / "audit.jsonl"))) + request = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": name, "arguments": {}}} + with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): + with pytest.raises(AuthorizationError) as denied: + ac.execute_action([[command]], raise_on_error=True) + assert denied.value.capability == Capability.READ_DATA + with pytest.raises(AuthorizationError) as denied: + tool.invoke({}) + assert denied.value.capability == Capability.READ_DATA + reply = json.loads(server.handle_line(json.dumps(request))) + assert reply["error"]["code"] == -32003 + assert calls == [] + assert capability_for_command(command) == capability_for_tool(name, True) == Capability.READ_DATA + with authorization_scope(AuthorizationContext("operator", Role.OPERATOR)): + ac.execute_action([[command]], raise_on_error=True) + assert tool.invoke({}) == {"controlled": True} + reply = json.loads(server.handle_line(json.dumps(request))) + assert not reply["result"]["isError"] + assert calls == [name, name, name] diff --git a/test/unit_test/headless/test_capability_surfaces.py b/test/unit_test/headless/test_capability_surfaces.py index f8fe183d1..f9d153d63 100644 --- a/test/unit_test/headless/test_capability_surfaces.py +++ b/test/unit_test/headless/test_capability_surfaces.py @@ -50,14 +50,14 @@ def test_executor_and_read_only_mcp_share_the_sdk_snapshot_without_accepting_sup tool.invoke({'context': {'input_state': 'available'}}) -def test_builder_and_rbac_declare_passive_capabilities_as_read_only(): +def test_builder_keeps_passive_metadata_read_only_but_rbac_requires_data_authority(): spec = COMMAND_SPECS['AC_probe_capabilities'] assert not spec.fields - assert capability_for_command('AC_probe_capabilities') == Capability.READ_SCREEN - assert capability_for_tool('ac_probe_capabilities', True) == Capability.READ_SCREEN + assert capability_for_command('AC_probe_capabilities') == Capability.READ_DATA + assert capability_for_tool('ac_probe_capabilities', True) == Capability.READ_DATA -def test_read_only_viewer_can_use_the_real_executor_and_jsonrpc_dispatcher(current, tmp_path): +def test_read_only_operator_can_use_the_real_executor_and_jsonrpc_dispatcher(current, tmp_path): from je_auto_control.utils.mcp_server.audit import AuditLogger from je_auto_control.utils.mcp_server.server import MCPServer tools = [tool for tool in build_default_tool_registry(read_only=True) if tool.name == 'ac_probe_capabilities'] @@ -65,7 +65,7 @@ def test_read_only_viewer_can_use_the_real_executor_and_jsonrpc_dispatcher(curre request = {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call', 'params': {'name': 'ac_probe_capabilities', 'arguments': {}}} expected = probe_capabilities(current).to_dict() - with authorization_scope(AuthorizationContext('reader', Role.VIEWER)): + with authorization_scope(AuthorizationContext('reader', Role.OPERATOR)): record = ac.execute_action([['AC_probe_capabilities']]) response = json.loads(server.handle_line(json.dumps(request))) assert expected in record.values() diff --git a/test/unit_test/headless/test_diagnostics_cancellable.py b/test/unit_test/headless/test_diagnostics_cancellable.py index 526902906..91b389ce1 100644 --- a/test/unit_test/headless/test_diagnostics_cancellable.py +++ b/test/unit_test/headless/test_diagnostics_cancellable.py @@ -110,11 +110,11 @@ def test_progress_and_report_stay_shared_with_read_only_executor_and_active_mcp( tool = next((item for item in build_default_tool_registry(read_only=True) if item.name == 'ac_diagnose'), None) assert tool is not None, 'the documented active diagnostic MCP entry point is absent' assert tool.input_schema.get('additionalProperties') is False - assert capability_for_command('AC_diagnose') == Capability.READ_SCREEN + assert capability_for_command('AC_diagnose') == Capability.READ_DATA expected = diagnostics.run_diagnostics().to_dict() progress = [] ctx = ToolCallContext('diagnostic', progress_token='p', notifier=lambda _method, value: progress.append(value)) - with authorization_scope(AuthorizationContext('reader', Role.VIEWER)): + with authorization_scope(AuthorizationContext('reader', Role.OPERATOR)): assert tool.invoke({}, ctx=ctx) == expected record = ac.execute_action([['AC_diagnose']]) assert expected in record.values() @@ -176,7 +176,7 @@ def no_error_capture(_tool): def call(connection): with server.connection_scope(connection_id=connection): - with authorization_scope(AuthorizationContext(connection, Role.VIEWER)): + with authorization_scope(AuthorizationContext(connection, Role.OPERATOR)): replies[connection] = json.loads(server.handle_line(json.dumps(request))) workers = {name: threading.Thread(target=call, args=(name,)) for name in entered} diff --git a/test/unit_test/headless/test_rest_read_data_routes.py b/test/unit_test/headless/test_rest_read_data_routes.py index dbee123d4..6ace31ff1 100644 --- a/test/unit_test/headless/test_rest_read_data_routes.py +++ b/test/unit_test/headless/test_rest_read_data_routes.py @@ -7,7 +7,7 @@ package, found by parsing both. Nothing here touches the screen, the mouse, the run-history database or the -USB ACL file: the two routes that would are replaced by recorders. +USB ACL file: tested host-data route handlers are replaced by recorders. """ import ast import inspect @@ -39,23 +39,23 @@ #: The whole table, written out: a change to any route has to be made here too. _EXPECTED_ROUTES = { ("GET", "/metrics"): _READ, - ("GET", "/jobs"): _READ, + ("GET", "/jobs"): _DATA, ("GET", "/history"): _DATA, ("GET", "/screenshot"): _READ, ("GET", "/mouse_position"): _READ, ("GET", "/screen_size"): _READ, ("GET", "/windows"): _READ, - ("GET", "/sessions"): _READ, + ("GET", "/sessions"): _DATA, ("GET", "/commands"): _READ, ("GET", "/inspector/recent"): _READ, ("GET", "/inspector/summary"): _READ, ("GET", "/usb/devices"): _READ, ("GET", "/usb/events"): _READ, - ("GET", "/usb/passthrough/status"): _READ, + ("GET", "/usb/passthrough/status"): _DATA, ("GET", "/usb/acl"): _DATA, - ("GET", "/usb/loopback/devices"): _READ, - ("GET", "/usb/remote/devices"): _READ, - ("GET", "/diagnose"): _READ, + ("GET", "/usb/loopback/devices"): _DATA, + ("GET", "/usb/remote/devices"): _DATA, + ("GET", "/diagnose"): _DATA, ("GET", "/openapi.json"): _READ, ("GET", "/audit/list"): _AUDIT, ("GET", "/audit/verify"): _AUDIT, @@ -97,6 +97,9 @@ ("POST", "/agent/trigger"): _DRIVE, } +_DATA_PATHS = ("/history", "/usb/acl", "/jobs", "/sessions", "/usb/passthrough/status", + "/usb/loopback/devices", "/usb/remote/devices", "/diagnose") + @pytest.fixture(autouse=True) def _no_ambient_rbac(monkeypatch): @@ -136,11 +139,8 @@ def handle(_ctx): return 200, payload return handle - monkeypatch.setitem(rest_server._GET_ROUTES, "/history", - recorder("/history", {"runs": [{"id": 7}]})) - monkeypatch.setitem(rest_server._GET_ROUTES, "/usb/acl", - recorder("/usb/acl", {"default": "deny", "rules": []})) - monkeypatch.setitem(rest_server._GET_ROUTES, "/jobs", recorder("/jobs", {"jobs": []})) + for path in _DATA_PATHS: + monkeypatch.setitem(rest_server._GET_ROUTES, path, recorder(path, {"controlled": True})) started = [] def start(**kwargs): @@ -186,7 +186,7 @@ def _wait_for_refusal(server, timeout_s: float = 5.0) -> bool: # --- what a role may read ----------------------------------------------------- -@pytest.mark.parametrize("path", ["/history", "/usb/acl"]) +@pytest.mark.parametrize("path", _DATA_PATHS) def test_a_viewer_is_refused_a_stored_record_route(rest, users, path): server = rest(user_store=users) status, body = _get(server, path, users.tokens[Role.VIEWER]) @@ -198,7 +198,7 @@ def test_a_viewer_is_refused_a_stored_record_route(rest, users, path): @pytest.mark.parametrize("role", [Role.OPERATOR, Role.ADMIN]) -@pytest.mark.parametrize("path", ["/history", "/usb/acl"]) +@pytest.mark.parametrize("path", _DATA_PATHS) def test_an_operator_and_an_admin_still_read_them(rest, users, role, path): server = rest(user_store=users) status, _body = _get(server, path, users.tokens[role]) @@ -209,7 +209,6 @@ def test_an_operator_and_an_admin_still_read_them(rest, users, role, path): def test_a_viewer_keeps_the_routes_that_observe_live_state(rest, users): server = rest(user_store=users) viewer = users.tokens[Role.VIEWER] - assert _get(server, "/jobs", viewer)[0] == 200 assert _get(server, "/commands", viewer)[0] == 200 assert _get(server, "/openapi.json", viewer)[0] == 200 @@ -235,7 +234,7 @@ def test_openapi_publishes_the_capability_of_the_data_routes(): paths = build_openapi_spec()["paths"] assert paths["/history"]["get"]["x-required-capability"] == Capability.READ_DATA assert paths["/usb/acl"]["get"]["x-required-capability"] == Capability.READ_DATA - assert paths["/jobs"]["get"]["x-required-capability"] == Capability.READ_SCREEN + assert paths["/jobs"]["get"]["x-required-capability"] == Capability.READ_DATA # --- the same data needs the same capability on both surfaces ------------------- @@ -377,18 +376,17 @@ def _dashboard_script() -> str: return path.read_text(encoding="utf-8") -def test_the_dashboard_calls_no_route_that_needs_read_data(): - """The page is read with whatever token is pasted in, a viewer's included.""" +def test_dashboard_panels_keep_their_endpoint_capability_including_data_refusals(): + """An operator dashboard does not grant a viewer its restricted panel data.""" fetched = {match.split("?")[0] - for match in re.findall(r'fetchJson\("([^"]+)"\)', _dashboard_script())} - assert fetched, "the script no longer fetches with a literal path this test can read" - for path in fetched: - assert ("GET", path) in REST_ROUTE_CAPABILITIES, path - assert not {("GET", path) for path in fetched} & DATA_ROUTES - needs = {path: capability_for_route("GET", path) for path in fetched} - assert needs["/audit/list"] == Capability.READ_AUDIT, "the one panel a viewer is refused" - assert {needed for path, needed in needs.items() if path != "/audit/list"} == { - Capability.READ_SCREEN} + for match in re.findall(r'fetchJson\("([^\"]+)"\)', _dashboard_script())} + assert {path: capability_for_route("GET", path) for path in fetched} == { + "/diagnose": Capability.READ_DATA, + "/sessions": Capability.READ_DATA, + "/inspector/summary": Capability.READ_SCREEN, + "/usb/devices": Capability.READ_SCREEN, + "/audit/list": Capability.READ_AUDIT, + } def test_the_dashboard_names_the_missing_capability_on_a_403(): From b6ed1302585667db964909eee6f738dc1d99ba03 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 19:24:52 +0800 Subject: [PATCH 036/161] Keep file sender ownership until actual worker completion --- CHANGELOG.md | 3 + Progress.md | 4 +- README.md | 4 +- README/README_zh-CN.md | 4 +- README/README_zh-TW.md | 4 +- architecture_explore.md | 16 +- .../operations_layer/operations_layer_doc.rst | 6 +- .../operations_layer/operations_layer_doc.rst | 5 +- docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- .../utils/remote_desktop/webrtc_file_tasks.py | 32 +++- .../headless/test_webrtc_sender_retirement.py | 138 ++++++++++++++++++ 12 files changed, 206 insertions(+), 19 deletions(-) create mode 100644 test/unit_test/headless/test_webrtc_sender_retirement.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e5c477eb6..2b9f3044d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] +- File-request cancellation retains the original sender worker and queue ownership + until actual completion, including repeated cancellation, without blocking the event loop. + - Align audited REST host-data routes and registered status/diagnostic commands with MCP `read_data` authority. Viewer requests are refused before providers execute; operator/admin diagnostics and cancellation remain supported. Dashboard panels diff --git a/Progress.md b/Progress.md index 9e857d53b..0c38f2ccb 100644 --- a/Progress.md +++ b/Progress.md @@ -539,8 +539,8 @@ F 還缺: 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 音訊、錄影與 LAN 廣播後端仍有吞掉清理錯誤或清掉失敗資源參照的路徑;錄影須分開記錄 flush 結果與容器關閉, - 不可重播可能已部分完成的 flush。`webrtc_file_tasks` 的 `asyncio.to_thread` 傳送器仍缺實際工作執行緒完成確認, - 取消並等候非同步包裝任務不代表傳送器已停止。上述缺口已用假資源重現,未執行原生/裝置/網路驗收。 + 不可重播可能已部分完成的 flush。傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; + 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/README.md b/README.md index 0275a8631..6f85d2652 100644 --- a/README.md +++ b/README.md @@ -67,10 +67,12 @@ Managed agent tasks and cross-host transfers include experimental features. See [MIT](LICENSE) © JE-Chen. [Third-party licenses](Third_Party_License.md). -Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. +Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. Stopping an entered file transfer depends on the backend's cooperative cancellation. WebRTC host/viewer `stop()` waits up to three seconds for software teardown. `PeerStopPending` retains the same running attempt; explicit retry waits on it. `PeerStopFailed` retains failed resources for explicit retry, and restarting is blocked until cleanup succeeds. Multi-viewer hosts retain failed sessions and their shared source. `FolderSyncEngine.stop_confirmed()` returns `False` while the original worker remains alive. These outcomes do not prove native device release; recovery after page destruction still needs durable ownership and retry integration. +Host-requested file sends remain owned until their sender worker exits, including after repeated stop requests. Stop signals cancellation and waits for that original worker; an uninterruptible backend operation can still leave stop pending. + MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. Dashboard panels report missing capabilities independently. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 1eab19e9d..1be7837a5 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -67,10 +67,12 @@ Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用 [MIT](../LICENSE) © JE-Chen. [第三方许可](../Third_Party_License.md). -关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。已进入发送阶段的文件传输不会因关闭页面而中断。 +关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。已进入发送阶段的文件传输须依后端的协作式取消停止。 WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStopPending` 保留同一个尚未完成的操作;显式重试只会继续等待。`PeerStopFailed` 保留清理失败的资源供显式重试,成功前禁止重新启动。Multi-viewer host 保留失败的 session 与共享来源。`FolderSyncEngine.stop_confirmed()` 在原工作线程仍存活时返回 `False`。这些结果不代表原生设备已释放;页面销毁后的恢复仍需持久资源保管与重试整合。 +主机文件请求会保留原发送工作,直到工作线程退出,重复停止也不会提前释放所有权。停止会通知取消并等待原工作;无法中断的后端操作仍可能让停止保持待完成。 + MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。Dashboard 各面板分别显示缺少的权限。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index a816d3a06..67f5f56eb 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -67,10 +67,12 @@ Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫 [MIT](../LICENSE) © JE-Chen. [Third-party licenses](../Third_Party_License.md). -關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 +關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸須依後端的合作式取消停止。 WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStopPending` 保留同一個尚未完成的操作;明確重試只會繼續等待。`PeerStopFailed` 保留清理失敗的資源供明確重試,成功前禁止重新啟動。Multi-viewer host 保留失敗的 session 與共用來源。`FolderSyncEngine.stop_confirmed()` 在原工作執行緒仍存活時回傳 `False`。這些結果不代表原生裝置已釋放;頁面銷毀後的復原仍需持久資源保管與重試整合。 +主機檔案請求會保留原傳送工作,直到工作執行緒退出,重複停止也不會提前釋放所有權。停止會通知取消並等候原工作;無法中斷的後端操作仍可能讓停止維持待完成。 + MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。Dashboard 各面板分別顯示缺少的權限。 diff --git a/architecture_explore.md b/architecture_explore.md index 28148dc0a..b9ccc57cb 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,522 | -| 程式碼總行數 | 232,190 | +| 程式碼總行數 | 232,220 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 30,880 行。 +> 6 個套件、約 30,910 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 15,646 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 15,676 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -815,7 +815,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(15,646 行/74 檔) +#### `utils/remote_desktop/`(15,676 行/74 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -851,7 +851,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_file_callbacks.py` | 38 | Notify native file path and frozen receipt listeners while preserving original interruption objects. | | `webrtc_file_receive.py` | 101 | Bind file receivers to one authenticated peer and channel, retiring partial bytes when ownership ends. | | `webrtc_file_write.py` | 209 | Bounded observable DataChannel writes preserve caller cancellation and serialize file producers. | -| `webrtc_file_tasks.py` | 117 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | +| `webrtc_file_tasks.py` | 147 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | | `webrtc_files.py` | 416 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | | `lan_discovery.py` | 204 | mDNS/Zeroconf 區網探索。 | @@ -1437,7 +1437,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,185 個 `test_*.py`/11,516 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,186 個 `test_*.py`/11,520 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1530,7 +1530,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 61 | 22,084 | -| `utils/remote_desktop/` | 74 | 15,646 | +| `utils/remote_desktop/` | 74 | 15,676 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,042 | -| **總計** | **1,510** | **231,445** | +| **總計** | **1,510** | **231,475** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 88cf9dbb7..edc0fc822 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -764,7 +764,9 @@ worker for later observation; it is not permission to start an overlapping worke These are software completion contracts, not proof that every underlying native resource has retired. Media helpers may still suppress internal device errors. -Cancelling a file-request coroutine does not join its ``asyncio.to_thread`` sender; -that worker still depends on cooperative cancellation. +File-request cancellation signals the original sender and waits for its actual worker +completion. Repeated cancellation retains that worker and its queue slot until it exits. +The sender runs with the original context; an uninterruptible backend can leave stop +pending. This does not guarantee hard interruption or completion at process shutdown. Durable ownership and explicit retry after GUI page destruction are not yet supplied by these backend changes; callers must retain an owner when stop raises. diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index 6fff6a019..ce250fc20 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -691,6 +691,7 @@ future 仍在執行;重試只會等待該 future,不另送 coroutine。``Pee 執行緒是否已退出。``False`` 表示仍保留工作供後續觀測,不代表可啟動重疊工作。 以上只承諾軟體操作完成,不證明所有底層原生資源已退出。媒體輔助類別仍可能吞掉 -內部裝置錯誤。取消檔案請求 coroutine 不等於等待其 ``asyncio.to_thread`` 傳送工作 -退出;該工作仍依賴合作式取消。本次後端變更尚未提供 GUI 頁面銷毀後的持久保管與明確重試;停止 +內部裝置錯誤。取消檔案請求會通知原傳送器並等候工作執行緒實際退出;重複取消 +仍保留該工作及佇列名額。傳送器使用原呼叫情境,無法中斷的後端可能讓停止維持 +待完成;不保證強制中斷或行程結束時完成。後端尚未提供 GUI 頁面銷毀後的持久保管與明確重試;停止 拋出例外時,呼叫端必須保留擁有者。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 660f50183..203be9cca 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -83,3 +83,9 @@ - **What:** Six REST routes and seven registered executor commands now require read_data for audited host records, device inventories, capability metadata and diagnostics. MCP policy and stronger overrides remain unchanged. Viewer denial occurs before providers run; operator access and cancellable diagnostics remain available. Dashboard panels keep their capability-specific refusal behavior. - **Evidence:** All five assigned full-suite failures reproduced. New fake-provider checks demonstrated seven executor bypasses before the fix, then proved denial through executor, direct MCP and JSON-RPC. The unchanged REST source-pairing assertion passes; loopback tests cover all eight data routes. Author verification passed 459 cases, Mypy, Ruff and strict Sphinx. Parent source review confirmed command registrations and policy scope; integration passed 60 affected cases, 49 document/quality gates and warnings-as-errors Sphinx. - **Open items:** Unlisted executor commands, REST-only device/event/inspector classifications and diagnostic initialization side effects remain in Progress.md. All 16 prior full-suite failures now have passing scoped corrections; a new whole-suite result is not claimed. + +## U-20261111-27 · 2026-11-11 · Await actual file sender completion after cancellation · #done #remote + +- **What:** File-request tasks retain the original default-executor Future, copied call context and queue ownership until the sender function exits. Repeated cancellation signals the sender without discarding its completion observation. Work cancelled before executor capacity becomes available never enters the sender. Provider outcomes are transferred as values, avoiding unobserved shield errors while preserving cancellation identity. +- **Evidence:** Parent implementation passed 38 fake sender/file-delivery cases. Independent review passed 52 cases plus probes for direct and wrapped control-signal identity, repeated cancellation and host teardown with an independently closed fake peer. Parent integration passed the same 52 cases, 49 document/quality gates and a warnings-as-errors Sphinx build. Mypy, Ruff and diff checks passed. No real file transfer, device or network connection was used for the new worker tests. +- **Limits:** An uninterruptible backend can leave stop pending. Process termination, native release and durable GUI cleanup/retry remain separate work. This change does not interrupt arbitrary backend calls forcibly. diff --git a/docs/updates/README.md b/docs/updates/README.md index 194d0e149..a06560d47 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-27 | 2026-11-11 | Await actual file sender completion after cancellation | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-26 | 2026-11-11 | Enforce host-data authority across REST and executor reads | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-25 | 2026-11-11 | Align remote GUI tests with queued page ownership | #done #tests | [2026-11-b](2026-11-b.md) | | U-20261111-24 | 2026-11-11 | Record fixed-source full-suite failures and coverage | #snapshot #verification | [2026-11-b](2026-11-b.md) | @@ -645,7 +646,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 15 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 16 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py b/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py index 90914a7e5..e46ace60c 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py +++ b/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py @@ -4,6 +4,7 @@ import asyncio import json from concurrent.futures import CancelledError +from contextvars import copy_context from dataclasses import dataclass, field from functools import partial from threading import Event @@ -82,7 +83,9 @@ def cancelled() -> bool: try: if cancelled(): return - await asyncio.to_thread(sender, path, remote_name=name, cancelled=cancelled) + work = partial(copy_context().run, sender, path, remote_name=name, cancelled=cancelled) + worker = asyncio.get_running_loop().run_in_executor(None, _sender_outcome, work, stop) + await _observe_sender(worker, stop) except CancelledError: return # This owned background request has no separate caller waiting for its cancellation. except (OSError, RuntimeError, ValueError) as error: @@ -93,6 +96,33 @@ def cancelled() -> bool: stop.set() +def _sender_outcome(work: Callable[[], None], stop: Event) -> Optional[BaseException]: + """Carry provider failures as values so shield cancellation cannot lose their observation.""" + try: + if not stop.is_set(): + work() + except BaseException as error: # reason: transfer the original worker outcome to its owning request + return error + return None + + +async def _observe_sender(worker: asyncio.Future[Optional[BaseException]], stop: Event) -> None: + """Keep the original worker owned until it exits, even after repeated cancellation.""" + interruption: Optional[asyncio.CancelledError] = None + while not worker.done(): + try: + await asyncio.shield(worker) + except asyncio.CancelledError as error: + if interruption is None: + interruption = error + stop.set() + if interruption is not None: + raise interruption + outcome = worker.result() + if outcome is not None: + raise outcome + + def file_request_failure(channel: Optional[_Channel], name: str, active: Callable[[], bool]) -> Callable[[str], None]: """Bind error replies to the original control channel; invoke only on that channel's event loop.""" diff --git a/test/unit_test/headless/test_webrtc_sender_retirement.py b/test/unit_test/headless/test_webrtc_sender_retirement.py new file mode 100644 index 000000000..20f51248d --- /dev/null +++ b/test/unit_test/headless/test_webrtc_sender_retirement.py @@ -0,0 +1,138 @@ +"""File-request cancellation observes the original fake sender's actual completion.""" +import asyncio +from concurrent.futures import CancelledError, ThreadPoolExecutor +from contextvars import ContextVar +import threading + +import pytest + +from je_auto_control.utils.remote_desktop import webrtc_file_tasks as requests + + +async def wait_for(predicate): + async with asyncio.timeout(3): + while not predicate(): + await asyncio.sleep(0.001) + + +@pytest.mark.parametrize('failure', [False, True]) +def test_repeated_cancel_keeps_sender_and_queue_owned_until_actual_exit(failure): + entered, release, exited, cancellation_seen = (threading.Event() for _ in range(4)) + calls, failures = [], [] + + def sender(path, remote_name=None, *, cancelled=None): + calls.append(path) + entered.set() + try: + if not release.wait(3): + raise TimeoutError('test sender was not released') + if cancelled(): + cancellation_seen.set() + if failure: + raise OSError('late provider failure') + finally: + exited.set() + + async def drive(): + owned, channel = set(), object() + requests.start_file_request(owned, sender, 'first', 'name', channel, lambda: True, failures.append) + requests.start_file_request(owned, sender, 'queued', 'name', channel, lambda: True, failures.append) + stopping = None + try: + await wait_for(entered.is_set) + stopping = asyncio.create_task(requests.cancel_file_requests(owned)) + await wait_for(lambda: len(owned) == 1) + original = next(iter(owned)) + original.cancel('second stop') + await asyncio.sleep(0) + assert not original.done() + assert not stopping.done() + assert not exited.is_set() + assert any(queue.channel is channel and queue.users == 1 for queue in requests._queues.values()) + assert calls == ['first'] + release.set() + await asyncio.wait_for(stopping, 3) + assert exited.is_set() and cancellation_seen.is_set() + assert not owned + assert not any(queue.channel is channel for queue in requests._queues.values()) + assert failures == [] + finally: + release.set() + if stopping is not None: + await asyncio.gather(stopping, return_exceptions=True) + await requests.cancel_file_requests(owned) + + asyncio.run(drive()) + + +@pytest.mark.parametrize('outcome', ['success', 'error', 'cancel']) +def test_sender_context_and_uncancelled_results_preserve_existing_contract(outcome): + context = ContextVar('sender-authority', default='ambient') + observed, failures = [], [] + + def sender(path, remote_name=None, *, cancelled=None): + observed.append((context.get(), path, remote_name, cancelled())) + if outcome == 'error': + raise OSError('provider failed') + if outcome == 'cancel': + raise CancelledError() + + async def drive(): + token = context.set('original') + try: + await requests.push_requested_file(sender, 'file', 'name', lambda: True, failures.append) + finally: + context.reset(token) + + asyncio.run(drive()) + assert observed == [('original', 'file', 'name', False)] + assert failures == (['provider failed'] if outcome == 'error' else []) + + +def test_cancellation_before_request_starts_never_submits_sender(): + calls = [] + + async def drive(): + owned = set() + requests.start_file_request(owned, lambda *args, **kwargs: calls.append(args), + 'file', 'name', object(), lambda: True, calls.append) + await requests.cancel_file_requests(owned) + assert not owned + + asyncio.run(drive()) + assert calls == [] + + +def test_cancelled_work_waiting_for_executor_capacity_does_not_enter_sender(): + entered, release = threading.Event(), threading.Event() + calls = [] + + def occupy_executor(): + entered.set() + if not release.wait(3): + raise TimeoutError('executor blocker was not released') + + async def drive(): + loop = asyncio.get_running_loop() + loop.set_default_executor(ThreadPoolExecutor(max_workers=1)) + blocker = loop.run_in_executor(None, occupy_executor) + task = None + try: + await wait_for(entered.is_set) + task = asyncio.create_task(requests.push_requested_file( + lambda *args, **kwargs: calls.append(args), 'file', 'name', lambda: True, calls.append)) + await asyncio.sleep(0) + task.cancel() + await asyncio.sleep(0) + assert not task.done() + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert calls == [] + finally: + release.set() + await blocker + if task is not None: + await asyncio.gather(task, return_exceptions=True) + + asyncio.run(drive()) From be16e4d62732ab8dda859d7c2863bf3dcc4e0908 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 19:33:06 +0800 Subject: [PATCH 037/161] Preserve media retirement outcomes and original resource ownership --- CHANGELOG.md | 4 + Progress.md | 6 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 26 +- docs/media_retirement_contract.md | 38 ++ .../doc/new_features/media_retirement_doc.rst | 13 + docs/source/Eng/eng_index.rst | 1 + .../doc/new_features/media_retirement_doc.rst | 13 + docs/source/Zh/zh_index.rst | 1 + docs/updates/2026-11-b.md | 7 + docs/updates/README.md | 3 +- je_auto_control/utils/remote_desktop/audio.py | 143 +++-- .../utils/remote_desktop/audio_retirement.py | 121 ++++ je_auto_control/utils/remote_desktop/host.py | 28 +- .../utils/remote_desktop/lan_discovery.py | 61 +- .../utils/remote_desktop/media_retirement.py | 89 +++ .../utils/remote_desktop/session_recorder.py | 87 ++- .../utils/remote_desktop/webrtc_audio.py | 100 ++- .../utils/remote_desktop/webrtc_mic.py | 92 ++- pyproject.toml | 2 + .../headless/test_media_retirement.py | 579 ++++++++++++++++++ .../headless/test_remote_desktop_audio.py | 6 +- .../headless/test_webrtc_media_audit.py | 6 +- .../headless/test_webrtc_opus_audio.py | 17 +- 26 files changed, 1275 insertions(+), 174 deletions(-) create mode 100644 docs/media_retirement_contract.md create mode 100644 docs/source/Eng/doc/new_features/media_retirement_doc.rst create mode 100644 docs/source/Zh/doc/new_features/media_retirement_doc.rst create mode 100644 je_auto_control/utils/remote_desktop/audio_retirement.py create mode 100644 je_auto_control/utils/remote_desktop/media_retirement.py create mode 100644 test/unit_test/headless/test_media_retirement.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b9f3044d..dadd245b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- Retain original audio, recording and LAN advertisement cleanup outcomes. Reject unsafe + flush/close replay and report pending work or uncertain finalization through typed + errors. Application caretaker and GUI integration remain pending. + - File-request cancellation retains the original sender worker and queue ownership until actual completion, including repeated cancellation, without blocking the event loop. diff --git a/Progress.md b/Progress.md index 0c38f2ccb..55ea35a6f 100644 --- a/Progress.md +++ b/Progress.md @@ -538,8 +538,10 @@ F 還缺: - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 - 音訊、錄影與 LAN 廣播後端仍有吞掉清理錯誤或清掉失敗資源參照的路徑;錄影須分開記錄 flush 結果與容器關閉, - 不可重播可能已部分完成的 flush。傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; + peer 的音訊建構、替換與停用,以及 GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; + 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 清理與發布准入仍缺整合。 + 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 + 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/README.md b/README.md index 6f85d2652..e1ba6cfa7 100644 --- a/README.md +++ b/README.md @@ -80,3 +80,5 @@ REST host-data reads now follow the matching MCP authority: jobs, remote session Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. Internal Windows process-memory preparation can now measure a selected process image file through retained read-only handles, with bounded hashing and retryable cleanup. This is observed file evidence, not loaded-code or fixture attestation; native acceptance and public memory tools remain unavailable. See [the contract](docs/process_memory_contract.md). + +Media producer shutdown now reports pending or uncertain cleanup and retains original resources. Audio and recorder failures are never turned into success by unsafe close or flush replay. LAN close supports explicit retry; application caretaker and GUI integration remain pending. See [the retirement contract](docs/media_retirement_contract.md). diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 1be7837a5..9395c8ac9 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -80,3 +80,5 @@ REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、US 主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 内部 Windows 进程内存准备工作新增映像文件测量,通过保留的只读 handle 执行有界哈希并保留失败清理供重试。这只是观察到的文件证据,不是已加载代码或 fixture 的身份证明;原生验收及公开内存工具仍未提供。详见[契约](../docs/process_memory_contract.md)。 + +媒体 producer 关闭会报告待完成或不确定的清理结果,并保留原始资源。音频与录影不会通过不安全的 close/flush 重播宣称成功;LAN close 可明确重试。应用程序 caretaker 与 GUI 整合仍待完成。详见[清理契约](../docs/media_retirement_contract.md)。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 67f5f56eb..74451300c 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -80,3 +80,5 @@ REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、US 主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 內部 Windows 行程記憶體準備工作新增映像檔量測,透過保留的唯讀 handle 執行有界雜湊並保留失敗清理供重試。這只是觀測到的檔案證據,不是已載入程式碼或 fixture 的身分證明;原生驗收及公開記憶體工具仍未提供。詳見[契約](../docs/process_memory_contract.md)。 + +媒體 producer 關閉會回報待完成或不確定的清理結果,並保留原始資源。音訊與錄影不會透過不安全的 close/flush 重播宣稱成功;LAN close 可明確重試。應用程式 caretaker 與 GUI 整合仍待完成。詳見[清理契約](../docs/media_retirement_contract.md)。 diff --git a/architecture_explore.md b/architecture_explore.md index b9ccc57cb..b9e6f9269 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,522 | -| 程式碼總行數 | 232,220 | +| Python 模組總數(含周邊子專案) | 1,524 | +| 程式碼總行數 | 232,645 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 30,910 行。 +> 6 個套件、約 31,335 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 15,676 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,101 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -815,7 +815,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(15,676 行/74 檔) +#### `utils/remote_desktop/`(16,101 行/76 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -828,7 +828,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_viewer.py` | 695 | WebRTC 檢視端:接收視訊並送出輸入。 | | `webrtc_retirement.py` | 183 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | | `webrtc_peer_cleanup.py` | 88 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | -| `host.py` | 686 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | +| `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | | `viewer.py` | 743 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | @@ -846,7 +846,9 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence.py` | 238 | 多檢視者的執行緒安全在場註冊表。 | | `jpeg_recorder_encrypted.py` | 239 | AES-GCM 加密版 session 錄影。 | | `address_book.py` | 229 | 檢視端的主機通訊錄。 | -| `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 243 / 207 / 155 | 音訊擷取播放、音訊軌、麥克風上行。 | +| `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 250 / 277 / 195 | 音訊擷取播放、音訊軌、麥克風上行。 | +| `audio_retirement.py` | 121 | 保留單一音訊串流世代、准入中的操作與無法確認的清理結果。 | +| `media_retirement.py` | 89 | 區分媒體資源釋放與最終化狀態,傳遞失敗或取消時仍需保留的擁有者。 | | `webrtc_file_commit.py` | 355 | Confirm native file publication with bounded authenticated probes and transfer/hash/size receipt matching. | | `webrtc_file_callbacks.py` | 38 | Notify native file path and frozen receipt listeners while preserving original interruption objects. | | `webrtc_file_receive.py` | 101 | Bind file receivers to one authenticated peer and channel, retiring partial bytes when ownership ends. | @@ -854,7 +856,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_file_tasks.py` | 147 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | | `webrtc_files.py` | 416 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | -| `lan_discovery.py` | 204 | mDNS/Zeroconf 區網探索。 | +| `lan_discovery.py` | 247 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 197 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | @@ -865,7 +867,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `trust_list.py` | 139 | 自動接受的檢視端信任清單。 | | `webrtc_inspector.py` | 138 | 行程級的 `StatsSnapshot` 滾動視窗。 | | `input_dispatch.py` | 161 | 在主機端套用輸入訊息。 | -| `session_recorder.py` | 145 | 以 PyAV 把 WebRTC 影格錄成 mp4。 | +| `session_recorder.py` | 186 | 以 PyAV 把 WebRTC 影格錄成 mp4。 | | `totp.py` | 159 | RFC 6238 TOTP(零外部相依)。 | | `file_receipts.py` | 29 | Immutable local publication receipts keep received bytes distinct from later edits to their target path. | | `clipboard_delivery.py` | 62 | Deliver clipboard data under its captured local authority and concrete connection owner. Once-bound ClipboardReceiver weakly pins the origin; queued deliveries keep the concrete peer alive without a registration self-cycle. | @@ -1437,7 +1439,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,186 個 `test_*.py`/11,520 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,187 個 `test_*.py`/11,543 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1530,7 +1532,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 61 | 22,084 | -| `utils/remote_desktop/` | 74 | 15,676 | +| `utils/remote_desktop/` | 76 | 16,101 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1549,7 +1551,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,042 | -| **總計** | **1,510** | **231,475** | +| **總計** | **1,512** | **231,900** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/media_retirement_contract.md b/docs/media_retirement_contract.md new file mode 100644 index 000000000..157887387 --- /dev/null +++ b/docs/media_retirement_contract.md @@ -0,0 +1,38 @@ +# Media producer retirement + +Audio capture/playback, session recording, and LAN advertisement distinguish stopped input from confirmed resource retirement. Their `retirement_status` is an immutable snapshot. `stop()` raises `MediaRetirementError` when retirement is pending or uncertain. The exception derives from `AutoControlException` and `RuntimeError`, and retains its original `owner` for inspection. Retain the owner independently of a page or a task callback. + +```python +from je_auto_control.utils.remote_desktop.media_retirement import MediaRetirementError + +try: + producer.stop() +except MediaRetirementError as error: + original_owner = error.owner + status = error.status + # Persist this owner and outcome in the application's retirement owner. +``` + +`resources` and `finalization` are separate `Completion` values. `CONFIRMED` acknowledges the operation, `PENDING` means admitted work remains, and `UNCERTAIN` means an operation failed without a reliable completion observation. `retryable` describes whether a remaining operation can be attempted; it grants no authority to execute it. A terminal uncertain result remains visible on repeated stop calls. Success does not prove native device behavior beyond the library acknowledgement. + +## Audio + +Each stream generation owns its admission gate. Callbacks and writes are admitted only after native start acknowledges success; callbacks during start are dropped. Late capture callbacks are dropped, and an admitted callback or write keeps retirement pending until it returns. Stop does not wait on a callback that could itself be asking to stop. Retry the same owner after the operation finishes. A new start cannot overwrite an unresolved generation. Successfully retired instances can start a new generation; callbacks from the previous generation remain rejected. + +Native stop and close use sounddevice's `ignore_errors=False`. Cleanup does not reload the optional backend. Both operations are attempted even if stop fails. A failed stop leaves graceful finalization uncertain even when close succeeds. A failed close retains the original stream wrapper, but is not automatically retried. Sounddevice clears its native pointer before reporting a close error, so calling close again cannot recover or acknowledge the original close. Failed-start cleanup follows the same ownership rule. + +## Recording + +Stopping closes frame admission under the same lock used for encoding. Encoder flush is attempted once, including packet iteration and muxing. Partial flush, mux, write, or setup failures remain recorded. Container close still runs independently. A failed PyAV close is terminal uncertain because it may mark the trailer operation done before raising. Repeating close could then return normally without repairing the failed trailer. The failed container remains owned for diagnosis. + +`has_output` indicates that initialization succeeded; it does not mean that the recording was finalized or can be read. Only a complete retirement status acknowledges successful finalization. A recorder is terminal after stop; create a new instance for another recording. + +## LAN advertisement + +Unregister is attempted once, and Zeroconf close is attempted even when unregister fails. Zeroconf documents close as idempotent, so a failed close can be retried on that same owner. Successful close does not convert failed unregister into a confirmed goodbye. Constructor failure attempts cleanup and returns a retained owner through `MediaRetirementError` if ordinary cleanup remains unresolved. Cancellation and hard control signals keep their original identity. For those signals, `interrupted_retirement_owners(error)` returns the explicitly attached cleanup owners, including when the interruption was wrapped. The application must retain those owners before discarding its error outcome. + +## Wrappers and current limits + +Mic wrappers retain children when child stop fails. Opus track ending also rejects queued PCM and wakes a waiting receive operation. Opus receiver cancellation retains the exact task until actual completion is observed; cancellation requested is not completion. Repeated stop can observe a completed task. Direct TCP host cleanup continues socket/client teardown after an audio failure and retains the original capture for later observation. + +These producer contracts do not complete application shutdown. The application caretaker, original-authority Diagnostics retries, GUI success reporting, HostBrowser cleanup, and all peer replacement/discard paths still require integration. In particular, a GUI must not display a recording as saved just because `has_output` is true. Existing consumer paths that swallow errors or drop references are not made durable by this producer unit. Native media/network acceptance remains pending. Validation for this unit uses injected resources and event-loop tasks only. diff --git a/docs/source/Eng/doc/new_features/media_retirement_doc.rst b/docs/source/Eng/doc/new_features/media_retirement_doc.rst new file mode 100644 index 000000000..9b1bae956 --- /dev/null +++ b/docs/source/Eng/doc/new_features/media_retirement_doc.rst @@ -0,0 +1,13 @@ +Media producer retirement +========================= + +Audio, recording and LAN advertisement expose immutable retirement status and +raise ``MediaRetirementError`` for pending or uncertain cleanup. The error retains +the original owner and derives from ``AutoControlException`` and ``RuntimeError``. +Resource closure and finalization have separate acknowledgements. Recording flush +is attempted once; uncertain PyAV or sounddevice close is never replayed to claim +success. Zeroconf close supports retry on its original owner. + +This producer unit does not complete application caretaker, GUI saved-result +reporting, peer replacement/discard paths, or HostBrowser cleanup. Native acceptance +remains pending; validation uses injected resources only. diff --git a/docs/source/Eng/eng_index.rst b/docs/source/Eng/eng_index.rst index 0198e2b75..571ec9575 100644 --- a/docs/source/Eng/eng_index.rst +++ b/docs/source/Eng/eng_index.rst @@ -26,6 +26,7 @@ Comprehensive guides for all AutoControl features. doc/cli/cli_doc doc/create_project/create_project_doc doc/new_features/new_features_doc + doc/new_features/media_retirement_doc doc/new_features/v2_features_doc doc/new_features/healing_evaluation_doc doc/new_features/v3_features_doc diff --git a/docs/source/Zh/doc/new_features/media_retirement_doc.rst b/docs/source/Zh/doc/new_features/media_retirement_doc.rst new file mode 100644 index 000000000..27cb1aa05 --- /dev/null +++ b/docs/source/Zh/doc/new_features/media_retirement_doc.rst @@ -0,0 +1,13 @@ +媒體 producer 清理 +=================== + +音訊、錄影與 LAN 廣告會提供不可變的清理狀態,並在清理待完成或結果不確定時拋出 +``MediaRetirementError``。錯誤保留原始 owner,並繼承 ``AutoControlException`` +與 ``RuntimeError``。資源關閉與輸出完成各自記錄確認結果。 + +錄影 flush 只嘗試一次;PyAV 或 sounddevice 關閉結果不確定時,不會透過重播呼叫 +宣稱成功。Zeroconf close 可在原始 owner 上重試。取消與中斷訊號維持原始身分; +若建構期間清理失敗,可透過 ``interrupted_retirement_owners(error)`` 取得保留的 owner。 + +此 producer 單元尚未完成應用程式 caretaker、GUI 儲存成功提示、peer 替換及丟棄路徑, +以及 HostBrowser 清理整合。原生驗收仍待完成;本單元使用注入的資源驗證。 diff --git a/docs/source/Zh/zh_index.rst b/docs/source/Zh/zh_index.rst index 6039f979c..989d106f1 100644 --- a/docs/source/Zh/zh_index.rst +++ b/docs/source/Zh/zh_index.rst @@ -26,6 +26,7 @@ AutoControl 所有功能的完整使用指南。 doc/cli/cli_doc doc/create_project/create_project_doc doc/new_features/new_features_doc + doc/new_features/media_retirement_doc doc/new_features/v2_features_doc doc/new_features/healing_evaluation_doc doc/new_features/v3_features_doc diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 203be9cca..1661dcf70 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -89,3 +89,10 @@ - **What:** File-request tasks retain the original default-executor Future, copied call context and queue ownership until the sender function exits. Repeated cancellation signals the sender without discarding its completion observation. Work cancelled before executor capacity becomes available never enters the sender. Provider outcomes are transferred as values, avoiding unobserved shield errors while preserving cancellation identity. - **Evidence:** Parent implementation passed 38 fake sender/file-delivery cases. Independent review passed 52 cases plus probes for direct and wrapped control-signal identity, repeated cancellation and host teardown with an independently closed fake peer. Parent integration passed the same 52 cases, 49 document/quality gates and a warnings-as-errors Sphinx build. Mypy, Ruff and diff checks passed. No real file transfer, device or network connection was used for the new worker tests. - **Limits:** An uninterruptible backend can leave stop pending. Process termination, native release and durable GUI cleanup/retry remain separate work. This change does not interrupt arbitrary backend calls forcibly. + +## U-20261111-28 · 2026-11-11 · Preserve media producer retirement outcomes and original resources · #done #remote + +- **What:** Added immutable resource/finalization outcomes and retained-owner failure handoff. Audio admits work only after start completes, retains in-flight operations and uncertain closes, and rejects late generations. Recorder flush and close are attempted once; uncertain results remain visible. Advertisement separates unregister from retryable Zeroconf close. Mic/Opus wrappers retain failed children and observe task completion; TCP host audio failure no longer skips independent teardown. Interrupted constructors preserve the original signal and expose retained owners explicitly. +- **Evidence:** Writer verification passed a 90-case audited scope; final cleanup passed 34 injected producer cases and three-target typing for eight modules. Independent narrowed producer/structural verification passed 49 cases. Parent integration passed 49 producer/structural cases and 204 producer, Opus, peer lifecycle and document/complexity cases, plus warnings-as-errors Sphinx. Production text matches the reviewed source. Ruff, Bandit, Pylint errors, complexity and file budgets passed. Installed SDK source explains why sounddevice and PyAV failed closes cannot be verified by replaying a no-op close. +- **Validation scope:** Focused acceptance uses injected resources and event-loop tasks. An earlier reviewer run passed 72 cases but also included loopback TCP tests and a UDP route lookup; it is not fake-only or native media acceptance. No actual audio device, desktop input or capture was tested. +- **Open items:** Peer constructor/replacement/discard ownership, HostBrowser, GUI saved/failed reporting, durable caretaker and original-authority Diagnostics retry remain in Progress.md. Producer outcomes alone do not make every consumer durable; terminal uncertainty must not become success through generic retry. diff --git a/docs/updates/README.md b/docs/updates/README.md index a06560d47..e041ccdbc 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-28 | 2026-11-11 | Preserve media producer retirement outcomes and original resources | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-27 | 2026-11-11 | Await actual file sender completion after cancellation | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-26 | 2026-11-11 | Enforce host-data authority across REST and executor reads | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-25 | 2026-11-11 | Align remote GUI tests with queued page ownership | #done #tests | [2026-11-b](2026-11-b.md) | @@ -646,7 +647,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 16 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 17 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/audio.py b/je_auto_control/utils/remote_desktop/audio.py index 7e39ad2fa..37346c2ee 100644 --- a/je_auto_control/utils/remote_desktop/audio.py +++ b/je_auto_control/utils/remote_desktop/audio.py @@ -12,8 +12,13 @@ """ import threading from dataclasses import dataclass -from typing import Any, Callable, Optional +from typing import Any, Callable, Optional, cast +from je_auto_control.utils.remote_desktop.audio_retirement import AudioLease, AudioOutputStream, AudioStream +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, MediaRetirementError, RetirementStatus, require_retired, preserve_interrupted_owner, +) from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -51,44 +56,6 @@ def _device_errors(sd: Any) -> tuple: return (OSError, RuntimeError, sd.PortAudioError) -def _open_started(sd: Any, factory: Callable[[], Any]) -> Any: - """Create a stream and start it; a stream that fails to start is closed. - - Raises :class:`AudioBackendError`: a raw ``PortAudioError`` escaped the - ``RuntimeError`` / ``OSError`` guards around every caller, and a stream - kept after a failed ``start()`` made every later ``start()`` a no-op. - """ - errors = _device_errors(sd) - try: - stream = factory() - except errors as error: - raise AudioBackendError(f"audio device unavailable: {error}") from error - try: - stream.start() - except errors as error: - _close_quietly(stream, errors) - raise AudioBackendError(f"audio device failed to start: {error}") from error - return stream - - -def _close_quietly(stream: Any, errors: tuple) -> None: - try: - stream.close() - except errors as error: - autocontrol_logger.debug("audio stream close: %r", error) - - -def _stop_and_close(stream: Any) -> None: - """Stop and close ``stream``; device errors on the way out are logged, never raised.""" - errors = _device_errors(_load_sounddevice()) - try: - stream.stop() - except errors as error: - autocontrol_logger.debug("audio stream stop: %r", error) - finally: - _close_quietly(stream, errors) - - def is_audio_backend_available() -> bool: """Return True if ``sounddevice`` can be imported.""" try: @@ -109,7 +76,45 @@ class AudioCaptureConfig: block_frames: int = DEFAULT_BLOCK_FRAMES -class AudioCapture: +class _AudioOwner: + """Serialize start/retire on one retained stream generation.""" + + _lease: Optional[AudioLease] + _lock: threading.Lock + + @property + def retirement_status(self) -> RetirementStatus: + if self._lease is None: + return RetirementStatus(True, Completion.CONFIRMED, Completion.CONFIRMED) + return self._lease.status + + def _start_stream(self, lease: AudioLease, factory: Callable[[], AudioStream]) -> None: + try: + lease.stream = factory() + lease.stream.start() + lease.activate() + except BaseException as error: + try: + lease.retire(started=False) + except BaseException as cleanup_error: + preserve_interrupted_owner(self, error, cleanup_error) + raise + if not lease.status.complete: + preserve_interrupted_owner(self, error) + raise MediaRetirementError(self) from error + raise_caused_run_interruption(error) + raise AudioBackendError("audio device failed to start") from error + + def stop(self) -> None: + """Close admission and report any unconfirmed retirement.""" + with self._lock: + lease = self._lease + if lease is not None: + lease.retire() + require_retired(self) + + +class AudioCapture(_AudioOwner): """Capture mono int16 PCM blocks and hand them to ``on_block`` as bytes. ``on_block`` is invoked from the audio library's internal thread, so @@ -133,7 +138,7 @@ def __init__(self, on_block: AudioBlockCallback, self._sample_rate = int(sample_rate) self._channels = int(channels) self._block_frames = int(block_frames) - self._stream: Optional[Any] = None + self._lease: Optional[AudioLease] = None self._lock = threading.Lock() @property @@ -146,31 +151,34 @@ def channels(self) -> int: @property def is_running(self) -> bool: - return self._stream is not None + return self._lease is not None and self._lease.running def start(self) -> None: """Open the input stream; subsequent blocks fire ``on_block`` callbacks.""" with self._lock: - if self._stream is not None: + if self.is_running: return + if self._lease is not None: + require_retired(self) sd = _load_sounddevice() - self._stream = _open_started(sd, lambda: sd.RawInputStream( + lease = AudioLease() + self._lease = lease + self._start_stream(lease, lambda: sd.RawInputStream( samplerate=self._sample_rate, channels=self._channels, dtype=SAMPLE_DTYPE, blocksize=self._block_frames, device=self._device, - callback=self._raw_callback, + callback=lambda *args: self._raw_callback_for(lease, *args), )) - def stop(self) -> None: - """Stop and release the input stream.""" - with self._lock: - stream = self._stream - self._stream = None - if stream is None: + def _raw_callback_for(self, lease, *args) -> None: + if not lease.enter(): return - _stop_and_close(stream) + try: + self._raw_callback(*args) + finally: + lease.leave() def _raw_callback(self, indata, frames, time_info, status) -> None: del frames, time_info # unused — block size is fixed @@ -185,7 +193,7 @@ def _raw_callback(self, indata, frames, time_info, status) -> None: return -class AudioPlayer: +class AudioPlayer(_AudioOwner): """Play int16 PCM bytes through the default (or chosen) output device.""" def __init__(self, device: Optional[int] = None, @@ -196,22 +204,26 @@ def __init__(self, device: Optional[int] = None, self._device = device self._sample_rate = int(sample_rate) self._channels = int(channels) - self._stream: Optional[Any] = None + self._lease: Optional[AudioLease] = None self._write_errors: tuple = (OSError, RuntimeError) self._lock = threading.Lock() @property def is_running(self) -> bool: - return self._stream is not None + return self._lease is not None and self._lease.running def start(self) -> None: """Open the output stream so :meth:`play` becomes valid.""" with self._lock: - if self._stream is not None: + if self.is_running: return + if self._lease is not None: + require_retired(self) sd = _load_sounddevice() self._write_errors = _device_errors(sd) - self._stream = _open_started(sd, lambda: sd.RawOutputStream( + lease = AudioLease() + self._lease = lease + self._start_stream(lease, lambda: sd.RawOutputStream( samplerate=self._sample_rate, channels=self._channels, dtype=SAMPLE_DTYPE, @@ -224,20 +236,15 @@ def play(self, chunk: bytes) -> None: raise TypeError("chunk must be bytes-like") if not chunk: return - stream = self._stream - if stream is None: + lease = self._lease + if lease is None or not lease.enter(): raise RuntimeError("AudioPlayer is not running; call start() first") try: - stream.write(bytes(chunk)) + cast(AudioOutputStream, lease.stream).write(bytes(chunk)) except self._write_errors as error: + raise_caused_run_interruption(error) # Late writes after stop / device removal — ignored so the # network thread keeps flowing; PortAudioError included. autocontrol_logger.debug("audio write dropped: %r", error) - - def stop(self) -> None: - with self._lock: - stream = self._stream - self._stream = None - if stream is None: - return - _stop_and_close(stream) + finally: + lease.leave() diff --git a/je_auto_control/utils/remote_desktop/audio_retirement.py b/je_auto_control/utils/remote_desktop/audio_retirement.py new file mode 100644 index 000000000..b35dfb8ca --- /dev/null +++ b/je_auto_control/utils/remote_desktop/audio_retirement.py @@ -0,0 +1,121 @@ +"""One sounddevice stream generation and its admitted operations.""" +import threading +from typing import Protocol + +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption + +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, RetirementStatus, +) + + +class AudioStream(Protocol): + """Operations shared by input and output streams.""" + + def start(self) -> object: ... + def stop(self, *, ignore_errors: bool) -> object: ... + def close(self, *, ignore_errors: bool) -> object: ... + + +class AudioOutputStream(AudioStream, Protocol): + """Only output generations support writing PCM.""" + + def write(self, data: bytes) -> object: ... + + +class AudioLease: + """Keep the exact stream even when sounddevice loses its native pointer.""" + + def __init__(self) -> None: + self.stream: AudioStream | None = None + self._lock = threading.Lock() + self._admitting = False + self._retiring = False + self._operations = 0 + self._closing = False + self._close_attempted = False + self._resources = Completion.PENDING + self._finalization = Completion.PENDING + self._failures: tuple[str, ...] = () + + def activate(self) -> None: + with self._lock: + self._admitting = True + + @property + def running(self) -> bool: + with self._lock: + return self._admitting and self.stream is not None + + def enter(self) -> bool: + with self._lock: + if not self._admitting: + return False + self._operations += 1 + return True + + def leave(self) -> None: + with self._lock: + self._operations -= 1 + + @property + def status(self) -> RetirementStatus: + with self._lock: + pending = self._retiring and not self._close_attempted + failures = self._failures + if pending: + failures += ("audio.operations_pending",) + return RetirementStatus(self._retiring, self._resources, + self._finalization, pending, failures) + + def retire(self, *, started: bool = True) -> None: + with self._lock: + self._admitting = False + self._retiring = True + if self._operations or self._closing or self._close_attempted: + return + self._closing = True + try: + self._retire_stream(started) + finally: + with self._lock: + self._closing = False + + def _retire_stream(self, started: bool) -> None: + stream = self.stream + if stream is None: + self._resources = Completion.CONFIRMED + self._finalization = Completion.CONFIRMED + self._close_attempted = True + return + stop_failure = self._stop_stream(stream) if started else None + if not started: + self._finalization = Completion.CONFIRMED + close_failure = self._close_stream(stream) + for failure in (stop_failure, close_failure): + if failure is not None: + raise_caused_run_interruption(failure) + + def _stop_stream(self, stream: AudioStream) -> BaseException | None: + try: + stream.stop(ignore_errors=False) + except BaseException as error: # reason: close independently before preserving control signals + self._finalization = Completion.UNCERTAIN + self._failures += ("audio.stop",) + return error + self._finalization = Completion.CONFIRMED + return None + + def _close_stream(self, stream: AudioStream) -> BaseException | None: + # sounddevice clears _ptr before checking Pa_CloseStream's result. + # A repeated close cannot acknowledge the first call's release. + self._close_attempted = True + try: + stream.close(ignore_errors=False) + except BaseException as error: # reason: record uncertain ownership before preserving control signals + self._resources = Completion.UNCERTAIN + self._failures += ("audio.close",) + return error + self._resources = Completion.CONFIRMED + self.stream = None + return None diff --git a/je_auto_control/utils/remote_desktop/host.py b/je_auto_control/utils/remote_desktop/host.py index 714e839ee..42f2f1d19 100644 --- a/je_auto_control/utils/remote_desktop/host.py +++ b/je_auto_control/utils/remote_desktop/host.py @@ -8,6 +8,8 @@ from typing import Any, Callable, List, Mapping, Optional, Sequence from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.remote_desktop.media_retirement import MediaRetirementError +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.remote_desktop.audio import ( AudioCapture, AudioCaptureConfig, ) @@ -281,9 +283,14 @@ def stop(self, timeout: float = 2.0) -> None: def _stop_locked(self, timeout: float) -> None: if self._listen_sock is None: + self._stop_audio_capture() return self._shutdown.set() - self._stop_audio_capture() + audio_error = None + try: + self._stop_audio_capture() + except BaseException as error: # reason: finish independent host cleanup before preserving the audio failure + audio_error = error try: self._listen_sock.close() except OSError: @@ -310,9 +317,14 @@ def _stop_locked(self, timeout: float) -> None: self._accept_thread = None self._capture_thread = None self._cursor_thread = None + if audio_error is not None: + raise_caused_run_interruption(audio_error) + raise audio_error def _start_audio_capture(self) -> None: """Open the audio input stream when audio capture is enabled.""" + if self._audio_capture is not None: + self._stop_audio_capture() config = self._audio_config if not config.enabled: return @@ -321,10 +333,12 @@ def _start_audio_capture(self) -> None: try: self._audio_capture.start() except (OSError, RuntimeError) as error: + raise_caused_run_interruption(error) autocontrol_logger.warning( "remote_desktop audio capture failed to start: %r", error, ) - self._audio_capture = None + if not isinstance(error, MediaRetirementError): + self._audio_capture = None return try: capture = AudioCapture( @@ -334,12 +348,15 @@ def _start_audio_capture(self) -> None: channels=config.channels, block_frames=config.block_frames, ) + self._audio_capture = capture capture.start() except (OSError, RuntimeError) as error: + raise_caused_run_interruption(error) autocontrol_logger.warning( "remote_desktop audio capture disabled: %r", error, ) - self._audio_capture = None + if not isinstance(error, MediaRetirementError): + self._audio_capture = None return self._audio_capture = capture @@ -347,10 +364,7 @@ def _stop_audio_capture(self) -> None: capture = self._audio_capture if capture is None: return - try: - capture.stop() - except (OSError, RuntimeError): - pass + capture.stop() self._audio_capture = None def _broadcast_audio(self, chunk: bytes) -> None: diff --git a/je_auto_control/utils/remote_desktop/lan_discovery.py b/je_auto_control/utils/remote_desktop/lan_discovery.py index 10a77dea2..677951344 100644 --- a/je_auto_control/utils/remote_desktop/lan_discovery.py +++ b/je_auto_control/utils/remote_desktop/lan_discovery.py @@ -16,7 +16,11 @@ import threading from typing import Callable, Dict, List, Optional +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, RetirementStatus, require_retired, preserve_interrupted_owner, +) try: from zeroconf import ServiceBrowser, ServiceInfo, ServiceListener, Zeroconf @@ -67,13 +71,20 @@ def __init__(self, *, host_id: str, port: int = 0, "pip install je_auto_control[discovery]" ) self._host_id = host_id + self._retire_lock = threading.Lock() + self._unregister = Completion.PENDING + self._release = Completion.PENDING + self._stopping = False + self._info = None self._zc = Zeroconf() try: ip = self._register(host_id, port, signaling_url, server_name) - except BaseException: - # A taken name (NonUniqueNameException) left this instance's - # sockets and thread running. - self._zc.close() + except BaseException as error: + try: + self.stop() + except BaseException as cleanup_error: + preserve_interrupted_owner(self, error, cleanup_error) + raise cleanup_error from error raise autocontrol_logger.info( "lan discovery: advertised host_id=%s on %s", host_id, ip, @@ -97,12 +108,44 @@ def _register(self, host_id: str, port: int, signaling_url: Optional[str], self._zc.register_service(self._info) return ip + @property + def retirement_status(self) -> RetirementStatus: + with self._retire_lock: + failed: tuple[str, ...] = () + if self._unregister is Completion.UNCERTAIN: + failed += ("advertiser.unregister",) + if self._release is not Completion.CONFIRMED: + failed += ("advertiser.close",) + return RetirementStatus(self._stopping, self._release, + self._unregister, + self._stopping and self._release is not Completion.CONFIRMED, + failed) + def stop(self) -> None: - try: - self._zc.unregister_service(self._info) - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("zeroconf unregister: %r", error) - self._zc.close() + """Retain a failed close; a failed goodbye remains uncertain.""" + failures = [] + with self._retire_lock: + self._stopping = True + if self._unregister is Completion.PENDING: + self._unregister = Completion.UNCERTAIN + try: + if self._info is not None: + self._zc.unregister_service(self._info) + except BaseException as error: # reason: finish close and then preserve any control signal + failures.append(error) + else: + self._unregister = Completion.CONFIRMED + if self._release is not Completion.CONFIRMED: + try: + self._zc.close() + except BaseException as error: # reason: finish close and then preserve any control signal + failures.append(error) + self._release = Completion.UNCERTAIN + else: + self._release = Completion.CONFIRMED + for failure in failures: + raise_caused_run_interruption(failure) + require_retired(self) class _BrowseListener: diff --git a/je_auto_control/utils/remote_desktop/media_retirement.py b/je_auto_control/utils/remote_desktop/media_retirement.py new file mode 100644 index 000000000..b9e1ad3c4 --- /dev/null +++ b/je_auto_control/utils/remote_desktop/media_retirement.py @@ -0,0 +1,89 @@ +"""Observable media retirement without confusing finalization with release.""" +from dataclasses import dataclass +from enum import Enum +from typing import Protocol + +from je_auto_control.utils.exception.exceptions import AutoControlException +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption + + +class Completion(Enum): + """Acknowledgement of one independent retirement obligation.""" + + PENDING = "pending" + CONFIRMED = "confirmed" + UNCERTAIN = "uncertain" + + +@dataclass(frozen=True) +class RetirementStatus: + """A snapshot, never an instruction or authority to retry.""" + + admission_closed: bool + resources: Completion + finalization: Completion + retryable: bool = False + failed_steps: tuple[str, ...] = () + + @property + def complete(self) -> bool: + return (self.admission_closed + and self.resources is Completion.CONFIRMED + and self.finalization is Completion.CONFIRMED) + + +class RetirementOwner(Protocol): + """An original owner retained by callers after failed retirement.""" + + @property + def retirement_status(self) -> RetirementStatus: ... + + def stop(self) -> None: ... + + +class MediaRetirementError(AutoControlException, RuntimeError): + """Retirement is pending or uncertain; ``owner`` keeps its resources.""" + + def __init__(self, owner: RetirementOwner) -> None: + self.owner = owner + self.status = owner.retirement_status + super().__init__("media retirement incomplete: " + + ", ".join(self.status.failed_steps)) + + +def require_retired(owner: RetirementOwner) -> None: + """Preserve the ordinary stop contract only for confirmed completion.""" + if not owner.retirement_status.complete: + raise MediaRetirementError(owner) + + +def raise_cleanup_failures(failures: list[BaseException]) -> None: + """After independent cleanup, preserve control identity before ordinary errors.""" + for failure in failures: + raise_caused_run_interruption(failure) + if failures: + raise failures[0] + + +@dataclass(frozen=True) +class _InterruptedOwners: + owners: tuple[RetirementOwner, ...] + + +def interrupted_retirement_owners(error: BaseException) -> tuple[RetirementOwner, ...]: + """Recover constructor cleanup owners without replacing a control signal.""" + retained = getattr(error, "_media_retirement_owners", None) + return retained.owners if isinstance(retained, _InterruptedOwners) else () + + +def preserve_interrupted_owner(owner: RetirementOwner, *failures: BaseException) -> None: + """Attach an explicit handoff to the original signal before propagating it.""" + for failure in failures: + try: + raise_caused_run_interruption(failure) + except BaseException as signal: + owners = interrupted_retirement_owners(signal) + if not any(item is owner for item in owners): + owners += (owner,) + setattr(signal, "_media_retirement_owners", _InterruptedOwners(owners)) + raise diff --git a/je_auto_control/utils/remote_desktop/session_recorder.py b/je_auto_control/utils/remote_desktop/session_recorder.py index 33ea117e4..512eaf4c3 100644 --- a/je_auto_control/utils/remote_desktop/session_recorder.py +++ b/je_auto_control/utils/remote_desktop/session_recorder.py @@ -3,7 +3,7 @@ The viewer's frame callback fires on the asyncio thread. ``SessionRecorder`` is thread-safe: ``write_frame`` may be called from that thread while ``stop`` is called from the Qt thread. Only one open recording per -instance — call :meth:`stop` before reusing. +instance. Create a new recorder after stopping. """ from __future__ import annotations @@ -18,7 +18,11 @@ "Session recording requires the 'webrtc' extra (PyAV).", ) from exc +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, RetirementStatus, require_retired, +) _DEFAULT_CODEC = "libx264" @@ -54,6 +58,10 @@ def __init__(self, output_path: str, *, self._stream: Optional["av.video.stream.VideoStream"] = None self._started = False self._closed = False + self._flush = Completion.PENDING + self._release = Completion.PENDING + self._close_attempted = False + self._failures: tuple[str, ...] = () def _open(self, frame) -> Tuple[ "av.container.OutputContainer", "av.video.stream.VideoStream", @@ -63,6 +71,7 @@ def _open(self, frame) -> Tuple[ return self._container, self._stream self._path.parent.mkdir(parents=True, exist_ok=True) container = av.open(str(self._path), mode="w") + self._container = container try: stream = container.add_stream(self._codec, rate=self._fps) if not isinstance(stream, av.video.stream.VideoStream): @@ -70,8 +79,8 @@ def _open(self, frame) -> Tuple[ stream.width = frame.width stream.height = frame.height stream.pix_fmt = self._pixel_format - except (ValueError, OSError, RuntimeError): - container.close() + except BaseException: + self._failures += ("recorder.setup",) raise self._container = container self._stream = stream @@ -93,40 +102,72 @@ def write_frame(self, frame) -> None: container, stream = self._open(frame) for packet in stream.encode(frame): container.mux(packet) - except (ValueError, OSError, RuntimeError) as error: + except BaseException as error: autocontrol_logger.warning( "session_recorder: write failed, stopping: %r", error, ) + self._failures += ("recorder.write",) self._closed = True - self._teardown_locked() + try: + self._teardown_locked() + except BaseException: + raise_caused_run_interruption(error) + raise + raise_caused_run_interruption(error) def stop(self) -> None: """Flush the encoder and close the file.""" with self._lock: - if self._closed: - return self._closed = True self._teardown_locked() + require_retired(self) def _teardown_locked(self) -> None: - container, stream = self._container, self._stream - if stream is not None and container is not None: - try: - for packet in stream.encode(None): - container.mux(packet) - except (ValueError, OSError, RuntimeError) as error: - autocontrol_logger.debug( - "session_recorder: flush failed: %r", error, - ) - if container is not None: - try: - container.close() - except (ValueError, OSError, RuntimeError) as error: - autocontrol_logger.debug( - "session_recorder: close failed: %r", error, - ) + flush_failure = self._flush_once() + close_failure = self._close_once() + for failure in (flush_failure, close_failure): + if failure is not None: + raise_caused_run_interruption(failure) + + def _flush_once(self) -> BaseException | None: + if self._flush is not Completion.PENDING: + return None + self._flush = Completion.UNCERTAIN + try: + if self._stream is not None and self._container is not None: + for packet in self._stream.encode(None): + self._container.mux(packet) + except BaseException as error: # reason: close independently before preserving interruption + self._failures += ("recorder.flush",) + return error + self._flush = Completion.CONFIRMED + return None + + def _close_once(self) -> BaseException | None: + if self._close_attempted: + return None + # PyAV may mark _done after a failed trailer write; replay proves nothing. + self._close_attempted = True + try: + if self._container is not None: + self._container.close() + except BaseException as error: # reason: retain uncertain ownership before preserving interruption + self._release = Completion.UNCERTAIN + self._failures += ("recorder.close",) + return error + self._release = Completion.CONFIRMED self._container = None self._stream = None + return None + + @property + def retirement_status(self) -> RetirementStatus: + with self._lock: + finalized = self._flush + if self._failures: + finalized = Completion.UNCERTAIN + return RetirementStatus(self._closed, self._release, finalized, + False, self._failures) @property def is_active(self) -> bool: diff --git a/je_auto_control/utils/remote_desktop/webrtc_audio.py b/je_auto_control/utils/remote_desktop/webrtc_audio.py index 739ff4dc1..154942ff2 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_audio.py +++ b/je_auto_control/utils/remote_desktop/webrtc_audio.py @@ -22,6 +22,7 @@ try: import av + from av.error import FFmpegError import numpy as np from aiortc import MediaStreamTrack except ImportError as exc: # pragma: no cover - optional dep @@ -29,7 +30,11 @@ "Opus audio uplink requires the 'webrtc' extra (aiortc + av).", ) from exc +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, RetirementStatus, require_retired, raise_cleanup_failures, +) from je_auto_control.utils.remote_desktop.audio import ( AudioBackendError, AudioCapture, AudioPlayer, is_audio_backend_available, ) @@ -84,13 +89,17 @@ def _start_capture(self) -> None: ) def _on_block(self, pcm_bytes: bytes) -> None: + if self.readyState == "ended": + return # Called from the sounddevice thread. try: self._loop.call_soon_threadsafe(self._enqueue, pcm_bytes) - except RuntimeError: - pass # loop closed; drop block silently + except RuntimeError as error: + raise_caused_run_interruption(error) def _enqueue(self, pcm_bytes: bytes) -> None: + if self.readyState == "ended": + return if self._queue.full(): try: self._queue.get_nowait() # drop oldest to keep latency bounded @@ -102,7 +111,12 @@ def _enqueue(self, pcm_bytes: bytes) -> None: pass async def recv(self) -> "av.AudioFrame": + from aiortc.mediastreams import MediaStreamError + if self.readyState == "ended": + raise MediaStreamError pcm_bytes = await self._queue.get() + if pcm_bytes is None or self.readyState == "ended": + raise MediaStreamError samples = np.frombuffer(pcm_bytes, dtype=np.int16) # av.AudioFrame.from_ndarray expects shape (channels, samples) for # planar layouts; for "s16" (interleaved) it expects (1, total). @@ -116,17 +130,37 @@ async def recv(self) -> "av.AudioFrame": self._timestamp += samples.shape[0] // self._channels return frame + def _end_queue(self) -> None: + while not self._queue.empty(): + self._queue.get_nowait() + self._queue.put_nowait(None) + + @property + def retirement_status(self) -> RetirementStatus: + if self._capture is not None: + return self._capture.retirement_status + return RetirementStatus(self.readyState == "ended", Completion.CONFIRMED, + Completion.CONFIRMED) + def stop(self) -> None: + failures = [] try: super().stop() - finally: + except BaseException as error: # reason: attempt independent child cleanup before preserving failures + failures.append(error) + try: + if not self._loop.is_closed(): + self._loop.call_soon_threadsafe(self._end_queue) + except BaseException as error: # reason: attempt independent child cleanup before preserving failures + failures.append(error) + try: with self._lock: if self._capture is not None: - try: - self._capture.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("opus mic stop: %r", error) + self._capture.stop() self._capture = None + except BaseException as error: # reason: attempt independent child cleanup before preserving failures + failures.append(error) + raise_cleanup_failures(failures) class OpusMicReceiver: @@ -147,10 +181,13 @@ def __init__(self, sample_rate: int = _DEFAULT_SAMPLE_RATE, self._player.start() self._task: Optional[asyncio.Task] = None self._stopped = False + self._player_retired = False self._resampler: Optional[Any] = None def consume(self, track) -> None: """Spawn a background task that drains ``track.recv()`` into the player.""" + if self._stopped: + raise AudioBackendError("audio receiver is stopped") if self._task is not None: return self._task = asyncio.ensure_future(self._loop(track)) @@ -160,13 +197,14 @@ async def _loop(self, track) -> None: try: while not self._stopped: frame = await track.recv() - if not bool(self._player.is_running): + if self._stopped or not bool(self._player.is_running): return for chunk in self._to_player_pcm(frame): self._player.play(chunk) except (asyncio.CancelledError, MediaStreamError): autocontrol_logger.info("opus mic receiver ended") except (OSError, RuntimeError) as error: + raise_caused_run_interruption(error) autocontrol_logger.info("opus mic receiver ended: %r", error) def _to_player_pcm(self, frame) -> list: @@ -182,7 +220,8 @@ def _to_player_pcm(self, frame) -> list: ) try: converted = self._resampler.resample(frame) - except (TypeError, ValueError, RuntimeError, av.FFmpegError) as error: # TypeError: not an AudioFrame + except (TypeError, ValueError, RuntimeError, FFmpegError) as error: # TypeError: not an AudioFrame + raise_caused_run_interruption(error) autocontrol_logger.debug("audio frame resample: %r", error) return [] chunks = [] @@ -193,15 +232,46 @@ def _to_player_pcm(self, frame) -> list: chunks.append(arr.tobytes()) return chunks + @property + def retirement_status(self) -> RetirementStatus: + if not self._player_retired: + return self._player.retirement_status + pending = self._task is not None and not self._task.done() + closed_loop = pending and self._task is not None and self._task.get_loop().is_closed() + resources = Completion.CONFIRMED + if pending: + resources = Completion.UNCERTAIN if closed_loop else Completion.PENDING + return RetirementStatus(self._stopped, resources, + Completion.CONFIRMED, pending and not closed_loop, + ("audio.task_pending",) if pending else ()) + def stop(self) -> None: self._stopped = True - if self._task is not None: - self._task.cancel() - self._task = None + failures = [] + try: + self._cancel_task() + except BaseException as error: # reason: attempt independent child cleanup before preserving failures + failures.append(error) try: - self._player.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("audio player stop: %r", error) + if not self._player_retired: + self._player.stop() + self._player_retired = True + except BaseException as error: # reason: attempt independent child cleanup before preserving failures + failures.append(error) + raise_cleanup_failures(failures) + require_retired(self) + + def _cancel_task(self) -> None: + if self._task is None: + return + if self._task.done(): + task, self._task = self._task, None + if not task.cancelled(): + task.result() + return + loop = self._task.get_loop() + if not loop.is_closed(): + loop.call_soon_threadsafe(self._task.cancel) __all__ = ["OpusMicAudioTrack", "OpusMicReceiver"] diff --git a/je_auto_control/utils/remote_desktop/webrtc_mic.py b/je_auto_control/utils/remote_desktop/webrtc_mic.py index e00602c77..69e7d4770 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_mic.py +++ b/je_auto_control/utils/remote_desktop/webrtc_mic.py @@ -17,6 +17,7 @@ import threading from typing import Optional +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.audio import ( AudioBackendError, AudioCapture, AudioPlayer, is_audio_backend_available, @@ -46,6 +47,8 @@ def __init__(self, channel, *, self._device = device self._capture: Optional[AudioCapture] = None self._lock = threading.Lock() + self._stopped = False + self._generation = 0 def start(self) -> None: if not is_audio_backend_available(): @@ -54,9 +57,15 @@ def start(self) -> None: ) with self._lock: if self._capture is not None: - return + if not self._stopped: + return + self._capture.stop() + self._capture = None + self._stopped = True + self._generation += 1 + generation = self._generation capture = AudioCapture( - on_block=self._on_block, + on_block=lambda data: self._on_generation(data, generation), device=self._device, sample_rate=self._sample_rate, channels=self._channels, @@ -64,34 +73,50 @@ def start(self) -> None: ) # Kept only once started: a device that failed to start left it # set, and every later start() returned early. - capture.start() self._capture = capture + try: + capture.start() + except BaseException as error: + try: + capture.stop() + except BaseException: + raise_caused_run_interruption(error) + raise + self._capture = None + raise + self._stopped = False autocontrol_logger.info("mic uplink: capture started (%d Hz)", self._sample_rate) def stop(self) -> None: + self._stopped = True with self._lock: + self._stopped = True if self._capture is None: return - try: - self._capture.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("mic uplink stop: %r", error) + self._capture.stop() self._capture = None def is_running(self) -> bool: return self._capture is not None and bool(self._capture.is_running) def _on_block(self, pcm_bytes: bytes) -> None: - if self._channel is None: + self._on_generation(pcm_bytes, self._generation) + + def _on_generation(self, pcm_bytes: bytes, generation: int) -> None: + if self._stopped or generation != self._generation or self._channel is None: return - get_bridge().call_soon(self._safe_send, pcm_bytes) + get_bridge().call_soon(self._safe_send, pcm_bytes, generation) - def _safe_send(self, data: bytes) -> None: - try: - self._channel.send(data) - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("mic chunk send: %r", error) + def _safe_send(self, data: bytes, generation: int) -> None: + with self._lock: + if self._stopped or generation != self._generation: + return + try: + self._channel.send(data) + except (RuntimeError, OSError) as error: + raise_caused_run_interruption(error) + autocontrol_logger.debug("mic chunk send: %r", error) class MicUplinkReceiver: @@ -106,6 +131,7 @@ def __init__(self, *, self._device = device self._player: Optional[AudioPlayer] = None self._lock = threading.Lock() + self._stopped = False def start(self) -> None: if not is_audio_backend_available(): @@ -114,25 +140,38 @@ def start(self) -> None: ) with self._lock: if self._player is not None: - return + if not self._stopped: + return + self._player.stop() + self._player = None + self._stopped = True player = AudioPlayer( device=self._device, sample_rate=self._sample_rate, channels=self._channels, ) - player.start() # kept only once started, as for the capture self._player = player + try: + player.start() + except BaseException as error: + try: + player.stop() + except BaseException: + raise_caused_run_interruption(error) + raise + self._player = None + raise + self._stopped = False autocontrol_logger.info("mic uplink: playback started (%d Hz)", self._sample_rate) def stop(self) -> None: + self._stopped = True with self._lock: + self._stopped = True if self._player is None: return - try: - self._player.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("mic uplink stop: %r", error) + self._player.stop() self._player = None def is_running(self) -> bool: @@ -144,12 +183,13 @@ def on_chunk(self, chunk) -> None: return with self._lock: player = self._player - if player is None or not bool(player.is_running): - return - try: - player.play(bytes(chunk)) - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("mic playback: %r", error) + if self._stopped or player is None or not bool(player.is_running): + return + try: + player.play(bytes(chunk)) + except (RuntimeError, OSError) as error: + raise_caused_run_interruption(error) + autocontrol_logger.debug("mic playback: %r", error) __all__ = ["MicUplinkSender", "MicUplinkReceiver"] diff --git a/pyproject.toml b/pyproject.toml index ebea2395c..4aa3dfc2b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -356,6 +356,8 @@ ignore_missing_imports = true module = [ "je_auto_control.utils.remote_desktop.webrtc_retirement", "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", + "je_auto_control.utils.remote_desktop.media_retirement", + "je_auto_control.utils.remote_desktop.audio_retirement", "je_auto_control.android.apps", "je_auto_control.android.input", "je_auto_control.android.screen", diff --git a/test/unit_test/headless/test_media_retirement.py b/test/unit_test/headless/test_media_retirement.py new file mode 100644 index 000000000..80b7751d4 --- /dev/null +++ b/test/unit_test/headless/test_media_retirement.py @@ -0,0 +1,579 @@ +"""Producer acknowledgements with fake resources only.""" +import asyncio +import threading +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from je_auto_control.utils.exception.exceptions import AutoControlException +from je_auto_control.utils.remote_desktop import audio, lan_discovery +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, MediaRetirementError, +) + + +class Stream: + def __init__(self, *, fail=(), callback=None, **kwargs): + self.fail = set(fail) + self.callback = callback + self.calls = [] + + def _call(self, step): + self.calls.append(step) + if step in self.fail: + raise OSError(step) + + def start(self): + self._call("start") + + def stop(self, *, ignore_errors): + assert ignore_errors is False + self._call("stop") + + def close(self, *, ignore_errors): + assert ignore_errors is False + self._call("close") + + def write(self, data): + self._call("write") + + +def backend(monkeypatch, fail=()): + streams = [] + + def create(**kwargs): + stream = Stream(fail=fail, **kwargs) + streams.append(stream) + return stream + + monkeypatch.setattr(audio, "_load_sounddevice", lambda: SimpleNamespace( + PortAudioError=OSError, RawInputStream=create, RawOutputStream=create)) + return streams + + +@pytest.mark.parametrize("fail", [("stop",), ("close",), ("stop", "close")]) +def test_audio_failure_is_retained_and_never_replayed(monkeypatch, fail): + streams = backend(monkeypatch, fail) + player = audio.AudioPlayer() + player.start() + for _ in range(2): + with pytest.raises(MediaRetirementError) as caught: + player.stop() + assert caught.value.owner is player + assert isinstance(caught.value, AutoControlException) + assert streams[0].calls == ["start", "stop", "close"] + assert not player.is_running + assert not player.retirement_status.retryable + with pytest.raises(MediaRetirementError): + player.start() + assert len(streams) == 1 + + +def test_audio_failed_start_retains_failed_close(monkeypatch): + streams = backend(monkeypatch, ("start", "close")) + player = audio.AudioPlayer() + with pytest.raises(MediaRetirementError) as caught: + player.start() + assert caught.value.owner is player + assert player._lease.stream is streams[0] + assert streams[0].calls == ["start", "close"] + + +def test_audio_cleanup_does_not_reload_backend(monkeypatch): + streams = backend(monkeypatch) + player = audio.AudioPlayer() + player.start() + monkeypatch.setattr(audio, "_load_sounddevice", lambda: pytest.fail("reload")) + player.stop() + player.stop() + assert streams[0].calls == ["start", "stop", "close"] + assert player.retirement_status.complete + + +def test_capture_inflight_operation_defers_cleanup_and_rejects_old_generation(monkeypatch): + streams = backend(monkeypatch) + entered, release = threading.Event(), threading.Event() + blocks = [] + + def block(data): + blocks.append(data) + entered.set() + assert release.wait(2) + + capture = audio.AudioCapture(block) + capture.start() + old = streams[0] + thread = threading.Thread(target=old.callback, args=(b"one", 1, None, None)) + thread.start() + try: + assert entered.wait(2) + with pytest.raises(MediaRetirementError): + capture.stop() + assert capture.retirement_status.retryable + assert old.calls == ["start"] + old.callback(b"late", 1, None, None) + finally: + release.set() + thread.join(2) + capture.stop() + capture.start() + old.callback(b"replaced", 1, None, None) + assert blocks == [b"one"] + capture.stop() + + +def test_callback_can_request_its_own_retirement_without_deadlock(monkeypatch): + streams = backend(monkeypatch) + results = [] + + def stop(_data): + with pytest.raises(MediaRetirementError): + capture.stop() + results.append(True) + + capture = audio.AudioCapture(stop) + capture.start() + streams[0].callback(b"one", 1, None, None) + assert results == [True] + capture.stop() + + +class Encoder: + def __init__(self, fail=False): + self.calls = [] + self.fail = fail + + def encode(self, frame): + self.calls.append(frame) + yield "packet" + if self.fail: + raise OSError("partial flush") + + +class Container: + def __init__(self, *, fail_close=False, fail_mux=False): + self.close_calls = 0 + self.packets = [] + self.fail_close = fail_close + self.fail_mux = fail_mux + + def mux(self, packet): + self.packets.append(packet) + if self.fail_mux: + raise OSError("partial mux") + + def close(self): + self.close_calls += 1 + if self.fail_close: + raise OSError("trailer") + + +@pytest.mark.parametrize("flush,mux,close", [(True, False, False), (False, True, False), + (False, False, True), (True, False, True)]) +def test_recorder_uncertain_flush_or_close_never_becomes_saved(flush, mux, close): + from je_auto_control.utils.remote_desktop.session_recorder import SessionRecorder + recorder = SessionRecorder("unused.mp4") + stream, container = Encoder(flush), Container(fail_close=close, fail_mux=mux) + recorder._stream, recorder._container = stream, container + for _ in range(2): + with pytest.raises(MediaRetirementError): + recorder.stop() + assert stream.calls == [None] + assert container.packets == ["packet"] + assert container.close_calls == 1 + assert recorder.retirement_status.finalization is Completion.UNCERTAIN + assert not recorder.retirement_status.retryable + if close: + assert recorder._container is container + + +def test_recorder_setup_failure_retains_container_when_close_fails(monkeypatch): + from je_auto_control.utils.remote_desktop import session_recorder + container = Container(fail_close=True) + container.add_stream = lambda *args, **kwargs: object() + monkeypatch.setattr(Path, "mkdir", lambda *args, **kwargs: None) + monkeypatch.setattr(session_recorder.av, "open", lambda *args, **kwargs: container) + recorder = session_recorder.SessionRecorder("unused.mp4") + recorder.write_frame(SimpleNamespace(width=1, height=1)) + assert recorder._container is container + assert not recorder.is_active + with pytest.raises(MediaRetirementError): + recorder.stop() + assert container.close_calls == 1 + + +def advertiser(monkeypatch, *, fail_unregister=False, close_failures=0): + calls = [] + + def unregister(_info): + calls.append("unregister") + if fail_unregister: + raise OSError("goodbye") + + def close(): + calls.append("close") + if calls.count("close") <= close_failures: + raise OSError("close") + + zc = SimpleNamespace(register_service=lambda info: None, + unregister_service=unregister, close=close) + monkeypatch.setattr(lan_discovery, "_AVAILABLE", True) + monkeypatch.setattr(lan_discovery, "Zeroconf", lambda: zc) + monkeypatch.setattr(lan_discovery, "ServiceInfo", lambda *a, **k: object()) + monkeypatch.setattr(lan_discovery, "_local_ip", lambda: "127.0.0.1") + monkeypatch.setattr(lan_discovery.socket, "gethostname", lambda: "fake") + return lan_discovery.HostAdvertiser(host_id="fake"), calls, zc + + +def test_advertiser_retry_closes_original_without_repeating_unregister(monkeypatch): + owner, calls, zc = advertiser(monkeypatch, close_failures=1) + with pytest.raises(MediaRetirementError) as caught: + owner.stop() + assert caught.value.owner is owner and owner._zc is zc + assert owner.retirement_status.retryable + owner.stop() + owner.stop() + assert calls == ["unregister", "close", "close"] + + +def test_advertiser_closed_does_not_prove_goodbye(monkeypatch): + owner, calls, _ = advertiser(monkeypatch, fail_unregister=True) + for _ in range(2): + with pytest.raises(MediaRetirementError): + owner.stop() + assert owner.retirement_status.resources is Completion.CONFIRMED + assert owner.retirement_status.finalization is Completion.UNCERTAIN + assert not owner.retirement_status.retryable + assert calls == ["unregister", "close"] + + +def test_advertiser_constructor_error_hands_out_cleanup_owner(monkeypatch): + owner, _, zc = advertiser(monkeypatch, close_failures=1) + zc.register_service = lambda info: (_ for _ in ()).throw(OSError("register")) + with pytest.raises(MediaRetirementError) as caught: + lan_discovery.HostAdvertiser(host_id="another") + assert caught.value.owner is not owner + caught.value.owner.stop() + + +def test_opus_receiver_retains_pending_task_until_observed(monkeypatch): + from je_auto_control.utils.remote_desktop import webrtc_audio + monkeypatch.setattr(webrtc_audio, "is_audio_backend_available", lambda: True) + monkeypatch.setattr(webrtc_audio, "AudioPlayer", lambda **kw: SimpleNamespace( + start=lambda: None, stop=lambda: None)) + + async def run(): + receiver = webrtc_audio.OpusMicReceiver() + task = asyncio.create_task(asyncio.sleep(100)) + receiver._task = task + with pytest.raises(MediaRetirementError): + receiver.stop() + assert receiver._task is task + with pytest.raises(RuntimeError): + receiver.consume(object()) + await asyncio.gather(task, return_exceptions=True) + receiver.stop() + assert receiver.retirement_status.complete + + asyncio.run(run()) + + +def test_recorder_success_is_idempotent_and_rejects_late_frames(): + from je_auto_control.utils.remote_desktop.session_recorder import SessionRecorder + recorder = SessionRecorder("unused.mp4") + stream, container = Encoder(), Container() + recorder._stream, recorder._container = stream, container + recorder.stop() + recorder.write_frame(object()) + recorder.stop() + assert recorder.retirement_status.complete + assert stream.calls == [None] and container.close_calls == 1 + + +def test_host_audio_failure_does_not_skip_socket_or_client_cleanup(): + from je_auto_control.utils.remote_desktop.host import RemoteDesktopHost + calls = [] + + def failed_stop(): + calls.append("audio") + raise OSError("retained failure") + + host = object.__new__(RemoteDesktopHost) + capture = SimpleNamespace(stop=failed_stop) + host._audio_capture = capture + host._lifecycle_lock = threading.Lock() + host._shutdown = threading.Event() + host._listen_sock = SimpleNamespace(close=lambda: calls.append("socket")) + host._frame_cond = threading.Condition() + host._clients_lock = threading.Lock() + host._clients = [SimpleNamespace(stop=lambda: calls.append("client"))] + host._file_receiver = None + host._accept_thread = host._capture_thread = host._cursor_thread = None + with pytest.raises(OSError): + host.stop() + assert calls == ["audio", "socket", "client"] + assert host._audio_capture is capture + with pytest.raises(OSError): + host.stop() + assert calls[-1] == "audio" + + +def test_opus_capture_failure_retains_child_and_wakes_recv(monkeypatch): + from aiortc.mediastreams import MediaStreamError + from je_auto_control.utils.remote_desktop import webrtc_audio + streams = backend(monkeypatch, ("close",)) + monkeypatch.setattr(webrtc_audio, "is_audio_backend_available", lambda: True) + + async def run(): + track = webrtc_audio.OpusMicAudioTrack() + receive = asyncio.create_task(track.recv()) + await asyncio.sleep(0) + child = track._capture + with pytest.raises(MediaRetirementError): + track.stop() + assert track._capture is child and track.readyState == "ended" + with pytest.raises(MediaStreamError): + await asyncio.wait_for(receive, 1) + track._enqueue(b"late") + assert track._queue.empty() + + asyncio.run(run()) + assert streams[0].calls == ["start", "stop", "close"] + + +def test_mic_queued_send_does_not_cross_replacement_generation(monkeypatch): + from je_auto_control.utils.remote_desktop import webrtc_mic + backend(monkeypatch) + queued, sent = [], [] + monkeypatch.setattr(webrtc_mic, "is_audio_backend_available", lambda: True) + monkeypatch.setattr(webrtc_mic, "get_bridge", lambda: SimpleNamespace( + call_soon=lambda fn, *args: queued.append((fn, args)))) + sender = webrtc_mic.MicUplinkSender(SimpleNamespace(send=sent.append)) + sender.start() + sender._on_block(b"old") + sender.stop() + sender.start() + for fn, args in queued: + fn(*args) + assert sent == [] + sender.stop() + + +def interruption(wrapped): + from je_auto_control.utils.exception.control_signals import OperationCancelledError + signal = OperationCancelledError("fake") + error = RuntimeError("wrapped") if wrapped else signal + if wrapped: + error.__cause__ = signal + return signal, error + + +@pytest.mark.parametrize("wrapped", [False, True]) +@pytest.mark.parametrize("producer", ["audio", "recorder", "advertiser"]) +def test_interruption_identity_survives_independent_close(monkeypatch, producer, wrapped): + signal, error = interruption(wrapped) + + def interrupted(*args, **kwargs): + raise error + + if producer == "audio": + streams = backend(monkeypatch) + owner = audio.AudioPlayer() + owner.start() + streams[0].stop = interrupted + def closed(): + return "close" in streams[0].calls + elif producer == "recorder": + from je_auto_control.utils.remote_desktop.session_recorder import SessionRecorder + owner = SessionRecorder("unused.mp4") + container = Container() + owner._container = container + owner._stream = SimpleNamespace(encode=interrupted) + def closed(): + return container.close_calls == 1 + else: + owner, calls, zc = advertiser(monkeypatch) + zc.unregister_service = interrupted + def closed(): + return "close" in calls + with pytest.raises(type(signal)) as caught: + owner.stop() + assert caught.value is signal + assert closed() + + +def test_play_during_factory_acquisition_is_rejected(monkeypatch): + entered, release = threading.Event(), threading.Event() + streams = backend(monkeypatch) + original = audio._load_sounddevice() + + def factory(**kwargs): + entered.set() + assert release.wait(2) + return original.RawOutputStream(**kwargs) + + monkeypatch.setattr(audio, "_load_sounddevice", lambda: SimpleNamespace( + PortAudioError=OSError, RawOutputStream=factory)) + player = audio.AudioPlayer() + thread = threading.Thread(target=player.start) + thread.start() + try: + assert entered.wait(2) + assert not player.is_running + with pytest.raises(RuntimeError): + player.play(b"pcm") + finally: + release.set() + thread.join(2) + player.stop() + assert streams[0].calls == ["start", "stop", "close"] + + +def test_opus_loop_close_race_does_not_skip_capture_cleanup(monkeypatch): + from je_auto_control.utils.remote_desktop import webrtc_audio + streams = backend(monkeypatch) + monkeypatch.setattr(webrtc_audio, "is_audio_backend_available", lambda: True) + + def broken_schedule(*args): + raise RuntimeError("loop closed") + + async def run(): + track = webrtc_audio.OpusMicAudioTrack() + track._loop = SimpleNamespace(is_closed=lambda: False, + call_soon_threadsafe=broken_schedule) + with pytest.raises(RuntimeError, match="loop closed"): + track.stop() + assert track._capture is None + + asyncio.run(run()) + assert streams[0].calls == ["start", "stop", "close"] + + +def test_opus_done_task_failure_is_observed_once_after_player_cleanup(monkeypatch): + from je_auto_control.utils.remote_desktop import webrtc_audio + streams = backend(monkeypatch) + monkeypatch.setattr(webrtc_audio, "is_audio_backend_available", lambda: True) + signal, error = interruption(True) + + async def fail(): + raise error + + async def run(): + receiver = webrtc_audio.OpusMicReceiver() + receiver._task = asyncio.create_task(fail()) + await asyncio.sleep(0) + with pytest.raises(type(signal)) as caught: + receiver.stop() + assert caught.value is signal + assert receiver._task is None + assert receiver._player_retired + receiver.stop() + assert receiver.retirement_status.complete + + asyncio.run(run()) + assert streams[0].calls == ["start", "stop", "close"] + + +def test_mic_retained_failure_refuses_new_start(monkeypatch): + from je_auto_control.utils.remote_desktop import webrtc_mic + streams = backend(monkeypatch, ("close",)) + monkeypatch.setattr(webrtc_mic, "is_audio_backend_available", lambda: True) + sender = webrtc_mic.MicUplinkSender(object()) + sender.start() + child = sender._capture + with pytest.raises(MediaRetirementError): + sender.stop() + with pytest.raises(MediaRetirementError): + sender.start() + assert sender._capture is child and len(streams) == 1 + + +def test_audio_hard_interrupt_still_attempts_close(monkeypatch): + streams = backend(monkeypatch) + owner = audio.AudioPlayer() + owner.start() + signal = KeyboardInterrupt() + + def interrupted(**kwargs): + raise signal + + streams[0].stop = interrupted + with pytest.raises(KeyboardInterrupt) as caught: + owner.stop() + assert caught.value is signal + assert streams[0].calls == ["start", "close"] + + +def test_constructor_interruption_has_explicit_original_cleanup_owner(monkeypatch): + from je_auto_control.utils.remote_desktop.media_retirement import interrupted_retirement_owners + _, _, zc = advertiser(monkeypatch, close_failures=1) + signal, error = interruption(True) + + def interrupted(_info): + raise error + + zc.register_service = interrupted + with pytest.raises(type(signal)) as caught: + lan_discovery.HostAdvertiser(host_id="interrupted") + assert caught.value is signal + (owner,) = interrupted_retirement_owners(signal) + assert owner._zc is zc and owner.retirement_status.retryable + owner.stop() + assert owner.retirement_status.complete + + +@pytest.mark.parametrize("kind", ["sender", "receiver"]) +def test_mic_stop_waiting_for_start_keeps_admission_closed(monkeypatch, kind): + from je_auto_control.utils.remote_desktop import webrtc_mic + entered, release, stopping = threading.Event(), threading.Event(), threading.Event() + children, sent = [], [] + + class Child: + def __init__(self, **kwargs): + self.callback = kwargs.get("on_block") + children.append(self) + + def start(self): + entered.set() + assert release.wait(2) + + def stop(self): + pass + + class Lock: + def __init__(self): + self.lock = threading.Lock() + + def __enter__(self): + if threading.current_thread().name == "retire": + stopping.set() + self.lock.acquire() + + def __exit__(self, *args): + self.lock.release() + + monkeypatch.setattr(webrtc_mic, "is_audio_backend_available", lambda: True) + monkeypatch.setattr(webrtc_mic, "AudioCapture", Child) + monkeypatch.setattr(webrtc_mic, "AudioPlayer", Child) + monkeypatch.setattr(webrtc_mic, "get_bridge", lambda: SimpleNamespace( + call_soon=lambda fn, *args: fn(*args))) + owner = (webrtc_mic.MicUplinkSender(SimpleNamespace(send=sent.append)) if kind == "sender" + else webrtc_mic.MicUplinkReceiver()) + owner._lock = Lock() + starter = threading.Thread(target=owner.start) + stopper = threading.Thread(target=owner.stop, name="retire") + starter.start() + try: + assert entered.wait(2) + stopper.start() + assert stopping.wait(2) + finally: + release.set() + starter.join(2) + if stopper.ident is not None: + stopper.join(2) + assert owner._stopped + if kind == "sender": + children[0].callback(b"late PCM") + assert sent == [] diff --git a/test/unit_test/headless/test_remote_desktop_audio.py b/test/unit_test/headless/test_remote_desktop_audio.py index a30d74cb8..ab73a2bb9 100644 --- a/test/unit_test/headless/test_remote_desktop_audio.py +++ b/test/unit_test/headless/test_remote_desktop_audio.py @@ -30,10 +30,10 @@ def __init__(self, *, callback=None, **_kwargs) -> None: def start(self) -> None: self.started = True - def stop(self) -> None: + def stop(self, ignore_errors=True) -> None: self.started = False - def close(self) -> None: + def close(self, ignore_errors=True) -> None: self.closed = True @@ -135,7 +135,7 @@ def __init__(self) -> None: def start(self) -> None: self.started = True - def stop(self) -> None: + def stop(self, ignore_errors=True) -> None: self.stopped = True diff --git a/test/unit_test/headless/test_webrtc_media_audit.py b/test/unit_test/headless/test_webrtc_media_audit.py index fd119ee09..afbe7fd4c 100644 --- a/test/unit_test/headless/test_webrtc_media_audit.py +++ b/test/unit_test/headless/test_webrtc_media_audit.py @@ -37,10 +37,10 @@ def write(self, _data): if self.fail_write: raise _PortAudioError("device removed") - def stop(self): + def stop(self, ignore_errors=True): pass - def close(self): + def close(self, ignore_errors=True): self.closed = True @@ -103,7 +103,7 @@ class _Zeroconf: def register_service(self, _info): raise RuntimeError("NonUniqueNameException") - def close(self): + def close(self, ignore_errors=True): closed.append(True) monkeypatch.setattr(lan_discovery, "_AVAILABLE", True) diff --git a/test/unit_test/headless/test_webrtc_opus_audio.py b/test/unit_test/headless/test_webrtc_opus_audio.py index 7fdcc27fb..80243f5dd 100644 --- a/test/unit_test/headless/test_webrtc_opus_audio.py +++ b/test/unit_test/headless/test_webrtc_opus_audio.py @@ -262,11 +262,13 @@ def test_a_capture_that_fails_to_close_still_leaves_the_track_stopped(): async def _drive(): track = OpusMicAudioTrack() _FakeCapture.instances[0].stop_error = OSError("device unplugged") - track.stop() + with pytest.raises(OSError): + track.stop() return track track = asyncio.run(_drive()) - assert track._capture is None + assert track.readyState == "ended" + assert track._capture is _FakeCapture.instances[0] # --- the host's inbound receiver ---------------------------------------------- @@ -386,9 +388,12 @@ async def _drive(): receiver = OpusMicReceiver() receiver.consume(FrameTrack(_frame(np.array([[1]], dtype=np.int16)))) task = receiver._task + with pytest.raises(RuntimeError): + receiver.stop() + assert receiver._task is task + await asyncio.sleep(0) receiver.stop() assert receiver._task is None - await asyncio.sleep(0) return task task = asyncio.run(_drive()) @@ -402,8 +407,10 @@ def test_stopping_a_receiver_that_never_consumed_still_closes_the_player(): assert _FakePlayer.instances[0].stopped -def test_a_player_that_fails_to_close_does_not_escape_stop(monkeypatch): +def test_a_player_that_fails_to_close_is_reported_and_retained(monkeypatch): receiver = OpusMicReceiver() monkeypatch.setattr( _FakePlayer.instances[0], "stop_error", OSError("stream already closed")) - receiver.stop() + with pytest.raises(OSError): + receiver.stop() + assert receiver._player is _FakePlayer.instances[0] From 578fb0e6c916a950736d14c8582944db580d5b25 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 19:42:17 +0800 Subject: [PATCH 038/161] Protect REST operational records and restore dashboard success status --- CHANGELOG.md | 6 ++ Progress.md | 2 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 12 +-- .../operations_layer/operations_layer_doc.rst | 19 +++- .../operations_layer/operations_layer_doc.rst | 18 ++-- docs/updates/2026-11-b.md | 6 ++ docs/updates/README.md | 3 +- je_auto_control/utils/rbac/policy.py | 18 ++-- .../utils/rest_api/dashboard/app.js | 1 + .../headless/test_capability_data_parity.py | 22 +++++ .../headless/test_rest_read_data_routes.py | 87 ++++++++++++++++--- 14 files changed, 161 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dadd245b1..809847a1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- Require `read_data` for USB enumeration/events, retained inspector statistics and + process metrics over REST, and for the four matching registered AC reads. + Viewer denial happens before providers or metrics child queries execute; + operator/admin and legacy shared-token access remain supported. Session dashboard + refresh also clears a prior error after access is restored. + - Retain original audio, recording and LAN advertisement cleanup outcomes. Reject unsafe flush/close replay and report pending work or uncertain finalization through typed errors. Application caretaker and GUI integration remain pending. diff --git a/Progress.md b/Progress.md index 55ea35a6f..0f2409c6c 100644 --- a/Progress.md +++ b/Progress.md @@ -143,7 +143,7 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - `ac_list_plugins` 的外掛 factory,以及 `ac_web_list_commands`/`ac_web_current_url` 的實際相依版本初始化契約尚待審查;目前不列入唯讀目錄,完整目錄仍要求 `read_data`。本機 sibling 原始碼不代表部署版本驗收。 - `ac_diagnose` 的預設 audit-log 初始化可能建立固定目錄及 SQLite schema;全域零寫入診斷與外部 SDK 初始化副作用仍未驗證。 - - 尚需審查未列入 `COMMAND_CAPABILITIES` 的 executor 指令與 REST-only USB device/event、inspector 路由的資料權限;未列指令目前仍依賴提交入口授權,不能把已核對的 MCP/REST/指令配對視為完整分類。 + - 尚需完整審查未列入 `COMMAND_CAPABILITIES` 的 executor 指令;未列指令目前仍依賴提交入口授權,不能把已核對的指令視為完整分類。若改為執行時預設拒絕,須同時處理預檢中的動作清單與一般資料串列,避免誤拒正常資料。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, diff --git a/README.md b/README.md index e1ba6cfa7..175740650 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ Host-requested file sends remain owned until their sender worker exits, includin MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. -REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. Dashboard panels report missing capabilities independently. +REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. USB enumeration/events, retained inspector statistics and process metrics also require `read_data`, as do `AC_list_usb_devices`, `AC_usb_recent_events`, `AC_inspector_recent` and `AC_inspector_summary`. Dashboard panels report missing capabilities independently and clear stale rows. A successful session refresh also clears its previous error status. Unlisted executor-command authorization remains a separate audit scope. Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 9395c8ac9..06e853cd1 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -75,7 +75,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStop MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 -REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。Dashboard 各面板分别显示缺少的权限。 +REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。USB 枚举/事件、保留的 inspector 统计与进程 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同样检查此权限。Dashboard 各面板分别显示缺少的权限并清除旧数据;session 刷新成功后也会清除先前的错误状态。未列入权限表的 executor 命令仍属于另一项审查范围。 主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 74451300c..9edebc9b9 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -75,7 +75,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStop MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 -REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。Dashboard 各面板分別顯示缺少的權限。 +REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。USB 列舉/事件、保留的 inspector 統計與程序 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同樣檢查此權限。Dashboard 各面板分別顯示缺少的權限並清除舊資料;session 重新整理成功後也會清除先前的錯誤狀態。未列入權限表格的 executor 指令仍屬另一項審查範圍。 主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 diff --git a/architecture_explore.md b/architecture_explore.md index b9e6f9269..4d099e70c 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,524 | -| 程式碼總行數 | 232,645 | +| 程式碼總行數 | 232,649 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,459 行。 +> 13 個套件、約 4,463 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -674,7 +674,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/governance/` | 243 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | -| `utils/rbac/` | 1,712 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | +| `utils/rbac/` | 1,716 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | @@ -1439,7 +1439,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `scripts/dev_release.py` | 只用標準函式庫的發佈輔助腳本 | dev 通道(PyPI 的 `je_auto_control_dev`)的版本與比對:`prepare` 把 `dev.toml` 寫成 `pyproject.toml`,版本取 PyPI 最新一版加一個 patch(`dev.toml` 的版本只是下限,不回寫 repo);`changed dist` 把建好的 wheel 跟 PyPI 最新一版逐檔比對,內容沒變就不上傳。只給 `dev.yml` 的 `publish-dev` job 與拋棄式的 checkout 用,因為 `prepare` 會蓋掉 `pyproject.toml`。 | | `docs/` | Sphinx(`API`/`Eng`/`Zh`/`getting_started`) | Read the Docs 文件。 | | `architecture_diagram/` | drawio + png | 既有的架構圖原始檔。 | -| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,187 個 `test_*.py`/11,543 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | +| `test/` | `unit_test/headless`(主要)、`unit_test/flow_control`、`integrated_test`、`gui_test`、`manual_test`、`verify`、`test_source` | 1,187 個 `test_*.py`/11,546 個測試函式。**注意**:`test/unit_test/` 下的 `*_test.py` 是會真的驅動滑鼠鍵盤的手動示範腳本,因此 `pyproject.toml` 把 `python_files` 釘成 `test_*.py`。`unit_test/headless/conftest.py` 有一個 autouse fixture,每個測試結束都沖掉 Qt 排隊中的 `deleteLater()`——不沖會讓殘留的 widget 在後面某個不相干的測試裡被銷毀,曾經整個直譯器 `__fastfail`。`test_doc_counts.py` 守住文件引用的指令/工具/子套件/範例數,`test_doc_line_counts.py` 守住所有行數(`--fix` 可一次重新產生)。 `verify/macos_verify.py` 是在真的 `macos-14` runner 上量測 TCC 到底允許什麼的探針(macOS 是唯一沒有容器可用的支援平台),不被 pytest 收集。 | --- @@ -1550,8 +1550,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,042 | -| **總計** | **1,512** | **231,900** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,046 | +| **總計** | **1,512** | **231,904** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index edc0fc822..540ad5ebf 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -242,13 +242,14 @@ rotated token or a changed role applies to the next request. * - ``read_screen`` - viewer, operator, admin - ``GET /screenshot``, ``/mouse_position``, ``/screen_size``, ``/windows``, - ``/commands``, ``/inspector/recent``, ``/inspector/summary``, - ``/usb/devices``, ``/usb/events``, ``/metrics``, ``/openapi.json`` + ``/commands``, ``/openapi.json`` * - ``read_data`` - operator, admin - ``GET /history``, ``/usb/acl``, ``/jobs``, ``/sessions``, ``/usb/passthrough/status``, ``/usb/loopback/devices``, - ``/usb/remote/devices``, ``/diagnose``; matching MCP host-data reads + ``/usb/remote/devices``, ``/diagnose``, ``/usb/devices``, ``/usb/events``, + ``/inspector/recent``, ``/inspector/summary``, ``/metrics``; + matching MCP host-data reads * - ``drive_input`` - operator, admin - ``POST /execute``, ``/execute_file``, ``/usb/loopback/open``, @@ -281,6 +282,15 @@ routes now match the MCP tools reading the same sources. ``/diagnose`` also requ A viewer receives 403 before a provider runs; operator/admin and shared-token servers without a user store retain their existing access. +USB enumeration returns device identity metadata, including serial and bus location; +USB events retain add/remove records. Inspector endpoints return process-wide numeric +WebRTC history and summaries, not a caller-scoped stream. Metrics expose aggregate +request/authentication counters, audit-row count, active-session/job counts and uptime. +These five REST reads require ``read_data``. Metrics checks authorization on its +special text-response path before querying audit, registry or scheduler providers. +``AC_list_usb_devices``, ``AC_usb_recent_events``, ``AC_inspector_recent`` and +``AC_inspector_summary`` enforce the same data requirement before provider dispatch. + The registered commands ``AC_probe_capabilities``, ``AC_diagnose``, ``AC_remote_host_status``, ``AC_remote_viewer_status``, ``AC_usb_passthrough_status``, ``AC_usb_loopback_list`` and ``AC_usb_remote_list`` enforce the same data authority. @@ -290,8 +300,9 @@ calls outside an authorization scope retain their existing behavior. This audit not classify all unlisted executor commands: those still rely on their entry surface. Dashboard panels retain their functionality and independently display missing -capabilities. Diagnostics and sessions require ``read_data``; audit requires +capabilities. Diagnostics, sessions, inspector and USB panels require ``read_data``; audit requires ``read_audit``. Refused panels clear their rows while other panels keep refreshing. +A successful session refresh clears any previous error status. The source-pairing regression continues to reject REST/MCP policy disagreements. Being allowed to ``POST /execute`` is being allowed to run actions, not every diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index ce250fc20..276dd0d0a 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -211,13 +211,13 @@ token 控制項。Python 伺服器的 ``token`` 屬性仍保留設定的共用 t * - ``read_screen`` - viewer、operator、admin - ``GET /screenshot``、``/mouse_position``、``/screen_size``、``/windows``、 - ``/commands``、``/inspector/recent``、``/inspector/summary``、 - ``/usb/devices``、``/usb/events``、``/metrics``、``/openapi.json`` + ``/commands``、``/openapi.json`` * - ``read_data`` - operator、admin - ``GET /history``、``/usb/acl``、``/jobs``、``/sessions``、 ``/usb/passthrough/status``、``/usb/loopback/devices``、 - ``/usb/remote/devices``、``/diagnose``,及對應的 MCP 主機資料讀取 + ``/usb/remote/devices``、``/diagnose``、``/usb/devices``、``/usb/events``、 + ``/inspector/recent``、``/inspector/summary``、``/metrics``,及對應 MCP 主機資料讀取 * - ``drive_input`` - operator、admin - ``POST /execute``、``/execute_file``、``/usb/loopback/open``、 @@ -247,6 +247,13 @@ token 控制項。Python 伺服器的 ``token`` 屬性仍保留設定的共用 t ``read_data``:檢查會讀取主機環境,並可能主動擷取畫面。viewer 在提供者執行前 收到 403;operator/admin 及未使用使用者存放檔的共用 token 伺服器維持原存取權。 +USB 列舉回傳裝置身分中繼資料,包括序號與 bus location;事件保留新增/移除紀錄。 +Inspector 端點回傳整個程序的 WebRTC 數值歷史與摘要,不依呼叫者區分。Metrics 回傳 +請求/驗證計數、稽核筆數、連線/排程數量及執行時間。這五個 REST 讀取需要 +``read_data``;metrics 的特殊文字回應入口會在查詢稽核、registry、scheduler 前檢查。 +``AC_list_usb_devices``、``AC_usb_recent_events``、``AC_inspector_recent`` 與 +``AC_inspector_summary`` 也會在執行提供者之前檢查相同資料權限。 + 已註冊的 ``AC_probe_capabilities``、``AC_diagnose``、``AC_remote_host_status``、 ``AC_remote_viewer_status``、``AC_usb_passthrough_status``、``AC_usb_loopback_list`` 與 ``AC_usb_remote_list`` 也要求相同資料權限。被動能力探測仍讀取環境/PATH 與 @@ -254,8 +261,9 @@ token 控制項。Python 伺服器的 ``token`` 屬性仍保留設定的共用 t 直接呼叫維持原行為。本次審查沒有涵蓋所有未列入表格的 executor 指令;那些指令 仍依賴接收請求入口的權限。 -Dashboard 保留功能,各面板分別顯示缺少的權限。診斷與 session 需要 ``read_data``, -稽核需要 ``read_audit``;被拒面板清除舊資料,其他面板持續更新。來源配對測試仍會 +Dashboard 保留功能,各面板分別顯示缺少的權限。診斷、session、inspector 與 USB 面板需要 ``read_data``, +稽核需要 ``read_audit``;被拒面板清除舊資料,其他面板持續更新。 +session 重新整理成功後會清除先前的錯誤狀態。來源配對測試仍會 拒絕 REST 與 MCP 的權限不一致。 可以 ``POST /execute`` 代表可以執行動作,不代表可以執行每一個指令。替動作檔簽章 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 1661dcf70..9bd732a5f 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -96,3 +96,9 @@ - **Evidence:** Writer verification passed a 90-case audited scope; final cleanup passed 34 injected producer cases and three-target typing for eight modules. Independent narrowed producer/structural verification passed 49 cases. Parent integration passed 49 producer/structural cases and 204 producer, Opus, peer lifecycle and document/complexity cases, plus warnings-as-errors Sphinx. Production text matches the reviewed source. Ruff, Bandit, Pylint errors, complexity and file budgets passed. Installed SDK source explains why sounddevice and PyAV failed closes cannot be verified by replaying a no-op close. - **Validation scope:** Focused acceptance uses injected resources and event-loop tasks. An earlier reviewer run passed 72 cases but also included loopback TCP tests and a UDP route lookup; it is not fake-only or native media acceptance. No actual audio device, desktop input or capture was tested. - **Open items:** Peer constructor/replacement/discard ownership, HostBrowser, GUI saved/failed reporting, durable caretaker and original-authority Diagnostics retry remain in Progress.md. Producer outcomes alone do not make every consumer durable; terminal uncertainty must not become success through generic retry. + +## U-20261111-29 · 2026-11-11 · Protect remaining REST operational records and restore dashboard status · #done #security + +- **What:** USB enumeration/events, retained inspector statistics and process metrics now require read_data over REST; four registered USB/inspector commands enforce the same authority. Metrics authorization occurs before audit/session/scheduler child queries. Operator/admin and legacy shared-token access remain supported. Session dashboard refresh now clears an earlier refusal after access is restored. +- **Evidence:** Source audit traced the exact operational/device fields and registered command aliases. Author checks passed 484 cases; parent integration passed 69 focused cases, 49 document/quality gates and warnings-as-errors Sphinx. Fake-DOM execution of actual dashboard JavaScript verified downgrade clears stale rows and one refused panel does not stop permitted panels. Parent extended that probe to reproduce stale session error status after role restoration, then verified the one-line correction. No browser or native device enumeration ran; REST transport tests used loopback with fake providers. +- **Open items:** General unlisted executor-command policy and action-list versus ordinary-data preflight remain separate work in Progress.md. This does not claim a sandbox for trusted host Python or a new whole-suite result. diff --git a/docs/updates/README.md b/docs/updates/README.md index e041ccdbc..f9ddb969d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-29 | 2026-11-11 | Protect remaining REST operational records and restore dashboard status | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-28 | 2026-11-11 | Preserve media producer retirement outcomes and original resources | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-27 | 2026-11-11 | Await actual file sender completion after cancellation | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-26 | 2026-11-11 | Enforce host-data authority across REST and executor reads | #done #security | [2026-11-b](2026-11-b.md) | @@ -647,7 +648,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 17 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 18 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/rbac/policy.py b/je_auto_control/utils/rbac/policy.py index 122656e3f..4acf0456d 100644 --- a/je_auto_control/utils/rbac/policy.py +++ b/je_auto_control/utils/rbac/policy.py @@ -50,7 +50,7 @@ ("GET", "/agent/task"): _DRIVE, ("POST", "/agent/shutdown"): _HOSTS, ("POST", "/agent/recover_target"): _HOSTS, - ("GET", "/metrics"): _READ, + ("GET", "/metrics"): _DATA, ("GET", "/jobs"): _DATA, ("GET", "/history"): _DATA, # run history, as ac_list_run_history ("GET", "/screenshot"): _READ, @@ -59,10 +59,10 @@ ("GET", "/windows"): _READ, ("GET", "/sessions"): _DATA, ("GET", "/commands"): _READ, - ("GET", "/inspector/recent"): _READ, - ("GET", "/inspector/summary"): _READ, - ("GET", "/usb/devices"): _READ, - ("GET", "/usb/events"): _READ, + ("GET", "/inspector/recent"): _DATA, + ("GET", "/inspector/summary"): _DATA, + ("GET", "/usb/devices"): _DATA, + ("GET", "/usb/events"): _DATA, ("GET", "/usb/passthrough/status"): _DATA, ("GET", "/usb/acl"): _DATA, # the stored ACL, as ac_usb_acl_list ("GET", "/usb/loopback/devices"): _DATA, @@ -89,8 +89,8 @@ "transfer", "transfer/peer")}) #: The routes that need ``read_data``: the ones returning records or -#: configuration the host keeps, by the rule :data:`DATA_TOOLS` states. Each -#: has an MCP tool reading the same thing, and the two must agree. +#: configuration the host keeps, by the rule :data:`DATA_TOOLS` states. Where +#: an MCP tool reads the same source, the requirements must agree. DATA_ROUTES = frozenset( route for route, needed in REST_ROUTE_CAPABILITIES.items() if needed == _DATA) @@ -108,6 +108,10 @@ "AC_usb_passthrough_status": _DATA, "AC_usb_loopback_list": _DATA, "AC_usb_remote_list": _DATA, + "AC_list_usb_devices": _DATA, + "AC_usb_recent_events": _DATA, + "AC_inspector_recent": _DATA, + "AC_inspector_summary": _DATA, "AC_mcp_tool_search": _READ, "AC_mcp_tool_schema": _READ, "AC_history_capture": _DRIVE, diff --git a/je_auto_control/utils/rest_api/dashboard/app.js b/je_auto_control/utils/rest_api/dashboard/app.js index 98789f1df..5063fa28e 100644 --- a/je_auto_control/utils/rest_api/dashboard/app.js +++ b/je_auto_control/utils/rest_api/dashboard/app.js @@ -160,6 +160,7 @@ async function refreshDiagnostics() { async function refreshSessions() { try { const data = await fetchJson("/sessions"); + setPanelStatus("sessions", "Updated", "ok"); panelEl("sessions").querySelector("[data-rows]").textContent = JSON.stringify(data, null, 2); } catch (error) { diff --git a/test/unit_test/headless/test_capability_data_parity.py b/test/unit_test/headless/test_capability_data_parity.py index c4ce55cfb..da0958234 100644 --- a/test/unit_test/headless/test_capability_data_parity.py +++ b/test/unit_test/headless/test_capability_data_parity.py @@ -52,3 +52,25 @@ def read(): reply = json.loads(server.handle_line(json.dumps(request))) assert not reply["result"]["isError"] assert calls == [name, name, name] + + +@pytest.mark.parametrize("command", ["AC_list_usb_devices", "AC_usb_recent_events", + "AC_inspector_recent", "AC_inspector_summary"]) +@pytest.mark.parametrize("strict", [False, True]) +def test_device_and_telemetry_commands_refuse_viewer_before_provider(command, strict, monkeypatch): + calls = [] + monkeypatch.setitem(ac.executor.event_dict, command, lambda: calls.append(command)) + assert capability_for_command(command) == Capability.READ_DATA + with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): + if strict: + with pytest.raises(AuthorizationError) as denied: + ac.execute_action([[command]], raise_on_error=True) + assert denied.value.capability == Capability.READ_DATA + else: + result = ac.execute_action([[command]]) + assert any("read_data" in str(value) for value in result.values()) + assert calls == [] + for role in (Role.OPERATOR, Role.ADMIN): + with authorization_scope(AuthorizationContext(role, role)): + ac.execute_action([[command]], raise_on_error=True) + assert calls == [command, command] diff --git a/test/unit_test/headless/test_rest_read_data_routes.py b/test/unit_test/headless/test_rest_read_data_routes.py index 6ace31ff1..53caae491 100644 --- a/test/unit_test/headless/test_rest_read_data_routes.py +++ b/test/unit_test/headless/test_rest_read_data_routes.py @@ -38,7 +38,7 @@ #: The whole table, written out: a change to any route has to be made here too. _EXPECTED_ROUTES = { - ("GET", "/metrics"): _READ, + ("GET", "/metrics"): _DATA, ("GET", "/jobs"): _DATA, ("GET", "/history"): _DATA, ("GET", "/screenshot"): _READ, @@ -47,10 +47,10 @@ ("GET", "/windows"): _READ, ("GET", "/sessions"): _DATA, ("GET", "/commands"): _READ, - ("GET", "/inspector/recent"): _READ, - ("GET", "/inspector/summary"): _READ, - ("GET", "/usb/devices"): _READ, - ("GET", "/usb/events"): _READ, + ("GET", "/inspector/recent"): _DATA, + ("GET", "/inspector/summary"): _DATA, + ("GET", "/usb/devices"): _DATA, + ("GET", "/usb/events"): _DATA, ("GET", "/usb/passthrough/status"): _DATA, ("GET", "/usb/acl"): _DATA, ("GET", "/usb/loopback/devices"): _DATA, @@ -98,7 +98,8 @@ } _DATA_PATHS = ("/history", "/usb/acl", "/jobs", "/sessions", "/usb/passthrough/status", - "/usb/loopback/devices", "/usb/remote/devices", "/diagnose") + "/usb/loopback/devices", "/usb/remote/devices", "/diagnose", + "/usb/devices", "/usb/events", "/inspector/recent", "/inspector/summary") @pytest.fixture(autouse=True) @@ -215,9 +216,9 @@ def test_a_viewer_keeps_the_routes_that_observe_live_state(rest, users): def test_the_shared_token_is_not_restricted(rest): server = rest(token="shared-secret") - assert _get(server, "/history", "shared-secret")[0] == 200 - assert _get(server, "/usb/acl", "shared-secret")[0] == 200 - assert server.served == ["/history", "/usb/acl"] + for path in _DATA_PATHS: + assert _get(server, path, "shared-secret")[0] == 200 + assert server.served == list(_DATA_PATHS) # --- the table --------------------------------------------------------------- @@ -234,7 +235,8 @@ def test_openapi_publishes_the_capability_of_the_data_routes(): paths = build_openapi_spec()["paths"] assert paths["/history"]["get"]["x-required-capability"] == Capability.READ_DATA assert paths["/usb/acl"]["get"]["x-required-capability"] == Capability.READ_DATA - assert paths["/jobs"]["get"]["x-required-capability"] == Capability.READ_DATA + for path in (*_DATA_PATHS, "/metrics"): + assert paths[path]["get"]["x-required-capability"] == Capability.READ_DATA # --- the same data needs the same capability on both surfaces ------------------- @@ -383,8 +385,8 @@ def test_dashboard_panels_keep_their_endpoint_capability_including_data_refusals assert {path: capability_for_route("GET", path) for path in fetched} == { "/diagnose": Capability.READ_DATA, "/sessions": Capability.READ_DATA, - "/inspector/summary": Capability.READ_SCREEN, - "/usb/devices": Capability.READ_SCREEN, + "/inspector/summary": Capability.READ_DATA, + "/usb/devices": Capability.READ_DATA, "/audit/list": Capability.READ_AUDIT, } @@ -395,3 +397,64 @@ def test_the_dashboard_names_the_missing_capability_on_a_403(): assert "resp.status === 403" in script assert "required_capability" in script assert "not available to" in script + + +@pytest.fixture +def metrics_providers(monkeypatch): + """Record every metrics child query and render without reading host state.""" + from je_auto_control.utils.rest_api.rest_metrics import RestMetrics + calls = [] + monkeypatch.setattr(rest_server, "_count_audit_rows", lambda _audit: calls.append("audit") or 11) + monkeypatch.setattr(rest_server, "_count_active_sessions", lambda: calls.append("sessions") or 2) + monkeypatch.setattr(rest_server, "_count_scheduler_jobs", lambda: calls.append("jobs") or 3) + original = RestMetrics.render + def render(metrics, **values): + calls.append("render") + return original(metrics, **values) + monkeypatch.setattr(RestMetrics, "render", render) + return calls + + +def _metrics_get(server, token): + host, port = server.address + request = urllib.request.Request(f"{_SCHEME}://{host}:{port}/metrics", + headers={"Authorization": f"Bearer {token}"}) + try: + response = urllib.request.urlopen(request, timeout=10) # nosec B310 # reason: loopback test server + except urllib.error.HTTPError as error: + response = error + with response: + return response.code, response.headers["Content-Type"], response.read().decode("utf-8") + + +@pytest.mark.parametrize("role", [Role.VIEWER, Role.OPERATOR, Role.ADMIN, None]) +def test_metrics_special_dispatch_checks_authority_before_child_queries(rest, users, metrics_providers, role): + server = rest(token="shared-secret") if role is None else rest(user_store=users) + token = "shared-secret" if role is None else users.tokens[role] + status, content_type, body = _metrics_get(server, token) + if role == Role.VIEWER: + assert status == 403 + assert json.loads(body)["required_capability"] == Capability.READ_DATA + assert metrics_providers == [] + else: + assert status == 200 + assert content_type.startswith("text/plain; version=0.0.4") + assert "autocontrol_rest_audit_rows 11" in body + assert "autocontrol_active_sessions 2" in body + assert "autocontrol_scheduler_jobs 3" in body + assert metrics_providers == ["audit", "sessions", "jobs", "render"] + + +@pytest.mark.parametrize("path", ["/metrics", "/usb/devices", "/usb/events", + "/inspector/recent", "/inspector/summary"]) +def test_operational_reads_recheck_role_before_providers_on_next_request(rest, users, metrics_providers, path): + server = rest(user_store=users) + token = users.tokens[Role.OPERATOR] + read = _metrics_get if path == "/metrics" else lambda target, credential: _get(target, path, credential) + assert read(server, token)[0] == 200 + server.served.clear() + metrics_providers.clear() + users.set_role(f"{Role.OPERATOR}-user", Role.VIEWER) + assert read(server, token)[0] == 403 + assert server.served == [] + assert metrics_providers == [] From 86e9f7a8ff73486368a05e1e47de710795427cce Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 20:02:40 +0800 Subject: [PATCH 039/161] Retain LAN browser cleanup and interruption ownership --- CHANGELOG.md | 4 + Progress.md | 2 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 14 +- docs/media_retirement_contract.md | 13 +- .../doc/new_features/media_retirement_doc.rst | 7 +- .../doc/new_features/media_retirement_doc.rst | 6 +- docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- .../utils/remote_desktop/lan_discovery.py | 161 ++++++++++++++-- .../headless/test_browser_retirement.py | 180 ++++++++++++++++++ 13 files changed, 375 insertions(+), 27 deletions(-) create mode 100644 test/unit_test/headless/test_browser_retirement.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 809847a1c..93d8f7b91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- Retain unfinished HostBrowser cleanup, reject late publications, and observe the + original browser thread without replaying cancellation. One-shot browsing preserves + interruption identity and retained cleanup ownership. Dialog integration remains pending. + - Require `read_data` for USB enumeration/events, retained inspector statistics and process metrics over REST, and for the four matching registered AC reads. Viewer denial happens before providers or metrics child queries execute; diff --git a/Progress.md b/Progress.md index 0f2409c6c..6cad336af 100644 --- a/Progress.md +++ b/Progress.md @@ -539,7 +539,7 @@ F 還缺: 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 peer 的音訊建構、替換與停用,以及 GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; - 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 清理與發布准入仍缺整合。 + 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 diff --git a/README.md b/README.md index 175740650..68e267892 100644 --- a/README.md +++ b/README.md @@ -82,3 +82,5 @@ Host read-only mode applies the same restrictions to explicitly supplied registr Internal Windows process-memory preparation can now measure a selected process image file through retained read-only handles, with bounded hashing and retryable cleanup. This is observed file evidence, not loaded-code or fixture attestation; native acceptance and public memory tools remain unavailable. See [the contract](docs/process_memory_contract.md). Media producer shutdown now reports pending or uncertain cleanup and retains original resources. Audio and recorder failures are never turned into success by unsafe close or flush replay. LAN close supports explicit retry; application caretaker and GUI integration remain pending. See [the retirement contract](docs/media_retirement_contract.md). + +HostBrowser also rejects late publications and retains unfinished thread/close ownership; dialog integration remains pending. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 06e853cd1..792cb4b52 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -82,3 +82,5 @@ REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、US 内部 Windows 进程内存准备工作新增映像文件测量,通过保留的只读 handle 执行有界哈希并保留失败清理供重试。这只是观察到的文件证据,不是已加载代码或 fixture 的身份证明;原生验收及公开内存工具仍未提供。详见[契约](../docs/process_memory_contract.md)。 媒体 producer 关闭会报告待完成或不确定的清理结果,并保留原始资源。音频与录影不会通过不安全的 close/flush 重播宣称成功;LAN close 可明确重试。应用程序 caretaker 与 GUI 整合仍待完成。详见[清理契约](../docs/media_retirement_contract.md)。 + +HostBrowser 也会拒绝晚到发布,并保留未完成的线程与关闭所有权;对话框整合仍待完成。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 9edebc9b9..fda2f6b2f 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -82,3 +82,5 @@ REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、US 內部 Windows 行程記憶體準備工作新增映像檔量測,透過保留的唯讀 handle 執行有界雜湊並保留失敗清理供重試。這只是觀測到的檔案證據,不是已載入程式碼或 fixture 的身分證明;原生驗收及公開記憶體工具仍未提供。詳見[契約](../docs/process_memory_contract.md)。 媒體 producer 關閉會回報待完成或不確定的清理結果,並保留原始資源。音訊與錄影不會透過不安全的 close/flush 重播宣稱成功;LAN close 可明確重試。應用程式 caretaker 與 GUI 整合仍待完成。詳見[清理契約](../docs/media_retirement_contract.md)。 + +HostBrowser 亦會拒絕晚到發布,並保留未完成的執行緒與關閉所有權;對話框整合仍待完成。 diff --git a/architecture_explore.md b/architecture_explore.md index 4d099e70c..89cc7723e 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,524 | -| 程式碼總行數 | 232,649 | +| 程式碼總行數 | 232,780 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 31,335 行。 +> 6 個套件、約 31,466 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,101 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,232 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -815,7 +815,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,101 行/76 檔) +#### `utils/remote_desktop/`(16,232 行/76 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -856,7 +856,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_file_tasks.py` | 147 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | | `webrtc_files.py` | 416 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | -| `lan_discovery.py` | 247 | mDNS/Zeroconf 區網探索。 | +| `lan_discovery.py` | 378 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 197 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | @@ -1532,7 +1532,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 61 | 22,084 | -| `utils/remote_desktop/` | 76 | 16,101 | +| `utils/remote_desktop/` | 76 | 16,232 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1551,7 +1551,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,046 | -| **總計** | **1,512** | **231,904** | +| **總計** | **1,512** | **232,035** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/media_retirement_contract.md b/docs/media_retirement_contract.md index 157887387..4f031fd15 100644 --- a/docs/media_retirement_contract.md +++ b/docs/media_retirement_contract.md @@ -31,8 +31,19 @@ Stopping closes frame admission under the same lock used for encoding. Encoder f Unregister is attempted once, and Zeroconf close is attempted even when unregister fails. Zeroconf documents close as idempotent, so a failed close can be retried on that same owner. Successful close does not convert failed unregister into a confirmed goodbye. Constructor failure attempts cleanup and returns a retained owner through `MediaRetirementError` if ordinary cleanup remains unresolved. Cancellation and hard control signals keep their original identity. For those signals, `interrupted_retirement_owners(error)` returns the explicitly attached cleanup owners, including when the interruption was wrapped. The application must retain those owners before discarding its error outcome. +## LAN browsing + +HostBrowser closes publication admission before cleanup. An admitted callback keeps +retirement pending until it returns, including when that callback requests stop. +Browser cancellation is attempted once; completion requires observing the original +browser thread exit and acknowledgement of Zeroconf close. Only that documented +idempotent close is retried. A failed constructor can leave acquisition uncertain, +even after known resources close. Retain its error owner; never infer completion +from the absence of a returned browser object. One-shot browsing preserves an +original interruption and attaches the browser owner when cleanup also fails. + ## Wrappers and current limits Mic wrappers retain children when child stop fails. Opus track ending also rejects queued PCM and wakes a waiting receive operation. Opus receiver cancellation retains the exact task until actual completion is observed; cancellation requested is not completion. Repeated stop can observe a completed task. Direct TCP host cleanup continues socket/client teardown after an audio failure and retains the original capture for later observation. -These producer contracts do not complete application shutdown. The application caretaker, original-authority Diagnostics retries, GUI success reporting, HostBrowser cleanup, and all peer replacement/discard paths still require integration. In particular, a GUI must not display a recording as saved just because `has_output` is true. Existing consumer paths that swallow errors or drop references are not made durable by this producer unit. Native media/network acceptance remains pending. Validation for this unit uses injected resources and event-loop tasks only. +These producer contracts do not complete application shutdown. The application caretaker, original-authority Diagnostics retries, GUI success reporting, HostBrowser dialog ownership, and all peer replacement/discard paths still require integration. In particular, a GUI must not display a recording as saved just because `has_output` is true. Existing consumer paths that swallow errors or drop references are not made durable by this producer unit. Native media/network acceptance remains pending. Validation for this unit uses injected resources and event-loop tasks only. diff --git a/docs/source/Eng/doc/new_features/media_retirement_doc.rst b/docs/source/Eng/doc/new_features/media_retirement_doc.rst index 9b1bae956..32348163b 100644 --- a/docs/source/Eng/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Eng/doc/new_features/media_retirement_doc.rst @@ -8,6 +8,11 @@ Resource closure and finalization have separate acknowledgements. Recording flus is attempted once; uncertain PyAV or sounddevice close is never replayed to claim success. Zeroconf close supports retry on its original owner. +HostBrowser rejects late publications, retains admitted callbacks and observes the +original browser thread after one cancellation attempt. Its Zeroconf close can be +retried; failed acquisition remains uncertain. One-shot interruption preserves its +identity and exposes the retained owner if cleanup also fails. + This producer unit does not complete application caretaker, GUI saved-result -reporting, peer replacement/discard paths, or HostBrowser cleanup. Native acceptance +reporting, peer replacement/discard paths, or HostBrowser dialog ownership. Native acceptance remains pending; validation uses injected resources only. diff --git a/docs/source/Zh/doc/new_features/media_retirement_doc.rst b/docs/source/Zh/doc/new_features/media_retirement_doc.rst index 27cb1aa05..15090844a 100644 --- a/docs/source/Zh/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Zh/doc/new_features/media_retirement_doc.rst @@ -9,5 +9,9 @@ 宣稱成功。Zeroconf close 可在原始 owner 上重試。取消與中斷訊號維持原始身分; 若建構期間清理失敗,可透過 ``interrupted_retirement_owners(error)`` 取得保留的 owner。 +HostBrowser 拒絕晚到發布,保留已進入的回呼,並在一次取消要求後觀察原始執行緒。 +Zeroconf close 可重試;建構取得資源失敗仍維持不確定。單次瀏覽中斷時,若清理也失敗, +會保留原始中斷訊號並附上資源 owner。 + 此 producer 單元尚未完成應用程式 caretaker、GUI 儲存成功提示、peer 替換及丟棄路徑, -以及 HostBrowser 清理整合。原生驗收仍待完成;本單元使用注入的資源驗證。 +以及 HostBrowser 對話框所有權整合。原生驗收仍待完成;本單元使用注入的資源驗證。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 9bd732a5f..8d60ab52c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -102,3 +102,9 @@ - **What:** USB enumeration/events, retained inspector statistics and process metrics now require read_data over REST; four registered USB/inspector commands enforce the same authority. Metrics authorization occurs before audit/session/scheduler child queries. Operator/admin and legacy shared-token access remain supported. Session dashboard refresh now clears an earlier refusal after access is restored. - **Evidence:** Source audit traced the exact operational/device fields and registered command aliases. Author checks passed 484 cases; parent integration passed 69 focused cases, 49 document/quality gates and warnings-as-errors Sphinx. Fake-DOM execution of actual dashboard JavaScript verified downgrade clears stale rows and one refused panel does not stop permitted panels. Parent extended that probe to reproduce stale session error status after role restoration, then verified the one-line correction. No browser or native device enumeration ran; REST transport tests used loopback with fake providers. - **Open items:** General unlisted executor-command policy and action-list versus ordinary-data preflight remain separate work in Progress.md. This does not claim a sandbox for trusted host Python or a new whole-suite result. + +## U-20261111-30 · 2026-11-11 · Retain LAN browser cleanup and interruption ownership · #done #remote + +- **What:** HostBrowser closes publication admission, retains admitted callbacks, attempts cancellation once and observes the original browser thread. Documented idempotent Zeroconf close can retry; failed acquisition remains uncertain. Constructor and one-shot interruptions preserve original signal identity and expose retained cleanup owners. +- **Evidence:** Parent and independent reviewer each passed 42 injected browser/media cases. Ruff, Mypy and complexity checks passed. The reviewer reproduced a one-shot interruption being replaced by cleanup failure; the regression now verifies original signal identity, retained ownership and successful same-owner close retry without cancellation replay. +- **Limits:** No real Zeroconf, network, audio or desktop acceptance ran. GUI dialog ownership, application caretaker and original-authority retries remain in Progress.md. diff --git a/docs/updates/README.md b/docs/updates/README.md index f9ddb969d..6d9048720 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-30 | 2026-11-11 | Retain LAN browser cleanup and interruption ownership | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-29 | 2026-11-11 | Protect remaining REST operational records and restore dashboard status | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-28 | 2026-11-11 | Preserve media producer retirement outcomes and original resources | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-27 | 2026-11-11 | Await actual file sender completion after cancellation | #done #remote | [2026-11-b](2026-11-b.md) | @@ -648,7 +649,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 18 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 19 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/lan_discovery.py b/je_auto_control/utils/remote_desktop/lan_discovery.py index 677951344..e131397b8 100644 --- a/je_auto_control/utils/remote_desktop/lan_discovery.py +++ b/je_auto_control/utils/remote_desktop/lan_discovery.py @@ -19,7 +19,7 @@ from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.media_retirement import ( - Completion, RetirementStatus, require_retired, preserve_interrupted_owner, + Completion, MediaRetirementError, RetirementStatus, require_retired, preserve_interrupted_owner, ) try: @@ -152,14 +152,51 @@ class _BrowseListener: """Adapter that pumps zeroconf events into the user callback.""" def __init__(self, on_change: Callable[[Dict[str, dict]], None]) -> None: - self._on_change = on_change + self._on_change: Optional[Callable[[Dict[str, dict]], None]] = on_change self._services: Dict[str, dict] = {} self._lock = threading.Lock() + self._publishing = 0 + + def retire(self) -> None: + """Close publication admission and release the callback without waiting for it.""" + with self._lock: + self._on_change = None + self._services.clear() + + @property + def idle(self) -> bool: + with self._lock: + return self._publishing == 0 + + def _publish(self, snapshot: Dict[str, dict]) -> None: + with self._lock: + callback = self._on_change + if callback is None: + return + self._publishing += 1 + try: + callback(snapshot) + finally: + with self._lock: + self._publishing -= 1 def add_service(self, zc: "Zeroconf", type_: str, name: str) -> None: + with self._lock: + if self._on_change is None: + return info = zc.get_service_info(type_, name, timeout=2000) if info is None: return + record = self._service_record(info, name) + with self._lock: + if self._on_change is None: + return + self._services[name] = record + snapshot = dict(self._services) + self._publish(snapshot) + + @staticmethod + def _service_record(info: "ServiceInfo", name: str) -> dict: props = info.properties or {} host_id = (props.get(b"host_id") or b"").decode( "utf-8", errors="replace", @@ -168,25 +205,24 @@ def add_service(self, zc: "Zeroconf", type_: str, name: str) -> None: "utf-8", errors="replace", ) addresses = [socket.inet_ntoa(a) for a in (info.addresses or [])] - with self._lock: - self._services[name] = { + return { "name": name, "host_id": host_id, "signaling_url": signaling_url, "ip": addresses[0] if addresses else "", "port": info.port or 0, - } - snapshot = dict(self._services) - self._on_change(snapshot) + } def remove_service(self, zc: "Zeroconf", type_: str, name: str) -> None: # zc / type_ are positional callback parameters required by the # Zeroconf ServiceListener interface; we only need ``name`` here. del zc, type_ # suppress S1172 about the unused signature args with self._lock: + if self._on_change is None: + return self._services.pop(name, None) snapshot = dict(self._services) - self._on_change(snapshot) + self._publish(snapshot) def update_service(self, zc: "Zeroconf", type_: str, name: str) -> None: # Re-fetch and treat as add (replaces old entry under same name) @@ -206,22 +242,110 @@ def __init__(self, on_change: Callable[[Dict[str, dict]], None]) -> None: "LAN discovery needs the 'discovery' extra: " "pip install je_auto_control[discovery]" ) - self._zc = Zeroconf() + self._state_lock = threading.Lock() + self._retire_lock = threading.Lock() + self._stopping = False + self._cancel_attempted = False + self._browser_done = False + self._acquisition_uncertain = False + self._release = Completion.PENDING + self._failures: set[str] = set() + self._browser: Optional[ServiceBrowser] = None self._listener = _BrowseListener(on_change) + self._zc: Optional[Zeroconf] = None try: + self._zc = Zeroconf() self._browser = ServiceBrowser( self._zc, _SERVICE_TYPE, listener=self._listener, ) - except BaseException: - self._zc.close() + except BaseException as error: # reason: retain partial acquisition before preserving constructor interruption + self._acquisition_uncertain = True + self._failures.add("browser.acquire") + try: + self.stop() + except BaseException as cleanup_error: # reason: retain ownership and preserve the original control signal + preserve_interrupted_owner(self, error, cleanup_error) + raise MediaRetirementError(self) from error raise + @property + def retirement_status(self) -> RetirementStatus: + idle = self._listener.idle + with self._state_lock: + finalized = Completion.CONFIRMED if self._browser_done and idle else Completion.PENDING + if self._acquisition_uncertain: + finalized = Completion.UNCERTAIN + resources = self._release if finalized is Completion.CONFIRMED else finalized + complete = resources is Completion.CONFIRMED and finalized is Completion.CONFIRMED + retryable = self._stopping and not complete and ( + (self._zc is not None and self._release is not Completion.CONFIRMED) + or not self._acquisition_uncertain) + return RetirementStatus(self._stopping, resources, finalized, retryable, + tuple(sorted(self._failures))) + def stop(self) -> None: + """Close publication, attempt cancellation once and observe original resource completion.""" + self._listener.retire() + with self._state_lock: + self._stopping = True + if not self._retire_lock.acquire(blocking=False): + require_retired(self) + return + failures: list[BaseException] = [] + try: + if self._listener.idle: + self._cancel_browser(failures) + self._close_zeroconf(failures) + self._observe_browser(failures) + finally: + self._retire_lock.release() + preserve_interrupted_owner(self, *failures) + require_retired(self) + + def _cancel_browser(self, failures: list[BaseException]) -> None: + with self._state_lock: + if self._cancel_attempted or self._browser is None: + return + self._cancel_attempted = True try: self._browser.cancel() - except (RuntimeError, OSError): - pass - self._zc.close() + except BaseException as error: # reason: close Zeroconf independently before preserving interruption + failures.append(error) + with self._state_lock: + self._failures.add("browser.cancel") + + def _close_zeroconf(self, failures: list[BaseException]) -> None: + zc = self._zc + if zc is None: + return + with self._state_lock: + if self._release is Completion.CONFIRMED: + return + try: + zc.close() + except BaseException as error: # reason: retain the documented retryable close before preserving interruption + failures.append(error) + with self._state_lock: + self._release = Completion.UNCERTAIN + self._failures.add("browser.close") + else: + with self._state_lock: + self._release = Completion.CONFIRMED + self._failures.discard("browser.close") + + def _observe_browser(self, failures: list[BaseException]) -> None: + if self._browser is None: + return + try: + finished = not self._browser.is_alive() + except BaseException as error: # reason: failed observation cannot acknowledge thread completion + failures.append(error) + with self._state_lock: + self._failures.add("browser.observe") + return + with self._state_lock: + self._browser_done = finished + self._failures.discard("browser.observe") def list_local_services(timeout_s: float = 2.0) -> List[dict]: @@ -236,7 +360,14 @@ def _on(services: Dict[str, dict]) -> None: browser = HostBrowser(on_change=_on) try: done.wait(timeout=timeout_s) - finally: + except BaseException as error: # reason: preserve interruption while retaining incomplete browser cleanup + try: + browser.stop() + except BaseException as cleanup_error: # reason: attach ownership before preserving the original control signal + preserve_interrupted_owner(browser, error, cleanup_error) + raise + raise + else: browser.stop() return list(snapshot.values()) diff --git a/test/unit_test/headless/test_browser_retirement.py b/test/unit_test/headless/test_browser_retirement.py new file mode 100644 index 000000000..378b77317 --- /dev/null +++ b/test/unit_test/headless/test_browser_retirement.py @@ -0,0 +1,180 @@ +"""LAN browser cleanup observes fake threads and denies retired publications.""" +import threading +from types import SimpleNamespace + +import pytest + +from je_auto_control.utils.exception.control_signals import OperationCancelledError +from je_auto_control.utils.remote_desktop import lan_discovery as discovery +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, MediaRetirementError, interrupted_retirement_owners, +) + + +@pytest.fixture +def backend(monkeypatch): + calls = [] + + class Zeroconf: + close_failures = 0 + + def close(self): + calls.append('close') + if self.close_failures: + self.close_failures -= 1 + raise OSError('fake close failure') + + class Browser: + def __init__(self, zc, kind, listener): + self.listener = listener + self.alive = True + self.failure = None + + def cancel(self): + calls.append('cancel') + if self.failure is not None: + raise self.failure + self.alive = False + + def is_alive(self): + return self.alive + + monkeypatch.setattr(discovery, '_AVAILABLE', True) + monkeypatch.setattr(discovery, 'Zeroconf', Zeroconf) + monkeypatch.setattr(discovery, 'ServiceBrowser', Browser) + return SimpleNamespace(calls=calls, Zeroconf=Zeroconf) + + +def notify(owner): + owner._listener.remove_service(None, 'fake', 'late') + + +def test_cancel_failure_retains_original_browser_and_never_replays_cancel(backend): + published = [] + owner = discovery.HostBrowser(published.append) + browser = owner._browser + browser.failure = OSError('fake cancellation failure') + with pytest.raises(MediaRetirementError) as failure: + owner.stop() + assert failure.value.owner is owner + assert owner._browser is browser + assert backend.calls == ['cancel', 'close'] + notify(owner) + assert published == [] + with pytest.raises(MediaRetirementError): + owner.stop() + assert backend.calls == ['cancel', 'close'] + browser.alive = False + owner.stop() + assert owner.retirement_status.complete + assert backend.calls == ['cancel', 'close'] + + +def test_retry_only_repeats_documented_idempotent_close(backend): + owner = discovery.HostBrowser(lambda _: None) + owner._zc.close_failures = 1 + with pytest.raises(MediaRetirementError) as failure: + owner.stop() + assert failure.value.status.retryable + owner.stop() + owner.stop() + assert backend.calls == ['cancel', 'close', 'close'] + assert owner.retirement_status.complete + + +def test_in_flight_publication_stays_owned_without_blocking_or_closing_its_resources(backend): + entered, release = threading.Event(), threading.Event() + + def callback(_): + entered.set() + assert release.wait(3) + + owner = discovery.HostBrowser(callback) + thread = threading.Thread(target=notify, args=(owner,)) + thread.start() + try: + assert entered.wait(3) + with pytest.raises(MediaRetirementError) as failure: + owner.stop() + assert failure.value.status.resources is Completion.PENDING + assert backend.calls == [] + finally: + release.set() + thread.join(3) + owner.stop() + assert owner.retirement_status.complete + + +def test_callback_reentrant_stop_does_not_join_itself(backend): + observed = [] + + def callback(_): + with pytest.raises(MediaRetirementError) as failure: + owner.stop() + observed.append(failure.value.status) + + owner = discovery.HostBrowser(callback) + notify(owner) + assert len(observed) == 1 and observed[0].retryable + assert backend.calls == [] + owner.stop() + assert owner.retirement_status.complete + + +@pytest.mark.parametrize('interrupted', [False, True]) +def test_failed_browser_constructor_keeps_acquisition_uncertainty_and_close_owner(backend, monkeypatch, interrupted): + backend.Zeroconf.close_failures = 1 + original = OperationCancelledError('test') if interrupted else OSError('partial constructor') + + def failed(*args, **kwargs): + raise original + + monkeypatch.setattr(discovery, 'ServiceBrowser', failed) + with pytest.raises(type(original) if interrupted else MediaRetirementError) as caught: + discovery.HostBrowser(lambda _: None) + if interrupted: + assert caught.value is original + (owner,) = interrupted_retirement_owners(original) + else: + owner = caught.value.owner + assert owner.retirement_status.retryable + with pytest.raises(MediaRetirementError): + owner.stop() + assert backend.calls == ['close', 'close'] + assert owner.retirement_status.resources is Completion.UNCERTAIN + assert not owner.retirement_status.retryable + + +def test_interruption_preserves_identity_after_independent_close(backend): + owner = discovery.HostBrowser(lambda _: None) + signal = OperationCancelledError('original') + wrapped = OSError('wrapper') + wrapped.__cause__ = signal + owner._browser.failure = wrapped + with pytest.raises(OperationCancelledError) as caught: + owner.stop() + assert caught.value is signal + assert interrupted_retirement_owners(signal) == (owner,) + assert backend.calls == ['cancel', 'close'] + + +def test_one_shot_interruption_retains_browser_when_cleanup_fails(backend, monkeypatch): + signal = OperationCancelledError('browse interrupted') + backend.Zeroconf.close_failures = 1 + + class InterruptedWait: + def wait(self, timeout): + raise signal + + monkeypatch.setattr(discovery, 'threading', SimpleNamespace( + Lock=threading.Lock, Event=InterruptedWait, + )) + with pytest.raises(OperationCancelledError) as caught: + discovery.list_local_services() + assert caught.value is signal + (owner,) = interrupted_retirement_owners(signal) + assert not owner.retirement_status.complete + assert backend.calls == ['cancel', 'close'] + owner.stop() + assert owner.retirement_status.complete + assert backend.calls == ['cancel', 'close', 'close'] From a2c4f27dd536890e71e89921fc534a6ef9f39d5a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 20:11:48 +0800 Subject: [PATCH 040/161] Bind delayed session retirement to original resources --- CHANGELOG.md | 3 + Progress.md | 2 + README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 14 ++-- docs/media_retirement_contract.md | 10 +++ .../doc/new_features/media_retirement_doc.rst | 6 ++ .../doc/new_features/media_retirement_doc.rst | 5 ++ docs/updates/2026-11-b.md | 6 ++ docs/updates/README.md | 3 +- .../utils/remote_desktop/multi_viewer.py | 65 +++++++++++++++---- .../test_remote_desktop_multi_viewer.py | 57 ++++++++++++++++ 13 files changed, 158 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93d8f7b91..7d92817c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] +- Bind delayed MultiViewer session retirement to its original peer and screen source. + Owned offers preserve cleanup identity before delivery; existing tuple APIs remain compatible. + - Retain unfinished HostBrowser cleanup, reject late publications, and observe the original browser thread without replaying cancellation. One-shot browsing preserves interruption identity and retained cleanup ownership. Dialog integration remains pending. diff --git a/Progress.md b/Progress.md index 6cad336af..60be5ce24 100644 --- a/Progress.md +++ b/Progress.md @@ -544,6 +544,8 @@ F 還缺: 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 - **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 +- **F3 session 所有權**:GUI 斷線及丟棄 offer 路徑仍須在背景排程前取得原始 session 清理物件; + peer 建構及畫面來源訂閱的部分失敗所有權仍須補齊。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 **只記未完成的事。** 完成的工作記在 [docs/updates/](docs/updates/README.md)(每月一個批次檔, diff --git a/README.md b/README.md index 68e267892..f5321e50f 100644 --- a/README.md +++ b/README.md @@ -84,3 +84,5 @@ Internal Windows process-memory preparation can now measure a selected process i Media producer shutdown now reports pending or uncertain cleanup and retains original resources. Audio and recorder failures are never turned into success by unsafe close or flush replay. LAN close supports explicit retry; application caretaker and GUI integration remain pending. See [the retirement contract](docs/media_retirement_contract.md). HostBrowser also rejects late publications and retains unfinished thread/close ownership; dialog integration remains pending. + +MultiViewerHost can return an owned offer or capture an original-session retirement receipt, so delayed cleanup cannot stop a replacement peer or screen source. GUI adoption remains pending. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 792cb4b52..da9b11707 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -84,3 +84,5 @@ REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、US 媒体 producer 关闭会报告待完成或不确定的清理结果,并保留原始资源。音频与录影不会通过不安全的 close/flush 重播宣称成功;LAN close 可明确重试。应用程序 caretaker 与 GUI 整合仍待完成。详见[清理契约](../docs/media_retirement_contract.md)。 HostBrowser 也会拒绝晚到发布,并保留未完成的线程与关闭所有权;对话框整合仍待完成。 + +MultiViewerHost 可返回含原始 session 清理对象的 offer,延后清理不会停止替换后的连接或画面来源;GUI 接入仍待完成。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index fda2f6b2f..516357136 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -84,3 +84,5 @@ REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、US 媒體 producer 關閉會回報待完成或不確定的清理結果,並保留原始資源。音訊與錄影不會透過不安全的 close/flush 重播宣稱成功;LAN close 可明確重試。應用程式 caretaker 與 GUI 整合仍待完成。詳見[清理契約](../docs/media_retirement_contract.md)。 HostBrowser 亦會拒絕晚到發布,並保留未完成的執行緒與關閉所有權;對話框整合仍待完成。 + +MultiViewerHost 可回傳含原始 session 清理物件的 offer,延後清理不會停止替換後的連線或畫面來源;GUI 接入仍待完成。 diff --git a/architecture_explore.md b/architecture_explore.md index 89cc7723e..3b1adcbf3 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,524 | -| 程式碼總行數 | 232,780 | +| 程式碼總行數 | 232,823 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 31,466 行。 +> 6 個套件、約 31,509 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,232 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,275 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -815,7 +815,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,232 行/76 檔) +#### `utils/remote_desktop/`(16,275 行/76 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -834,7 +834,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 564 | `AC_remote_*` 指令使用的行程級單例。 | | `webrtc_transport.py` | 421 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | -| `multi_viewer.py` | 421 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | +| `multi_viewer.py` | 464 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 323 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | @@ -1532,7 +1532,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 61 | 22,084 | -| `utils/remote_desktop/` | 76 | 16,232 | +| `utils/remote_desktop/` | 76 | 16,275 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1551,7 +1551,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,046 | -| **總計** | **1,512** | **232,035** | +| **總計** | **1,512** | **232,078** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/media_retirement_contract.md b/docs/media_retirement_contract.md index 4f031fd15..81705d7ad 100644 --- a/docs/media_retirement_contract.md +++ b/docs/media_retirement_contract.md @@ -44,6 +44,16 @@ original interruption and attaches the browser owner when cleanup also fails. ## Wrappers and current limits +MultiViewerHost offers `create_owned_session_offer()` for asynchronous delivery. +The result contains `session_id`, `sdp`, and a `retirement` receipt retaining the +original peer and shared screen source. Use `session_retirement(session_id)` to +capture an existing session before queuing cleanup. Calling the receipt's `stop()` +retries only that generation. A reused ID or replacement source is unaffected; +other sessions retain their shared source. The legacy `create_session_offer()` +still returns its two-item tuple, and `stop_session(id)` targets the current ID. +GUI disconnect and discarded-offer paths still need to adopt these receipts. +This does not resolve all partial peer-constructor or source-subscription failures. + Mic wrappers retain children when child stop fails. Opus track ending also rejects queued PCM and wakes a waiting receive operation. Opus receiver cancellation retains the exact task until actual completion is observed; cancellation requested is not completion. Repeated stop can observe a completed task. Direct TCP host cleanup continues socket/client teardown after an audio failure and retains the original capture for later observation. These producer contracts do not complete application shutdown. The application caretaker, original-authority Diagnostics retries, GUI success reporting, HostBrowser dialog ownership, and all peer replacement/discard paths still require integration. In particular, a GUI must not display a recording as saved just because `has_output` is true. Existing consumer paths that swallow errors or drop references are not made durable by this producer unit. Native media/network acceptance remains pending. Validation for this unit uses injected resources and event-loop tasks only. diff --git a/docs/source/Eng/doc/new_features/media_retirement_doc.rst b/docs/source/Eng/doc/new_features/media_retirement_doc.rst index 32348163b..b98a68916 100644 --- a/docs/source/Eng/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Eng/doc/new_features/media_retirement_doc.rst @@ -13,6 +13,12 @@ original browser thread after one cancellation attempt. Its Zeroconf close can b retried; failed acquisition remains uncertain. One-shot interruption preserves its identity and exposes the retained owner if cleanup also fails. +MultiViewerHost's ``create_owned_session_offer()`` returns the SDP and original +session retirement receipt. Capture an existing session with ``session_retirement(id)`` +before queuing cleanup. Receipt retries cannot stop a replacement peer or screen +source even when its session ID is reused. The legacy tuple-returning API remains. +GUI disconnect and discarded offers still need to adopt this ownership. + This producer unit does not complete application caretaker, GUI saved-result reporting, peer replacement/discard paths, or HostBrowser dialog ownership. Native acceptance remains pending; validation uses injected resources only. diff --git a/docs/source/Zh/doc/new_features/media_retirement_doc.rst b/docs/source/Zh/doc/new_features/media_retirement_doc.rst index 15090844a..bfd124676 100644 --- a/docs/source/Zh/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Zh/doc/new_features/media_retirement_doc.rst @@ -13,5 +13,10 @@ HostBrowser 拒絕晚到發布,保留已進入的回呼,並在一次取消 Zeroconf close 可重試;建構取得資源失敗仍維持不確定。單次瀏覽中斷時,若清理也失敗, 會保留原始中斷訊號並附上資源 owner。 +MultiViewerHost 的 ``create_owned_session_offer()`` 回傳 SDP 與原始 session 清理物件。 +排入背景工作前,可用 ``session_retirement(id)`` 取得既有連線的清理物件; +即使 ID 重用,重試也不會停止新的連線或畫面來源。既有 tuple API 保持相容。 +GUI 斷線與丟棄 offer 路徑仍須接入此所有權。 + 此 producer 單元尚未完成應用程式 caretaker、GUI 儲存成功提示、peer 替換及丟棄路徑, 以及 HostBrowser 對話框所有權整合。原生驗收仍待完成;本單元使用注入的資源驗證。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 8d60ab52c..03c80fe6d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -108,3 +108,9 @@ - **What:** HostBrowser closes publication admission, retains admitted callbacks, attempts cancellation once and observes the original browser thread. Documented idempotent Zeroconf close can retry; failed acquisition remains uncertain. Constructor and one-shot interruptions preserve original signal identity and expose retained cleanup owners. - **Evidence:** Parent and independent reviewer each passed 42 injected browser/media cases. Ruff, Mypy and complexity checks passed. The reviewer reproduced a one-shot interruption being replaced by cleanup failure; the regression now verifies original signal identity, retained ownership and successful same-owner close retry without cancellation replay. - **Limits:** No real Zeroconf, network, audio or desktop acceptance ran. GUI dialog ownership, application caretaker and original-authority retries remain in Progress.md. + +## U-20261111-31 · 2026-11-11 · Bind delayed session retirement to original resources · #done #remote + +- **What:** MultiViewerHost can return an owned offer or capture an existing session receipt. Receipts retain the original peer and shared source. Every delayed source-release path now compares the captured source under the coordinator lock; ID reuse cannot retarget an old cleanup request. Existing tuple-returning offer creation remains compatible. +- **Evidence:** A fake baseline reproduced delayed ID-only cleanup stopping a replacement. Parent verification passed 68 coordinator/peer-ownership cases, Ruff and Mypy. Independent review passed 54 coordinator cases and a fake interposition probe that replaced the session before the original owned outcome was delivered; old receipt cleanup left the new peer and source alive. +- **Limits:** GUI disconnect/discard adoption, durable caretaker and partial source/peer construction ownership remain in Progress.md. All runtime evidence uses injected peers/tracks; no native capture or network acceptance is claimed. diff --git a/docs/updates/README.md b/docs/updates/README.md index 6d9048720..7425e7192 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-31 | 2026-11-11 | Bind delayed session retirement to original resources | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-30 | 2026-11-11 | Retain LAN browser cleanup and interruption ownership | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-29 | 2026-11-11 | Protect remaining REST operational records and restore dashboard status | #done #security | [2026-11-b](2026-11-b.md) | | U-20261111-28 | 2026-11-11 | Preserve media producer retirement outcomes and original resources | #done #remote | [2026-11-b](2026-11-b.md) | @@ -649,7 +650,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 19 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 20 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/multi_viewer.py b/je_auto_control/utils/remote_desktop/multi_viewer.py index 01f902384..a31c02c34 100644 --- a/je_auto_control/utils/remote_desktop/multi_viewer.py +++ b/je_auto_control/utils/remote_desktop/multi_viewer.py @@ -9,6 +9,7 @@ from __future__ import annotations import secrets +from dataclasses import dataclass from functools import partial import threading from datetime import datetime, timezone @@ -61,6 +62,32 @@ def stop(self) -> None: self._track.stop() +@dataclass(frozen=True) +class SessionRetirement: + """Retain the original peer and shared source for delayed retirement.""" + + session_id: str + _coordinator: MultiViewerHost + _peer: WebRTCDesktopHost + _source: _ScreenSource + + def stop(self) -> None: + self._coordinator._stop_owned_session(self.session_id, self._peer) + self._coordinator._maybe_release_source(self._source) + + +@dataclass(frozen=True) +class OwnedSessionOffer: + """Offer whose cleanup identity was captured before delivery.""" + + retirement: SessionRetirement + sdp: str + + @property + def session_id(self) -> str: + return self.retirement.session_id + + class MultiViewerHost: """Runs N concurrent ``WebRTCDesktopHost`` instances over one capture. @@ -124,6 +151,11 @@ def _annotate(self, data: dict) -> None: def create_session_offer(self) -> Tuple[str, str]: """Mint a new session: returns ``(session_id, offer_sdp)``.""" + offer = self.create_owned_session_offer() + return offer.session_id, offer.sdp + + def create_owned_session_offer(self) -> OwnedSessionOffer: + """Mint an offer with original-resource ownership for delayed delivery.""" with self._lock: if self._retiring or self._source_stopping or self._source_failed: raise PeerStopPending("finish retiring previous sessions before creating another") @@ -149,22 +181,30 @@ def create_session_offer(self) -> Tuple[str, str]: ) self._sessions[session_id] = host self._creating.add(host) + retirement = SessionRetirement(session_id, self, host, self._source) try: offer = host.create_offer(peer_label=f"viewer-{session_id[:6]}") except BaseException: with self._lock: self._creating.discard(host) - self._stop_owned_session(session_id, host) - self._maybe_release_source() + retirement.stop() raise with self._lock: self._creating.discard(host) retiring = self._retiring.get(session_id) is host if retiring: - self._stop_owned_session(session_id, host) - self._maybe_release_source() + retirement.stop() raise PeerLifecycleError("session stopped during offer creation") - return session_id, offer + return OwnedSessionOffer(retirement, offer) + + def session_retirement(self, session_id: str) -> SessionRetirement: + """Capture the currently registered generation before queuing cleanup.""" + with self._lock: + host = self._sessions[session_id] + source = self._source + if source is None: + raise PeerLifecycleError("session has no owned screen source") + return SessionRetirement(session_id, self, host, source) def accept_session_answer(self, session_id: str, answer_sdp: str) -> None: host = self._require_session(session_id) @@ -173,9 +213,10 @@ def accept_session_answer(self, session_id: str, answer_sdp: str) -> None: def stop_session(self, session_id: str) -> None: with self._lock: host = self._sessions.get(session_id) + source = self._source if host is not None: self._stop_owned_session(session_id, host) - self._maybe_release_source() + self._maybe_release_source(source) def _stop_owned_session(self, session_id: str, host: WebRTCDesktopHost) -> None: with self._lock: @@ -197,15 +238,16 @@ def stop_all(self) -> None: with self._lock: sessions = list(self._sessions.items()) self._retiring.update(sessions) + source = self._source attempt = CleanupAttempt() for session_id, host in sessions: attempt.run(partial(self._stop_owned_session, session_id, host), "session") - attempt.run(self._maybe_release_source, "screen source") + attempt.run(partial(self._maybe_release_source, source), "screen source") attempt.finish() - def _maybe_release_source(self) -> None: + def _maybe_release_source(self, expected: Optional[_ScreenSource]) -> None: with self._lock: - if self._sessions or self._source is None: + if self._sessions or self._source is None or self._source is not expected: return if self._source_stopping: raise PeerStopPending("screen source stop is still running") @@ -370,12 +412,13 @@ def _prune_later(self, session_id: str, token: object = None) -> None: if token is not None and self._session_tokens.get(session_id) is not token: return host = self._sessions.get(session_id) + source = self._source if host is None: return def retire() -> None: try: self._stop_owned_session(session_id, host) - self._maybe_release_source() + self._maybe_release_source(source) except (RuntimeError, OSError): autocontrol_logger.warning("session retirement remains pending") threading.Thread(target=retire, name="webrtc-prune", daemon=True).start() @@ -418,4 +461,4 @@ def _emit() -> None: _FINAL_STATES = frozenset({"failed", "closed"}) -__all__ = ["MultiViewerHost"] +__all__ = ["MultiViewerHost", "OwnedSessionOffer", "SessionRetirement"] diff --git a/test/unit_test/headless/test_remote_desktop_multi_viewer.py b/test/unit_test/headless/test_remote_desktop_multi_viewer.py index 77d92babd..e11fb23bb 100644 --- a/test/unit_test/headless/test_remote_desktop_multi_viewer.py +++ b/test/unit_test/headless/test_remote_desktop_multi_viewer.py @@ -123,6 +123,63 @@ def _host(**kwargs) -> MultiViewerHost: return MultiViewerHost(**kwargs) +def test_retirement_receipt_never_stops_reused_session_id(monkeypatch): + monkeypatch.setattr(mv.secrets, "token_hex", lambda _: "reused") + coordinator = _host() + original = coordinator.create_owned_session_offer() + receipt = coordinator.session_retirement(original.session_id) + original.retirement.stop() + replacement = coordinator.create_owned_session_offer() + replacement_peer = _FakeHost.instances[-1] + replacement_track = coordinator.screen_track() + receipt.stop() + assert not replacement_peer.stopped + assert not replacement_track.stopped + assert coordinator.session_count() == 1 + replacement.retirement.stop() + + +def test_old_receipt_cannot_retry_replacement_source_failure(monkeypatch): + coordinator = _host() + original = coordinator.create_owned_session_offer() + original.retirement.stop() + replacement = coordinator.create_owned_session_offer() + source_calls = [] + + def fail_close(): + source_calls.append("close") + raise OSError("new source cleanup failed") + + monkeypatch.setattr(coordinator.screen_track(), "stop", fail_close) + with pytest.raises(OSError): + replacement.retirement.stop() + assert coordinator.session_count() == 0 + original.retirement.stop() + assert source_calls == ["close"] + with pytest.raises(OSError): + replacement.retirement.stop() + assert source_calls == ["close", "close"] + + +def test_receipt_retries_original_peer_without_stopping_other_sessions(): + coordinator = _host() + first = coordinator.create_owned_session_offer() + peer = _FakeHost.instances[-1] + second = coordinator.create_owned_session_offer() + other = _FakeHost.instances[-1] + track = coordinator.screen_track() + peer.raise_on.add("stop") + with pytest.raises(RuntimeError): + first.retirement.stop() + assert coordinator.session_count() == 2 + peer.raise_on.clear() + first.retirement.stop() + assert coordinator.session_count() == 1 + assert not other.stopped and not track.stopped + second.retirement.stop() + assert track.stopped + + # --- construction ------------------------------------------------------------- def test_a_host_without_a_token_is_refused(): From d601fccfd1d3cbbd134f77ced34ed7dfbcf2cfcc Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Wed, 11 Nov 2026 20:14:36 +0800 Subject: [PATCH 041/161] Retain peer media failures and observe live cleanup --- CHANGELOG.md | 4 + Progress.md | 3 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 27 +- docs/media_retirement_contract.md | 6 +- .../doc/new_features/media_retirement_doc.rst | 8 +- .../doc/new_features/media_retirement_doc.rst | 7 +- docs/updates/2026-11-b.md | 6 + docs/updates/README.md | 3 +- .../utils/remote_desktop/webrtc_audio.py | 25 +- .../utils/remote_desktop/webrtc_host.py | 75 +-- .../utils/remote_desktop/webrtc_host_media.py | 111 +++-- .../remote_desktop/webrtc_media_owners.py | 243 ++++++++++ .../remote_desktop/webrtc_peer_cleanup.py | 96 +++- .../utils/remote_desktop/webrtc_retirement.py | 11 +- .../utils/remote_desktop/webrtc_viewer.py | 181 +++++--- pyproject.toml | 1 + .../headless/test_webrtc_host_media.py | 29 +- .../headless/test_webrtc_media_consumers.py | 432 ++++++++++++++++++ .../headless/test_webrtc_viewer_media.py | 12 +- 22 files changed, 1101 insertions(+), 185 deletions(-) create mode 100644 je_auto_control/utils/remote_desktop/webrtc_media_owners.py create mode 100644 test/unit_test/headless/test_webrtc_media_consumers.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d92817c4..07eb9ba39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- WebRTC peers retain media constructor and disable failures, expose cached slot outcomes, + observe actual receiver/task completion, and guard deferred media operations against + peer replacement. GUI caretaker and Diagnostics integration remain pending. + - Bind delayed MultiViewer session retirement to its original peer and screen source. Owned offers preserve cleanup identity before delivery; existing tuple APIs remain compatible. diff --git a/Progress.md b/Progress.md index 60be5ce24..28fc3ee11 100644 --- a/Progress.md +++ b/Progress.md @@ -538,8 +538,9 @@ F 還缺: - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 - peer 的音訊建構、替換與停用,以及 GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; + GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 + 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 diff --git a/README.md b/README.md index f5321e50f..a9f65dbbd 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Host read-only mode applies the same restrictions to explicitly supplied registr Internal Windows process-memory preparation can now measure a selected process image file through retained read-only handles, with bounded hashing and retryable cleanup. This is observed file evidence, not loaded-code or fixture attestation; native acceptance and public memory tools remain unavailable. See [the contract](docs/process_memory_contract.md). -Media producer shutdown now reports pending or uncertain cleanup and retains original resources. Audio and recorder failures are never turned into success by unsafe close or flush replay. LAN close supports explicit retry; application caretaker and GUI integration remain pending. See [the retirement contract](docs/media_retirement_contract.md). +WebRTC peers also retain failed media constructors and children, observe live disable completion, and bind deferred renegotiation to its original peer. Media producer shutdown now reports pending or uncertain cleanup and retains original resources. Audio and recorder failures are never turned into success by unsafe close or flush replay. LAN close supports explicit retry; application caretaker and GUI integration remain pending. See [the retirement contract](docs/media_retirement_contract.md). HostBrowser also rejects late publications and retains unfinished thread/close ownership; dialog integration remains pending. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index da9b11707..6fd5271c1 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -81,7 +81,7 @@ REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、US 内部 Windows 进程内存准备工作新增映像文件测量,通过保留的只读 handle 执行有界哈希并保留失败清理供重试。这只是观察到的文件证据,不是已加载代码或 fixture 的身份证明;原生验收及公开内存工具仍未提供。详见[契约](../docs/process_memory_contract.md)。 -媒体 producer 关闭会报告待完成或不确定的清理结果,并保留原始资源。音频与录影不会通过不安全的 close/flush 重播宣称成功;LAN close 可明确重试。应用程序 caretaker 与 GUI 整合仍待完成。详见[清理契约](../docs/media_retirement_contract.md)。 +WebRTC peer 也会保留媒体构造与清理失败的原始资源,观测即时停用完成,并将延后协商绑定原 peer。媒体 producer 关闭会报告待完成或不确定的清理结果,并保留原始资源。音频与录影不会通过不安全的 close/flush 重播宣称成功;LAN close 可明确重试。应用程序 caretaker 与 GUI 整合仍待完成。详见[清理契约](../docs/media_retirement_contract.md)。 HostBrowser 也会拒绝晚到发布,并保留未完成的线程与关闭所有权;对话框整合仍待完成。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 516357136..8f385eaba 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -81,7 +81,7 @@ REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、US 內部 Windows 行程記憶體準備工作新增映像檔量測,透過保留的唯讀 handle 執行有界雜湊並保留失敗清理供重試。這只是觀測到的檔案證據,不是已載入程式碼或 fixture 的身分證明;原生驗收及公開記憶體工具仍未提供。詳見[契約](../docs/process_memory_contract.md)。 -媒體 producer 關閉會回報待完成或不確定的清理結果,並保留原始資源。音訊與錄影不會透過不安全的 close/flush 重播宣稱成功;LAN close 可明確重試。應用程式 caretaker 與 GUI 整合仍待完成。詳見[清理契約](../docs/media_retirement_contract.md)。 +WebRTC peer 也會保留媒體建構與清理失敗的原始資源,觀測即時停用完成,並將延後協商綁定原 peer。媒體 producer 關閉會回報待完成或不確定的清理結果,並保留原始資源。音訊與錄影不會透過不安全的 close/flush 重播宣稱成功;LAN close 可明確重試。應用程式 caretaker 與 GUI 整合仍待完成。詳見[清理契約](../docs/media_retirement_contract.md)。 HostBrowser 亦會拒絕晚到發布,並保留未完成的執行緒與關閉所有權;對話框整合仍待完成。 diff --git a/architecture_explore.md b/architecture_explore.md index 3b1adcbf3..3877f23a5 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,524 | -| 程式碼總行數 | 232,823 | +| Python 模組總數(含周邊子專案) | 1,525 | +| 程式碼總行數 | 233,257 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 31,509 行。 +> 6 個套件、約 31,943 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,275 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,709 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -815,7 +815,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,275 行/76 檔) +#### `utils/remote_desktop/`(16,709 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -824,10 +824,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `webrtc_host.py` | 735 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | -| `webrtc_viewer.py` | 695 | WebRTC 檢視端:接收視訊並送出輸入。 | -| `webrtc_retirement.py` | 183 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | -| `webrtc_peer_cleanup.py` | 88 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | +| `webrtc_host.py` | 744 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | +| `webrtc_viewer.py` | 736 | WebRTC 檢視端:接收視訊並送出輸入。 | +| `webrtc_retirement.py` | 186 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | +| `webrtc_media_owners.py` | 243 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | +| `webrtc_peer_cleanup.py` | 154 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | | `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | | `viewer.py` | 743 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | @@ -846,7 +847,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence.py` | 238 | 多檢視者的執行緒安全在場註冊表。 | | `jpeg_recorder_encrypted.py` | 239 | AES-GCM 加密版 session 錄影。 | | `address_book.py` | 229 | 檢視端的主機通訊錄。 | -| `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 250 / 277 / 195 | 音訊擷取播放、音訊軌、麥克風上行。 | +| `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 250 / 296 / 195 | 音訊擷取播放、音訊軌、麥克風上行。 | | `audio_retirement.py` | 121 | 保留單一音訊串流世代、准入中的操作與無法確認的清理結果。 | | `media_retirement.py` | 89 | 區分媒體資源釋放與最終化狀態,傳遞失敗或取消時仍需保留的擁有者。 | | `webrtc_file_commit.py` | 355 | Confirm native file publication with bounded authenticated probes and transfer/hash/size receipt matching. | @@ -858,7 +859,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | | `lan_discovery.py` | 378 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | -| `webrtc_host_media.py` | 197 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | +| `webrtc_host_media.py` | 250 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | | `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | @@ -1532,7 +1533,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,579 | | `utils/mcp_server/` | 61 | 22,084 | -| `utils/remote_desktop/` | 76 | 16,275 | +| `utils/remote_desktop/` | 77 | 16,709 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1551,7 +1552,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,046 | -| **總計** | **1,512** | **232,078** | +| **總計** | **1,513** | **232,512** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/media_retirement_contract.md b/docs/media_retirement_contract.md index 81705d7ad..ca915296c 100644 --- a/docs/media_retirement_contract.md +++ b/docs/media_retirement_contract.md @@ -56,4 +56,8 @@ This does not resolve all partial peer-constructor or source-subscription failur Mic wrappers retain children when child stop fails. Opus track ending also rejects queued PCM and wakes a waiting receive operation. Opus receiver cancellation retains the exact task until actual completion is observed; cancellation requested is not completion. Repeated stop can observe a completed task. Direct TCP host cleanup continues socket/client teardown after an audio failure and retains the original capture for later observation. -These producer contracts do not complete application shutdown. The application caretaker, original-authority Diagnostics retries, GUI success reporting, HostBrowser dialog ownership, and all peer replacement/discard paths still require integration. In particular, a GUI must not display a recording as saved just because `has_output` is true. Existing consumer paths that swallow errors or drop references are not made durable by this producer unit. Native media/network acceptance remains pending. Validation for this unit uses injected resources and event-loop tasks only. +WebRTC host/viewer peers now adopt constructor cleanup owners before optional initialization errors are logged. Their `media_failures` property returns cached immutable slot outcomes, so callers can distinguish producer terminal uncertainty from pending task completion without entering a device lock. A status of `None` means that a non-producer operation failed without a producer acknowledgement; it is not success. + +Peer media fields clear only after confirmed cleanup. Failed microphone enable/disable and track-detach operations keep their original children and refuse conflicting replacement. Live audio/video disable tasks retain the original peer and child. Receiver cancellation is observed asynchronously, including on the receiver's own loop. Full peer stop continues unrelated slot cleanup and peer close while a different task remains pending. A concurrently running microphone startup produces a pending stop outcome; the bridge loop does not block waiting for its operation lock. Closed-loop tasks remain owned with terminal uncertainty. Deferred renegotiation cannot apply an old offer or answer to a replacement peer. + +These backend contracts do not complete application shutdown. The application caretaker, original-authority Diagnostics retries, GUI success reporting and HostBrowser dialog ownership still require integration. In particular, a GUI must not display a recording as saved just because `has_output` is true. GUI consumer paths that swallow errors or drop references are not made durable by backend ownership alone. Native media/network acceptance remains pending. Validation for this unit uses injected resources and event-loop tasks only. diff --git a/docs/source/Eng/doc/new_features/media_retirement_doc.rst b/docs/source/Eng/doc/new_features/media_retirement_doc.rst index b98a68916..2b0a5ba97 100644 --- a/docs/source/Eng/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Eng/doc/new_features/media_retirement_doc.rst @@ -19,6 +19,12 @@ before queuing cleanup. Receipt retries cannot stop a replacement peer or screen source even when its session ID is reused. The legacy tuple-returning API remains. GUI disconnect and discarded offers still need to adopt this ownership. +Peer hosts and viewers adopt failed-constructor cleanup owners and expose cached, +immutable ``media_failures``. Failed children cannot be overwritten. Live disable +observes original task completion, and peer close proceeds alongside unrelated +media cleanup. A busy microphone-start slot reports pending without blocking the +bridge loop on its lock. Deferred detach and renegotiation bind their original peer. + This producer unit does not complete application caretaker, GUI saved-result -reporting, peer replacement/discard paths, or HostBrowser dialog ownership. Native acceptance +reporting, GUI discard paths, or HostBrowser dialog ownership. Native acceptance remains pending; validation uses injected resources only. diff --git a/docs/source/Zh/doc/new_features/media_retirement_doc.rst b/docs/source/Zh/doc/new_features/media_retirement_doc.rst index bfd124676..98a2fd97b 100644 --- a/docs/source/Zh/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Zh/doc/new_features/media_retirement_doc.rst @@ -18,5 +18,10 @@ MultiViewerHost 的 ``create_owned_session_offer()`` 回傳 SDP 與原始 sessio 即使 ID 重用,重試也不會停止新的連線或畫面來源。既有 tuple API 保持相容。 GUI 斷線與丟棄 offer 路徑仍須接入此所有權。 -此 producer 單元尚未完成應用程式 caretaker、GUI 儲存成功提示、peer 替換及丟棄路徑, +Host/viewer peer 會接收建構失敗的清理 owner,並透過 ``media_failures`` 提供快取的 +不可變結果。失敗的子資源不能被覆寫;即時停用會觀測原 task 的實際完成,其他媒體與 +peer 關閉仍可獨立進行。麥克風啟動佔用中的 slot 會回報待完成,不會卡住 bridge loop +等待鎖。延後執行的 detach 與重新協商均綁定原 peer。 + +此 producer 單元尚未完成應用程式 caretaker、GUI 儲存成功提示、GUI 丟棄路徑, 以及 HostBrowser 對話框所有權整合。原生驗收仍待完成;本單元使用注入的資源驗證。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 03c80fe6d..7a5c0d0db 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -114,3 +114,9 @@ - **What:** MultiViewerHost can return an owned offer or capture an existing session receipt. Receipts retain the original peer and shared source. Every delayed source-release path now compares the captured source under the coordinator lock; ID reuse cannot retarget an old cleanup request. Existing tuple-returning offer creation remains compatible. - **Evidence:** A fake baseline reproduced delayed ID-only cleanup stopping a replacement. Parent verification passed 68 coordinator/peer-ownership cases, Ruff and Mypy. Independent review passed 54 coordinator cases and a fake interposition probe that replaced the session before the original owned outcome was delivered; old receipt cleanup left the new peer and source alive. - **Limits:** GUI disconnect/discard adoption, durable caretaker and partial source/peer construction ownership remain in Progress.md. All runtime evidence uses injected peers/tracks; no native capture or network acceptance is claimed. + +## U-20261111-32 · 2026-11-11 · Retain peer media failures and observe live cleanup · #done #remote + +- **What:** Host/viewer peers retain failed media constructors and children, reject conflicting replacements, observe original live-disable tasks, and bind deferred detach/renegotiation to original peers. Cached immutable media_failures distinguishes pending operations from terminal uncertainty. Microphone startup contention reports pending without blocking the bridge loop; independent voice and peer cleanup continue. Successful cleanup clears its pending snapshot. +- **Evidence:** Author verification passed 266 scoped cases and final affected suites, three-target typing, Ruff, Bandit, Pylint errors, complexity and strict Sphinx. Independent review passed 184 runtime and 17 structural cases, then 75 and 39 cases after final changes. Parent verified all 18 manifest hashes and imported 11 code/test/config paths unchanged; integration with session receipts passed 238 cases. Runtime evidence uses injected resources and event-loop tasks. +- **Limits:** Application caretaker, GUI normal/discard ownership, original-authority Diagnostics retries, bounded local admission closure and native acceptance remain in Progress.md. Backend ownership does not make GUI discard paths durable. diff --git a/docs/updates/README.md b/docs/updates/README.md index 7425e7192..aa2673451 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261111-32 | 2026-11-11 | Retain peer media failures and observe live cleanup | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-31 | 2026-11-11 | Bind delayed session retirement to original resources | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-30 | 2026-11-11 | Retain LAN browser cleanup and interruption ownership | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-29 | 2026-11-11 | Protect remaining REST operational records and restore dashboard status | #done #security | [2026-11-b](2026-11-b.md) | @@ -650,7 +651,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | File | Period | Entries | |---|---|---:| -| [2026-11-b.md](2026-11-b.md) | 2026-11 | 20 | +| [2026-11-b.md](2026-11-b.md) | 2026-11 | 21 | | [2026-11.md](2026-11.md) | 2026-11 | 43 | | [2026-10-f.md](2026-10-f.md) | 2026-10 | 5 | | [2026-10-e.md](2026-10-e.md) | 2026-10 | 91 | diff --git a/je_auto_control/utils/remote_desktop/webrtc_audio.py b/je_auto_control/utils/remote_desktop/webrtc_audio.py index 154942ff2..3ebbd9633 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_audio.py +++ b/je_auto_control/utils/remote_desktop/webrtc_audio.py @@ -33,7 +33,7 @@ from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.media_retirement import ( - Completion, RetirementStatus, require_retired, raise_cleanup_failures, + Completion, MediaRetirementError, RetirementStatus, require_retired, raise_cleanup_failures, ) from je_auto_control.utils.remote_desktop.audio import ( AudioBackendError, AudioCapture, AudioPlayer, is_audio_backend_available, @@ -143,7 +143,7 @@ def retirement_status(self) -> RetirementStatus: Completion.CONFIRMED) def stop(self) -> None: - failures = [] + failures: list[BaseException] = [] try: super().stop() except BaseException as error: # reason: attempt independent child cleanup before preserving failures @@ -232,6 +232,25 @@ def _to_player_pcm(self, frame) -> list: chunks.append(arr.tobytes()) return chunks + async def stop_confirmed(self) -> None: + """Observe the original drain task on its loop before acknowledging stop.""" + failures: list[BaseException] = [] + try: + self.stop() + except MediaRetirementError as error: + if error.owner is not self or not error.status.retryable: + failures.append(error) + except BaseException as error: # reason: observe the task despite an independent player or scheduling failure + failures.append(error) + task = self._task + try: + if task is not None and not task.done() and not task.get_loop().is_closed(): + await asyncio.wait({task}) + self.stop() + except BaseException as error: # reason: preserve earlier controls after observing actual task completion + failures.append(error) + raise_cleanup_failures(failures) + @property def retirement_status(self) -> RetirementStatus: if not self._player_retired: @@ -247,7 +266,7 @@ def retirement_status(self) -> RetirementStatus: def stop(self) -> None: self._stopped = True - failures = [] + failures: list[BaseException] = [] try: self._cancel_task() except BaseException as error: # reason: attempt independent child cleanup before preserving failures diff --git a/je_auto_control/utils/remote_desktop/webrtc_host.py b/je_auto_control/utils/remote_desktop/webrtc_host.py index 1025c5daa..231b832fc 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host.py @@ -19,9 +19,10 @@ import threading from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional, Tuple +from je_auto_control.utils.remote_desktop.webrtc_media_owners import MediaFailure, PeerMediaOwners from je_auto_control.utils.remote_desktop.webrtc_peer_cleanup import stop_host from je_auto_control.utils.remote_desktop.webrtc_retirement import ( - PeerRetirement, stop_resource, + PeerRetirement, PeerStopFailed, stop_resource, ) from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -148,6 +149,7 @@ def __init__(self, *, token: str, # NOSONAR python:S107 # remove themselves from this set in their done callback. self._background_tasks: set = set() self._retirement = PeerRetirement() + self._media_owners = PeerMediaOwners() self._closed = threading.Event() self._lock = threading.Lock() @@ -171,12 +173,17 @@ def accept_answer(self, answer_sdp: str) -> None: def stop(self) -> None: """Wait for software teardown; retain and report unfinished attempts.""" - if self._pc is None and not self._retirement.unsettled: + if self._pc is None and not self._retirement.unsettled and not self._media_owners.unsettled: return self._closed.set() self._authenticated = self._has_pending_viewer = False self._retirement.stop(get_bridge().submit, self._async_stop) + @property + def media_failures(self) -> tuple[MediaFailure, ...]: + """Cached outcomes of unresolved original media owners.""" + return self._media_owners.failures + @property def authenticated(self) -> bool: return self._authenticated @@ -192,7 +199,8 @@ async def _async_create_offer(self) -> str: return await self._create_offer() async def _create_offer(self) -> str: - if self._pc is not None: + self._media_owners.require_available() + if self._pc is not None or self._media_owners.unsettled: await self._stop_peer() self._retirement.require_startable() self._closed.clear() @@ -202,27 +210,19 @@ async def _create_offer(self) -> str: if self._external_video_track is not None: self._video_track = self._external_video_track else: - self._video_track = ScreenVideoTrack( + self._video_track = self._media_owners.create("screen track", lambda: ScreenVideoTrack( monitor_index=self._config.monitor_index, fps=self._config.fps, region=self._config.region, show_cursor=self._config.show_cursor, - ) + ), optional=False) self._pc.addTrack(self._video_track) if self._config.accept_viewer_video: self._pc.addTransceiver("video", direction="recvonly") if self._config.accept_viewer_audio_opus: self._pc.addTransceiver("audio", direction="recvonly") if self._config.host_voice: - try: - from je_auto_control.utils.remote_desktop.webrtc_audio import ( - OpusMicAudioTrack, - ) - self._host_voice_track = OpusMicAudioTrack() - self._pc.addTrack(self._host_voice_track) - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("host voice init: %r", error) - self._host_voice_track = None + self._attach_host_voice() self._control_channel = self._pc.createDataChannel("ctrl") self._wire_control_channel(self._control_channel) self._mic_channel = self._pc.createDataChannel("mic") @@ -289,15 +289,14 @@ def _start_opus_audio_receive(self, track) -> None: from je_auto_control.utils.remote_desktop.webrtc_audio import ( OpusMicReceiver, ) + self._media_owners.require_available("opus receiver") if self._opus_audio_receiver is not None: return - try: - receiver = OpusMicReceiver() - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("opus audio receiver init: %r", error) + receiver = self._media_owners.create("opus receiver", OpusMicReceiver) + if receiver is None: return self._opus_audio_receiver = receiver - receiver.consume(track) + self._media_owners.activate("opus receiver", lambda: receiver.consume(track), receiver) autocontrol_logger.info("webrtc host: receiving Opus audio from viewer") async def _consume_viewer_video(self, track) -> None: @@ -468,19 +467,21 @@ def enable_mic_receive(self) -> None: from je_auto_control.utils.remote_desktop.webrtc_mic import ( MicUplinkReceiver, ) - if self._mic_receiver is not None: - return - self._mic_receiver = MicUplinkReceiver() - self._mic_receiver.start() + with self._media_owners.operation_lock("mic receiver"): + self._media_owners.require_available("mic receiver") + if self._closed.is_set(): + raise PeerStopFailed("peer is stopping") + if self._mic_receiver is not None: + return + self._mic_receiver = self._media_owners.create("mic receiver", MicUplinkReceiver) + if self._mic_receiver is not None: + self._media_owners.activate("mic receiver", self._mic_receiver.start, self._mic_receiver, + admitted=lambda: not self._closed.is_set()) def disable_mic_receive(self) -> None: - if self._mic_receiver is None: - return - try: - self._mic_receiver.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("mic receiver stop: %r", error) - self._mic_receiver = None + with self._media_owners.operation_lock("mic receiver"): + self._media_owners.stop_field("mic receiver", self._mic_receiver) + self._mic_receiver = None def _wire_control_channel(self, channel) -> None: @channel.on("open") @@ -576,17 +577,25 @@ def _safe_audit_log(self, event_type: str) -> None: except (RuntimeError, OSError): pass - async def _async_apply_renegotiate_answer(self, sdp: str) -> None: + def _async_apply_renegotiate_answer(self, sdp: str) -> Coroutine[Any, Any, None]: + return self._apply_renegotiate_answer(self._pc, sdp) + + async def _apply_renegotiate_answer(self, peer, sdp: str) -> None: + if self._pc is not peer: + return async with self._retirement.starting(): - if self._pc is None: + if peer is None or self._pc is not peer or self._closed.is_set(): return try: - await self._pc.setRemoteDescription( + await peer.setRemoteDescription( RTCSessionDescription(sdp=sdp, type="answer"), ) except (RuntimeError, OSError) as error: + raise_caused_run_interruption(error) autocontrol_logger.warning("apply renegotiate answer: %r", error) return + if self._pc is not peer or self._closed.is_set(): + return # Viewer may have just attached a fresh track. If our consume # task has died (because the previous track stopped), spawn a # new one against the same receiver. diff --git a/je_auto_control/utils/remote_desktop/webrtc_host_media.py b/je_auto_control/utils/remote_desktop/webrtc_host_media.py index 0b8a2797d..3b01541cf 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host_media.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host_media.py @@ -9,15 +9,18 @@ from __future__ import annotations import asyncio +import threading from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.remote_desktop.webrtc_media_owners import PeerMediaOwners from je_auto_control.utils.remote_desktop.webrtc_transport import ( get_bridge, wait_for_ice_gathering, ) if TYPE_CHECKING: # imported lazily at runtime to keep startup cheap - from je_auto_control.utils.remote_desktop.webrtc_audio import OpusMicReceiver + from je_auto_control.utils.remote_desktop.webrtc_audio import OpusMicReceiver, OpusMicAudioTrack from je_auto_control.utils.remote_desktop.webrtc_transport import ( RTCPeerConnection, WebRTCConfig, ) @@ -36,6 +39,9 @@ class MediaNegotiationMixin: # every one of these. The block is stripped at runtime, so nothing # here can shadow what the host actually binds. _pc: Optional["RTCPeerConnection"] + _media_owners: PeerMediaOwners + _closed: threading.Event + _host_voice_track: Optional["OpusMicAudioTrack"] _config: "WebRTCConfig" _viewer_video_task: Optional[asyncio.Task] _opus_audio_receiver: Optional["OpusMicReceiver"] @@ -44,6 +50,26 @@ class MediaNegotiationMixin: _consume_viewer_video: Callable[[Any], Coroutine[Any, Any, None]] _start_opus_audio_receive: Callable[[Any], None] + def _attach_host_voice(self) -> None: + from je_auto_control.utils.remote_desktop.webrtc_audio import OpusMicAudioTrack + self._media_owners.require_available("host voice") + if self._host_voice_track is not None or self._pc is None: + return + track = self._media_owners.create("host voice", OpusMicAudioTrack) + if track is not None: + self._host_voice_track = track + self._pc.addTrack(track) + + def _current_media_peer(self, peer: object) -> bool: + return peer is not None and self._pc is peer and not self._closed.is_set() + + def _queue_for_media_peer(self, action: Callable[[], object]) -> None: + peer = self._pc + def run() -> None: + if peer is not None and self._pc is peer and not self._closed.is_set(): + action() + get_bridge().call_soon(run) + def _maybe_resubscribe_viewer_video(self) -> None: if not (self._config.accept_viewer_video and self._viewer_video_task is None @@ -83,30 +109,30 @@ def _receiver_track(transceiver): receiver = transceiver.receiver return receiver.track if receiver is not None else None - async def _async_renegotiate(self) -> None: - """Host-initiated renegotiation: new offer → viewer over ctrl channel.""" - if self._pc is None: + def _async_renegotiate(self) -> Coroutine[Any, Any, None]: + return self._renegotiate_peer(self._pc) + + async def _renegotiate_peer(self, peer: Optional["RTCPeerConnection"]) -> None: + if peer is None or not self._current_media_peer(peer): return try: - offer = await self._pc.createOffer() - await self._pc.setLocalDescription(offer) - await wait_for_ice_gathering(self._pc) + offer = await peer.createOffer() + if not self._current_media_peer(peer): + return + await peer.setLocalDescription(offer) + await wait_for_ice_gathering(peer) except (RuntimeError, OSError) as error: + raise_caused_run_interruption(error) autocontrol_logger.warning("renegotiate offer: %r", error) return - self._send_ctrl({ - "type": "renegotiate_offer", - "sdp": self._pc.localDescription.sdp, - }) - autocontrol_logger.info("webrtc host: sent renegotiate offer") + if self._current_media_peer(peer): + self._send_ctrl({"type": "renegotiate_offer", "sdp": peer.localDescription.sdp}) def request_renegotiation(self) -> None: """Public sync entry: kick off a fresh SDP exchange over ctrl channel.""" if self._pc is None: return - get_bridge().call_soon( - lambda: self._spawn_bg(self._async_renegotiate()), - ) + self._queue_for_media_peer(lambda: self._spawn_bg(self._async_renegotiate())) def enable_accept_viewer_video(self) -> None: """Live-add a recvonly video transceiver and renegotiate. @@ -116,15 +142,17 @@ def enable_accept_viewer_video(self) -> None: """ if self._pc is None: return + self._media_owners.require_available("viewer video task") self._config.accept_viewer_video = True - get_bridge().call_soon(self._add_recvonly_video_and_renegotiate) + self._queue_for_media_peer(self._add_recvonly_video_and_renegotiate) def enable_accept_viewer_audio_opus(self) -> None: """Live-add a recvonly audio transceiver and renegotiate.""" if self._pc is None: return + self._media_owners.require_available("opus receiver") self._config.accept_viewer_audio_opus = True - get_bridge().call_soon(self._add_recvonly_audio_and_renegotiate) + self._queue_for_media_peer(self._add_recvonly_audio_and_renegotiate) def _add_recvonly_video_and_renegotiate(self) -> None: if self._pc is None: @@ -151,14 +179,18 @@ def disable_accept_viewer_video(self) -> None: if self._pc is None: return self._config.accept_viewer_video = False - get_bridge().call_soon(self._deactivate_recvonly_video) + task = self._viewer_video_task + self._queue_for_media_peer( + lambda: self._deactivate_recvonly_video() if self._viewer_video_task is task else None) def disable_accept_viewer_audio_opus(self) -> None: """Mark the recvonly audio slot inactive + stop the Opus receiver.""" if self._pc is None: return self._config.accept_viewer_audio_opus = False - get_bridge().call_soon(self._deactivate_recvonly_audio) + receiver = self._opus_audio_receiver + self._queue_for_media_peer( + lambda: self._deactivate_recvonly_audio() if self._opus_audio_receiver is receiver else None) def _deactivate_recvonly_video(self) -> None: if self._pc is None: @@ -171,10 +203,8 @@ def _deactivate_recvonly_video(self) -> None: video_ts[1].direction = "inactive" except (RuntimeError, OSError) as error: autocontrol_logger.debug("inactivate video: %r", error) - if self._viewer_video_task is not None: - self._viewer_video_task.cancel() - self._viewer_video_task = None - self._spawn_bg(self._async_renegotiate()) + peer, task = self._pc, self._viewer_video_task + self._media_owners.schedule("viewer video task", lambda: self._retire_live_video(peer, task)) def _deactivate_recvonly_audio(self) -> None: if self._pc is None: @@ -188,10 +218,33 @@ def _deactivate_recvonly_audio(self) -> None: audio_ts[0].direction = "sendonly" if sending else "inactive" except (RuntimeError, OSError) as error: autocontrol_logger.debug("inactivate audio: %r", error) - if self._opus_audio_receiver is not None: - try: - self._opus_audio_receiver.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("opus receiver stop: %r", error) + peer, receiver = self._pc, self._opus_audio_receiver + if receiver is None: + self._spawn_bg(self._async_renegotiate()) + return + self._media_owners.schedule("opus receiver", lambda: self._retire_live_audio(peer, receiver)) + + async def _retire_live_audio(self, peer, receiver) -> None: + if self._pc is not peer or self._opus_audio_receiver is not receiver: + return + await self._media_owners.stop_field_async("opus receiver", receiver) + if self._opus_audio_receiver is receiver: self._opus_audio_receiver = None - self._spawn_bg(self._async_renegotiate()) + if self._pc is peer and not self._closed.is_set(): + self._spawn_bg(self._async_renegotiate()) + + async def _retire_live_video(self, peer, task) -> None: + if self._pc is not peer or self._viewer_video_task is not task: + return + if task is not None: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + finally: + if task.done() and self._viewer_video_task is task: + self._viewer_video_task = None + self._media_owners.settled("viewer video task") + if self._pc is peer and not self._closed.is_set(): + self._spawn_bg(self._async_renegotiate()) diff --git a/je_auto_control/utils/remote_desktop/webrtc_media_owners.py b/je_auto_control/utils/remote_desktop/webrtc_media_owners.py new file mode 100644 index 000000000..aa891d079 --- /dev/null +++ b/je_auto_control/utils/remote_desktop/webrtc_media_owners.py @@ -0,0 +1,243 @@ +"""Original media owners retained across peer constructor and cleanup failures.""" +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +from functools import partial +import threading +from typing import Callable, Coroutine, Protocol, TypeVar, runtime_checkable + +from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption +from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, MediaRetirementError, RetirementOwner, RetirementStatus, interrupted_retirement_owners, +) +from je_auto_control.utils.remote_desktop.webrtc_retirement import ( + CleanupAttempt, PeerStopFailed, PeerStopPending, Stoppable, +) + + +@runtime_checkable +class AsyncMediaStop(Protocol): + async def stop_confirmed(self) -> None: ... + + +async def stop_media(resource: Stoppable) -> None: + """Observe actual asynchronous completion when the producer provides it.""" + if isinstance(resource, AsyncMediaStop): + await resource.stop_confirmed() + else: + resource.stop() + + +@dataclass(frozen=True) +class MediaFailure: + slot: str + status: RetirementStatus | None + + +Media = TypeVar("Media", bound=Stoppable) + + +class PeerMediaOwners: + """Keep field failures and constructor orphans without replacing typed fields.""" + + def __init__(self) -> None: + self._lock = threading.RLock() + self._operation_locks: dict[str, threading.RLock] = {} + self._active: set[str] = set() + self._failed: dict[str, RetirementStatus | None] = {} + self._orphans: list[tuple[str, RetirementOwner]] = [] + self._snapshots: dict[int, RetirementStatus] = {} + self._tasks: dict[str, asyncio.Task[None]] = {} + + def operation_lock(self, slot: str) -> threading.RLock: + with self._lock: + if slot not in self._operation_locks: + self._operation_locks[slot] = threading.RLock() + return self._operation_locks[slot] + + @property + def unsettled(self) -> bool: + with self._lock: + return bool(self._active or self._failed or self._orphans or self._tasks) + + @property + def failures(self) -> tuple[MediaFailure, ...]: + with self._lock: + fields = tuple(MediaFailure(slot, status) for slot, status in self._failed.items()) + orphans = tuple(MediaFailure(slot, self._snapshots[id(owner)]) + for slot, owner in self._orphans) + pending = tuple(MediaFailure(slot, self._task_status(task)) + for slot, task in self._tasks.items() + if not task.done() and slot not in self._failed) + return fields + orphans + pending + + @staticmethod + def _task_status(task: asyncio.Task[None]) -> RetirementStatus: + closed = task.get_loop().is_closed() + return RetirementStatus(True, Completion.UNCERTAIN if closed else Completion.PENDING, + Completion.CONFIRMED, not closed, ("media.task_pending",)) + + def require_available(self, slot: str | None = None) -> None: + with self._lock: + failed = set(self._failed) | {name for name, _ in self._orphans} | set(self._tasks) + blocked = bool(failed) if slot is None else slot in failed + if blocked: + raise PeerStopFailed("original media cleanup remains unresolved") + + def create(self, slot: str, factory: Callable[[], Media], *, optional: bool = True) -> Media | None: + self.require_available(slot) + with self._lock: + self._active.add(slot) + try: + resource = factory() + except BaseException as error: # reason: adopt constructor owners before preserving controls + with self._lock: + self.adopt(slot, error) + self._active.discard(slot) + raise_caused_run_interruption(error) + if not optional or not isinstance(error, (RuntimeError, OSError)): + raise + autocontrol_logger.warning("%s initialization failed", slot) + return None + return resource + + def activate(self, slot: str, action: Callable[[], None], resource: Stoppable, + *, admitted: Callable[[], bool] | None = None) -> None: + try: + if admitted is not None and not admitted(): + raise PeerStopPending("peer stopped during media startup") + action() + if admitted is not None and not admitted(): + raise PeerStopPending("peer stopped during media startup") + except BaseException as error: # reason: preserve assigned ownership before propagating startup failure + self.failed(slot, error, resource) + raise_caused_run_interruption(error) + raise + + def schedule(self, slot: str, operation: Callable[[], Coroutine[object, object, None]]) -> None: + with self._lock: + previous = self._tasks.get(slot) + if previous is not None and not previous.done(): + return + if previous is not None: + self._tasks.pop(slot) + try: + previous.result() + except BaseException as error: # reason: explicit retry preserves controls and the cached failure + raise_caused_run_interruption(error) + coroutine = operation() + try: + task = asyncio.create_task(coroutine) + except BaseException: # reason: dispose of an unsubmitted coroutine without losing its retained field + coroutine.close() + raise + self._tasks[slot] = task + task.add_done_callback(partial(self._completed, slot)) + + def _completed(self, slot: str, task: asyncio.Task[None]) -> None: + failed = task.cancelled() or task.exception() is not None + with self._lock: + if self._tasks.get(slot) is not task: + return + if failed: + self._failed.setdefault(slot, None) + else: + self._tasks.pop(slot) + + async def retire_slot(self, slot: str, attempt: CleanupAttempt) -> None: + with self._lock: + task = self._tasks.get(slot) + if task is None: + return + await attempt.wait(partial(self._observe_task, task), slot) + if task.done(): + with self._lock: + if self._tasks.get(slot) is task: + self._tasks.pop(slot) + if self._failed.get(slot) is None: + self._failed.pop(slot, None) + + @staticmethod + async def _observe_task(task: asyncio.Task[None]) -> None: + if not task.done(): + if task.get_loop().is_closed(): + raise PeerStopFailed("media task loop closed before completion") + await asyncio.wait({task}) + task.result() + + def pending(self, slot: str) -> None: + with self._lock: + self._failed.setdefault(slot, RetirementStatus( + True, Completion.PENDING, Completion.PENDING, True, ("media.operation_pending",))) + + def failed(self, slot: str, error: BaseException, resource: Stoppable | None = None) -> None: + with self._lock: + status = error.status if isinstance(error, MediaRetirementError) else None + observed = getattr(resource, "retirement_status", None) + if status is None and isinstance(observed, RetirementStatus): + status = observed + self._failed[slot] = status if status is not None else self._failed.get(slot) + + def settled(self, slot: str) -> None: + with self._lock: + self._active.discard(slot) + self._failed.pop(slot, None) + + def adopt(self, slot: str, error: BaseException) -> None: + current: BaseException | None = error + seen: set[int] = set() + while current is not None and id(current) not in seen and len(seen) < 64: + seen.add(id(current)) + owners = interrupted_retirement_owners(current) + if isinstance(current, MediaRetirementError): + owners += (current.owner,) + self._retain(slot, owners) + current = current.__cause__ + + def _retain(self, slot: str, owners: tuple[RetirementOwner, ...]) -> None: + with self._lock: + for owner in owners: + if not any(item is owner for _, item in self._orphans): + self._orphans.append((slot, owner)) + self._snapshots[id(owner)] = owner.retirement_status + + def stop_field(self, slot: str, resource: Stoppable | None) -> None: + if resource is None: + return None + try: + resource.stop() + except BaseException as error: # reason: retain the field and failure before propagating its original signal + self.failed(slot, error, resource) + raise + self.settled(slot) + return None + + async def stop_field_async(self, slot: str, resource: Stoppable | None) -> None: + if resource is None: + return None + try: + await stop_media(resource) + except BaseException as error: # reason: retain the field until actual asynchronous completion is acknowledged + self.failed(slot, error, resource) + raise + self.settled(slot) + return None + + async def retire_orphans(self, attempt: CleanupAttempt) -> None: + with self._lock: + orphans = tuple(self._orphans) + for slot, owner in orphans: + if await attempt.wait(partial(self._stop_orphan, owner), slot): + with self._lock: + self._orphans = [(name, item) for name, item in self._orphans if item is not owner] + self._snapshots.pop(id(owner), None) + + async def _stop_orphan(self, owner: RetirementOwner) -> None: + try: + await stop_media(owner) + except BaseException: # reason: refresh the retained outcome before the cleanup aggregator handles failure + with self._lock: + self._snapshots[id(owner)] = owner.retirement_status + raise diff --git a/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py b/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py index dd7de7ec8..674814aa5 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py +++ b/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py @@ -2,11 +2,12 @@ from __future__ import annotations import asyncio -from typing import TYPE_CHECKING, Any, Coroutine +from typing import TYPE_CHECKING, Any, Callable, Coroutine from je_auto_control.utils.remote_desktop.webrtc_file_receive import close_file_receiver from je_auto_control.utils.remote_desktop.webrtc_file_tasks import cancel_file_requests -from je_auto_control.utils.remote_desktop.webrtc_retirement import CleanupAttempt +from je_auto_control.utils.remote_desktop.webrtc_retirement import CleanupAttempt, Resource +from je_auto_control.utils.remote_desktop.webrtc_media_owners import AsyncMediaStop, PeerMediaOwners if TYPE_CHECKING: from je_auto_control.utils.remote_desktop.webrtc_host import WebRTCDesktopHost @@ -41,10 +42,12 @@ async def _close_peer(owner: WebRTCDesktopHost | WebRTCDesktopViewer, async def _host_tasks(owner: WebRTCDesktopHost, attempt: CleanupAttempt) -> None: + await owner._media_owners.retire_slot("viewer video task", attempt) if owner._viewer_video_task is not None: task = owner._viewer_video_task if await attempt.wait(lambda: _cancel_task(task), "viewer video task") or task.done(): owner._viewer_video_task = None + owner._media_owners.settled("viewer video task") async def _viewer_tasks(owner: WebRTCDesktopViewer, attempt: CleanupAttempt) -> None: @@ -54,23 +57,89 @@ async def _viewer_tasks(owner: WebRTCDesktopViewer, attempt: CleanupAttempt) -> owner._receive_task = None +async def _retire_media(current: Callable[[], Resource | None], clear: Callable[[], None], label: str, + owners: PeerMediaOwners, attempt: CleanupAttempt) -> None: + await owners.retire_slot(label, attempt) + lock = owners.operation_lock(label) + if not lock.acquire(blocking=False): + owners.pending(label) + attempt.pending.append(label) + return + try: + resource = current() + if resource is None: + owners.settled(label) + clear() + return + if not isinstance(resource, AsyncMediaStop): + def stop_sync() -> None: + owners.stop_field(label, resource) + if attempt.run(stop_sync, label) and current() is resource: + clear() + return + finally: + lock.release() + await _retire_async_media(resource, current, clear, label, owners, attempt) + + +async def _retire_async_media(resource: Resource, current: Callable[[], Resource | None], + clear: Callable[[], None], label: str, + owners: PeerMediaOwners, attempt: CleanupAttempt) -> None: + async def stop() -> None: + await owners.stop_field_async(label, resource) + if not await attempt.wait(stop, label): + return + lock = owners.operation_lock(label) + if not lock.acquire(blocking=False): + owners.pending(label) + attempt.pending.append(label) + return + try: + if current() is resource: + clear() + finally: + lock.release() + + +async def _host_media(owner: WebRTCDesktopHost, attempt: CleanupAttempt) -> None: + owners = owner._media_owners + await asyncio.gather( + _retire_media(lambda: owner._host_voice_track, lambda: setattr(owner, "_host_voice_track", None), + "host voice", owners, attempt), + _retire_media(lambda: owner._opus_audio_receiver, lambda: setattr(owner, "_opus_audio_receiver", None), + "opus receiver", owners, attempt), + _retire_media(lambda: owner._mic_receiver, lambda: setattr(owner, "_mic_receiver", None), + "mic receiver", owners, attempt), + _retire_media(lambda: owner._video_track if owner._external_video_track is None else None, + lambda: setattr(owner, "_video_track", None), "screen track", owners, attempt), + ) + + +async def _viewer_media(owner: WebRTCDesktopViewer, attempt: CleanupAttempt) -> None: + owners = owner._media_owners + await asyncio.gather( + _retire_media(lambda: owner._host_voice_receiver, lambda: setattr(owner, "_host_voice_receiver", None), + "host voice", owners, attempt), + _retire_media(lambda: owner._opus_audio_track, lambda: setattr(owner, "_opus_audio_track", None), + "opus mic track", owners, attempt), + _retire_media(lambda: owner._mic_sender, lambda: setattr(owner, "_mic_sender", None), + "mic sender", owners, attempt), + _retire_media(lambda: owner._viewer_screen_track, lambda: setattr(owner, "_viewer_screen_track", None), + "screen track", owners, attempt), + ) + + async def stop_host(owner: WebRTCDesktopHost) -> None: owner._closed.set() owner._authenticated = owner._has_pending_viewer = False attempt = CleanupAttempt() - owner._host_voice_track = attempt.stop(owner._host_voice_track, "host voice") - owner._opus_audio_receiver = attempt.stop(owner._opus_audio_receiver, "opus receiver") - owner._mic_receiver = attempt.stop(owner._mic_receiver, "mic receiver") - if owner._external_video_track is None: - owner._video_track = attempt.stop(owner._video_track, "screen track") - else: - owner._video_track = None attempt.run(owner._release_usb_claims, "USB claims") if owner._auth_deadline_handle is not None: owner._auth_deadline_handle.cancel() owner._auth_deadline_handle = None await _wait_steps( - _close_peer(owner, attempt), _host_tasks(owner, attempt), + _close_peer(owner, attempt), _host_tasks(owner, attempt), _host_media(owner, attempt), + owner._media_owners.retire_orphans(attempt), attempt.wait(lambda: cancel_file_requests(owner._background_tasks), "file requests"), ) attempt.finish() @@ -80,9 +149,6 @@ async def stop_viewer(owner: WebRTCDesktopViewer) -> None: owner._closed.set() owner._authenticated = False attempt = CleanupAttempt() - owner._host_voice_receiver = attempt.stop(owner._host_voice_receiver, "host voice") - owner._opus_audio_track = attempt.stop(owner._opus_audio_track, "opus mic track") - owner._viewer_screen_track = attempt.stop(owner._viewer_screen_track, "screen track") - owner._mic_sender = attempt.stop(owner._mic_sender, "mic sender") - await _wait_steps(_close_peer(owner, attempt), _viewer_tasks(owner, attempt)) + await _wait_steps(_close_peer(owner, attempt), _viewer_tasks(owner, attempt), + _viewer_media(owner, attempt), owner._media_owners.retire_orphans(attempt)) attempt.finish() diff --git a/je_auto_control/utils/remote_desktop/webrtc_retirement.py b/je_auto_control/utils/remote_desktop/webrtc_retirement.py index b90c6ee43..28f70d611 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_retirement.py +++ b/je_auto_control/utils/remote_desktop/webrtc_retirement.py @@ -42,6 +42,7 @@ class CleanupAttempt: def __init__(self) -> None: self.failed: list[str] = [] self.pending: list[str] = [] + self._errors: list[BaseException] = [] def run(self, action: Callable[[], None], label: str) -> bool: try: @@ -49,8 +50,8 @@ def run(self, action: Callable[[], None], label: str) -> bool: except PeerStopPending: self.pending.append(label) return False - except Exception as error: # reason: Preserve cancellation; ordinary failures retain the resource for retry. - raise_caused_run_interruption(error) + except BaseException as error: # reason: finish independent cleanup before preserving controls + self._errors.append(error) self.failed.append(label) return False return True @@ -61,8 +62,8 @@ async def wait(self, action: Callable[[], Coroutine[Any, Any, None]], label: str except PeerStopPending: self.pending.append(label) return False - except Exception as error: # reason: Independent resources still need cleanup after an ordinary step failure. - raise_caused_run_interruption(error) + except BaseException as error: # reason: retain failures until independent asynchronous cleanup has run + self._errors.append(error) self.failed.append(label) return False return True @@ -73,6 +74,8 @@ def stop(self, resource: Resource | None, label: str) -> Resource | None: return None def finish(self) -> None: + for error in self._errors: + raise_caused_run_interruption(error) if self.failed: raise PeerStopFailed("unfinished cleanup: " + ", ".join(self.failed)) if self.pending: diff --git a/je_auto_control/utils/remote_desktop/webrtc_viewer.py b/je_auto_control/utils/remote_desktop/webrtc_viewer.py index 2ee6c355d..704075cd9 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_viewer.py +++ b/je_auto_control/utils/remote_desktop/webrtc_viewer.py @@ -11,9 +11,11 @@ import threading from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional +from je_auto_control.utils.remote_desktop.webrtc_media_owners import MediaFailure, PeerMediaOwners +from je_auto_control.utils.remote_desktop.media_retirement import raise_cleanup_failures from je_auto_control.utils.remote_desktop.webrtc_peer_cleanup import stop_viewer from je_auto_control.utils.remote_desktop.webrtc_retirement import ( - PeerRetirement, stop_resource, + PeerRetirement, PeerStopFailed, stop_resource, ) from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -97,6 +99,7 @@ def __init__(self, *, token: str, self._read_only = False self._host_fingerprint: Optional[str] = None self._retirement = PeerRetirement() + self._media_owners = PeerMediaOwners() self._closed = threading.Event() # Pin fire-and-forget asyncio tasks so they aren't reaped before # they finish (S7502). Tasks self-discard via a done callback. @@ -148,24 +151,25 @@ def request_send_sas(self) -> None: def enable_mic_send(self) -> None: """Start streaming local microphone PCM to the host.""" - if self._mic_sender is not None: - return - if self._mic_channel is None: - raise RuntimeError("mic channel not open yet; connect first") - from je_auto_control.utils.remote_desktop.webrtc_mic import ( - MicUplinkSender, - ) - self._mic_sender = MicUplinkSender(self._mic_channel) - self._mic_sender.start() + from je_auto_control.utils.remote_desktop.webrtc_mic import MicUplinkSender + with self._media_owners.operation_lock("mic sender"): + self._media_owners.require_available("mic sender") + if self._closed.is_set(): + raise PeerStopFailed("peer is stopping") + if self._mic_sender is not None: + return + if self._mic_channel is None: + raise PeerStopFailed("mic channel not open yet; connect first") + self._mic_sender = self._media_owners.create( + "mic sender", lambda: MicUplinkSender(self._mic_channel)) + if self._mic_sender is not None: + self._media_owners.activate("mic sender", self._mic_sender.start, self._mic_sender, + admitted=lambda: not self._closed.is_set()) def disable_mic_send(self) -> None: - if self._mic_sender is None: - return - try: - self._mic_sender.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("mic sender stop: %r", error) - self._mic_sender = None + with self._media_owners.operation_lock("mic sender"): + self._media_owners.stop_field("mic sender", self._mic_sender) + self._mic_sender = None @property def mic_active(self) -> bool: @@ -234,6 +238,8 @@ def toggle_share_screen(self, enable: bool) -> None: consume task again. Repeated ON/OFF cycles thus cost one renegotiation per ON; the OFF side is free. """ + if enable: + self._media_owners.require_available("screen track") self._config.share_my_screen = bool(enable) if not enable: self._inplace_detach_track(kind="video") @@ -245,6 +251,8 @@ def toggle_share_screen(self, enable: bool) -> None: def toggle_opus_mic(self, enable: bool) -> None: """Live-toggle Opus mic uplink (OFF in-place, ON renegotiates).""" + if enable: + self._media_owners.require_available("opus mic track") self._config.share_my_audio_opus = bool(enable) if not enable: self._inplace_detach_track(kind="audio") @@ -253,54 +261,75 @@ def toggle_opus_mic(self, enable: bool) -> None: return self.request_renegotiation() + def _current_media_peer(self, peer: object) -> bool: + return peer is not None and self._pc is peer and not self._closed.is_set() + def _inplace_detach_track(self, *, kind: str) -> None: - """OFF path: replaceTrack(None) + stop, but skip renegotiation.""" - if self._pc is None: - return - track_attr = ("_viewer_screen_track" if kind == "video" - else "_opus_audio_track") - track = getattr(self, track_attr, None) - if track is None: - return - for transceiver in self._pc.getTransceivers(): - if transceiver.kind != kind: - continue - if transceiver.sender.track is not track: - continue + """Bind delayed detach to the original peer and track.""" + peer = self._pc + attr = "_viewer_screen_track" if kind == "video" else "_opus_audio_track" + track = getattr(self, attr) + if peer is not None and track is not None: + get_bridge().call_soon(lambda: self._detach_media_track(peer, attr, track)) + + def _detach_media_track(self, peer: RTCPeerConnection, attr: str, track) -> None: + label = "screen track" if attr == "_viewer_screen_track" else "opus mic track" + with self._media_owners.operation_lock(label): + if not self._current_media_peer(peer) or getattr(self, attr) is not track: + return + if peer is None: + return + kind = "video" if attr == "_viewer_screen_track" else "audio" + failures = self._detach_sender(peer, kind, track) try: - transceiver.sender.replaceTrack(None) - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("detach track: %r", error) - break - try: - track.stop() - except (RuntimeError, OSError) as error: - autocontrol_logger.debug("track.stop on detach: %r", error) - setattr(self, track_attr, None) - - async def _async_handle_renegotiate(self, offer_sdp: str) -> None: - """Apply a host-initiated renegotiation offer.""" + self._media_owners.stop_field(label, track) + except BaseException as error: # reason: retain both outcomes before propagating controls + failures.append(error) + if failures: + self._media_owners.failed(label, failures[0]) + raise_cleanup_failures(failures) + setattr(self, attr, None) + + @staticmethod + def _detach_sender(peer, kind: str, track) -> list[BaseException]: + for transceiver in peer.getTransceivers(): + if transceiver.kind == kind and transceiver.sender.track is track: + try: + transceiver.sender.replaceTrack(None) + except BaseException as error: # reason: stop the original track before propagating detach failure + return [error] + break + return [] + + def _async_handle_renegotiate(self, offer_sdp: str) -> Coroutine[Any, Any, None]: + return self._handle_renegotiate(self._pc, offer_sdp) + + async def _handle_renegotiate(self, peer, offer_sdp: str) -> None: + """Apply the offer only to its original peer generation.""" + if self._pc is not peer: + return async with self._retirement.starting(): - if self._pc is None: + if peer is None or not self._current_media_peer(peer): return try: - await self._pc.setRemoteDescription( + await peer.setRemoteDescription( RTCSessionDescription(sdp=offer_sdp, type="offer"), ) - if self._config.share_my_screen and self._viewer_screen_track is None: - self._attach_viewer_screen_track() - if (self._config.share_my_audio_opus - and self._opus_audio_track is None): - self._attach_opus_audio_track() - answer = await self._pc.createAnswer() - await self._pc.setLocalDescription(answer) - await wait_for_ice_gathering(self._pc) + if not self._current_media_peer(peer): + return + self._attach_optional_tracks() + answer = await peer.createAnswer() + await peer.setLocalDescription(answer) + await wait_for_ice_gathering(peer) except (RuntimeError, OSError) as error: + raise_caused_run_interruption(error) autocontrol_logger.warning("renegotiate handle: %r", error) return + if not self._current_media_peer(peer): + return self._send({ "type": "renegotiate_answer", - "sdp": self._pc.localDescription.sdp, + "sdp": peer.localDescription.sdp, }) autocontrol_logger.info("webrtc viewer: sent renegotiate answer") @@ -335,7 +364,7 @@ def _on_viewer_file_done(self, path) -> None: def stop(self) -> None: """Wait for software teardown; retain and report unfinished attempts.""" - if self._pc is None and not self._retirement.unsettled: + if self._pc is None and not self._retirement.unsettled and not self._media_owners.unsettled: return self._closed.set() self._authenticated = False @@ -347,6 +376,11 @@ def connection_identity(self) -> object: identity: object = self._pc return identity + @property + def media_failures(self) -> tuple[MediaFailure, ...]: + """Cached outcomes of unresolved original media owners.""" + return self._media_owners.failures + @property def authenticated(self) -> bool: return self._authenticated @@ -372,7 +406,8 @@ async def _async_process_offer(self, offer_sdp: str) -> str: return await self._process_offer(offer_sdp) async def _process_offer(self, offer_sdp: str) -> str: - if self._pc is not None: + self._media_owners.require_available() + if self._pc is not None or self._media_owners.unsettled: # The whole previous session goes, not only its peer connection: # tracks, receivers and the authenticated flag outlived it. await self._stop_peer() @@ -386,15 +421,18 @@ async def _process_offer(self, offer_sdp: str) -> str: self._wire_pc_handlers(self._pc) offer = RTCSessionDescription(sdp=offer_sdp, type="offer") await self._pc.setRemoteDescription(offer) - if self._config.share_my_screen: - self._attach_viewer_screen_track() - if self._config.share_my_audio_opus: - self._attach_opus_audio_track() + self._attach_optional_tracks() answer = await self._pc.createAnswer() await self._pc.setLocalDescription(answer) await wait_for_ice_gathering(self._pc) return self._pc.localDescription.sdp + def _attach_optional_tracks(self) -> None: + if self._config.share_my_screen and self._viewer_screen_track is None: + self._attach_viewer_screen_track() + if self._config.share_my_audio_opus and self._opus_audio_track is None: + self._attach_opus_audio_track() + def _attach_viewer_screen_track(self) -> None: """Attach our screen to the host's recvonly video slot. @@ -407,6 +445,9 @@ def _attach_viewer_screen_track(self) -> None: from je_auto_control.utils.remote_desktop.webrtc_transport import ( ScreenVideoTrack, ) + self._media_owners.require_available("screen track") + if self._viewer_screen_track is not None: + return video_transceivers = [ t for t in self._require_pc().getTransceivers() if t.kind == "video" ] @@ -417,12 +458,12 @@ def _attach_viewer_screen_track(self) -> None: ) return target = video_transceivers[1] - track = ScreenVideoTrack( + track = self._media_owners.create("screen track", lambda: ScreenVideoTrack( monitor_index=self._config.monitor_index, fps=self._config.fps, region=self._config.region, show_cursor=self._config.show_cursor, - ) + ), optional=False) self._viewer_screen_track = track target.sender.replaceTrack(track) target.direction = "sendonly" @@ -442,10 +483,11 @@ def _attach_opus_audio_track(self) -> None: ) return target = audio_transceivers[0] - try: - track = OpusMicAudioTrack() - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("opus mic track init: %r", error) + self._media_owners.require_available("opus mic track") + if self._opus_audio_track is not None: + return + track = self._media_owners.create("opus mic track", OpusMicAudioTrack) + if track is None: return self._opus_audio_track = track target.sender.replaceTrack(track) @@ -546,15 +588,14 @@ def _start_host_voice_play(self, track) -> None: from je_auto_control.utils.remote_desktop.webrtc_audio import ( OpusMicReceiver, ) + self._media_owners.require_available("host voice") if self._host_voice_receiver is not None: return - try: - receiver = OpusMicReceiver() - except (RuntimeError, OSError) as error: - autocontrol_logger.warning("host voice play init: %r", error) + receiver = self._media_owners.create("host voice", OpusMicReceiver) + if receiver is None: return self._host_voice_receiver = receiver - receiver.consume(track) + self._media_owners.activate("host voice", lambda: receiver.consume(track), receiver) autocontrol_logger.info("webrtc viewer: playing host voice") async def _consume_video(self, track) -> None: diff --git a/pyproject.toml b/pyproject.toml index 4aa3dfc2b..193400cbb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -357,6 +357,7 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_retirement", "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", "je_auto_control.utils.remote_desktop.media_retirement", + "je_auto_control.utils.remote_desktop.webrtc_media_owners", "je_auto_control.utils.remote_desktop.audio_retirement", "je_auto_control.android.apps", "je_auto_control.android.input", diff --git a/test/unit_test/headless/test_webrtc_host_media.py b/test/unit_test/headless/test_webrtc_host_media.py index ec0d93906..8563f4c53 100644 --- a/test/unit_test/headless/test_webrtc_host_media.py +++ b/test/unit_test/headless/test_webrtc_host_media.py @@ -17,6 +17,9 @@ """ import asyncio import types +import threading + +from je_auto_control.utils.remote_desktop.webrtc_media_owners import PeerMediaOwners import pytest @@ -28,7 +31,12 @@ class _Bridge: def call_soon(self, callback): - callback() + async def drive(): + callback() + pending = asyncio.all_tasks() - {asyncio.current_task()} + if pending: + await asyncio.gather(*pending) + asyncio.run(drive()) class _Receiver: @@ -71,12 +79,22 @@ def __init__(self): def cancel(self): self.cancelled = True + def done(self): + return self.cancelled + + def __await__(self): + async def finish(): + return None + return finish().__await__() + class _Host(MediaNegotiationMixin): """A host with exactly the attributes the mixin's docstring asks for.""" def __init__(self, pc=None, config=None): self._pc = pc + self._closed = threading.Event() + self._media_owners = PeerMediaOwners() self._config = config or _Config() self._viewer_video_task = None self._opus_audio_receiver = None @@ -238,16 +256,17 @@ def stop(self): assert host._opus_audio_receiver is None -def test_a_receiver_that_throws_on_stop_is_still_dropped(): +def test_a_receiver_that_throws_on_stop_remains_owned(): class _Opus: def stop(self): raise OSError("already gone") host = _Host(_PeerConnection(_Transceiver("audio")), _Config(accept_viewer_audio_opus=True)) - host._opus_audio_receiver = _Opus() - host.disable_accept_viewer_audio_opus() - assert host._opus_audio_receiver is None + receiver = host._opus_audio_receiver = _Opus() + with pytest.raises(OSError): + host.disable_accept_viewer_audio_opus() + assert host._opus_audio_receiver is receiver # === Re-subscribing after a renegotiation =================================== diff --git a/test/unit_test/headless/test_webrtc_media_consumers.py b/test/unit_test/headless/test_webrtc_media_consumers.py new file mode 100644 index 000000000..93f8eb478 --- /dev/null +++ b/test/unit_test/headless/test_webrtc_media_consumers.py @@ -0,0 +1,432 @@ +"""Peer media ownership through injected constructors, tracks and peer objects.""" +import asyncio +import threading +from types import SimpleNamespace + +import pytest + +from headless._webrtc_doubles import AuditLog, Bridge, FakePeerConnection, Stoppable, Track, Transceiver +from je_auto_control.utils.exception.control_signals import OperationCancelledError +from je_auto_control.utils.remote_desktop import webrtc_audio, webrtc_host, webrtc_host_media, webrtc_viewer +from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, MediaRetirementError, RetirementStatus, preserve_interrupted_owner, +) +from je_auto_control.utils.remote_desktop.webrtc_media_owners import PeerMediaOwners +from je_auto_control.utils.remote_desktop.webrtc_retirement import CleanupAttempt, PeerStopFailed, PeerStopPending + + +class Owner: + def __init__(self, failed=True): + self.failed = failed + self.calls = 0 + + @property + def retirement_status(self): + return RetirementStatus(True, Completion.UNCERTAIN if self.failed else Completion.CONFIRMED, + Completion.CONFIRMED, False, ("fake.close",) if self.failed else ()) + + def start(self): + pass + + def stop(self): + self.calls += 1 + if self.failed: + raise MediaRetirementError(self) + + +@pytest.fixture(autouse=True) +def fake_boundaries(monkeypatch): + monkeypatch.setattr(webrtc_host, "default_audit_log", AuditLog) + monkeypatch.setattr(webrtc_host, "get_bridge", Bridge) + monkeypatch.setattr(webrtc_viewer, "get_bridge", Bridge) + monkeypatch.setattr(webrtc_audio, "is_audio_backend_available", lambda: True) + monkeypatch.setattr(webrtc_audio, "AudioPlayer", lambda **kw: Owner(False)) + + +def make_peer(role): + owner = (webrtc_host.WebRTCDesktopHost(token="fake") if role.startswith("host") + else webrtc_viewer.WebRTCDesktopViewer(token="fake")) + owner._pc = FakePeerConnection() + owner._pc.transceivers = [Transceiver("audio")] + return owner + + +def constructor_entry(owner, role): + if role == "host-track": + return owner._attach_host_voice + if role == "host-receiver": + return lambda: owner._start_opus_audio_receive(object()) + if role == "viewer-track": + return owner._attach_opus_audio_track + return lambda: owner._start_host_voice_play(object()) + + +@pytest.mark.parametrize("role", ["host-track", "host-receiver", "viewer-track", "viewer-receiver"]) +@pytest.mark.parametrize("control", [False, True]) +def test_constructor_failure_adopts_original_owner_before_optional_catch(monkeypatch, role, control): + owner = make_peer(role) + resource = Owner() + calls = [] + signal = OperationCancelledError("constructor") + error = MediaRetirementError(resource) + if control: + try: + preserve_interrupted_owner(resource, signal) + except OperationCancelledError: + pass + error = RuntimeError("wrapped") + error.__cause__ = signal + + def failed(): + calls.append(True) + raise error + + name = "OpusMicAudioTrack" if role.endswith("track") else "OpusMicReceiver" + monkeypatch.setattr(webrtc_audio, name, failed) + invoke = constructor_entry(owner, role) + if control: + with pytest.raises(OperationCancelledError) as caught: + invoke() + assert caught.value is signal + else: + invoke() + assert owner.media_failures[0].status is not None + assert not owner.media_failures[0].status.retryable + with pytest.raises(PeerStopFailed): + invoke() + assert len(calls) == 1 + owner._pc = None + with pytest.raises(PeerStopFailed): + owner.stop() + assert resource.calls == 1 + resource.failed = False + owner.stop() + assert resource.calls == 2 and owner.media_failures == () + + +def test_one_successful_orphan_does_not_clear_another_failure(): + owners = PeerMediaOwners() + failed, successful = Owner(), Owner(False) + owners.adopt("same slot", MediaRetirementError(failed)) + owners.adopt("same slot", MediaRetirementError(successful)) + attempt = CleanupAttempt() + asyncio.run(owners.retire_orphans(attempt)) + assert len(owners.failures) == 1 + assert owners.failures[0].status == failed.retirement_status + with pytest.raises(PeerStopFailed): + owners.require_available("same slot") + + +@pytest.mark.parametrize("role", ["host", "viewer"]) +def test_failed_mic_disable_retains_child_and_refuses_replacement(role): + owner = make_peer(role) + child = Owner() + attr = "_mic_receiver" if role == "host" else "_mic_sender" + setattr(owner, attr, child) + disable = owner.disable_mic_receive if role == "host" else owner.disable_mic_send + enable = owner.enable_mic_receive if role == "host" else owner.enable_mic_send + with pytest.raises(MediaRetirementError): + disable() + with pytest.raises(PeerStopFailed): + enable() + assert getattr(owner, attr) is child + + +def test_full_peer_stop_observes_receiver_task_while_closing_other_resources(): + async def drive(): + entered, cancelled, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + + class Input: + async def recv(self): + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cancelled.set() + await release.wait() + raise + + host = make_peer("host") + peer = host._pc + receiver = webrtc_audio.OpusMicReceiver() + receiver.consume(Input()) + host._opus_audio_receiver = receiver + host._mic_receiver = mic = Stoppable() + await entered.wait() + stop = asyncio.create_task(host._async_stop()) + await cancelled.wait() + assert peer.closed and mic.stopped + assert not stop.done() and host._opus_audio_receiver is receiver + release.set() + await asyncio.wait_for(stop, 1) + assert host._opus_audio_receiver is None and host._pc is None + + asyncio.run(drive()) + + +def test_closed_loop_receiver_reports_terminal_status_without_waiting(): + async def drive(): + receiver = webrtc_audio.OpusMicReceiver() + receiver._task = SimpleNamespace(done=lambda: False, + get_loop=lambda: SimpleNamespace(is_closed=lambda: True)) + with pytest.raises(MediaRetirementError) as caught: + await asyncio.wait_for(receiver.stop_confirmed(), .2) + assert not caught.value.status.retryable + assert caught.value.status.resources is Completion.UNCERTAIN + + asyncio.run(drive()) + + +def test_media_control_signal_does_not_skip_peer_close(): + async def drive(): + host = make_peer("host") + peer = host._pc + signal = OperationCancelledError("stop") + wrapped = RuntimeError("wrapped") + wrapped.__cause__ = signal + host._host_voice_track = Stoppable(error=wrapped) + host._mic_receiver = mic = Stoppable() + with pytest.raises(OperationCancelledError) as caught: + await host._async_stop() + assert caught.value is signal and peer.closed and mic.stopped + assert host._host_voice_track is not None + + asyncio.run(drive()) + + +def test_queued_viewer_detach_does_not_touch_replacement(monkeypatch): + queued = [] + monkeypatch.setattr(webrtc_viewer, "get_bridge", lambda: SimpleNamespace(call_soon=queued.append)) + viewer = make_peer("viewer") + old, replacement = Track("audio"), Track("audio") + viewer._opus_audio_track = old + viewer.toggle_opus_mic(False) + viewer._opus_audio_track = replacement + slot = Transceiver("audio", track=replacement) + viewer._pc.transceivers = [slot] + queued[0]() + assert not replacement.stopped and slot.sender.replaced == [] + + +@pytest.mark.parametrize("role", ["host", "viewer"]) +def test_queued_renegotiation_is_inert_after_peer_replacement(role): + owner = make_peer(role) + pending = (owner._async_apply_renegotiate_answer("old") if role == "host" + else owner._async_handle_renegotiate("old")) + replacement = FakePeerConnection() + owner._pc = replacement + asyncio.run(pending) + assert replacement.remote_descriptions == [] + + +def test_host_offer_cannot_be_applied_to_replacement_after_await(monkeypatch): + async def drive(): + entered, release = asyncio.Event(), asyncio.Event() + host = make_peer("host") + old = host._pc + + async def offer(): + entered.set() + await release.wait() + return SimpleNamespace(sdp="old") + + old.createOffer = offer + task = asyncio.create_task(host._async_renegotiate()) + await entered.wait() + replacement = host._pc = FakePeerConnection() + release.set() + await task + assert not hasattr(replacement, "local_description_arg") + + asyncio.run(drive()) + + +def live_host(monkeypatch): + host = make_peer("host") + monkeypatch.setattr(webrtc_host_media, "get_bridge", lambda: SimpleNamespace( + call_soon=lambda fn: fn())) + host._spawn_bg = lambda coroutine: coroutine.close() + return host + + +def test_live_audio_disable_finishes_on_its_loop_and_allows_enable(monkeypatch): + async def drive(): + host = live_host(monkeypatch) + + class Input: + async def recv(self): + await asyncio.Event().wait() + + receiver = webrtc_audio.OpusMicReceiver() + receiver.consume(Input()) + host._opus_audio_receiver = receiver + await asyncio.sleep(0) + host.disable_accept_viewer_audio_opus() + await asyncio.gather(*host._media_owners._tasks.values()) + await asyncio.sleep(0) + assert host._opus_audio_receiver is None and host.media_failures == () + host.enable_accept_viewer_audio_opus() + assert host._config.accept_viewer_audio_opus + + asyncio.run(drive()) + + +def test_explicit_live_disable_retry_uses_same_original_child(monkeypatch): + class Receiver: + calls = 0 + + def stop(self): + pass + + async def stop_confirmed(self): + self.calls += 1 + if self.calls == 1: + raise OSError("temporary failure") + + async def drive(): + host = live_host(monkeypatch) + child = host._opus_audio_receiver = Receiver() + host.disable_accept_viewer_audio_opus() + await asyncio.gather(*host._media_owners._tasks.values(), return_exceptions=True) + await asyncio.sleep(0) + assert host._opus_audio_receiver is child and host.media_failures + with pytest.raises(PeerStopFailed): + host.enable_accept_viewer_audio_opus() + host.disable_accept_viewer_audio_opus() + await asyncio.gather(*host._media_owners._tasks.values()) + await asyncio.sleep(0) + assert child.calls == 2 and host._opus_audio_receiver is None + assert host.media_failures == () + + asyncio.run(drive()) + + +def test_pending_live_video_does_not_block_independent_mic_or_peer_close(monkeypatch): + async def drive(): + host = live_host(monkeypatch) + entered, cancelled, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + + async def receive(): + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cancelled.set() + await release.wait() + raise + + task = host._viewer_video_task = asyncio.create_task(receive()) + mic = host._mic_receiver = Stoppable() + peer = host._pc + await entered.wait() + host.disable_accept_viewer_video() + await cancelled.wait() + with pytest.raises(PeerStopFailed): + host.enable_accept_viewer_video() + stop = asyncio.create_task(host._async_stop()) + for _ in range(5): + await asyncio.sleep(0) + assert peer.closed and mic.stopped + assert not stop.done() and host._viewer_video_task is task + release.set() + await asyncio.wait_for(stop, 1) + assert host._viewer_video_task is None + + asyncio.run(drive()) + + +def test_live_video_error_is_visible_and_observed_once(monkeypatch): + async def drive(): + host = live_host(monkeypatch) + + async def fail(): + raise RuntimeError("video failed") + + host._viewer_video_task = asyncio.create_task(fail()) + await asyncio.sleep(0) + host.disable_accept_viewer_video() + await asyncio.gather(*host._media_owners._tasks.values(), return_exceptions=True) + await asyncio.sleep(0) + assert host.media_failures and host._viewer_video_task is None + with pytest.raises(PeerStopFailed): + await host._async_stop() + await host._async_stop() + assert host.media_failures == () + + asyncio.run(drive()) + + +def test_queued_host_disable_does_not_touch_new_peer_or_receiver(monkeypatch): + queued = [] + monkeypatch.setattr(webrtc_host_media, "get_bridge", lambda: SimpleNamespace(call_soon=queued.append)) + host = make_peer("host") + host._opus_audio_receiver = Owner(False) + host.disable_accept_viewer_audio_opus() + replacement = host._opus_audio_receiver = Owner(False) + peer = host._pc = FakePeerConnection() + queued[0]() + assert replacement.calls == 0 and peer.transceivers == [] + + +def test_closed_loop_live_task_stays_owned_with_terminal_snapshot(): + owners = PeerMediaOwners() + task = SimpleNamespace(done=lambda: False, + get_loop=lambda: SimpleNamespace(is_closed=lambda: True)) + owners._tasks["video"] = task + attempt = CleanupAttempt() + asyncio.run(owners.retire_slot("video", attempt)) + with pytest.raises(PeerStopFailed): + attempt.finish() + assert owners._tasks["video"] is task + assert owners.failures[0].status.resources is Completion.UNCERTAIN + assert not owners.failures[0].status.retryable + + +def test_blocked_mic_start_does_not_block_peer_close_or_loop_progress(monkeypatch): + from je_auto_control.utils.remote_desktop import webrtc_mic + entered, release = threading.Event(), threading.Event() + errors = [] + + class Child: + stopped = False + + def start(self): + entered.set() + assert release.wait(2) + + def stop(self): + self.stopped = True + + child = Child() + monkeypatch.setattr(webrtc_mic, "MicUplinkReceiver", lambda: child) + host = make_peer("host") + peer = host._pc + voice = host._host_voice_track = Stoppable() + + def start(): + try: + host.enable_mic_receive() + except BaseException as error: + errors.append(error) + + starter = threading.Thread(target=start) + starter.start() + try: + assert entered.wait(2) + + async def retire(): + with pytest.raises(PeerStopPending): + await asyncio.wait_for(host._async_stop(), .5) + assert peer.closed and voice.stopped and host._mic_receiver is child + assert host.media_failures[0].status.resources is Completion.PENDING + assert host.media_failures[0].status.retryable + await asyncio.sleep(0) + + asyncio.run(retire()) + finally: + release.set() + starter.join(2) + assert len(errors) == 1 and isinstance(errors[0], PeerStopPending) + asyncio.run(host._async_stop()) + assert child.stopped and host._mic_receiver is None + assert host.media_failures == () diff --git a/test/unit_test/headless/test_webrtc_viewer_media.py b/test/unit_test/headless/test_webrtc_viewer_media.py index d59e7e86f..be3e84d5a 100644 --- a/test/unit_test/headless/test_webrtc_viewer_media.py +++ b/test/unit_test/headless/test_webrtc_viewer_media.py @@ -315,12 +315,13 @@ def test_a_sender_that_rejects_the_detach_still_stops_the_capture(): slot.sender.replace_error = RuntimeError("connection closed") pc.transceivers = [slot] viewer._viewer_screen_track = track - viewer.toggle_share_screen(False) + with pytest.raises(RuntimeError): + viewer.toggle_share_screen(False) assert track.stopped - assert viewer._viewer_screen_track is None + assert viewer._viewer_screen_track is track -def test_a_capture_that_fails_to_stop_is_still_forgotten(): +def test_a_capture_that_fails_to_stop_remains_owned(): viewer, pc = _connected() class _StubbornTrack(Track): @@ -330,8 +331,9 @@ def stop(self): track = _StubbornTrack("video") pc.transceivers = [Transceiver("video", track=track)] viewer._viewer_screen_track = track - viewer.toggle_share_screen(False) - assert viewer._viewer_screen_track is None + with pytest.raises(OSError): + viewer.toggle_share_screen(False) + assert viewer._viewer_screen_track is track # --- host-initiated renegotiation --------------------------------------------- From edc6205d300dae999b9e1a239ade99e5c69dc19a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 01:03:20 +0800 Subject: [PATCH 042/161] Create test_coverage.md --- test_coverage.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 test_coverage.md diff --git a/test_coverage.md b/test_coverage.md new file mode 100644 index 000000000..1d7d1bcd7 --- /dev/null +++ b/test_coverage.md @@ -0,0 +1,41 @@ +# 測試覆蓋度:AutoControlGUI + +測量日期:2026-10-28。數字來自這台 Windows 機器上的一次實測,不是估計,也不是只數檔案。 + +| 項目 | 內容 | +|---|---| +| 直譯器 | 3.14.4 | +| 直譯器說明 | 專案 .venv | +| 工具 | coverage 7.15.0,`coverage run --branch` | +| 測量範圍 | `je_auto_control`、`je_auto_control_pytest` | +| 測試路徑 | `test/unit_test/headless test/unit_test/flow_control` | +| 命令 | `python -m coverage run --branch --source=je_auto_control,je_auto_control_pytest -m pytest test/unit_test/headless test/unit_test/flow_control` | +| 敘述覆蓋 | 89.79%(61641 / 68651) | +| 分支覆蓋 | 81.66%(14069 / 17228) | +| 測試結果 | 13361 passed, 70 skipped, 1 warning in 959.37s (0:15:59) | +| 耗時 | 969.1 秒 | + +敘述覆蓋是執行到的敘述數除以全部敘述數。分支覆蓋是執行到的分支數除以全部分支數。兩者分開算,沒有把分支混進敘述百分比。 + +## 這次怎麼量 + +測試路徑沿用 pyproject 的 `test/unit_test/headless` 與 `test/unit_test/flow_control`。`test/unit_test` 裡的 `*_test.py` 會驅動真實滑鼠與鍵盤,沒有納入。測量用 `coverage run -m pytest`,避免 pytest 外掛在 coverage 啟動前先匯入整個套件。CI 的 `fail_under = 81` 把分支算進總分,而且設定排除 `gui` 與 `language_wrapper`;本檔的兩個百分比是全套件的敘述覆蓋與分支覆蓋,演算法不同。 + +## 覆蓋較低的檔案 + +只列這次測量裡敘述覆蓋最低的檔案,最多 12 個。 + +| 檔案 | 敘述覆蓋 | 已覆蓋 / 敘述 | +|---|---:|---:| +| `je_auto_control/linux_with_x11/core/utils/x11_linux_vk.py` | 0.0% | 0 / 190 | +| `je_auto_control/linux_with_x11/uinput/_device.py` | 0.0% | 0 / 123 | +| `je_auto_control/osx/listener/osx_listener.py` | 0.0% | 0 / 114 | +| `je_auto_control/linux_with_x11/listener/x11_linux_listener.py` | 0.0% | 0 / 82 | +| `je_auto_control/osx/screen/osx_screen.py` | 0.0% | 0 / 52 | +| `je_auto_control/linux_with_x11/uinput/mouse.py` | 0.0% | 0 / 48 | +| `je_auto_control/utils/xml/xml_file/xml_file.py` | 0.0% | 0 / 44 | +| `je_auto_control/utils/rest_api/__main__.py` | 0.0% | 0 / 37 | +| `je_auto_control/wrapper/_platform_linux.py` | 0.0% | 0 / 36 | +| `je_auto_control/linux_with_x11/keyboard/x11_linux_keyboard_control.py` | 0.0% | 0 / 34 | +| `je_auto_control/osx/keyboard/osx_keyboard.py` | 0.0% | 0 / 33 | +| `je_auto_control/linux_with_x11/record/x11_linux_record.py` | 0.0% | 0 / 29 | From 29447fef6650bc59f17e5d94b87bb2c10d9e1363 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:07:39 +0800 Subject: [PATCH 043/161] Record removing the stale dev package from the shared venv --- Progress.md | 3 ++- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Progress.md b/Progress.md index 28fc3ee11..1e8876c86 100644 --- a/Progress.md +++ b/Progress.md @@ -165,7 +165,8 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` `TODO` — 小項目,各自獨立 -- **本機的共用 `.venv` 裝著 `je_auto_control_dev 0.0.136`**,它的 `pytest11` 進入點還是舊的重量級路徑;重裝即可,不影響 CI。 +- **本機共用 `.venv` 落後 `pyproject.toml` 一個釘選**(U-20261112-01 之後):pillow 12.3.0(要求 `==13.0.0`)、 + PySide6 6.11.2(`[gui]` 要求 6.12.0)。共用環境的升級需要使用者同意,沒有動;不影響 CI。 - **free-threaded**:呼叫者身分、綁定的裝置、自愈的執行標記與 stop token 都改成只在設定它的執行緒上有效(`utils/thread_bound.py`)。 這台機器沒有 free-threaded 直譯器:驗證用的是模擬繼承與真的 `-X thread_inherit_context=1`(3.14.7,GIL 開著);`free-threaded-scope` job(3.14t)是第一次真的跑。 - **能力探測**:Windows 的鎖定工作站、session 0、低完整性與擷取失敗分支只用假資料判斷;macOS 的三個 preflight 呼叫只對假物件跑過, diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 7a5c0d0db..858f17885 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -120,3 +120,10 @@ - **What:** Host/viewer peers retain failed media constructors and children, reject conflicting replacements, observe original live-disable tasks, and bind deferred detach/renegotiation to original peers. Cached immutable media_failures distinguishes pending operations from terminal uncertainty. Microphone startup contention reports pending without blocking the bridge loop; independent voice and peer cleanup continue. Successful cleanup clears its pending snapshot. - **Evidence:** Author verification passed 266 scoped cases and final affected suites, three-target typing, Ruff, Bandit, Pylint errors, complexity and strict Sphinx. Independent review passed 184 runtime and 17 structural cases, then 75 and 39 cases after final changes. Parent verified all 18 manifest hashes and imported 11 code/test/config paths unchanged; integration with session receipts passed 238 cases. Runtime evidence uses injected resources and event-loop tasks. - **Limits:** Application caretaker, GUI normal/discard ownership, original-authority Diagnostics retries, bounded local admission closure and native acceptance remain in Progress.md. Backend ownership does not make GUI discard paths durable. + +## U-20261112-01 · 2026-11-12 · Remove the stale dev package from the shared .venv · #done #tooling + +- **What:** Closes the `Progress.md` › 雜項 item about `je_auto_control_dev 0.0.136`. The shared `.venv` held that wheel next to the editable install; both registered the old `pytest11` value `je_auto_control.utils.pytest_plugin.plugin`, and outside the repository the wheel's copy in `site-packages/je_auto_control/` shadowed the working tree. The wheel was uninstalled, 793 orphaned `*.pyc` files it left in that directory (no sources) were removed, and the editable install was refreshed from `dev` with `pip install --no-deps -e .`. +- **Before / after:** `je_auto_control` 0.0.225 editable + `je_auto_control_dev` 0.0.136 → `je_auto_control` 1.2.0 editable only; `pytest11` resolves to `je_auto_control_pytest`; `import je_auto_control` from another directory now resolves to the working tree. +- **Not changed:** no third-party package was installed or upgraded (`--no-deps`). `pip check` reports the shared env one pin behind `pyproject.toml` (pillow 12.3.0 vs `==13.0.0`; PySide6 6.11.2 vs the `[gui]` pin 6.12.0); recorded in `Progress.md` › 雜項. +- **Evidence:** `test_pytest_entrypoint_light.py` and `test_coverage_measurement.py` (6 passed) from the shared env. diff --git a/docs/updates/README.md b/docs/updates/README.md index aa2673451..ad434419f 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-01 | 2026-11-12 | Remove the stale dev package from the shared .venv | #done #tooling | [2026-11-b](2026-11-b.md) | | U-20261111-32 | 2026-11-11 | Retain peer media failures and observe live cleanup | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-31 | 2026-11-11 | Bind delayed session retirement to original resources | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-30 | 2026-11-11 | Retain LAN browser cleanup and interruption ownership | #done #remote | [2026-11-b](2026-11-b.md) | From 9d7ae7c9a68d0cd136a3d263b8e51c9d40704cdd Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:09:23 +0800 Subject: [PATCH 044/161] Close the minimatch item: the revised advisory no longer covers 5.1.9 --- Progress.md | 10 +--------- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/2026-11.md | 2 +- docs/updates/README.md | 1 + 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Progress.md b/Progress.md index 1e8876c86..af0316475 100644 --- a/Progress.md +++ b/Progress.md @@ -754,7 +754,7 @@ ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime gra | 秘密金庫(`${secrets.NAME}`) | `cryptography` | 同上 | | ACME/TLS 發證、加密錄影 | `cryptography` | 模組層 `ImportError` 轉述(照 `webrtc_transport` 慣例) | -`BLOCKED` — 仍需相容的上游 wheel:`opencv-python>=4.8,<6`、 +`BLOCKED`(2026-11-12 以下方指令重驗,三者仍無 win_arm64 wheel;cryptography 仍只到 46.0.3)— 仍需相容的上游 wheel:`opencv-python>=4.8,<6`、 `cryptography>=50.0.0` 與 `aiortc` 的傳遞相依 `google-crc32c`。 不能為相容性降低 cryptography 安全下限。上游提供相容版本後,需重驗安裝與功能, 再移除 `pyproject.toml` 中相應平台標記並同步更新 @@ -772,11 +772,3 @@ pip install --dry-run --only-binary=:all: --platform win_arm64 --python-version 它只影響 wheel 相容性標籤,所以拿本機做 `--dry-run` **驗不到標記的效果**(兩個 套件依舊會被要求)。能驗的是兩件事:直接評估 marker(上面那支測試在做的), 以及 `windows-11-arm` 那一格自己綠。 - -## minimatch 11 在 VS Code 擴充套件 - -`BLOCKED` — `autocontrol-lsp/vscode/package-lock.json` 的 `minimatch` 5.1.9 有 Dependabot 警示 -GHSA-g3hv-75wg-m249(moderate),只有 11.0.1 起修好(U-20261101-17)。它來自 `vscode-languageclient` 9.0.1, -會被 esbuild 打包進擴充套件;到 11.0.0 為止的每一版都要求 `minimatch` ^5 或 ^10,並呼叫 minimatch 11 已移除的 -`Minimatch#makeRe()`,所以用 `overrides` 強制 11 會讓文件篩選在執行時壞掉。等 `vscode-languageclient` -出支援 minimatch 11 的版本,再升級並重新產生 lock。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 858f17885..f11a84de0 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -127,3 +127,10 @@ - **Before / after:** `je_auto_control` 0.0.225 editable + `je_auto_control_dev` 0.0.136 → `je_auto_control` 1.2.0 editable only; `pytest11` resolves to `je_auto_control_pytest`; `import je_auto_control` from another directory now resolves to the working tree. - **Not changed:** no third-party package was installed or upgraded (`--no-deps`). `pip check` reports the shared env one pin behind `pyproject.toml` (pillow 12.3.0 vs `==13.0.0`; PySide6 6.11.2 vs the `[gui]` pin 6.12.0); recorded in `Progress.md` › 雜項. - **Evidence:** `test_pytest_entrypoint_light.py` and `test_coverage_measurement.py` (6 passed) from the shared env. + +## U-20261112-02 · 2026-11-12 · minimatch 5.1.9 is outside the revised advisory range · #done #deps #security + +- **What:** Closes the `BLOCKED` `Progress.md` item "minimatch 11 在 VS Code 擴充套件" and corrects U-20261101-17. GHSA-g3hv-75wg-m249 was revised on 2026-11-04: its only vulnerable range is now `>= 7.0.0, < 11.0.1` (patched 11.0.1). `autocontrol-lsp/vscode/package-lock.json` locks `minimatch` 5.1.9, which that range does not include, so the lock needs no override and no wait for `vscode-languageclient`. +- **Evidence:** `gh api advisories/GHSA-g3hv-75wg-m249` (updated 2026-11-04T16:50:04Z, not withdrawn). The repository's Dependabot alerts list no `minimatch` alert in any state and 0 open alerts. npm: `vscode-languageclient` 11.0.0 (2026-10-22) requires `minimatch ^10.2.6`, inside the range, so upgrading the client to its latest release would move the extension *into* the advisory; the lock stays on 9.0.1. +- **Files:** `Progress.md`, this entry, the index row, the pointer added to U-20261101-17. +- **Open items:** none. diff --git a/docs/updates/2026-11.md b/docs/updates/2026-11.md index 5a8c2595f..c0dae15e5 100644 --- a/docs/updates/2026-11.md +++ b/docs/updates/2026-11.md @@ -558,7 +558,7 @@ Index and query commands: [README.md](README.md). New entries go at the end. 32 passed). - **Downstream:** TestPioneer and WebRunner lock Pillow through `je_auto_control`; they move to 13.0.0 once a release carries this pin. -- **Open items:** `Progress.md`, "minimatch 11 在 VS Code 擴充套件". +- **Open items:** `Progress.md`, "minimatch 11 在 VS Code 擴充套件". → corrected in U-20261112-02 (the advisory no longer covers 5.1.9). ## U-20261102-01 · 2026-11-02 · Merge the release line into dev for 1.1.0 · #release #migration diff --git a/docs/updates/README.md b/docs/updates/README.md index ad434419f..b5dd3252f 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-02 | 2026-11-12 | minimatch 5.1.9 is outside the revised advisory range | #done #deps #security | [2026-11-b](2026-11-b.md) | | U-20261112-01 | 2026-11-12 | Remove the stale dev package from the shared .venv | #done #tooling | [2026-11-b](2026-11-b.md) | | U-20261111-32 | 2026-11-11 | Retain peer media failures and observe live cleanup | #done #remote | [2026-11-b](2026-11-b.md) | | U-20261111-31 | 2026-11-11 | Bind delayed session retirement to original resources | #done #remote | [2026-11-b](2026-11-b.md) | From d60dd3aa1922311c20f758aee966d1735680dd77 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:24:43 +0800 Subject: [PATCH 045/161] Run each MCP tool call as a stoppable run that a client cancel stops notifications/cancelled only set the call's event, so an action list kept running and the MCP image/pixel waits slept through it, out of reach of ac_stop_execution too. --- CHANGELOG.md | 7 + Progress.md | 5 +- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 25 +-- .../Eng/doc/mcp_server/mcp_server_doc.rst | 10 +- .../Zh/doc/mcp_server/mcp_server_doc.rst | 8 +- docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + je_auto_control/utils/mcp_server/_call_run.py | 58 +++++++ je_auto_control/utils/mcp_server/context.py | 14 +- je_auto_control/utils/mcp_server/server.py | 2 +- .../utils/mcp_server/tools/_base.py | 7 +- .../utils/mcp_server/tools/_handlers_runs.py | 8 +- .../mcp_server/tools/_handlers_screen.py | 9 +- test/unit_test/headless/test_mcp_call_run.py | 151 ++++++++++++++++++ 17 files changed, 293 insertions(+), 26 deletions(-) create mode 100644 je_auto_control/utils/mcp_server/_call_run.py create mode 100644 test/unit_test/headless/test_mcp_call_run.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 07eb9ba39..80f0001ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- Each MCP `tools/call` now runs as a stoppable executor run (`mcp-…`). `notifications/cancelled` + stops it: an action list from `ac_execute_actions` halts before its next action and + `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll, answered `-32800` as before for a + cancelled call. `ac_stop_execution()` without a `run_id` (and any other `stop_execution()` + caller) now also stops MCP calls in progress, reported as an `ExecutionStopped` tool error, + and `ac_list_executions` lists them, excluding its own call. + - WebRTC peers retain media constructor and disable failures, expose cached slot outcomes, observe actual receiver/task completion, and guard deferred media operations against peer replacement. GUI caretaker and Diagnostics integration remain pending. diff --git a/Progress.md b/Progress.md index af0316475..df4a8b2ac 100644 --- a/Progress.md +++ b/Progress.md @@ -116,11 +116,10 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 - **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep; - MCP 自己的輪詢(`ac_wait_for_image`/`ac_wait_for_pixel`)不在可停止的執行裡。非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 + 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 -- **WebRTC**:`StatsPoller.start()` 會在 GUI 執行緒上最多等 2 秒(`future.result(timeout=2.0)`,是啟動路徑,沒動)。LAN 廣播的註冊與取消已移出 GUI 執行緒, - 但真的 zeroconf 的時間與名稱衝突行為只對假物件測過。 +- **WebRTC**:LAN 廣播的註冊與取消已移出 GUI 執行緒,但真的 zeroconf 的時間與名稱衝突行為只對假物件測過。 - **切換主題後那幾個事件迴圈回合內**,以被暫存的頁面為 parent 的 `QMessageBox` 會相對於隱藏的暫存 widget 定位(只影響位置)。 系統匣路徑在 offscreen 下沒有 tray,`_on_tray_open` 是直接呼叫測的。基準(`benchmarks/gui_*.py`)CI 仍不設門檻。 - **把 Python 建的 widget 放進分頁列在結束時崩潰**:已查明觸發條件——分頁列按鈕上接了 Python callable、又有排隊中的 `deleteLater()`、而行程經 `os._exit` 離開; diff --git a/README.md b/README.md index a9f65dbbd..7e83e83c4 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,8 @@ Host-requested file sends remain owned until their sender worker exits, includin MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. +An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first. + REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. USB enumeration/events, retained inspector statistics and process metrics also require `read_data`, as do `AC_list_usb_devices`, `AC_usb_recent_events`, `AC_inspector_recent` and `AC_inspector_summary`. Dashboard panels report missing capabilities independently and clear stale rows. A successful session refresh also clears its previous error status. Unlisted executor-command authorization remains a separate audit scope. Host read-only mode applies the same restrictions to explicitly supplied registries and later registrations. Both admission and refreshed invocation check mixed arguments. Configured MCP failure screenshots require a writable tool and a refreshed caller with drive authority; readonly calls and viewers never trigger them. This does not promise that every dependency or diagnostic read has no initialization side effects. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 6fd5271c1..7e3096df2 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -75,6 +75,8 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStop MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 +MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完。 + REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。USB 枚举/事件、保留的 inspector 统计与进程 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同样检查此权限。Dashboard 各面板分别显示缺少的权限并清除旧数据;session 刷新成功后也会清除先前的错误状态。未列入权限表的 executor 命令仍属于另一项审查范围。 主机只读模式对外部提供的目录及后续注册应用相同限制,接收请求及重新核对身份后的调用都检查混合用途参数。MCP 配置的失败截图需要可写入的工具及重新核对后具输入操作权限的调用者;只读调用与 viewer 不会触发截图。这不表示所有依赖包或诊断读取均无初始化副作用。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 8f385eaba..7ac6e80db 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -75,6 +75,8 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStop MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 +MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完。 + REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。USB 列舉/事件、保留的 inspector 統計與程序 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同樣檢查此權限。Dashboard 各面板分別顯示缺少的權限並清除舊資料;session 重新整理成功後也會清除先前的錯誤狀態。未列入權限表格的 executor 指令仍屬另一項審查範圍。 主機唯讀模式對外部提供的目錄及後續註冊套用相同限制,接收請求及重新核對身分後的呼叫都檢查混合用途參數。MCP 設定的失敗截圖需要可寫入的工具及重新核對後具輸入操作權限的呼叫者;唯讀呼叫與 viewer 不會觸發截圖。這不表示所有相依套件或診斷讀取均無初始化副作用。 diff --git a/architecture_explore.md b/architecture_explore.md index 3877f23a5..619ad759a 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -11,7 +11,7 @@ CI 以 `python scripts/generate_facade_exports.py --check` 檢查一致性。六 > 擷取每個模組的 docstring 與頂層公開名稱;統計數字取自實際檔案,非估算。 > 指令數與公開 API 數以 `executor.known_commands()` 與 `je_auto_control.__all__` 在工作樹上實測取得。 > -> **掃描時間**:2026-11-11 **版本**:`pyproject.toml` version `1.2.0` **分支**:`dev` +> **掃描時間**:2026-11-12 **版本**:`pyproject.toml` version `1.2.0` **分支**:`dev` --- @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,525 | -| 程式碼總行數 | 233,257 | +| Python 模組總數(含周邊子專案) | 1,526 | +| 程式碼總行數 | 233,339 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -516,7 +516,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,801 行。 +> 14 個套件、約 52,883 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -530,7 +530,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,084 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,166 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 660 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | @@ -756,7 +756,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,084 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,166 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -764,9 +764,9 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers.py` | 547 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | | `tools/_handlers_qa.py` | 619 | 同一種 adapter,QA 主題:斷言 DSL、資料驅動、SQL/PDF/郵件/HTTP 步驟、codegen、視覺回歸、狀態機、flaky 偵測與隔離、suite runner、無障礙稽核、裝置矩陣、媒體斷言。從 `_handlers.py` 依主題拆出的第一塊(750 行上限);兩者互不引用。 | | `tools/_handlers_input.py` | 221 | 同一種 adapter,輸入主題:滑鼠、鍵盤、虛擬手把(ViGEm)。 | -| `tools/_handlers_screen.py` | 344 | 同一種 adapter,螢幕主題:擷取、像素、影像與文字搜尋、螢幕錄影。 | +| `tools/_handlers_screen.py` | 349 | 同一種 adapter,螢幕主題:擷取、像素、影像與文字搜尋、螢幕錄影。 | | `tools/_handlers_system.py` | 592 | 同一種 adapter,桌面工作階段:視窗(狀態操作依正規化的後端成敗回覆)、行程與 shell、開檔、閒置與睡眠、音量、鎖定、輸入法狀態、欄位驗證與重試、色彩對比、變更排序、元件分類、剪貼簿。 | -| `tools/_handlers_runs.py` | 122 | 同一種 adapter,執行主題:executor、執行歷史、錄製、動作檔。 | +| `tools/_handlers_runs.py` | 124 | 同一種 adapter,執行主題:executor、執行歷史、錄製、動作檔。 | | `tools/_template_candidates.py` | 91 | 五個候選樣板工具,含縮圖、固定樣本驗證、路徑根目錄與取消。 | | `tools/_healing_source.py` | 41 | 原始步驟唯讀查閱工具,含進度、取消與目前路徑政策。 | | `tools/_healing_run.py` | 39 | 明確自癒操作與操作後驗證工具,保留受控失敗狀態。 | @@ -795,6 +795,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `_http_stateless.py` | 185 | MCP 2026-07-28 在 Streamable HTTP 上的規則:`MCP-Protocol-Version`/`Mcp-Method`/`Mcp-Name` 必須與 body 相符(`=?base64?…?=` 先解碼),不符是 400+`HeaderMismatch`;版本與中繼資料錯誤 400、未知方法 404。純函式,由 `http_transport.py` 回覆。 | | `http_sessions.py` | 301 | MCP 的 HTTP 傳輸用的 session 身分:`Mcp-Session-Id` 註冊表,以及每個 session 那條常駐的 server→client SSE 串流。 | | `_call_authority.py` | 31 | Bind anonymous MCP sessions to operator authority across direct and nested tool calls. | +| `_call_run.py` | 58 | 每次帶伺服器上下文的工具呼叫都是一個可停止的 executor 執行(`mcp-…`);`notifications/cancelled` 停掉它並回 `OperationCancelledError`。 | | `_origin_policies.py` | 114 | Connection-local roots and live task ceilings retire with their owning MCP authority. | | `_client_requests.py` | 278 | 伺服器主動送出的請求:`roots/list`/`elicitation/create`/`sampling/createMessage`,對應表與回應路由,以及破壞性工具的確認交握。只屬於握手時代:無狀態請求裡送出會丟例外。 | | `_stateless.py` | 267 | MCP 2026-07-28 無狀態版本,與以 `initialize` 握手的版本並存:逐請求的 `_meta`(版本、client 能力、`logLevel`)、`server/discover`、結果的 `resultType`/`serverInfo`/快取提示、`-32020`~`-32022` 錯誤碼,以及兩個時代逐請求分派的 mixin。 | @@ -805,13 +806,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `prompts.py` | 220 | MCP prompt 目錄。 | | `fake_backend.py` | 187 | CI/無頭測試用的記憶體內假後端。 | | `plugin_watcher.py` | 169 | 檔案變更時熱重載外掛工具的背景 watcher。 | -| `tools/_base.py` | 229 | 工具註冊表的共用型別與輔助;JSON 相容的 MCPToolResult 分離受控失敗旗標與資料。 | +| `tools/_base.py` | 234 | 工具註冊表的共用型別與輔助;JSON 相容的 MCPToolResult 分離受控失敗旗標與資料。 | | `tools/_readonly.py` | 32 | Read-only registry variants with enforced argument restrictions. 預設/外部/動態目錄共用篩選及呼叫限制。 | | `tools/_validation.py` | 124 | MCP 工具用到的 JSON Schema 子集驗證器。 | | `tools/plugin_tools.py` | 147 | 把外掛載入的 `AC_*` callable 包成 `MCPTool`。 | | `log_bridge.py` | 118 | 把 Python logging 記錄橋接成 MCP `notifications/message`;2026-07-28 的請求只收到自己設了 `logLevel` 時產生的記錄。 | | `audit.py` | 127 | MCP 工具呼叫稽核記錄。 | -| `context.py` | 69 | 傳給 opt-in 工具處理器的每次呼叫上下文,含取消、進度與伺服器路徑政策。 | +| `context.py` | 81 | 傳給 opt-in 工具處理器的每次呼叫上下文,含取消(同時停掉該次呼叫的 `StopToken`)、進度與伺服器路徑政策。 | | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | @@ -1532,7 +1533,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | | `gui/` | 150 | 40,579 | -| `utils/mcp_server/` | 61 | 22,084 | +| `utils/mcp_server/` | 62 | 22,166 | | `utils/remote_desktop/` | 77 | 16,709 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | @@ -1552,7 +1553,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,046 | -| **總計** | **1,513** | **232,512** | +| **總計** | **1,514** | **232,594** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst b/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst index bc9eec125..ed331d670 100644 --- a/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst +++ b/docs/source/Eng/doc/mcp_server/mcp_server_doc.rst @@ -88,6 +88,11 @@ Action executor / history ``ac_list_action_commands``, ``ac_list_run_history``, ``ac_stop_execution``, ``ac_list_executions`` (stop / list the stoppable runs; a list becomes stoppable by wrapping it in ``AC_run_stoppable``). + Every ``tools/call`` is itself a stoppable run, listed as ``mcp-…`` + while it runs (``ac_list_executions`` omits its own call): a stop ends an + ``ac_execute_actions`` list or an ``ac_wait_for_image`` / + ``ac_wait_for_pixel`` poll at its next checkpoint and answers the call as + a tool error. Scheduler / triggers / hotkeys ``ac_scheduler_add_job``, ``ac_scheduler_remove_job``, @@ -181,7 +186,10 @@ Logging notifications, progress, cancellation ``ctx.progress(value, total, message)`` to push ``notifications/progress`` (when the client supplied a ``progressToken``) and ``ctx.check_cancelled()`` to abort - cooperatively when ``notifications/cancelled`` arrives. + cooperatively when ``notifications/cancelled`` arrives. The cancel also + stops the call's stoppable run, so an action list the tool executes halts + at its next action and a wait on ``run_control.pause`` wakes at once; the + call is answered with ``-32800`` instead of a result. Starting the server (programmatic) ================================== diff --git a/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst b/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst index 87c8529d4..0f3736d95 100644 --- a/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst +++ b/docs/source/Zh/doc/mcp_server/mcp_server_doc.rst @@ -80,7 +80,10 @@ list-changed 通知與 elicitation。 ``ac_execute_actions``、``ac_execute_action_file``、 ``ac_list_action_commands``、``ac_list_run_history``、 ``ac_stop_execution``、``ac_list_executions``(停止/列出可停止的執行;把清單包進 - ``AC_run_stoppable`` 就是可停止的)。 + ``AC_run_stoppable`` 就是可停止的)。每個 ``tools/call`` 本身也是一個可停止的執行, + 執行期間以 ``mcp-…`` 列出(``ac_list_executions`` 不列自己這次呼叫):停止會讓 + ``ac_execute_actions`` 的清單或 ``ac_wait_for_image``/``ac_wait_for_pixel`` 的輪詢在 + 下一個檢查點結束,該次呼叫回報為工具錯誤。 排程 / 觸發 / 熱鍵 ``ac_scheduler_add_job``、``ac_scheduler_remove_job``、 @@ -161,7 +164,8 @@ Logging 通知 / Progress / Cancellation ``ctx.progress(value, total, message)`` 推送 ``notifications/progress``(client 須提供 ``progressToken``);呼 叫 ``ctx.check_cancelled()`` 在收到 ``notifications/cancelled`` - 時合作式中止。 + 時合作式中止。取消同時會停掉該次呼叫的可停止執行:工具執行的動作清單在下一個動作前停下, + 睡在 ``run_control.pause`` 上的等待立即醒來;該次呼叫以 ``-32800`` 回覆,而不是結果。 以程式啟動伺服器 ================ diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index f11a84de0..d9d99c8d4 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -134,3 +134,11 @@ - **Evidence:** `gh api advisories/GHSA-g3hv-75wg-m249` (updated 2026-11-04T16:50:04Z, not withdrawn). The repository's Dependabot alerts list no `minimatch` alert in any state and 0 open alerts. npm: `vscode-languageclient` 11.0.0 (2026-10-22) requires `minimatch ^10.2.6`, inside the range, so upgrading the client to its latest release would move the extension *into* the advisory; the lock stays on 9.0.1. - **Files:** `Progress.md`, this entry, the index row, the pointer added to U-20261101-17. - **Open items:** none. + +## U-20261112-03 · 2026-11-12 · MCP tool calls are stoppable runs; a cancel stops them · #done #mcp #executor + +- **What:** Closes the `Progress.md` › GUI › "stop 還叫不醒的" clause that `ac_wait_for_image` / `ac_wait_for_pixel` were outside every stoppable run, and the gap left by U-20261009-34 that `notifications/cancelled` only set the call's `cancelled_event`. `Tool.invoke` now runs every call that carries a server `ToolCallContext` under its own `StopToken` (`utils/mcp_server/_call_run.py`, run id `mcp-` + 12 hex). `ToolCallContext.cancel()` sets the event and stops that token; the server calls it on `notifications/cancelled`; a cancel that lands before the token exists is applied when the run starts. An `ExecutionStopped` raised while the call is cancelled becomes `OperationCancelledError` (answered `-32800`, audited `cancelled`); a stop from `ac_stop_execution` or another `stop_execution()` caller stays a tool error. The two waits sleep on `run_control.pause` (outside a run it is still `time.sleep`). `ac_list_executions` omits its own call. A call without a server context (`tool.invoke(args)` from Python) is not a run, as before. +- **Also:** the GUI bullet that `StatsPoller.start()` waits up to 2 s on the GUI thread was stale since U-20261111-17 and is removed from `Progress.md`. +- **Tests:** `test_mcp_call_run.py` (6): cancel and `stop_execution()` wake `ac_wait_for_pixel` during a 30 s poll (both fail with the old `time.sleep`), a cancel stops an `AC_sleep` action list before the next action, the listing omits only its own call, an early cancel, and no run without a context. With `test_mcp_stop_execution.py`, `test_mcp_server.py`, the doc-count, line-count, file-length, broad-except and complexity gates: 171 passed. The MCP / run-control / surface files (59): 1,608 passed, 1 failed in `test_sync_workspace_surfaces.py`, which fails identically on the unchanged tree (a `FileNotFoundError` under a 300-character pytest temp path on this machine). +- **Files:** `utils/mcp_server/{_call_run.py (new),context.py,server.py,tools/_base.py,tools/_handlers_runs.py,tools/_handlers_screen.py}`, `test_mcp_call_run.py` (new), both `mcp_server_doc.rst`, the three READMEs, `CHANGELOG.md`, `architecture_explore.md` (re-measured with `--fix`), `Progress.md`. +- **Open items:** a command already inside a backend still finishes before the stop is seen (unchanged, `Progress.md` › GUI). No real MCP client was used. diff --git a/docs/updates/README.md b/docs/updates/README.md index b5dd3252f..9a17ec046 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-03 | 2026-11-12 | MCP tool calls are stoppable runs; a cancel stops them | #done #mcp #executor | [2026-11-b](2026-11-b.md) | | U-20261112-02 | 2026-11-12 | minimatch 5.1.9 is outside the revised advisory range | #done #deps #security | [2026-11-b](2026-11-b.md) | | U-20261112-01 | 2026-11-12 | Remove the stale dev package from the shared .venv | #done #tooling | [2026-11-b](2026-11-b.md) | | U-20261111-32 | 2026-11-11 | Retain peer media failures and observe live cleanup | #done #remote | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/mcp_server/_call_run.py b/je_auto_control/utils/mcp_server/_call_run.py new file mode 100644 index 000000000..8282769d4 --- /dev/null +++ b/je_auto_control/utils/mcp_server/_call_run.py @@ -0,0 +1,58 @@ +"""Run one MCP tool call as a stoppable executor run that its cancellation stops. + +``notifications/cancelled`` used to set only the call's ``cancelled_event``: +a handler that polled :meth:`ToolCallContext.check_cancelled` noticed, but an +action list started by ``ac_execute_actions`` ran to its last action, and the +MCP polling waits (``ac_wait_for_image``, ``ac_wait_for_pixel``) slept through +the request. Every call that carries a :class:`ToolCallContext` now runs under +its own :class:`~je_auto_control.utils.executor.run_control.StopToken`: + +* the client's cancel stops the token, so the executor halts at its next + checkpoint and a wait sleeping on :func:`run_control.pause` wakes at once; + the stop surfaces as :class:`OperationCancelledError`, which the server + answers as a cancelled call rather than a tool failure; +* the call is listed by ``ac_list_executions`` and stopped by + ``ac_stop_execution`` (or any other ``stop_execution()`` caller, such as the + GUI) like every other stoppable run; such a stop is reported as the tool's + error, because the client did not ask for it. + +A call without a server context (``tool.invoke(arguments)`` from Python, or a +test's stand-in object) runs exactly as before. +""" +import uuid +from contextlib import contextmanager +from typing import Any, Iterator + +from je_auto_control.utils.mcp_server.context import ( + CLIENT_CANCEL_REASON, OperationCancelledError, ToolCallContext, +) + +#: Prefix of the run id an MCP tool call is listed under. +MCP_RUN_PREFIX = "mcp-" + + +@contextmanager +def tool_call_run(ctx: Any) -> Iterator[None]: + """Run the block as the stoppable run of the MCP call ``ctx`` describes.""" + if not isinstance(ctx, ToolCallContext): + yield + return + from je_auto_control.utils.executor.run_control import ( + ExecutionStopped, StopToken, stoppable_run, + ) + token = StopToken(f"{MCP_RUN_PREFIX}{uuid.uuid4().hex[:12]}") + ctx.stop_token = token + if ctx.cancelled: # cancelled before the token existed: ToolCallContext.cancel saw none + token.stop(CLIENT_CANCEL_REASON) + try: + with stoppable_run(token=token): + yield + except ExecutionStopped as stopped: + if ctx.cancelled: + raise OperationCancelledError(ctx.request_id) from stopped + raise + finally: + ctx.stop_token = None + + +__all__ = ["MCP_RUN_PREFIX", "tool_call_run"] diff --git a/je_auto_control/utils/mcp_server/context.py b/je_auto_control/utils/mcp_server/context.py index 06de7c8a5..c3af85440 100644 --- a/je_auto_control/utils/mcp_server/context.py +++ b/je_auto_control/utils/mcp_server/context.py @@ -12,6 +12,9 @@ from je_auto_control.utils.path_guard.policy import PathPolicy from je_auto_control.utils.exception.control_signals import OperationCancelledError as OperationCancelledError +#: The stop reason a run records when the MCP client cancelled its call. +CLIENT_CANCEL_REASON = "cancelled by the MCP client" + @dataclass class ToolCallContext: @@ -33,6 +36,15 @@ class ToolCallContext: path_policy: Optional[PathPolicy] = field(default=None, repr=False) session_id: str = "" tool_catalog: Optional[Callable[[], Any]] = field(default=None, repr=False) + #: The executor ``StopToken`` of the run this call executes as, while it runs. + stop_token: Optional[Any] = field(default=None, repr=False, compare=False) + + def cancel(self) -> None: + """Mark the call cancelled and stop the executor run it executes as.""" + self.cancelled_event.set() + token = self.stop_token + if token is not None: + token.stop(CLIENT_CANCEL_REASON) @property def cancelled(self) -> bool: @@ -66,4 +78,4 @@ def progress(self, value: float, total: Optional[float] = None, self.notifier("notifications/progress", params) -__all__ = ["OperationCancelledError", "ToolCallContext"] +__all__ = ["CLIENT_CANCEL_REASON", "OperationCancelledError", "ToolCallContext"] diff --git a/je_auto_control/utils/mcp_server/server.py b/je_auto_control/utils/mcp_server/server.py index 7610164c6..76239b8ae 100644 --- a/je_auto_control/utils/mcp_server/server.py +++ b/je_auto_control/utils/mcp_server/server.py @@ -509,7 +509,7 @@ def _cancel_active_call(self, params: Dict[str, Any]) -> None: with self._calls_lock: ctx = self._active_calls.get(call_key) if ctx is not None: - ctx.cancelled_event.set() + ctx.cancel() # also stops the executor run the call executes as autocontrol_logger.info( "MCP cancel signalled for call %r", request_id, ) diff --git a/je_auto_control/utils/mcp_server/tools/_base.py b/je_auto_control/utils/mcp_server/tools/_base.py index 099ce8647..5cc00b313 100644 --- a/je_auto_control/utils/mcp_server/tools/_base.py +++ b/je_auto_control/utils/mcp_server/tools/_base.py @@ -183,6 +183,9 @@ def invoke(self, arguments: Dict[str, Any], ctx: Any = None) -> Any: A source path policy follows managed submissions through legacy wrappers. Task-aware dispatch resolves this lazily carried policy's private metadata. + + A call from the server runs as its own stoppable executor run, which + the client's ``notifications/cancelled`` stops (``mcp_server._call_run``). """ if self.enforce_readonly_arguments: from je_auto_control.utils.mcp_server.tools._readonly import check_readonly_arguments @@ -190,8 +193,10 @@ def invoke(self, arguments: Dict[str, Any], ctx: Any = None) -> Any: from je_auto_control.utils.script_vars.execution import execution_scope from je_auto_control.utils.agent_runtime.origin_policy import source_policy_scope from je_auto_control.utils.mcp_server._call_authority import invocation_authority + from je_auto_control.utils.mcp_server._call_run import tool_call_run policy = getattr(ctx, "path_policy", None) - with execution_scope(), source_policy_scope(policy), invocation_authority(self, arguments, ctx): + with execution_scope(), source_policy_scope(policy), invocation_authority(self, arguments, ctx), \ + tool_call_run(ctx): if ctx is not None and _handler_accepts_ctx(self.handler): return self.handler(ctx=ctx, **arguments) return self.handler(**arguments) diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_runs.py b/je_auto_control/utils/mcp_server/tools/_handlers_runs.py index df7ce2f69..414dcdc11 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_runs.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_runs.py @@ -30,10 +30,12 @@ def stop_execution(run_id: Optional[str] = None, reason: str = "") -> Dict[str, return {"stopped": _stop(str(run_id) if run_id else None, str(reason or ""))} -def list_executions() -> List[Dict[str, Any]]: - """The stoppable runs in progress.""" +def list_executions(ctx: Any = None) -> List[Dict[str, Any]]: + """The stoppable runs in progress, other than the run of this MCP call itself.""" from je_auto_control.utils.executor.run_control import active_executions - return active_executions() + own = getattr(ctx, "stop_token", None) + own_id = own.run_id if own is not None else None + return [run for run in active_executions() if run["run_id"] != own_id] def list_action_commands() -> List[str]: diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_screen.py b/je_auto_control/utils/mcp_server/tools/_handlers_screen.py index 286cc7f1f..2ef730516 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_screen.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_screen.py @@ -107,12 +107,17 @@ def _matching_channels(raw: Any, target: List[int], tol: int) -> Optional[List[i def _sleep_before(deadline: float, poll_seconds: float) -> bool: - """Sleep one poll, never past ``deadline``; ``False`` once the deadline has passed.""" + """Sleep one poll, never past ``deadline``; ``False`` once the deadline has passed. + + The sleep is :func:`run_control.pause`: a call from the server runs as a + stoppable run, so a cancel or ``ac_stop_execution`` wakes it mid-poll. + """ import time as _time + from je_auto_control.utils.executor.run_control import pause remaining = deadline - _time.monotonic() if remaining <= 0: return False - _time.sleep(min(poll_seconds, remaining)) + pause(min(poll_seconds, remaining), sleep=_time.sleep) return True diff --git a/test/unit_test/headless/test_mcp_call_run.py b/test/unit_test/headless/test_mcp_call_run.py new file mode 100644 index 000000000..82b596802 --- /dev/null +++ b/test/unit_test/headless/test_mcp_call_run.py @@ -0,0 +1,151 @@ +"""An MCP tool call is a stoppable run that ``notifications/cancelled`` stops. + +Before, the cancel only set the call's ``cancelled_event``: an action list +ran to its end and ``ac_wait_for_image`` / ``ac_wait_for_pixel`` slept on +``time.sleep`` until their timeout, out of reach of ``ac_stop_execution``. +""" +import json +import threading +import time +from typing import Any, Dict + +import pytest + +from je_auto_control.utils.executor.run_control import ( + active_executions, current_stop_token, stop_execution, +) +from je_auto_control.utils.mcp_server._call_run import MCP_RUN_PREFIX +from je_auto_control.utils.mcp_server.context import OperationCancelledError, ToolCallContext +from je_auto_control.utils.mcp_server.server import MCPServer +from je_auto_control.utils.mcp_server.tools import MCPTool, build_default_tool_registry + +_EMPTY = {"type": "object", "properties": {}} + + +def _call(server: MCPServer, msg_id: int, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: + raw = server.handle_line(json.dumps({ + "jsonrpc": "2.0", "id": msg_id, "method": "tools/call", + "params": {"name": name, "arguments": arguments}, + })) + return json.loads(raw) + + +def _cancel(server: MCPServer, msg_id: int) -> None: + server.handle_line(json.dumps({ + "jsonrpc": "2.0", "method": "notifications/cancelled", + "params": {"requestId": msg_id, "reason": "test"}, + })) + + +def _start(server, msg_id, name, arguments): + """Run one call on a thread; return (thread, holder) once it is a listed run.""" + holder: Dict[str, Any] = {} + + def run(): + holder["started"] = time.monotonic() + holder["response"] = _call(server, msg_id, name, arguments) + holder["finished"] = time.monotonic() + + thread = threading.Thread(target=run, daemon=True) + thread.start() + deadline = time.monotonic() + 5.0 + while not any(r["run_id"].startswith(MCP_RUN_PREFIX) for r in active_executions()): + assert time.monotonic() < deadline, "the call never became a stoppable run" + time.sleep(0.01) + return thread, holder + + +@pytest.fixture() +def never_matching_pixel(monkeypatch): + import je_auto_control.wrapper.auto_control_screen as screen_module + monkeypatch.setattr(screen_module, "get_pixel", lambda x, y, hwnd=None: (0, 0, 0)) + + +def _wait_for_pixel_server() -> MCPServer: + tools = [tool for tool in build_default_tool_registry() if tool.name == "ac_wait_for_pixel"] + return MCPServer(tools=tools) + + +# One poll outlasts every bound below: only a wake mid-sleep can meet them. +_PIXEL_ARGS = {"x": 1, "y": 2, "target_rgb": [255, 0, 0], "timeout": 60.0, "poll": 30.0} + + +def test_cancel_wakes_wait_for_pixel_mid_poll(never_matching_pixel): + server = _wait_for_pixel_server() + thread, holder = _start(server, 11, "ac_wait_for_pixel", _PIXEL_ARGS) + _cancel(server, 11) + thread.join(timeout=10.0) + assert not thread.is_alive() + assert holder["response"]["error"]["code"] == -32800 + assert holder["finished"] - holder["started"] < 10.0 + assert active_executions() == [] + + +def test_stop_execution_ends_wait_for_pixel_as_a_tool_error(never_matching_pixel): + server = _wait_for_pixel_server() + thread, holder = _start(server, 12, "ac_wait_for_pixel", _PIXEL_ARGS) + assert stop_execution(reason="operator") == 1 + thread.join(timeout=10.0) + assert not thread.is_alive() + result = holder["response"]["result"] + assert result["isError"] is True + assert "ExecutionStopped" in result["content"][0]["text"] + + +def test_cancel_stops_an_action_list_the_call_runs(): + from je_auto_control.utils.executor.action_executor import execute_action + reached = [] + + def run_actions(): + execute_action([["AC_sleep", {"seconds": 30}]]) + reached.append("after") + return "done" + + server = MCPServer(tools=[MCPTool(name="run_actions", description="d", + input_schema=_EMPTY, handler=run_actions)]) + thread, holder = _start(server, 13, "run_actions", {}) + _cancel(server, 13) + thread.join(timeout=5.0) + assert not thread.is_alive() + assert holder["response"]["error"]["code"] == -32800 + assert reached == [] + + +def test_list_executions_omits_its_own_call_but_lists_others(never_matching_pixel): + tools = [tool for tool in build_default_tool_registry() + if tool.name in {"ac_wait_for_pixel", "ac_list_executions"}] + server = MCPServer(tools=tools) + thread, _holder = _start(server, 14, "ac_wait_for_pixel", _PIXEL_ARGS) + try: + listing = _call(server, 15, "ac_list_executions", {})["result"] + runs = listing.get("structuredContent", listing) + text = json.dumps(runs) + assert text.count(MCP_RUN_PREFIX) == 1 + finally: + _cancel(server, 14) + thread.join(timeout=5.0) + + +def test_a_cancel_that_arrives_before_the_run_still_stops_it(): + ctx = ToolCallContext(request_id=21) + ctx.cancel() + + def handler(): + from je_auto_control.utils.executor.run_control import pause + pause(30) + return "slept" + + tool = MCPTool(name="sleepy", description="d", input_schema=_EMPTY, handler=handler) + started = time.monotonic() + with pytest.raises(OperationCancelledError): + tool.invoke({}, ctx=ctx) + assert time.monotonic() - started < 5.0 + assert ctx.stop_token is None + + +def test_invoke_without_a_server_context_is_not_a_run(): + seen = [] + tool = MCPTool(name="plain", description="d", input_schema=_EMPTY, + handler=lambda: seen.append(current_stop_token()) or "ok") + assert tool.invoke({}) == "ok" + assert seen == [None] From 9baa278e54e8dcc4a6b3e49ae28d4b168fbf49d5 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:34:24 +0800 Subject: [PATCH 046/161] Send no press hold on iOS swipes and refuse off-screen Android pinches Checked against the uiautomator2 3.7.1 and facebook-wda 1.5.4 sources: WDA's swipe duration is the hold before moving, and uiautomator2 asserts non-negative points. --- CHANGELOG.md | 7 +++++ Progress.md | 13 +++++---- architecture_explore.md | 18 ++++++------ docs/source/Eng/doc/mobile/mobile_doc.rst | 15 ++++++---- docs/source/Zh/doc/mobile/mobile_doc.rst | 12 +++++--- docs/updates/2026-11-b.md | 9 ++++++ docs/updates/README.md | 1 + je_auto_control/android/input.py | 7 ++++- je_auto_control/ios/apps.py | 11 ++++++-- je_auto_control/ios/input.py | 15 ++++++++-- .../utils/mcp_server/tools/_factories.py | 5 ++-- .../headless/test_mobile_input_capture.py | 28 +++++++++++++++++++ 12 files changed, 111 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80f0001ad..f51a36369 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- iOS `swipe` (`Swipe` gestures, `AC_ios_swipe`, `ac_ios_swipe`) no longer presses for + `duration_s` before moving: facebook-wda's swipe duration is the start-point hold, so the + old mapping made swipes start as drags. WebDriverAgent sets the travel speed and + `duration_s` has no effect on iOS; a negative or NaN value is rejected. An Android pinch + whose fingers would reach past the left or top edge raises `DeviceError` instead of + uiautomator2's bare `AssertionError`. + - Each MCP `tools/call` now runs as a stoppable executor run (`mcp-…`). `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll, answered `-32800` as before for a diff --git a/Progress.md b/Progress.md index df4a8b2ac..cf21e729b 100644 --- a/Progress.md +++ b/Progress.md @@ -79,15 +79,18 @@ `BLOCKED` — 需要 Android 模擬器或實機、iPhone 與 WebDriverAgent;這台機器連 `adb` 都沒有 -U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WDA 測過。`uiautomator2` 與 `facebook-wda` 沒有安裝在開發環境裡, -方法名稱與參數是憑記憶寫的,第一次接上真的 SDK 很可能要修: +U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WDA 測過。方法名稱與簽章已對 SDK 原始碼核過 +(uiautomator2 3.7.1、facebook-wda 1.5.4,U-20261112-04):全部存在、參數相符;沒有一個在裝置上執行過。還沒驗的: -- uiautomator2:`send_keys`、`drag`、空 selector 的 `gesture(...)`(捏合)、`clipboard`/`set_clipboard`、對話框按鈕的 resource id。 -- facebook-wda:`app_launch`/`app_terminate`/`app_state`、`alert.*`、`set_clipboard`、`status()`、`orientation` 的值、元素的 `pinch`、`screenshot()` 回傳 PIL 影像。 +- uiautomator2:對話框按鈕的 resource id(`ACCEPT_BUTTONS`/`DISMISS_BUTTONS`)是裝置與 OEM 的資料,原始碼驗不到。 +- facebook-wda:`orientation` 只回 `PORTRAIT`/`LANDSCAPE`(原始碼的 docstring),`UIA_DEVICE_ORIENTATION_*` 兩個值是否真的會回來未知; + `app_state` 的 `value` 依 `XCUIApplicationState`(4 是前景),SDK 的 docstring 寫成 1–3,以 Apple 的列舉為準,沒在裝置上看過。 - 旋轉方向:螢幕截圖以面板自然方向回來時,`landscape_left` 轉 270°、`landscape_right` 轉 90°,是從文件推的,沒看過。 - Android:`input draganddrop` 是否存在、`monkey` 啟動輸出、`pidof`/`pm path` 的結束碼、`dumpsys activity activities` 的格式、`pkill -INT screenrecord` 能否收尾 MP4。 ADBKeyBoard 的送達無法由裝置確認,是從 IME 被選取推定的。 -- 已知限制:iOS 捏合忽略 `x`/`y`/`span`;iOS `app_state` 不會回 `not_installed`;iOS 的安裝/檔案/錄影沒有 adapter(只有 `MobileExtension` 協定與註冊點); +- 已知限制:iOS 捏合忽略 `x`/`y`/`span`;iOS 滑動忽略 `duration_s`(WDA 的 drag duration 是按住時間,不能設移動時間);iOS `app_state` 不會回 `not_installed`;iOS 的安裝/檔案/錄影沒有 adapter(只有 `MobileExtension` 協定與註冊點); + `DECIDE`:iOS 讀剪貼簿(`AC_ios_get_clipboard`、`WdaExtension.get_clipboard`)在 facebook-wda 1.5.4 會請 Siri 把 WDA 帶到前景約 3 秒、 + 再重新啟動原本在前景的 App——已寫進文件與能力說明,但是否該改成要明確啟用才讀,請維護者決定。 Mobile 分頁的 probe/run 已由 TabTask 在背景執行;真實 SDK 的逾時、取消與裝置回應仍待實機驗收。`AC_android_shell` 刻意不做成 MCP 工具,**請維護者確認**。 - 沒有 `examples/` 的實機腳本以外的 smoke;Xcode/WDA 的建置與簽章只寫成前置條件。 diff --git a/architecture_explore.md b/architecture_explore.md index 619ad759a..9eb6ea8ab 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,526 | -| 程式碼總行數 | 233,339 | +| 程式碼總行數 | 233,363 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -282,7 +282,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `android/find.py` | 108 | uiautomator2 widget 樹的元素查詢。 | | `ios/client.py` | 126 | `facebook-wda`(WebDriverAgent)封裝。 | | `ios/find.py` | 94 | XCUITest 無障礙查詢。 | -| `ios/input.py` | 83 | iOS 觸控與按鍵原語。 | +| `ios/input.py` | 94 | iOS 觸控與按鍵原語。 | | `ios/screen.py` | 85 | iOS 裝置螢幕擷取與尺寸。 | ### 5.4 能力層 `utils/`(313 個子套件) @@ -516,7 +516,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,883 行。 +> 14 個套件、約 52,884 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -530,7 +530,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,166 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,167 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 660 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | @@ -756,11 +756,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,166 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,167 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `tools/_factories.py` | 9,388 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | +| `tools/_factories.py` | 9,389 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | | `tools/_handlers.py` | 547 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | | `tools/_handlers_qa.py` | 619 | 同一種 adapter,QA 主題:斷言 DSL、資料驅動、SQL/PDF/郵件/HTTP 步驟、codegen、視覺回歸、狀態機、flaky 偵測與隔離、suite runner、無障礙稽核、裝置矩陣、媒體斷言。從 `_handlers.py` 依主題拆出的第一塊(750 行上限);兩者互不引用。 | | `tools/_handlers_input.py` | 221 | 同一種 adapter,輸入主題:滑鼠、鍵盤、虛擬手把(ViGEm)。 | @@ -1533,7 +1533,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | | `gui/` | 150 | 40,579 | -| `utils/mcp_server/` | 62 | 22,166 | +| `utils/mcp_server/` | 62 | 22,167 | | `utils/remote_desktop/` | 77 | 16,709 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | @@ -1552,8 +1552,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,046 | -| **總計** | **1,514** | **232,594** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,069 | +| **總計** | **1,514** | **232,618** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/mobile/mobile_doc.rst b/docs/source/Eng/doc/mobile/mobile_doc.rst index 323dcea78..b6e2f29c8 100644 --- a/docs/source/Eng/doc/mobile/mobile_doc.rst +++ b/docs/source/Eng/doc/mobile/mobile_doc.rst @@ -183,14 +183,17 @@ device input coordinates: - WDA touch-and-hold * - ``Swipe(x1, y1, x2, y2, duration_s)`` - ``input swipe`` - - WDA drag + - WDA drag with no press hold; WDA sets the travel speed, so + ``duration_s`` has no effect (WDA's drag duration is the hold) * - ``Drag(x1, y1, x2, y2, hold_s, duration_s)`` - ``input draganddrop``; falls back to ``uiautomator2`` on a device whose ``input`` lacks it - WDA drag with ``hold_s`` as the press duration * - ``Pinch(x, y, scale, duration_s, span)`` - ``uiautomator2`` two-pointer gesture; ``adb shell input`` has one - pointer, so without it this raises ``DeviceUnsupportedError`` + pointer, so without it this raises ``DeviceUnsupportedError``. A + finger that would start or end left of / above the screen raises + ``DeviceError`` - Pinch on the frontmost application. WDA pinches an element, not a coordinate, so ``x`` / ``y`` / ``span`` are ignored. @@ -324,9 +327,11 @@ reason:: * - ``clipboard`` - Through ``uiautomator2``; ``needs_dependency`` without it, because ``adb`` cannot reach the clipboard on current Android. - - Set only. Reading is allowed by WDA only while WDA itself is in front, - and raises ``DeviceUnsupportedError`` on a ``facebook-wda`` build - without ``get_clipboard``. + - Set; reading is allowed by WDA only while WDA itself is in front. + ``facebook-wda`` 1.5.4's ``get_clipboard`` asks Siri to open + WebDriverAgentRunner, waits 3 s, reads, and relaunches the app that was + in front, so the app under test leaves the foreground meanwhile. A + build without ``get_clipboard`` raises ``DeviceUnsupportedError``. * - ``recording`` - ``adb shell screenrecord`` (180 s at most), stopped with ``SIGINT`` so the file is finalised, then pulled and removed from the device. A diff --git a/docs/source/Zh/doc/mobile/mobile_doc.rst b/docs/source/Zh/doc/mobile/mobile_doc.rst index a5ad24e9a..81bbe9908 100644 --- a/docs/source/Zh/doc/mobile/mobile_doc.rst +++ b/docs/source/Zh/doc/mobile/mobile_doc.rst @@ -166,14 +166,16 @@ iOS 只請求 WDA 的 ``/status``\ 。 - WDA touch-and-hold * - ``Swipe(x1, y1, x2, y2, duration_s)`` - ``input swipe`` - - WDA drag + - 不按住的 WDA drag;移動速度由 WDA 決定,\ ``duration_s`` 沒有作用 + (WDA drag 的 duration 是按住的時間) * - ``Drag(x1, y1, x2, y2, hold_s, duration_s)`` - ``input draganddrop``\ ;裝置的 ``input`` 沒有這個子指令時退回 ``uiautomator2`` - WDA drag,\ ``hold_s`` 是按住的時間 * - ``Pinch(x, y, scale, duration_s, span)`` - ``uiautomator2`` 的雙指手勢;\ ``adb shell input`` 只有一個觸控點, - 沒裝的話丟 ``DeviceUnsupportedError`` + 沒裝的話丟 ``DeviceUnsupportedError``\ 。手指的起點或終點落在螢幕左方/上方 + 時丟 ``DeviceError`` - 對最前景的 App 做 pinch。WDA 的 pinch 對象是元素而不是座標,所以 ``x`` / ``y`` / ``span`` 會被忽略。 @@ -301,8 +303,10 @@ Device matrix 的裝置規格可以寫 ``app_id``\ :第一個步驟之前會 * - ``clipboard`` - 透過 ``uiautomator2``\ ;沒裝時是 ``needs_dependency``\ ,因為新版 Android 上 ``adb`` 碰不到剪貼簿。 - - 只能寫入。WDA 只在 WDA 自己位於前景時才允許讀取;\ ``facebook-wda`` - 版本沒有 ``get_clipboard`` 時丟 ``DeviceUnsupportedError``\ 。 + - 可寫入;WDA 只在 WDA 自己位於前景時才允許讀取。\ ``facebook-wda`` 1.5.4 + 的 ``get_clipboard`` 會請 Siri 開啟 WebDriverAgentRunner、等 3 秒、讀取, + 再重新啟動原本在前景的 App,期間受測 App 離開前景。沒有 ``get_clipboard`` + 的版本丟 ``DeviceUnsupportedError``\ 。 * - ``recording`` - ``adb shell screenrecord``\ (最長 180 秒),以 ``SIGINT`` 停止好讓檔案 收尾,再拉回主機並從裝置刪除。錄影是裝置端的狀態:關閉 session 不會 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d9d99c8d4..d35ee6b1e 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -142,3 +142,12 @@ - **Tests:** `test_mcp_call_run.py` (6): cancel and `stop_execution()` wake `ac_wait_for_pixel` during a 30 s poll (both fail with the old `time.sleep`), a cancel stops an `AC_sleep` action list before the next action, the listing omits only its own call, an early cancel, and no run without a context. With `test_mcp_stop_execution.py`, `test_mcp_server.py`, the doc-count, line-count, file-length, broad-except and complexity gates: 171 passed. The MCP / run-control / surface files (59): 1,608 passed, 1 failed in `test_sync_workspace_surfaces.py`, which fails identically on the unchanged tree (a `FileNotFoundError` under a 300-character pytest temp path on this machine). - **Files:** `utils/mcp_server/{_call_run.py (new),context.py,server.py,tools/_base.py,tools/_handlers_runs.py,tools/_handlers_screen.py}`, `test_mcp_call_run.py` (new), both `mcp_server_doc.rst`, the three READMEs, `CHANGELOG.md`, `architecture_explore.md` (re-measured with `--fix`), `Progress.md`. - **Open items:** a command already inside a backend still finishes before the stop is seen (unchanged, `Progress.md` › GUI). No real MCP client was used. + +## U-20261112-04 · 2026-11-12 · Mobile SDK calls checked against uiautomator2 and facebook-wda source · #done #mobile + +- **What:** Closes the part of `Progress.md` › 行動裝置 that said the uiautomator2 / facebook-wda method names were written from memory. The wheels `uiautomator2-3.7.1` and `facebook_wda-1.5.4` were downloaded into a scratch directory with `--no-deps` and read, not installed or run. Every call the adapters make exists with a matching signature: uiautomator2 `connect(serial)`, `Device.send_keys/drag(sx, sy, ex, ey, duration)/click(x, y)/clipboard/set_clipboard/dump_hierarchy`, `d()` → `UiObject.gesture(start1, start2, end1, end2, steps)`, `UiObject.exists` (a property whose `Exists.__bool__` queries the device), `.info`, `.wait(timeout=)`; facebook-wda `Client(url)`, `app_launch/app_terminate/app_state`, `tap/tap_hold/swipe/send_keys/press`, `alert.exists/text/accept/dismiss`, `set_clipboard/get_clipboard`, `status()`, `orientation`, `screenshot()` (Pillow by default), and `Selector.__getattr__` forwarding `pinch(scale, velocity)` to the element. +- **Fixed from the source:** (1) `ios/input.py:swipe` handed `duration_s` (default 0.5 s) to `Client.swipe`, whose `duration` is the press held at the start point (`/wda/dragfromtoforduration`); facebook-wda's own `swipe_left` and friends send none. iOS swipes now send no hold, `duration_s` has no effect there (a negative or NaN value is rejected), and `Drag` stays the gesture that holds. (2) uiautomator2's `pos_rel2abs` asserts `x >= 0` and `y >= 0`, so an Android pinch reaching past the left edge raised a bare `AssertionError`; it now raises `DeviceError` before the SDK is called. +- **Documented, not changed:** facebook-wda 1.5.4's `get_clipboard` asks Siri to open WebDriverAgentRunner, sleeps 3 s, reads, and relaunches the app that was in front. The iOS clipboard capability text, `WdaExtension.get_clipboard` and both mobile docs say so; whether reading should need an explicit opt-in is a `DECIDE` in `Progress.md`. +- **Tests:** `test_mobile_input_capture.py` +3 (iOS swipe sends hold 0, rejects negative and NaN, Android pinch past the edge is refused before uiautomator2). Mobile / iOS / Android test files: 576 passed, 1 skipped; catalogue and doc tests 2,223 passed after the map was re-measured. +- **Files:** `ios/input.py`, `ios/apps.py`, `android/input.py`, `utils/mcp_server/tools/_factories.py` (the `ac_ios_swipe` description), both `mobile_doc.rst`, `CHANGELOG.md`, `architecture_explore.md`, `Progress.md`. +- **Open items:** still nothing run on a device; dialog-button resource ids and the orientation values WDA really returns stay open in `Progress.md` › 行動裝置. diff --git a/docs/updates/README.md b/docs/updates/README.md index 9a17ec046..988a78126 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-04 | 2026-11-12 | Mobile SDK calls checked against uiautomator2 and facebook-wda source | #done #mobile | [2026-11-b](2026-11-b.md) | | U-20261112-03 | 2026-11-12 | MCP tool calls are stoppable runs; a cancel stops them | #done #mcp #executor | [2026-11-b](2026-11-b.md) | | U-20261112-02 | 2026-11-12 | minimatch 5.1.9 is outside the revised advisory range | #done #deps #security | [2026-11-b](2026-11-b.md) | | U-20261112-01 | 2026-11-12 | Remove the stale dev package from the shared .venv | #done #tooling | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/android/input.py b/je_auto_control/android/input.py index e55d935aa..bca5c0e3a 100644 --- a/je_auto_control/android/input.py +++ b/je_auto_control/android/input.py @@ -18,7 +18,7 @@ AdbError, AdbUnsupportedError, adb_text_safe, ) from je_auto_control.android.client import UIAutomatorDevice, translate_device_errors -from je_auto_control.wrapper.device_context import Drag, LongPress, Pinch, Swipe, Tap +from je_auto_control.wrapper.device_context import DeviceError, Drag, LongPress, Pinch, Swipe, Tap #: The IME of the ADBKeyBoard project, which accepts text as a broadcast. ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME" @@ -142,6 +142,11 @@ def pinch_points(gesture: Pinch) -> Tuple[Tuple[int, int], Tuple[int, int], @translate_device_errors def _ui_pinch(ui_device: UIAutomatorDevice, gesture: Pinch) -> None: start1, start2, end1, end2 = pinch_points(gesture) + if min(min(point) for point in (start1, start2, end1, end2)) < 0: + # uiautomator2's pos_rel2abs asserts x >= 0 and y >= 0: say so before it does. + raise DeviceError( + f"the pinch at ({gesture.x}, {gesture.y}) with span {gesture.span} " + "reaches past the left edge of the screen") steps = max(2, round(gesture.duration_s * _STEPS_PER_SECOND)) # A two-pointer gesture is performed on a UI object but takes absolute # points, so the empty selector (the root node) serves for any position. diff --git a/je_auto_control/ios/apps.py b/je_auto_control/ios/apps.py index 3dd5135ee..a48c120de 100644 --- a/je_auto_control/ios/apps.py +++ b/je_auto_control/ios/apps.py @@ -85,7 +85,8 @@ def capability(self, feature: str) -> DeviceCapability: if feature == "clipboard": return DeviceCapability( feature, STATE_AVAILABLE, - "set only: reading the pasteboard is allowed only while WDA is in front") + "set; reading brings WebDriverAgent to the front through Siri for about " + "3 s and then relaunches the app that was in front") if feature in ("install", "files", "recording"): return DeviceCapability(feature, STATE_NEEDS_DEPENDENCY, NEEDS_ADAPTER) return DeviceCapability(feature, STATE_UNSUPPORTED, f"unknown feature {feature!r}") @@ -121,7 +122,13 @@ def set_clipboard(self, text: str) -> None: _set_pasteboard(self._device_source(), text) def get_clipboard(self) -> str: - """The pasteboard's text, where this facebook-wda build can read it.""" + """The pasteboard's text, where this facebook-wda build can read it. + + WebDriverAgent reads the pasteboard only while it is in front, so + facebook-wda 1.5.4's ``get_clipboard`` asks Siri to open + WebDriverAgentRunner, waits 3 s, reads, and relaunches the app that + was in front: the app under test leaves the foreground meanwhile. + """ return _get_pasteboard(self._device_source()) diff --git a/je_auto_control/ios/input.py b/je_auto_control/ios/input.py index efc8b8e95..cb1a1af46 100644 --- a/je_auto_control/ios/input.py +++ b/je_auto_control/ios/input.py @@ -30,9 +30,20 @@ def long_press(x: int, y: int, duration_s: float = 1.0, def swipe(x1: int, y1: int, x2: int, y2: int, duration_s: float = 0.5, *, device: Optional[IOSDevice] = None) -> None: - """Linear swipe from ``(x1, y1)`` to ``(x2, y2)`` over ``duration_s``.""" + """Swipe from ``(x1, y1)`` to ``(x2, y2)``; WebDriverAgent sets the travel speed. + + facebook-wda's ``swipe(..., duration)`` is the press held at the start + point before moving (``/wda/dragfromtoforduration``), not the travel time, + and its own ``swipe_left`` and friends pass none. Handing ``duration_s`` + over as a hold made every swipe press for half a second first, which iOS + can read as the start of a drag. So no hold is sent and ``duration_s`` is + accepted for the shared :class:`Swipe` gesture but has no effect here; + :func:`drag` is the gesture that holds. + """ + if not float(duration_s) >= 0: # NOSONAR S1940 # reason: also rejects NaN + raise ValueError("duration_s must be zero or positive") handle = (device or default_ios_device()).handle - handle.swipe(int(x1), int(y1), int(x2), int(y2), float(duration_s)) + handle.swipe(int(x1), int(y1), int(x2), int(y2), 0) @translate_device_errors diff --git a/je_auto_control/utils/mcp_server/tools/_factories.py b/je_auto_control/utils/mcp_server/tools/_factories.py index 4779ef46f..00055256f 100644 --- a/je_auto_control/utils/mcp_server/tools/_factories.py +++ b/je_auto_control/utils/mcp_server/tools/_factories.py @@ -1126,8 +1126,9 @@ def ios_tools() -> List[MCPTool]: ), MCPTool( name="ac_ios_swipe", - description=("Swipe from (x1, y1) to (x2, y2) over " - "duration_s seconds."), + description=("Swipe from (x1, y1) to (x2, y2). WebDriverAgent " + "sets the travel speed; duration_s is accepted " + "and has no effect."), input_schema=schema({ "x1": {"type": "integer"}, "y1": {"type": "integer"}, diff --git a/test/unit_test/headless/test_mobile_input_capture.py b/test/unit_test/headless/test_mobile_input_capture.py index bd59e1f4b..c47d502ee 100644 --- a/test/unit_test/headless/test_mobile_input_capture.py +++ b/test/unit_test/headless/test_mobile_input_capture.py @@ -174,6 +174,34 @@ def test_ios_gestures(): ] +def test_ios_swipe_sends_no_hold(): + # facebook-wda's swipe duration is the press held before moving, so a + # travel time handed over as a hold made every swipe start as a drag. + handle = FakeWda() + _ios(handle).perform(Swipe(1, 2, 3, 4, duration_s=0.5)) + assert handle.input_calls == [ + {"op": "swipe", "x1": 1, "y1": 2, "x2": 3, "y2": 4, "duration": 0}] + + +def test_ios_swipe_rejects_a_negative_or_nan_duration(): + from je_auto_control.ios import input as ios_input + handle = FakeWda() + device = IOSDevice(url="http://wda.test:8100", handle=handle) + for bad in (-1.0, float("nan")): + with pytest.raises(ValueError): + ios_input.swipe(1, 2, 3, 4, bad, device=device) + assert handle.input_calls == [] + + +def test_android_pinch_past_the_left_edge_is_refused_before_uiautomator2(adb_host): + # uiautomator2 3.7.1's pos_rel2abs asserts x >= 0: a bare AssertionError otherwise. + handle = FakeU2() + session = _android(adb_host, ui_device=UIAutomatorDevice(handle=handle)) + with pytest.raises(DeviceError, match="left edge"): + session.perform(Pinch(50, 800, scale=2.0, span=400)) + assert handle.calls == [] + + def test_invalid_gestures_are_rejected(): with pytest.raises(DeviceError): Pinch(1, 2, scale=1) From a752db3a076f0a42de2aad8abf2a318ebc739f50 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:36:50 +0800 Subject: [PATCH 047/161] Update four WebRTC tests to the media retention contract They still expected a failed mic close to be forgotten and a failed recording to stop cleanly, which kept every dev headless square red. --- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + .../headless/test_webrtc_host_channels.py | 10 +++++++--- .../unit_test/headless/test_webrtc_media_types.py | 9 ++++++++- .../headless/test_webrtc_viewer_control.py | 15 ++++++++++----- 5 files changed, 33 insertions(+), 9 deletions(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d35ee6b1e..eb15a45c6 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -151,3 +151,10 @@ - **Tests:** `test_mobile_input_capture.py` +3 (iOS swipe sends hold 0, rejects negative and NaN, Android pinch past the edge is refused before uiautomator2). Mobile / iOS / Android test files: 576 passed, 1 skipped; catalogue and doc tests 2,223 passed after the map was re-measured. - **Files:** `ios/input.py`, `ios/apps.py`, `android/input.py`, `utils/mcp_server/tools/_factories.py` (the `ac_ios_swipe` description), both `mobile_doc.rst`, `CHANGELOG.md`, `architecture_explore.md`, `Progress.md`. - **Open items:** still nothing run on a device; dialog-button resource ids and the orientation values WDA really returns stay open in `Progress.md` › 行動裝置. + +## U-20261112-05 · 2026-11-12 · Four WebRTC tests still asserted the pre-retention contract · #incident #remote #ci + +- **What:** `dev` CI run 43064397517 (commit `edc6205d`) failed the same 4 tests on all four `pytest-headless` squares: `test_webrtc_host_channels.py::test_a_mic_that_fails_to_close_is_still_forgotten`, `test_webrtc_viewer_control.py::test_a_microphone_that_fails_to_close_is_still_forgotten`, and both parameters of `test_webrtc_media_types.py::test_recording_releases_container_when_video_stream_cannot_be_created`. They predate U-20261111-26/-32: a mic whose close fails is now retained with its failure and the error propagates (`WebRTCMediaOwners.stop_field`), and a recorder whose setup or write failed reports `MediaRetirementError` with `UNCERTAIN` finalization from `stop()` (`docs/media_retirement_contract.md`). The newer tests (`test_webrtc_media_consumers.py`, `test_media_retirement.py`) already assert that contract. +- **Fix:** the four tests now assert it too: the close error propagates, the original mic owner stays in place, `media_failures` is non-empty; the recorder's `stop()` raises `MediaRetirementError`, the container is still closed exactly once, and finalization is `UNCERTAIN`. No library code changed. +- **Evidence:** the three files: 140 passed locally (they failed 4 before). +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 988a78126..43833ce31 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-05 | 2026-11-12 | Four WebRTC tests still asserted the pre-retention contract | #incident #remote #ci | [2026-11-b](2026-11-b.md) | | U-20261112-04 | 2026-11-12 | Mobile SDK calls checked against uiautomator2 and facebook-wda source | #done #mobile | [2026-11-b](2026-11-b.md) | | U-20261112-03 | 2026-11-12 | MCP tool calls are stoppable runs; a cancel stops them | #done #mcp #executor | [2026-11-b](2026-11-b.md) | | U-20261112-02 | 2026-11-12 | minimatch 5.1.9 is outside the revised advisory range | #done #deps #security | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/test_webrtc_host_channels.py b/test/unit_test/headless/test_webrtc_host_channels.py index 438561ccf..70dcc79c5 100644 --- a/test/unit_test/headless/test_webrtc_host_channels.py +++ b/test/unit_test/headless/test_webrtc_host_channels.py @@ -394,12 +394,16 @@ def test_disabling_a_mic_that_was_never_enabled_is_a_no_op(host): assert host._mic_receiver is None -def test_a_mic_that_fails_to_close_is_still_forgotten(host): +def test_a_mic_that_fails_to_close_is_retained_and_reported(host): + # Since U-20261111-32 a failed close keeps its original owner instead of + # forgetting it (docs/media_retirement_contract.md). receiver = MicReceiver() receiver.stop_error = OSError("stream already closed") host._mic_receiver = receiver - host.disable_mic_receive() - assert host._mic_receiver is None + with pytest.raises(OSError, match="stream already closed"): + host.disable_mic_receive() + assert host._mic_receiver is receiver + assert host.media_failures # --- the files channel -------------------------------------------------------- diff --git a/test/unit_test/headless/test_webrtc_media_types.py b/test/unit_test/headless/test_webrtc_media_types.py index 4f67b1438..7a34a18ee 100644 --- a/test/unit_test/headless/test_webrtc_media_types.py +++ b/test/unit_test/headless/test_webrtc_media_types.py @@ -11,6 +11,9 @@ from je_auto_control.utils.remote_desktop import ( # noqa: E402 # reason: optional media dependencies hw_codec, session_recorder, ) +from je_auto_control.utils.remote_desktop.media_retirement import ( # noqa: E402 # reason: optional media dependencies + Completion, MediaRetirementError, +) from je_auto_control.utils.remote_desktop.webrtc_transport import ( # noqa: E402 # reason: optional media dependencies ScreenVideoTrack, ) @@ -43,8 +46,12 @@ def add_stream(*args, **kwargs): recorder.write_frame(av.VideoFrame(64, 64)) assert closed == [True] assert not recorder.is_active and not recorder.has_output - recorder.stop() + # The setup failure stays recorded, so stop reports an uncertain + # finalization instead of a clean one (docs/media_retirement_contract.md). + with pytest.raises(MediaRetirementError): + recorder.stop() assert closed == [True] + assert recorder.retirement_status.finalization is Completion.UNCERTAIN def test_h264_patch_encodes_and_restores_the_original_method(monkeypatch): diff --git a/test/unit_test/headless/test_webrtc_viewer_control.py b/test/unit_test/headless/test_webrtc_viewer_control.py index 6810f481e..3cce30131 100644 --- a/test/unit_test/headless/test_webrtc_viewer_control.py +++ b/test/unit_test/headless/test_webrtc_viewer_control.py @@ -441,13 +441,18 @@ def test_disabling_a_microphone_that_was_never_enabled_is_a_no_op(viewer): assert viewer.mic_active is False -def test_a_microphone_that_fails_to_close_is_still_forgotten(viewer, - mic_sender): +def test_a_microphone_that_fails_to_close_is_retained_and_reported(viewer, + mic_sender): + # Since U-20261111-32 a failed close keeps its original owner instead of + # forgetting it (docs/media_retirement_contract.md). viewer._mic_channel = Channel("mic") viewer.enable_mic_send() - viewer._mic_sender.stop_error = OSError("stream already closed") - viewer.disable_mic_send() - assert viewer._mic_sender is None + sender = viewer._mic_sender + sender.stop_error = OSError("stream already closed") + with pytest.raises(OSError, match="stream already closed"): + viewer.disable_mic_send() + assert viewer._mic_sender is sender + assert viewer.media_failures def test_a_sender_that_stopped_on_its_own_is_not_active(viewer, mic_sender): From f8b67fac5c95cb9248b496f760e8a6abefec0a71 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:51:56 +0800 Subject: [PATCH 048/161] Move the MCP tools/call path into its own mixin server.py was at 745 of its 750 lines; the failure screenshot is still looked up on the server module so the existing patch seam holds. --- Progress.md | 1 - architecture_explore.md | 17 +- docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + .../utils/mcp_server/_tool_calls.py | 179 ++++++++++++++++++ je_auto_control/utils/mcp_server/server.py | 136 +------------ test/unit_test/headless/test_mcp_call_run.py | 20 ++ 7 files changed, 226 insertions(+), 136 deletions(-) create mode 100644 je_auto_control/utils/mcp_server/_tool_calls.py diff --git a/Progress.md b/Progress.md index cf21e729b..da7edbe74 100644 --- a/Progress.md +++ b/Progress.md @@ -159,7 +159,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **變數範圍**:free-threaded 原生執行緒繼承與同時存取範圍的行為尚未實測。 - **遠端桌面的擁有者模型**:Quick Connect 沒有狀態列,它的連線被取代時視窗只是關掉;主機的 Stop 會停任何擁有者開的 host(刻意的); 只用假的 viewer/host 測過,真的 viewer 被擠掉時會不會觸發 `on_error` 而多跳一個警告框,沒看過。 -- **快到 750 行上限的檔案**:`utils/mcp_server/server.py`(744)——下一次要加東西就得先檢查預算,超標前拆分。 --- diff --git a/architecture_explore.md b/architecture_explore.md index 9eb6ea8ab..84ff7f3c7 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,526 | -| 程式碼總行數 | 233,363 | +| Python 模組總數(含周邊子專案) | 1,527 | +| 程式碼總行數 | 233,424 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -516,7 +516,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,884 行。 +> 14 個套件、約 52,945 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -530,7 +530,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,167 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,228 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 660 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | @@ -756,7 +756,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,167 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,228 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -790,7 +790,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers_vision_executor.py` | 564 | 70 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_locators.py` | 436 | 同一種 adapter,定位主題:無障礙樹、智慧等待、自我修復、螢幕觀察、座標空間、視覺與 OCR、影像去重、元件倉庫、A/B 定位。 | | `tools/_handlers_operations.py` | 656 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | -| `server.py` | 745 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、工具與 resource/prompt 處理器;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | +| `server.py` | 627 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、resource/prompt 處理器;`tools/call` 的准入、執行與稽核在 `_tool_calls.py`;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | +| `_tool_calls.py` | 179 | `tools/call` 路徑(`ToolCallMixin`):請求、RBAC、揭露目錄、schema、參數政策、限流與破壞性確認的准入,以 `ToolCallContext` 執行、寫稽核並轉成結果;失敗截圖在呼叫時才向 `server` 取 `_capture_error_screenshot`。 | | `http_transport.py` | 622 | MCP 的 HTTP 傳輸;宣告 2026-07-28 的請求走 `_http_stateless.py` 的標頭規則,不發 session。 | | `_http_stateless.py` | 185 | MCP 2026-07-28 在 Streamable HTTP 上的規則:`MCP-Protocol-Version`/`Mcp-Method`/`Mcp-Name` 必須與 body 相符(`=?base64?…?=` 先解碼),不符是 400+`HeaderMismatch`;版本與中繼資料錯誤 400、未知方法 404。純函式,由 `http_transport.py` 回覆。 | | `http_sessions.py` | 301 | MCP 的 HTTP 傳輸用的 session 身分:`Mcp-Session-Id` 註冊表,以及每個 session 那條常駐的 server→client SSE 串流。 | @@ -1533,7 +1534,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | | `gui/` | 150 | 40,579 | -| `utils/mcp_server/` | 62 | 22,167 | +| `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,709 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | @@ -1553,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,069 | -| **總計** | **1,514** | **232,618** | +| **總計** | **1,515** | **232,679** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index eb15a45c6..2696dcad8 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -158,3 +158,11 @@ - **Fix:** the four tests now assert it too: the close error propagates, the original mic owner stays in place, `media_failures` is non-empty; the recorder's `stop()` raises `MediaRetirementError`, the container is still closed exactly once, and finalization is `UNCERTAIN`. No library code changed. - **Evidence:** the three files: 140 passed locally (they failed 4 before). - **Open items:** none. + +## U-20261112-06 · 2026-11-12 · Split the tools/call path out of the MCP server module · #done #mcp #quality + +- **What:** Closes the `Progress.md` › 這一輪修正留下的後續 item that `utils/mcp_server/server.py` was at 744–745 of its 750 lines and had to be split before the next addition. Admission (`_prepare_tool_call`), execution and audit (`_handle_tools_call`, with the failure branch now its own `_tool_failure`) and `_build_call_context` moved unchanged into `ToolCallMixin` in the new `utils/mcp_server/_tool_calls.py`; `MCPServer` lists it first among its mixins. `server.py`: 745 → 627 lines; `_tool_calls.py`: 179. +- **Seam kept:** four test modules replace `server._capture_error_screenshot`. The mixin resolves that name on `server` when a tool fails, so the patch still applies; `server.py` keeps importing it (`# noqa: F401` with the reason), and a new test (`test_mcp_call_run.py::test_failure_screenshot_is_still_looked_up_on_the_server_module`) fails if the lookup ever binds early. +- **Evidence:** MCP, run-control, RBAC, surface, cross-project, facade and budget test files: 1,704 passed, 1 failed (the `test_sync_workspace_surfaces.py` long-path case that fails on the unchanged tree too, see U-20261112-03). Ruff and Radon clean; typing contract on win32/linux/darwin: 0 modules with errors. +- **Files:** `utils/mcp_server/{server.py,_tool_calls.py (new)}`, `test_mcp_call_run.py`, `architecture_explore.md` (re-measured with `--fix`), `Progress.md`. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 43833ce31..f7759210c 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-06 | 2026-11-12 | Split the tools/call path out of the MCP server module | #done #mcp #quality | [2026-11-b](2026-11-b.md) | | U-20261112-05 | 2026-11-12 | Four WebRTC tests still asserted the pre-retention contract | #incident #remote #ci | [2026-11-b](2026-11-b.md) | | U-20261112-04 | 2026-11-12 | Mobile SDK calls checked against uiautomator2 and facebook-wda source | #done #mobile | [2026-11-b](2026-11-b.md) | | U-20261112-03 | 2026-11-12 | MCP tool calls are stoppable runs; a cancel stops them | #done #mcp #executor | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/mcp_server/_tool_calls.py b/je_auto_control/utils/mcp_server/_tool_calls.py new file mode 100644 index 000000000..38d331db2 --- /dev/null +++ b/je_auto_control/utils/mcp_server/_tool_calls.py @@ -0,0 +1,179 @@ +"""The ``tools/call`` path of :class:`MCPServer`: admit, run, audit and answer one call. + +Split out of ``server.py``, which had reached 745 of its 750 lines. Admission +(:meth:`ToolCallMixin._prepare_tool_call`) checks the request, RBAC, the +disclosed catalogue, the tool's schema, the argument policy, the rate limit +and the destructive-tool confirmation; :meth:`ToolCallMixin._handle_tools_call` +runs the tool with a fresh :class:`ToolCallContext`, records the outcome in +the audit log and turns the result, or any failure, into a ``tools/call`` +result. + +The failure screenshot is looked up on ``server`` at call time, so +``server._capture_error_screenshot`` stays the seam callers and tests replace. +""" +import time +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional + +from je_auto_control.utils.exception.exceptions import AutoControlException +from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.logging.secret_scope import secret_log_scope +from je_auto_control.utils.mcp_server._authz import authorize_tool_call, capture_error_artifact +from je_auto_control.utils.mcp_server._input_required import AnsweredByGate +from je_auto_control.utils.mcp_server._protocol import ( + _InvalidToolArguments, _MCPError, _to_content_blocks, +) +from je_auto_control.utils.mcp_server.context import OperationCancelledError, ToolCallContext +from je_auto_control.utils.mcp_server.tools._base import _tool_result_error +from je_auto_control.utils.mcp_server.tools._validation import ( + undeclared_arguments, validate_arguments, +) + + +def _error_screenshot(name: str) -> Optional[str]: + """``server._capture_error_screenshot``, resolved when a tool fails.""" + from je_auto_control.utils.mcp_server import server + return server._capture_error_screenshot(name) + + +class ToolCallMixin: + """Admission and execution of ``tools/call`` for :class:`MCPServer`.""" + + if TYPE_CHECKING: + _tools: Dict[str, Any] + _audit: Any + _rate_limiter: Any + _read_only_tools: bool + _calls_lock: Any + _active_calls: Dict[Any, ToolCallContext] + _active_argument_policy: Any + _agent_session: str + _connection_id: Any + _notifier: Optional[Callable[[str, Dict[str, Any]], None]] + + # Provided by DisclosureServerMixin / ClientRequestMixin; the stubs + # mirror their parameters so the combined MCPServer type-checks. + def _tool_for_invocation(self, tool: Any) -> Any: ... + def _require_disclosed_tool(self, name: str, view: Any = None, tool: Any = None) -> None: ... + def _maybe_confirm_destructive(self, name: str, tool: Any, arguments: Dict[str, Any]) -> None: ... + def _accepted_tool_view(self) -> Any: ... + def _call_tool_catalog(self, view: Any = None) -> Callable[[], Any]: ... + + def _prepare_tool_call( + self, params: Dict[str, Any], tool_view: Any = None, + ) -> tuple[str, Any, Dict[str, Any]]: + """Validate a tools/call request; return ``(name, tool, arguments)``. + + Raises :class:`_MCPError` when the request is malformed, the tool is + unknown or the rate limit is hit, and :class:`_InvalidToolArguments` + when the arguments fail the tool's schema or name a path or value + reference the configured :attr:`argument_policy` refuses. The + arguments returned carry the canonical form of every checked path. + """ + name = params.get("name") + arguments = params.get("arguments") or {} + if not isinstance(name, str): + raise _MCPError(-32602, "tools/call requires string 'name'") + if not isinstance(arguments, dict): + raise _MCPError(-32602, "tools/call 'arguments' must be an object") + tool = self._tools.get(name) + if tool is None: + raise _MCPError(-32602, f"Unknown tool: {name}") + tool = self._tool_for_invocation(tool) + authorize_tool_call(tool, arguments, self._audit) # RBAC; a no-op without a user + self._require_disclosed_tool(name, tool_view, tool) + violation = (validate_arguments(tool.input_schema, arguments) + or undeclared_arguments(tool.input_schema, arguments)) + if violation is not None: + raise _InvalidToolArguments(f"Invalid arguments for {name}: {violation}") + try: + arguments = self._active_argument_policy.apply(name, tool.input_schema, arguments) + except AutoControlException as error: + raise _InvalidToolArguments(f"Invalid arguments for {name}: {error}") from error + if self._rate_limiter is not None and not self._rate_limiter.try_acquire(): + raise _MCPError(-32000, f"Rate limit exceeded for tool {name!r}") + self._maybe_confirm_destructive(name, tool, arguments) + return name, tool, arguments + + @secret_log_scope() + def _handle_tools_call(self, msg_id: Any, + params: Dict[str, Any]) -> Dict[str, Any]: + try: + view = self._accepted_tool_view() + name, tool, arguments = self._prepare_tool_call(params, view) + except _InvalidToolArguments as error: + return {"content": [{"type": "text", "text": str(error)}], "isError": True} + except AnsweredByGate as answered: + return answered.result + ctx = self._build_call_context(msg_id, params, view) + call_key = (self._connection_id, msg_id) + with self._calls_lock: + self._active_calls[call_key] = ctx + started_at = time.monotonic() + try: + result = tool.invoke(arguments, ctx=ctx) + except OperationCancelledError: + self._audit.record( + tool=name, arguments=arguments, status="cancelled", + duration_seconds=time.monotonic() - started_at, + ) + raise + except _MCPError: + raise + # Any exception, not a list: re.PatternError, ET.ParseError, cv2.error or + # a plugin's own error escaped the list, killed the worker thread and + # left the call unanswered (stdio) or dropped the connection (HTTP). + except Exception as error: # noqa: BLE001 # reason: a tool's failure of any type must answer the call with isError + return self._tool_failure(name, tool, arguments, error, started_at) + finally: + with self._calls_lock: + self._active_calls.pop(call_key, None) + failure = _tool_result_error(result) + self._audit.record( + tool=name, arguments=arguments, status="error" if failure is not None else "ok", + duration_seconds=time.monotonic() - started_at, + error_text=failure, + ) + response: Dict[str, Any] = { + "content": _to_content_blocks(result), + "isError": failure is not None, + } + # 2025-06-18 spec: tools with an outputSchema return their dict result + # as structuredContent for typed, token-cheap client consumption. + if tool.output_schema is not None and isinstance(result, dict): + response["structuredContent"] = result + return response + + def _tool_failure(self, name: str, tool: Any, arguments: Dict[str, Any], + error: Exception, started_at: float) -> Dict[str, Any]: + """Audit a tool that raised, with its failure screenshot, and answer ``isError``.""" + autocontrol_logger.warning("MCP tool %s failed: %r", name, error) + artifact = capture_error_artifact(tool, self._read_only_tools, _error_screenshot) + self._audit.record( + tool=name, arguments=arguments, status="error", + duration_seconds=time.monotonic() - started_at, + error_text=f"{type(error).__name__}: {error}", + artifact_path=artifact, + ) + error_text = f"{type(error).__name__}: {error}" + if artifact is not None: + error_text += f"\n(error screenshot saved to {artifact})" + return { + "content": [{"type": "text", "text": error_text}], + "isError": True, + } + + def _build_call_context(self, msg_id: Any, + params: Dict[str, Any], tool_view: Any = None) -> ToolCallContext: + meta = params.get("_meta") if isinstance(params.get("_meta"), + dict) else {} + progress_token = meta.get("progressToken") if isinstance(meta, dict) else None + return ToolCallContext( + request_id=msg_id, progress_token=progress_token, + notifier=self._notifier, + path_policy=self._active_argument_policy.path_policy, + session_id=f"{self._agent_session}:{self._connection_id}", + tool_catalog=self._call_tool_catalog(tool_view), + ) + + +__all__ = ["ToolCallMixin"] diff --git a/je_auto_control/utils/mcp_server/server.py b/je_auto_control/utils/mcp_server/server.py index 76239b8ae..57946690b 100644 --- a/je_auto_control/utils/mcp_server/server.py +++ b/je_auto_control/utils/mcp_server/server.py @@ -18,9 +18,8 @@ from je_auto_control.utils.cli_output import utf8_stream from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger -from je_auto_control.utils.logging.secret_scope import secret_log_scope from je_auto_control.utils.mcp_server._authz import ( - authorize_resource, authorize_tool_call, capture_error_artifact, visible_resources, + authorize_resource, visible_resources, ) from je_auto_control.utils.mcp_server.audit import AuditLogger from je_auto_control.utils.mcp_server._disclosure_server import DisclosureServerMixin @@ -41,27 +40,22 @@ from je_auto_control.utils.mcp_server.tools import ( MCPTool, build_default_tool_registry, ) -from je_auto_control.utils.mcp_server.tools._base import _tool_result_error -from je_auto_control.utils.mcp_server.tools._validation import ( - undeclared_arguments, validate_arguments, -) from je_auto_control.utils.mcp_server._argument_policy import ArgumentPolicy from je_auto_control.utils.mcp_server._origin_policies import OriginPoliciesMixin from je_auto_control.utils.mcp_server._client_requests import ( ClientRequestMixin, ) -from je_auto_control.utils.mcp_server._input_required import ( - AnsweredByGate, RequestStateSigner, -) +from je_auto_control.utils.mcp_server._input_required import RequestStateSigner from je_auto_control.utils.mcp_server._stateless import StatelessDispatchMixin from je_auto_control.utils.mcp_server._subscriptions import NO_RESPONSE, SubscriptionMixin +from je_auto_control.utils.mcp_server._tool_calls import ToolCallMixin from je_auto_control.utils.mcp_server._protocol import ( PROTOCOL_VERSION, # noqa: F401 # reason: re-exported; callers import it from server - _capture_error_screenshot, negotiate_protocol_version, - _coerce_params, _DISPATCH_ERRORS, _error_response, _invalid_envelope, _InvalidToolArguments, - _is_hashable, - _MCPError, _notification_message, _result_response, _server_info, _to_content_blocks, - _TOOLS_CALL_METHOD, + # The failure-screenshot seam: _tool_calls looks it up here at call time. + _capture_error_screenshot, # noqa: F401 # reason: patched on this module by callers and tests + negotiate_protocol_version, + _coerce_params, _DISPATCH_ERRORS, _error_response, _invalid_envelope, _is_hashable, + _MCPError, _notification_message, _result_response, _server_info, _TOOLS_CALL_METHOD, ) #: How long a transport waits for in-flight tool replies before it gives up @@ -69,7 +63,7 @@ WORKER_DRAIN_TIMEOUT = 10.0 -class MCPServer(StatelessDispatchMixin, SubscriptionMixin, ClientRequestMixin, +class MCPServer(ToolCallMixin, StatelessDispatchMixin, SubscriptionMixin, ClientRequestMixin, OriginPoliciesMixin, DisclosureServerMixin): """JSON-RPC 2.0 MCP server with a configurable tool registry.""" @@ -618,118 +612,6 @@ def _handle_prompts_get(self, params: Dict[str, Any]) -> Dict[str, Any]: raise _MCPError(-32602, f"Unknown prompt: {name}") return payload - def _prepare_tool_call( - self, params: Dict[str, Any], tool_view: Any = None, - ) -> tuple[str, Any, Dict[str, Any]]: - """Validate a tools/call request; return ``(name, tool, arguments)``. - - Raises :class:`_MCPError` when the request is malformed, the tool is - unknown or the rate limit is hit, and :class:`_InvalidToolArguments` - when the arguments fail the tool's schema or name a path or value - reference the configured :attr:`argument_policy` refuses. The - arguments returned carry the canonical form of every checked path. - """ - name = params.get("name") - arguments = params.get("arguments") or {} - if not isinstance(name, str): - raise _MCPError(-32602, "tools/call requires string 'name'") - if not isinstance(arguments, dict): - raise _MCPError(-32602, "tools/call 'arguments' must be an object") - tool = self._tools.get(name) - if tool is None: - raise _MCPError(-32602, f"Unknown tool: {name}") - tool = self._tool_for_invocation(tool) - authorize_tool_call(tool, arguments, self._audit) # RBAC; a no-op without a user - self._require_disclosed_tool(name, tool_view, tool) - violation = (validate_arguments(tool.input_schema, arguments) - or undeclared_arguments(tool.input_schema, arguments)) - if violation is not None: - raise _InvalidToolArguments(f"Invalid arguments for {name}: {violation}") - try: - arguments = self._active_argument_policy.apply(name, tool.input_schema, arguments) - except AutoControlException as error: - raise _InvalidToolArguments(f"Invalid arguments for {name}: {error}") from error - if self._rate_limiter is not None and not self._rate_limiter.try_acquire(): - raise _MCPError(-32000, f"Rate limit exceeded for tool {name!r}") - self._maybe_confirm_destructive(name, tool, arguments) - return name, tool, arguments - - @secret_log_scope() - def _handle_tools_call(self, msg_id: Any, - params: Dict[str, Any]) -> Dict[str, Any]: - try: - view = self._accepted_tool_view() - name, tool, arguments = self._prepare_tool_call(params, view) - except _InvalidToolArguments as error: - return {"content": [{"type": "text", "text": str(error)}], "isError": True} - except AnsweredByGate as answered: - return answered.result - ctx = self._build_call_context(msg_id, params, view) - call_key = (self._connection_id, msg_id) - with self._calls_lock: - self._active_calls[call_key] = ctx - started_at = time.monotonic() - try: - result = tool.invoke(arguments, ctx=ctx) - except OperationCancelledError: - self._audit.record( - tool=name, arguments=arguments, status="cancelled", - duration_seconds=time.monotonic() - started_at, - ) - raise - except _MCPError: - raise - # Any exception, not a list: re.PatternError, ET.ParseError, cv2.error or - # a plugin's own error escaped the list, killed the worker thread and - # left the call unanswered (stdio) or dropped the connection (HTTP). - except Exception as error: # noqa: BLE001 # reason: a tool's failure of any type must answer the call with isError - autocontrol_logger.warning("MCP tool %s failed: %r", name, error) - artifact = capture_error_artifact(tool, self._read_only_tools, _capture_error_screenshot) - self._audit.record( - tool=name, arguments=arguments, status="error", - duration_seconds=time.monotonic() - started_at, - error_text=f"{type(error).__name__}: {error}", - artifact_path=artifact, - ) - error_text = f"{type(error).__name__}: {error}" - if artifact is not None: - error_text += f"\n(error screenshot saved to {artifact})" - return { - "content": [{"type": "text", "text": error_text}], - "isError": True, - } - finally: - with self._calls_lock: - self._active_calls.pop(call_key, None) - failure = _tool_result_error(result) - self._audit.record( - tool=name, arguments=arguments, status="error" if failure is not None else "ok", - duration_seconds=time.monotonic() - started_at, - error_text=failure, - ) - response: Dict[str, Any] = { - "content": _to_content_blocks(result), - "isError": failure is not None, - } - # 2025-06-18 spec: tools with an outputSchema return their dict result - # as structuredContent for typed, token-cheap client consumption. - if tool.output_schema is not None and isinstance(result, dict): - response["structuredContent"] = result - return response - - def _build_call_context(self, msg_id: Any, - params: Dict[str, Any], tool_view: Any = None) -> ToolCallContext: - meta = params.get("_meta") if isinstance(params.get("_meta"), - dict) else {} - progress_token = meta.get("progressToken") if isinstance(meta, dict) else None - return ToolCallContext( - request_id=msg_id, progress_token=progress_token, - notifier=self._notifier, - path_policy=self._active_argument_policy.path_policy, - session_id=f"{self._agent_session}:{self._connection_id}", - tool_catalog=self._call_tool_catalog(tool_view), - ) - def _parse_request(line: str) -> "tuple[Optional[Dict[str, Any]], Optional[str]]": """``(message, None)`` for a well-formed JSON-RPC object, else ``(None, error reply)``.""" diff --git a/test/unit_test/headless/test_mcp_call_run.py b/test/unit_test/headless/test_mcp_call_run.py index 82b596802..ad66aa40d 100644 --- a/test/unit_test/headless/test_mcp_call_run.py +++ b/test/unit_test/headless/test_mcp_call_run.py @@ -149,3 +149,23 @@ def test_invoke_without_a_server_context_is_not_a_run(): handler=lambda: seen.append(current_stop_token()) or "ok") assert tool.invoke({}) == "ok" assert seen == [None] + + +def test_failure_screenshot_is_still_looked_up_on_the_server_module(monkeypatch): + # The tools/call path moved to _tool_calls.py; server._capture_error_screenshot + # must remain the seam callers and tests replace. + from je_auto_control.utils.mcp_server import server as server_module + shots = [] + monkeypatch.setattr(server_module, "_capture_error_screenshot", + lambda name: shots.append(name) or "shot.png") + + def broken(): + raise RuntimeError("boom") + + server = MCPServer(tools=[MCPTool(name="broken", description="d", + input_schema=_EMPTY, handler=broken)]) + result = _call(server, 31, "broken", {})["result"] + assert result["isError"] is True + assert "RuntimeError: boom" in result["content"][0]["text"] + assert "(error screenshot saved to shot.png)" in result["content"][0]["text"] + assert shots == ["broken"] From 7158d9a529a6587d1d07dc51aa16f2903b7868f3 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 02:52:39 +0800 Subject: [PATCH 049/161] Record the Windows path-length limit in config sync asset staging --- Progress.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Progress.md b/Progress.md index da7edbe74..4399a105d 100644 --- a/Progress.md +++ b/Progress.md @@ -173,6 +173,10 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **能力探測**:Windows 的鎖定工作站、session 0、低完整性與擷取失敗分支只用假資料判斷;macOS 的三個 preflight 呼叫只對假物件跑過, pyobjc 的 `Quartz` 有沒有 `CGPreflightListenEventAccess` 未知(沒有的話 `recording`/`stop_shortcut` 回 `unknown`)。 - **Windows 的版面鍵名**(`slash` 等 8 個)只在美式配置上實際呼叫過。 +- **設定同步在 Windows 的路徑長度**:`LongPathsEnabled=0` 的機器上,`test_sync_workspace_surfaces.py` 的長紀錄名稱案例 + (64+64 字元的 `scripts/…json`)在 `cache/.incoming-*/files/` 下組成 265 字元的路徑,`FileNotFoundError` 後回報 + `asset transfer could not publish a complete generation`(`utils/config_sync/assets.py`);CI 的暫存根目錄較短所以會過。 + 真的安裝把快取放在深一點的目錄時也會撞到。`TODO`:Windows 上改用 `\\?\` 長路徑,或在超出前以明確錯誤拒絕該紀錄名稱。 - **狀態機 `on_enter` 的單一動作寫法**以前一直被拒絕、從沒執行過(已修,U-20261009-24):依賴「它不會跑」的既有狀態機現在會跑它。 --- From 39339c3787fc692e4cd282930266041d1e8be95d Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 03:11:44 +0800 Subject: [PATCH 050/161] Build only the first start-up tab; the others when first selected Remote Desktop and Script Builder were built at start-up although only one tab is on screen; offscreen start-up drops from 3.2 s to 1.7 s. --- CHANGELOG.md | 7 ++ Progress.md | 1 - README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 8 +- docs/guides/en/setup.md | 2 +- docs/guides/zh-CN/setup.md | 2 +- docs/guides/zh-TW/setup.md | 2 +- docs/updates/2026-11-b.md | 9 ++ docs/updates/README.md | 1 + je_auto_control/gui/workspace.py | 97 ++++++++++++++++--- .../headless/test_gui_lazy_registry.py | 33 ++++++- 13 files changed, 146 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f51a36369..ca10c43bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- Of the three GUI tabs open at start, only Record is built then: Script Builder and Remote + Desktop sit in the tab bar as empty stand-ins and are built in place the first time they + are selected or their widget is asked for (`TabEntry.widget`, `activate_tab`). Offscreen, + median start-up went from 3.2 s to 1.7 s and memory from 172 MB to 111 MB. Code that + expected those two widgets to exist right after `AutoControlGUIWidget()` now builds them + on first access. + - iOS `swipe` (`Swipe` gestures, `AC_ios_swipe`, `ac_ios_swipe`) no longer presses for `duration_s` before moving: facebook-wda's swipe duration is the start-point hold, so the old mapping made swipes start as drags. WebDriverAgent sets the travel speed and diff --git a/Progress.md b/Progress.md index 4399a105d..c14dfd8e1 100644 --- a/Progress.md +++ b/Progress.md @@ -537,7 +537,6 @@ D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製 H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 F 還缺: -- **Remote Desktop 與 Script Builder 仍在啟動時建立**(預設開啟),啟動時間 2.6–2.7 秒裡大半是它們與門面匯入。 - **F2 其餘**:Diagnostics 以外面板的執行詳情,以及各面板的空白/錯誤/permission states 尚未全面交付。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 diff --git a/README.md b/README.md index 7e83e83c4..0325dcee1 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ Cancellation prevents later move/click steps, but cannot interrupt a native call Auto Click, Record and Script Executor own their controls and background tasks. Closing them stops local work; reopening creates fresh inputs. The shared recorder continues after its page closes, and a reopened page reads backend status (unknown when unsupported). This status does not verify native hook health. Ctrl+4 still stops scripts and auto-clicking. +Of the three tabs open at start, only Record is built then; Script Builder and Remote Desktop are built the first time they are selected, which roughly halves start-up time and memory. + View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there; other pages explicitly say when details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. WebRTC statistics polling starts in the background and discards late samples after it stops. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 7e3096df2..48550666d 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -41,6 +41,8 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, 自动点击、录制与脚本执行分页各自持有控件与后台任务;关闭会停止本页任务,重新打开会建立新的输入框。共享录制器不随分页关闭,重新打开后会读取后端状态,不支持查询时显示未知;此状态不代表原生钩子健康检查。Ctrl+4 仍可停止脚本与自动点击。 +启动时打开的三个标签页只先创建 Record;Script Builder 与 Remote Desktop 在第一次被选中时才创建,启动时间与内存约减半。 + View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态;其他分页尚未提供时会明确显示。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 WebRTC 统计轮询在后台启动,停止后会丢弃延迟到达的样本。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 7ac6e80db..15ab42f25 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -41,6 +41,8 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, 自動點擊、錄製與腳本執行分頁各自持有控制項與背景工作;關閉會停止本頁工作,重開會建立新的輸入欄位。共用錄製器不隨分頁關閉,重開後會讀取後端狀態,不支援查詢時顯示未知;此狀態不代表原生掛鉤健康檢查。Ctrl+4 仍可停止腳本與自動點擊。 +啟動時開著的三個分頁只先建立 Record;Script Builder 與 Remote Desktop 在第一次被選取時才建立,啟動時間與記憶體約減半。 + View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態;其他分頁尚未提供時會明確顯示。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 WebRTC 統計輪詢在背景啟動,停止後會捨棄晚到的樣本。 diff --git a/architecture_explore.md b/architecture_explore.md index 84ff7f3c7..ffa217e22 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,424 | +| 程式碼總行數 | 233,497 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1300,7 +1300,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 203 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | -| `workspace.py` | 393 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情。 | +| `workspace.py` | 466 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情。 | | `workspace_details.py` | 95 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 166 | Explicit transfer requests and consent preparation with revision-bound background observations. | @@ -1533,7 +1533,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 150 | 40,579 | +| `gui/` | 150 | 40,652 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,709 | | `utils/executor/` | 11 | 10,702 | @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,069 | -| **總計** | **1,515** | **232,679** | +| **總計** | **1,515** | **232,752** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/setup.md b/docs/guides/en/setup.md index a3a1d62c9..2ec193aa4 100644 --- a/docs/guides/en/setup.md +++ b/docs/guides/en/setup.md @@ -13,7 +13,7 @@ Optional extras, installed only when you need them: | Extra | Enables | |---|---| -| `gui` | PySide6 desktop application (51 tabs): a searchable navigation panel (`Ctrl+K`) lists every feature by category, tabs are built the first time they are opened, and **View → Theme** switches dark / light. Pages scroll in narrow windows; theme, text size, navigation visibility (`Ctrl+B`) and width are saved in `~/.je_auto_control/gui.ini` on close. Themes use Qt directly; `qt-material` is not required. | +| `gui` | PySide6 desktop application (51 tabs): a searchable navigation panel (`Ctrl+K`) lists every feature by category, tabs are built the first time they are opened (of the three open at start, only Record is built then; Script Builder and Remote Desktop are built when first selected), and **View → Theme** switches dark / light. Pages scroll in narrow windows; theme, text size, navigation visibility (`Ctrl+B`) and width are saved in `~/.je_auto_control/gui.ini` on close. Themes use Qt directly; `qt-material` is not required. | | `webrtc` | WebRTC remote desktop, USB passthrough (`aiortc`, `av`) | | `signaling` | Standalone signaling / rendezvous server (`fastapi`, `uvicorn`) | | `discovery` | mDNS / Zeroconf LAN host discovery | diff --git a/docs/guides/zh-CN/setup.md b/docs/guides/zh-CN/setup.md index f98ac44ac..897daf97c 100644 --- a/docs/guides/zh-CN/setup.md +++ b/docs/guides/zh-CN/setup.md @@ -13,7 +13,7 @@ pip install je_auto_control[gui] # 加上 PySide6 桌面应用 | Extra | 启用的功能 | |---|---| -| `gui` | PySide6 桌面应用(51 个标签页):左侧可搜索的导航面板(`Ctrl+K`)按分类列出全部功能,标签页在第一次打开时才创建,**View → Theme** 切换深色/浅色。窄窗口的内容可滚动;关闭窗口时,主题、字号、导航面板显示(`Ctrl+B`)与宽度会保存到 `~/.je_auto_control/gui.ini`。主题直接使用 Qt,不需要 `qt-material`。 | +| `gui` | PySide6 桌面应用(51 个标签页):左侧可搜索的导航面板(`Ctrl+K`)按分类列出全部功能,标签页在第一次打开时才创建(启动时打开的三个标签页只先创建 Record;Script Builder 与 Remote Desktop 在第一次被选中时才创建),**View → Theme** 切换深色/浅色。窄窗口的内容可滚动;关闭窗口时,主题、字号、导航面板显示(`Ctrl+B`)与宽度会保存到 `~/.je_auto_control/gui.ini`。主题直接使用 Qt,不需要 `qt-material`。 | | `webrtc` | WebRTC 远程桌面、USB 直通(`aiortc`、`av`) | | `signaling` | 独立的信令/rendezvous 服务器(`fastapi`、`uvicorn`) | | `discovery` | mDNS / Zeroconf 局域网主机发现 | diff --git a/docs/guides/zh-TW/setup.md b/docs/guides/zh-TW/setup.md index ffe015ffa..bf8f03ec2 100644 --- a/docs/guides/zh-TW/setup.md +++ b/docs/guides/zh-TW/setup.md @@ -13,7 +13,7 @@ pip install je_auto_control[gui] # 加上 PySide6 桌面應用程式 | Extra | 啟用的功能 | |---|---| -| `gui` | PySide6 桌面應用程式(51 個分頁):左側可搜尋的導覽面板(`Ctrl+K`)依分類列出全部功能,分頁在第一次開啟時才建立,**View → Theme** 切換深色/淺色。窄視窗的內容可捲動;關閉視窗時,主題、字級、導覽面板顯示(`Ctrl+B`)與寬度會存入 `~/.je_auto_control/gui.ini`。主題直接使用 Qt,不需要 `qt-material`。 | +| `gui` | PySide6 桌面應用程式(51 個分頁):左側可搜尋的導覽面板(`Ctrl+K`)依分類列出全部功能,分頁在第一次開啟時才建立(啟動時開著的三個分頁只先建立 Record;Script Builder 與 Remote Desktop 在第一次被選取時才建立),**View → Theme** 切換深色/淺色。窄視窗的內容可捲動;關閉視窗時,主題、字級、導覽面板顯示(`Ctrl+B`)與寬度會存入 `~/.je_auto_control/gui.ini`。主題直接使用 Qt,不需要 `qt-material`。 | | `webrtc` | WebRTC 遠端桌面、USB 直通(`aiortc`、`av`) | | `signaling` | 獨立的訊令/rendezvous 伺服器(`fastapi`、`uvicorn`) | | `discovery` | mDNS / Zeroconf 區網主機探索 | diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 2696dcad8..04f972dbd 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -166,3 +166,12 @@ - **Evidence:** MCP, run-control, RBAC, surface, cross-project, facade and budget test files: 1,704 passed, 1 failed (the `test_sync_workspace_surfaces.py` long-path case that fails on the unchanged tree too, see U-20261112-03). Ruff and Radon clean; typing contract on win32/linux/darwin: 0 modules with errors. - **Files:** `utils/mcp_server/{server.py,_tool_calls.py (new)}`, `test_mcp_call_run.py`, `architecture_explore.md` (re-measured with `--fix`), `Progress.md`. - **Open items:** none. + +## U-20261112-07 · 2026-11-12 · Build only the first start-up tab; the others when first selected · #done #gui #performance + +- **What:** Closes the `Progress.md` › 跨平台與 GUI 全面改版 › F item that Remote Desktop and Script Builder were built at start-up. Of the three tabs registered as open at start (`record`, `script_builder`, `remote_desktop`), `WorkspaceShell._add_tab` builds only the first; each of the others gets an empty `_UnbuiltPage` stand-in with its title and close button. Selecting it (`currentChanged`), or anything asking for `TabEntry.widget` (`activate_tab`, Actions handlers, `open_script_file`), builds the widget, and `ScrollableTabs.replace_page` seats it in the stand-in's scroll container: same index, title and selection, close button rebound to the real page, no tab removed or inserted. `_is_open` counts a stand-in as open, so the View → Tabs menu, navigation and tab order are unchanged; `hide_tab`, `close_tab` and the close button drop a stand-in without building anything; `retranslate` relabels stand-ins. +- **Measured** (`benchmarks/gui_startup.py --runs 3`, offscreen, this machine): median `startup_ms` 3,200.6 → 1,713.1, `build_window` 2,515.7 → 1,075.7, RSS 171.7 → 110.6 MB, modules loaded 593 → 503, `tabs_built` 3 → 1. Split by tab in fresh processes: the first tab pays about 1 s of shared imports (~500 modules), Remote Desktop about 0.9 s of its own (~400 modules, aiortc/av), Script Builder after Record about 60 ms. +- **Compatibility:** code that expected those two widgets to exist right after `AutoControlGUIWidget()` gets them on first access, built then (`CHANGELOG.md`). An embedder passing its own registry to `WorkspaceShell` still has every start-up tab built by `show_tab`, as before. +- **Tests:** `test_gui_lazy_registry.py` now pins `built_at_start == ["record"]` with all three still open, neither `remote_desktop_tab` nor `script_builder` imported at start, a selected stand-in built in its own tab, and a never-built tab closed without building and reopened built: 61 passed. GUI-related headless files (127): 1,836 passed, 2 failed, both failing identically on the unchanged tree (`test_sync_workspace_surfaces.py` long path, `test_a11y_window_audit.py::test_restoring_duplicate_titles_moves_each_window_once` order-dependent `KeyError`). +- **Files:** `gui/workspace.py`, `test_gui_lazy_registry.py`, the three READMEs, the three `docs/guides/*/setup.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** the remaining F items (F2 states, F3 TaskController and close lifecycle, F4 full benchmark comparison) stay in `Progress.md`. Not looked at on a real screen. diff --git a/docs/updates/README.md b/docs/updates/README.md index f7759210c..7941fa968 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-07 | 2026-11-12 | Build only the first start-up tab; the others when first selected | #done #gui #performance | [2026-11-b](2026-11-b.md) | | U-20261112-06 | 2026-11-12 | Split the tools/call path out of the MCP server module | #done #mcp #quality | [2026-11-b](2026-11-b.md) | | U-20261112-05 | 2026-11-12 | Four WebRTC tests still asserted the pre-retention contract | #incident #remote #ci | [2026-11-b](2026-11-b.md) | | U-20261112-04 | 2026-11-12 | Mobile SDK calls checked against uiautomator2 and facebook-wda source | #done #mobile | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index 83bb643be..e58176e45 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -89,16 +89,35 @@ def insertTab(self, index: int, widget: QWidget, *args: Any) -> int: # noqa: N8 container.setFrameShape(QScrollArea.Shape.NoFrame) container.setWidget(widget) result = super().insertTab(index, container, *args) + self._install_close_button(result, widget) + return result + + def _install_close_button(self, index: int, widget: QWidget) -> None: tab_bar = self.tabBar() for side in (QTabBar.ButtonPosition.LeftSide, QTabBar.ButtonPosition.RightSide): - old_button = tab_bar.tabButton(result, side) + old_button = tab_bar.tabButton(index, side) if old_button is not None: - tab_bar.setTabButton(result, side, None) + tab_bar.setTabButton(index, side, None) old_button.deleteLater() button = _CloseButton(tab_bar) button.clicked.connect(lambda: self.tabCloseRequested.emit(self.indexOf(widget))) - tab_bar.setTabButton(result, QTabBar.ButtonPosition.RightSide, button) - return result + tab_bar.setTabButton(index, QTabBar.ButtonPosition.RightSide, button) + + def replace_page(self, old: QWidget, new: QWidget) -> bool: + """Put ``new`` in ``old``'s place, keeping the tab's index, title and selection. + + ``old`` is detached but not deleted. ``False`` when ``old`` is not a page here. + """ + index = self.indexOf(old) + container = self.scroll_area(index) if index >= 0 else None + if container is None: + return False + detached = container.takeWidget() + if detached is not None: + detached.setParent(None) + container.setWidget(new) + self._install_close_button(index, new) + return True def removeTab(self, index: int) -> None: # noqa: N802 # reason: Qt override """Remove the scroll container while retaining ownership of its page.""" @@ -126,8 +145,22 @@ def retranslate(self) -> None: button.retranslate() +class _UnbuiltPage(QWidget): + """Stands in the tab bar for a start-up tab that has not been built yet.""" + + def __init__(self, key: str, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.tab_key = key + + class WorkspaceShell(TranslatableMixin, QWidget): - """Present one supplied tab registry and the active page's execution details.""" + """Present one supplied tab registry and the active page's execution details. + + Of the tabs registered as open at start-up, only the first is built then; + each of the others shows an empty stand-in until it is selected or its + widget is asked for, and is built in that tab's place at that moment. + Remote Desktop alone took about 0.9 s of the start-up. + """ tabs_changed = Signal() current_tab_changed = Signal() @@ -137,6 +170,7 @@ def __init__(self, registry: TabRegistry, parent: QWidget | None = None) -> None super().__init__(parent) self._tr_init() self.tab_registry = registry + self._unbuilt: dict[str, _UnbuiltPage] = {} self.tabs = ScrollableTabs() self.tabs.setDocumentMode(True) self.tabs.setUsesScrollButtons(True) @@ -213,17 +247,41 @@ def _add_tab( def adopt(page: QWidget) -> None: shell = owner() if shell is not None: - shell._adopt_hidden_tab(page) + shell._adopt_built_page(key, page) entry = TabEntry(key=key, title_key=title_key, factory=widget, category=category, default_visible=default_visible, actions=actions, retain_on_close=False, on_build=adopt) self.tab_registry.add(entry) - if default_visible: - self.tabs.addTab(entry.widget, language_wrapper.translate(title_key, title_key)) + title = language_wrapper.translate(title_key, title_key) + if default_visible and not isinstance(widget, QWidget) and self.tabs.count() > 0: + self._unbuilt[key] = page = _UnbuiltPage(key) + self.tabs.addTab(page, title) + elif default_visible: + self.tabs.addTab(entry.widget, title) elif isinstance(widget, QWidget): WorkspaceShell._adopt_hidden_tab(self, entry.widget) + def _adopt_built_page(self, key: str, page: QWidget) -> None: + """Seat a newly built page in its stand-in's tab, or keep it hidden and owned.""" + stand_in = self._unbuilt.pop(key, None) + if stand_in is not None and self.tabs.replace_page(stand_in, page): + stand_in.deleteLater() + return + self._adopt_hidden_tab(page) + + def _drop_unbuilt(self, key: str) -> bool: + """Close a start-up tab that was never built; ``False`` when ``key`` has none.""" + stand_in = self._unbuilt.pop(key, None) + if stand_in is None: + return False + index = self.tabs.indexOf(stand_in) + if index != -1: + self.tabs.removeTab(index) + stand_in.deleteLater() + self.tabs_changed.emit() + return True + def _adopt_hidden_tab(self, widget: QWidget) -> None: # Owned from the start: an unparented hidden tab outlived this # widget, and one a registry held a listener of (Presence) kept @@ -240,9 +298,14 @@ def _built_entries(self) -> List[Any]: return [entry for entry in self.tab_registry.entries if self._is_built(entry)] def _is_open(self, entry: Any) -> bool: + if entry.key in self._unbuilt: + return True return self._is_built(entry) and self.tabs.indexOf(entry.widget) != -1 def _on_current_tab_changed(self, _index: int) -> None: + page = self.tabs.currentWidget() + if isinstance(page, _UnbuiltPage): + self.tab_registry.open(page.tab_key) # builds it into the stand-in's place self._bind_details() self.current_tab_changed.emit() @@ -303,6 +366,8 @@ def list_registered_tabs(self) -> list[dict[str, Any]]: def current_tab_key(self) -> Optional[str]: """Key of the tab on screen, or ``None`` when every tab is closed.""" widget = self.tabs.currentWidget() + if isinstance(widget, _UnbuiltPage): + return widget.tab_key for entry in self._built_entries(): if entry.widget is widget: return str(entry.key) @@ -339,7 +404,7 @@ def activate_tab(self, key: str) -> bool: def hide_tab(self, key: str) -> None: """Close the tab ``key``; its widget is kept for the next time it is opened.""" entry = self._find_entry(key) - if entry is None or not self._is_built(entry): + if entry is None or self._drop_unbuilt(key) or not self._is_built(entry): return index = self.tabs.indexOf(entry.widget) if index != -1: @@ -348,6 +413,9 @@ def hide_tab(self, key: str) -> None: def _on_tab_close_requested(self, index: int) -> None: widget = self.tabs.widget(index) + if isinstance(widget, _UnbuiltPage): + self._drop_unbuilt(widget.tab_key) + return for entry in self._built_entries(): if entry.widget is widget: self.close_tab(entry.key) @@ -359,8 +427,10 @@ def close_tab(self, key: str) -> None: Unlike ``hide_tab``, closing a feature discards its local UI state and schedules cleanup of subscriptions and timers. Reopening rebuilds it. Remote Desktop keeps registry-owned sessions while retiring its view callbacks. + A start-up tab that was never built just leaves the tab bar. """ - self.tab_registry.close(key) + if not self._drop_unbuilt(key): + self.tab_registry.close(key) def _detach_closed_tab(self, page: QWidget) -> None: """Remove a closed page before its deferred Qt destruction.""" @@ -376,8 +446,11 @@ def retranslate(self) -> None: """Relabel tab titles and propagate into every child tab.""" self.tabs.retranslate() self.details.retranslate() - for entry in self._built_entries(): - index = self.tabs.indexOf(entry.widget) + for entry in self.tab_registry.entries: + stand_in = self._unbuilt.get(entry.key) + if stand_in is None and not self._is_built(entry): + continue + index = self.tabs.indexOf(stand_in if stand_in is not None else entry.widget) if index != -1: self.tabs.setTabText( index, language_wrapper.translate(entry.title_key, entry.title_key), diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index 05d3cfebb..6c81f9949 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -19,6 +19,8 @@ # Remote Desktop retains the main widget's optional-dependency fallback. OWN_TABS = {"remote_desktop"} OPEN_AT_START = ["record", "script_builder", "remote_desktop"] +# Only the first start-up tab is built; the others wait in the tab bar until selected. +BUILT_AT_START = ["record"] def test_keys_are_unique_and_the_start_tabs_are_the_three_documented(): @@ -93,6 +95,8 @@ def test_a_lazy_factory_imports_at_call_time(): "auto_click_imported_at_start": "je_auto_control.gui._auto_click_tab" in sys.modules, "script_imported_at_start": "je_auto_control.gui._script_tab" in sys.modules, "image_detect_imported_at_start": "je_auto_control.gui._image_detect_tab" in sys.modules, + "remote_desktop_imported_at_start": "je_auto_control.gui.remote_desktop_tab" in sys.modules, + "script_builder_imported_at_start": "je_auto_control.gui.script_builder" in sys.modules, } widget.list_registered_tabs() widget.retranslate() @@ -115,6 +119,19 @@ def test_a_lazy_factory_imports_at_call_time(): report["current_after_activate"] = widget.current_tab_key() report["changes"] = len(changes) report["unknown"] = widget.activate_tab("no_such_tab") + +index = [row["key"] for row in widget.list_registered_tabs() if row["visible"]].index("script_builder") +widget.tabs.setCurrentIndex(index) +report["selected_builds_in_place"] = (entries["script_builder"].built + and widget.tabs.widget(index) is entries["script_builder"].widget + and widget.current_tab_key() == "script_builder") +widget.close_tab("remote_desktop") +report["closing_unbuilt_builds_nothing"] = not entries["remote_desktop"].built +report["closed_unbuilt_is_gone"] = "remote_desktop" not in [ + row["key"] for row in widget.list_registered_tabs() if row["visible"]] +widget.show_tab("remote_desktop") +report["reopened_unbuilt_is_built"] = (entries["remote_desktop"].built + and widget.current_tab_key() == "remote_desktop") sys.stdout.write(json.dumps(report)) sys.stdout.flush() os._exit(0) @@ -136,9 +153,11 @@ def test_every_spec_is_registered_in_order(report): assert report["registered"] == report["specs"] -def test_only_the_start_tabs_and_the_widgets_own_forms_are_built(report): - assert set(report["built_at_start"]) == OWN_TABS | set(OPEN_AT_START) +def test_only_the_first_start_tab_is_built(report): + assert report["built_at_start"] == BUILT_AT_START assert report["open_at_start"] == OPEN_AT_START + assert not report["remote_desktop_imported_at_start"] + assert not report["script_builder_imported_at_start"] assert not report["variables_imported_at_start"] assert not report["presence_imported_at_start"] assert not report["image_detect_imported_at_start"] @@ -164,3 +183,13 @@ def test_activating_an_open_tab_only_selects_it(report): assert report["current_after_activate"] == "record" assert report["changes"] == 3 # opened, hidden, opened again assert report["unknown"] is False + + +def test_a_start_tab_is_built_in_its_place_when_selected(report): + assert report["selected_builds_in_place"] + + +def test_closing_a_start_tab_never_built_builds_nothing(report): + assert report["closing_unbuilt_builds_nothing"] + assert report["closed_unbuilt_is_gone"] + assert report["reopened_unbuilt_is_built"] From 8db7c85e7cb113271233199339c3a91663cc2147 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 03:12:12 +0800 Subject: [PATCH 051/161] Enroll the new MCP modules in the strict typing tier; close Qt stub nulls The strict-tier contract test failed on dev for _call_run and _tool_calls, and the Windows PySide6 stubs flagged two modules on the extras check. --- architecture_explore.md | 20 +++++++++---------- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + je_auto_control/gui/navigation.py | 19 +++++++++++------- .../utils/remote_desktop/webrtc_host.py | 10 ++++++---- .../remote_desktop/webrtc_media_owners.py | 8 +++++++- pyproject.toml | 2 ++ 7 files changed, 45 insertions(+), 22 deletions(-) diff --git a/architecture_explore.md b/architecture_explore.md index ffa217e22..a889138ee 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,497 | +| 程式碼總行數 | 233,510 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 31,943 行。 +> 6 個套件、約 31,951 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,709 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,717 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,709 行/77 檔) +#### `utils/remote_desktop/`(16,717 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -826,10 +826,10 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `webrtc_host.py` | 744 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | +| `webrtc_host.py` | 746 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | | `webrtc_viewer.py` | 736 | WebRTC 檢視端:接收視訊並送出輸入。 | | `webrtc_retirement.py` | 186 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | -| `webrtc_media_owners.py` | 243 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | +| `webrtc_media_owners.py` | 249 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | | `webrtc_peer_cleanup.py` | 154 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | | `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | | `viewer.py` | 743 | TCP 檢視端。 | @@ -1298,7 +1298,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_window.py` | 450 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | -| `navigation.py` | 203 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | +| `navigation.py` | 208 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | | `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | | `workspace.py` | 466 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情。 | | `workspace_details.py` | 95 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | @@ -1533,9 +1533,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 150 | 40,652 | +| `gui/` | 150 | 40,657 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,709 | +| `utils/remote_desktop/` | 77 | 16,717 | | `utils/executor/` | 11 | 10,702 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,069 | -| **總計** | **1,515** | **232,752** | +| **總計** | **1,515** | **232,765** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 04f972dbd..294f92e4b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -175,3 +175,10 @@ - **Tests:** `test_gui_lazy_registry.py` now pins `built_at_start == ["record"]` with all three still open, neither `remote_desktop_tab` nor `script_builder` imported at start, a selected stand-in built in its own tab, and a never-built tab closed without building and reopened built: 61 passed. GUI-related headless files (127): 1,836 passed, 2 failed, both failing identically on the unchanged tree (`test_sync_workspace_surfaces.py` long path, `test_a11y_window_audit.py::test_restoring_duplicate_titles_moves_each_window_once` order-dependent `KeyError`). - **Files:** `gui/workspace.py`, `test_gui_lazy_registry.py`, the three READMEs, the three `docs/guides/*/setup.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** the remaining F items (F2 states, F3 TaskController and close lifecycle, F4 full benchmark comparison) stay in `Progress.md`. Not looked at on a real screen. + +## U-20261112-08 · 2026-11-12 · Strict tier for the two new MCP modules; Windows Qt stub nulls · #incident #typing #ci + +- **What:** `dev` CI run 43077567957 (U-20261112-03) failed `test_typing_modernization_contract.py::test_every_module_is_strict_or_predates_the_tier` on top of the four WebRTC tests of U-20261112-05: the new `utils/mcp_server/_call_run.py`, and later `_tool_calls.py` (U-20261112-06), were not in the strict `[[tool.mypy.overrides]]` block. U-20261112-03 and -06 ran the typing contract but not that test. Both modules are now listed and pass strict mypy on win32, linux and darwin. +- **Also found:** `test/verify/typing_contract_verify.py --extras` on Windows (PySide6 6.11.2, aiortc 1.15.0) reported `gui.navigation` and `utils.remote_desktop.webrtc_host` as failing on the pre-session commit `edc6205d` as well. The Windows stubs type `QTreeWidgetItem.child()` as optional, and `WebRTCMediaOwners.create(...)` returned `Media | None` even with `optional=False`, which raises instead of returning `None`. `navigation.py` iterates through a `_features(group)` helper that skips missing children; `create` has an overload returning `Media` for `optional=False`; `webrtc_host.py` passes a local track to `addTrack`. CI's `typing-extras` job runs on Ubuntu, whose stubs did not flag the first. No behaviour change. +- **Evidence:** the strict-tier and `dev.toml` parity tests: 23 passed; extras-config mypy for the three modules on win32 and linux, and normal-config on win32 and darwin: no issues; navigation / WebRTC / media test files: 1,169 passed, 1 skipped. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 7941fa968..3443200a1 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-08 | 2026-11-12 | Strict tier for the two new MCP modules; Windows Qt stub nulls | #incident #typing #ci | [2026-11-b](2026-11-b.md) | | U-20261112-07 | 2026-11-12 | Build only the first start-up tab; the others when first selected | #done #gui #performance | [2026-11-b](2026-11-b.md) | | U-20261112-06 | 2026-11-12 | Split the tools/call path out of the MCP server module | #done #mcp #quality | [2026-11-b](2026-11-b.md) | | U-20261112-05 | 2026-11-12 | Four WebRTC tests still asserted the pre-retention contract | #incident #remote #ci | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/navigation.py b/je_auto_control/gui/navigation.py index 74df47c17..fd3e95432 100644 --- a/je_auto_control/gui/navigation.py +++ b/je_auto_control/gui/navigation.py @@ -137,13 +137,19 @@ def _groups(self) -> Iterator[QTreeWidgetItem]: if group is not None: yield group + @staticmethod + def _features(group: QTreeWidgetItem) -> Iterator[QTreeWidgetItem]: + for row in range(group.childCount()): + item = group.child(row) + if item is not None: + yield item + def apply_filter(self, text: str = "") -> int: """Hide what ``text`` does not match; return how many features remain.""" shown = 0 for group in self._groups(): in_group = 0 - for row in range(group.childCount()): - item = group.child(row) + for item in self._features(group): entry = {"title": item.text(0), "key": item.data(0, _KEY_ROLE)} hit = matches(text, entry, group.text(0)) item.setHidden(not hit) @@ -158,17 +164,16 @@ def visible_keys(self) -> List[str]: """Keys of the features the current search leaves on screen, top to bottom.""" keys: List[str] = [] for group in self._groups(): - for row in range(group.childCount()): - item = group.child(row) + for item in self._features(group): if not item.isHidden(): keys.append(str(item.data(0, _KEY_ROLE))) return keys def _first_match(self) -> Optional[QTreeWidgetItem]: for group in self._groups(): - for row in range(group.childCount()): - if not group.child(row).isHidden(): - return group.child(row) + for item in self._features(group): + if not item.isHidden(): + return item return None def activate_first_match(self) -> None: diff --git a/je_auto_control/utils/remote_desktop/webrtc_host.py b/je_auto_control/utils/remote_desktop/webrtc_host.py index 231b832fc..2867879ec 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host.py @@ -207,16 +207,18 @@ async def _create_offer(self) -> str: self._pc = RTCPeerConnection( configuration=self._config.to_rtc_configuration(), ) - if self._external_video_track is not None: - self._video_track = self._external_video_track + external = self._external_video_track + if external is not None: + track = external else: - self._video_track = self._media_owners.create("screen track", lambda: ScreenVideoTrack( + track = self._media_owners.create("screen track", lambda: ScreenVideoTrack( monitor_index=self._config.monitor_index, fps=self._config.fps, region=self._config.region, show_cursor=self._config.show_cursor, ), optional=False) - self._pc.addTrack(self._video_track) + self._video_track = track + self._pc.addTrack(track) if self._config.accept_viewer_video: self._pc.addTransceiver("video", direction="recvonly") if self._config.accept_viewer_audio_opus: diff --git a/je_auto_control/utils/remote_desktop/webrtc_media_owners.py b/je_auto_control/utils/remote_desktop/webrtc_media_owners.py index aa891d079..a99380c35 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_media_owners.py +++ b/je_auto_control/utils/remote_desktop/webrtc_media_owners.py @@ -5,7 +5,7 @@ from dataclasses import dataclass from functools import partial import threading -from typing import Callable, Coroutine, Protocol, TypeVar, runtime_checkable +from typing import Callable, Coroutine, Literal, Protocol, TypeVar, overload, runtime_checkable from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -86,6 +86,12 @@ def require_available(self, slot: str | None = None) -> None: if blocked: raise PeerStopFailed("original media cleanup remains unresolved") + @overload + def create(self, slot: str, factory: Callable[[], Media], *, optional: Literal[False]) -> Media: ... + + @overload + def create(self, slot: str, factory: Callable[[], Media], *, optional: bool = True) -> Media | None: ... + def create(self, slot: str, factory: Callable[[], Media], *, optional: bool = True) -> Media | None: self.require_available(slot) with self._lock: diff --git a/pyproject.toml b/pyproject.toml index 193400cbb..ff4e5e830 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -430,6 +430,8 @@ module = [ "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", "je_auto_control.utils.mcp_server._argument_policy", "je_auto_control.utils.mcp_server._authz", + "je_auto_control.utils.mcp_server._call_run", + "je_auto_control.utils.mcp_server._tool_calls", "je_auto_control.utils.mcp_server._http_origin", "je_auto_control.utils.mcp_server._http_responses", "je_auto_control.utils.mcp_server.disclosure", From d85a9f3014d2dfddbefa59d98268fe74bd6017c1 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 03:16:26 +0800 Subject: [PATCH 052/161] Follow AC_parallel branches with the executor result hook Tokens a branch issued reached the Script Builder only as the block's results[0] entry; each branch now reports under its own step path. --- CHANGELOG.md | 6 ++ Progress.md | 4 +- architecture_explore.md | 14 ++--- .../Eng/doc/new_features/new_features_doc.rst | 6 +- .../operations_layer/operations_layer_doc.rst | 4 +- .../Zh/doc/new_features/new_features_doc.rst | 5 +- .../operations_layer/operations_layer_doc.rst | 2 +- docs/updates/2026-11-b.md | 8 +++ docs/updates/README.md | 1 + .../utils/executor/flow_control.py | 6 +- je_auto_control/utils/executor/result_hook.py | 57 +++++++++++++++++-- .../headless/test_executor_result_hook.py | 40 +++++++++++-- .../test_script_builder_one_time_reveal.py | 9 +-- 13 files changed, 130 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca10c43bd..f9b53e3a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- The executor result hook (`result_callback`, `observe_results`) now follows `AC_parallel` + branches: a branch command is reported under the `AC_parallel` step with the branch's + 1-based index as `run`, and branches never call the callback concurrently. The Script + Builder therefore offers a token a branch issued as that command's own value instead of + `AC_parallel` `results[0].…`. + - Of the three GUI tabs open at start, only Record is built then: Script Builder and Remote Desktop sit in the tab bar as empty stand-ins and are built in place the first time they are selected or their widget is asked for (`TabEntry.widget`, `activate_tab`). Offscreen, diff --git a/Progress.md b/Progress.md index c14dfd8e1..8b068dfd9 100644 --- a/Progress.md +++ b/Progress.md @@ -114,8 +114,8 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 主執行緒 STA、其他執行緒進 MTA),Accessibility 分頁與 A11y Audit 已移出 GUI 執行緒。開發環境沒裝 `comtypes`,CI 也沒有同時有 `comtypes` 與桌面的 job, 測試全是假 COM 物件。未驗證的假設:MTA 工作執行緒上的 UIA 呼叫可用;焦點事件 callback 不需要 message pump; `import comtypes` 第一次發生在已經是 MTA 的執行緒上會丟 `OSError`(憑記憶,沒處理)。焦點等待的 cooperative cancellation 已有 headless 回歸測試;真實 COM 訂閱/解除與停止行為仍待原生驗收。 -- **Script Builder 的一次性值**:一次執行最多保留 200 個(`MAX_ONE_TIME_VALUES`,留前面的);`AC_parallel` 分支裡產生的值不經結果掛鉤回報, - 只能從區塊的結果裡取得(標成 `results[0].…`)。結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 +- **Script Builder 的一次性值**:一次執行最多保留 200 個(`MAX_ONE_TIME_VALUES`,留前面的)。 + 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 - **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep; diff --git a/architecture_explore.md b/architecture_explore.md index a889138ee..651a13954 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,510 | +| 程式碼總行數 | 233,557 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,496 行。 +> 25 個套件、約 19,543 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -304,7 +304,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,702 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,749 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | | `utils/input_macro/` | 477 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | @@ -744,12 +744,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | | `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,702 行)— 執行核心 +#### `utils/executor/`(10,749 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `action_executor.py` | 8,676 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | -| `flow_control.py` | 724 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | +| `flow_control.py` | 726 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | | `flow_data_commands.py` | 272 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | | `action_schema.py` | 225 | action list 的結構驗證:形狀、參數型別、未知指令拒絕。單一走訪同時支援兩種消費方式:`validate_actions()` 遇到第一個問題就拋、`unknown_command_names()` 收齊全部不認得的名字(REST `/execute` 用它回 400)。 | | `action_redaction.py` | 196 | 記錄與紀錄鍵用的遮蔽:`AC_secret_*` 的參數(金庫通行碼、機密值)在寫進 log、當成結果紀錄的鍵之前換成 `***`,巢狀在區塊指令裡的也一樣。 | @@ -1536,7 +1536,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `gui/` | 150 | 40,657 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,717 | -| `utils/executor/` | 11 | 10,702 | +| `utils/executor/` | 11 | 10,749 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,324 | @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,069 | -| **總計** | **1,515** | **232,765** | +| **總計** | **1,515** | **232,812** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/new_features_doc.rst b/docs/source/Eng/doc/new_features/new_features_doc.rst index 4135ea96d..a36d51bd2 100644 --- a/docs/source/Eng/doc/new_features/new_features_doc.rst +++ b/docs/source/Eng/doc/new_features/new_features_doc.rst @@ -55,8 +55,10 @@ whose results are in no execution record:: executor.execute_action(actions, result_callback=seen) -The hook lasts for that run on the calling thread only (a thread the run -starts, such as an ``AC_parallel`` branch, is not followed), a failed command +The hook lasts for that run on the calling thread. ``AC_parallel`` branches +are followed: a branch command's path is the ``AC_parallel`` step's path plus +the branch's 1-based index as ``run``, and two branches never call the +callback at the same time. Any other thread the run starts is not followed. A failed command and a ``dry_run`` report nothing, and a callback that raises is logged by its exception type and ignored. The run returns and logs the same with or without it. ``result`` is the recorded object: do not change it. To observe several diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 540ad5ebf..4c9694cc1 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -205,8 +205,8 @@ surface, each of which needs the ``manage_users`` capability: Rotate Token · alice · token``). At most 200 values are kept for one run -- the first ones; the result pane says when a run issued more. A run that was stopped or failed still offers what it had issued by then. The - hook follows the run's own thread, so a command in an ``AC_parallel`` - branch is offered from the block's result instead. The pane masks every + hook follows ``AC_parallel`` branches too, so a token a branch issued is + offered once, labelled by its branch. The pane masks every secret-named field (``token``, ``password``, ``api_key``...) of every command's result at any depth -- a lease token from ``AC_lease_secret`` / ``AC_lease_active``, the shared bearer token ``AC_rest_api_start`` / diff --git a/docs/source/Zh/doc/new_features/new_features_doc.rst b/docs/source/Zh/doc/new_features/new_features_doc.rst index fe5859a79..1df7ac8b9 100644 --- a/docs/source/Zh/doc/new_features/new_features_doc.rst +++ b/docs/source/Zh/doc/new_features/new_features_doc.rst @@ -52,8 +52,9 @@ Linux (``xclip`` 或 ``xsel``)。若無可用後端會拋出 ``RuntimeError``。 executor.execute_action(actions, result_callback=seen) -掛鉤只在該次執行、呼叫它的執行緒上有效(執行中啟動的執行緒,例如 ``AC_parallel`` -的分支,不會被跟到);失敗的指令與 ``dry_run`` 不會回報;callback 丟出例外時只記錄 +掛鉤只在該次執行、呼叫它的執行緒上有效。``AC_parallel`` 的分支會被跟到:分支裡指令的 +路徑是 ``AC_parallel`` 那一步的路徑,再加上以分支序號(從 1 起)為 ``run`` 的一層;兩個 +分支不會同時呼叫 callback。執行中啟動的其他執行緒不會被跟到。失敗的指令與 ``dry_run`` 不會回報;callback 丟出例外時只記錄 例外型別並忽略。有沒有掛鉤,執行的回傳值與 log 都相同。``result`` 就是紀錄裡的那個 物件,請勿修改。要觀察多次執行,可用 ``je_auto_control.utils.executor.result_hook`` 的 ``with observe_results(seen):``。 diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index 276dd0d0a..9c8481896 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -179,7 +179,7 @@ token 控制項。Python 伺服器的 ``token`` 屬性仍保留設定的共用 t 結果掛鉤回報給 Script Builder,值則以路徑標示(``步驟 2 › Loop 第 3 次,步驟 1 · User: Rotate Token · alice · token``)。一次執行最多保留 200 個值——保留最先 產生的;超過時結果面板會註明。被停止或失敗的執行,仍可看到在那之前已經產生的值。 - 掛鉤只跟著執行本身的執行緒,所以 ``AC_parallel`` 分支裡的指令改由區塊的結果取得。 + 掛鉤也會跟到 ``AC_parallel`` 的分支,所以分支產生的 token 只會出現一次,並以分支標示。 結果面板會遮蔽每個指令結果中、任何深度、名稱屬於機密的欄位(``token``、 ``password``、``api_key``…)——``AC_lease_secret``/``AC_lease_active`` 的租約 token、``AC_rest_api_start``/``AC_rest_api_status`` 回傳的共用 bearer token—— diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 294f92e4b..6ab15a13d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -182,3 +182,11 @@ - **Also found:** `test/verify/typing_contract_verify.py --extras` on Windows (PySide6 6.11.2, aiortc 1.15.0) reported `gui.navigation` and `utils.remote_desktop.webrtc_host` as failing on the pre-session commit `edc6205d` as well. The Windows stubs type `QTreeWidgetItem.child()` as optional, and `WebRTCMediaOwners.create(...)` returned `Media | None` even with `optional=False`, which raises instead of returning `None`. `navigation.py` iterates through a `_features(group)` helper that skips missing children; `create` has an overload returning `Media` for `optional=False`; `webrtc_host.py` passes a local track to `addTrack`. CI's `typing-extras` job runs on Ubuntu, whose stubs did not flag the first. No behaviour change. - **Evidence:** the strict-tier and `dev.toml` parity tests: 23 passed; extras-config mypy for the three modules on win32 and linux, and normal-config on win32 and darwin: no issues; navigation / WebRTC / media test files: 1,169 passed, 1 skipped. - **Open items:** none. + +## U-20261112-09 · 2026-11-12 · The result hook follows AC_parallel branches · #done #executor #gui + +- **What:** Closes the `Progress.md` › GUI › Script Builder one-time values clause (and the open item of U-20261009-40) that values produced in an `AC_parallel` branch never reached the result hook and were offered only from the block's result as `results[0].…`. `_ParallelRun` now captures the hook with the run's other per-thread state (`capture_branch_hook()`), and each branch thread binds it (`bound_branch_hook(hook, index)`): the branch gets its own frame stack, seeded with a frozen copy of the `AC_parallel` step's path and the branch's 1-based index as that step's `run`, the way a loop iteration is numbered. The callback is shared, so it is called under the observation's `RLock`: two branches never enter it at once, and a callback that runs the executor again on its own thread does not deadlock. Other threads a run starts are still not followed. +- **Script Builder:** `OneTimeCollector` already skips what a block repeats from its own body's steps (path prefix), so a branch's token is offered once, as `AC_lease_secret · token` at `AC_parallel › run 1, step 1`, not again from the block. +- **Tests:** `test_executor_result_hook.py`: branch commands reported under the step with runs 1 and 2; four branches with a 20 ms callback never overlap (5 calls, peak 1); no hook binds nothing. `test_script_builder_one_time_reveal.py`: the branch token is offered once with its branch path. Hook, redaction, Script Builder, executor and flow-control suites: 219 passed, 1 skipped; doc, budget, strict-tier and thread-scope gates: 79 passed; strict Sphinx clean. +- **Files:** `utils/executor/{result_hook.py,flow_control.py}`, the two tests, both `new_features_doc.rst` and `operations_layer_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** none for this; the dialog itself still has not been shown on a real screen (`Progress.md` › GUI). diff --git a/docs/updates/README.md b/docs/updates/README.md index 3443200a1..cbe96ff10 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-09 | 2026-11-12 | The result hook follows AC_parallel branches | #done #executor #gui | [2026-11-b](2026-11-b.md) | | U-20261112-08 | 2026-11-12 | Strict tier for the two new MCP modules; Windows Qt stub nulls | #incident #typing #ci | [2026-11-b](2026-11-b.md) | | U-20261112-07 | 2026-11-12 | Build only the first start-up tab; the others when first selected | #done #gui #performance | [2026-11-b](2026-11-b.md) | | U-20261112-06 | 2026-11-12 | Split the tools/call path out of the MCP server module | #done #mcp #quality | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/executor/flow_control.py b/je_auto_control/utils/executor/flow_control.py index f8e9b2750..7aa2067a1 100644 --- a/je_auto_control/utils/executor/flow_control.py +++ b/je_auto_control/utils/executor/flow_control.py @@ -29,6 +29,7 @@ from je_auto_control.utils.rbac.authorization import authorization_scope, current_authorization from je_auto_control.utils.action_journal.capture import bound_journal, current_journal from je_auto_control.utils.executor.dispatch import bound_command_guards, capture_command_guards +from je_auto_control.utils.executor.result_hook import bound_branch_hook, capture_branch_hook from je_auto_control.utils.exception.cancellation import cancellation_scope, current_cancellation_token from je_auto_control.utils.logging.secret_scope import bound_secret_scope, current_secret_scope from je_auto_control.utils.run_history.context import bound_history, current_history @@ -498,8 +499,9 @@ def __init__(self, executor: Any, branches: list) -> None: from je_auto_control.utils.agent_runtime.origin_policy import current_origin self._task_operation = current_operation() self._origin = current_origin() - # Branch threads do not inherit the run's stop token either. + # Branch threads do not inherit the run's stop token or result hook either. self._stop_token = current_stop_token() + self._result_hook = capture_branch_hook() self._stopped: Optional[ExecutionStopped] = None self.results: list = [None] * len(branches) self._failures: list = [0] * len(branches) @@ -537,7 +539,7 @@ def run_branch(self, index: int, branch: Any) -> None: bound_secret_scope(self._secret_scope), bound_history(self._history), bound_command_guards(self._command_guards), cancellation_scope(self._cancellation), operation_scope(self._task_operation), origin_scope(self._origin), - bound_stop_token(self._stop_token)): + bound_stop_token(self._stop_token), bound_branch_hook(self._result_hook, index)): self.results[index] = self._branch_executor().execute_action( branch, raise_on_error=self._strict, _validated=True) self._failures[index] = self._module.recorded_failures() diff --git a/je_auto_control/utils/executor/result_hook.py b/je_auto_control/utils/executor/result_hook.py index c0db63801..11ef999eb 100644 --- a/je_auto_control/utils/executor/result_hook.py +++ b/je_auto_control/utils/executor/result_hook.py @@ -21,8 +21,12 @@ A command that failed has no result and is not reported; neither is a ``dry_run``. The hook belongs to the thread that registered it and ends with -the ``with`` block: a thread started during the run (``AC_parallel``, a -scheduler) does not inherit it, and its commands are not reported. Nothing +the ``with`` block. An ``AC_parallel`` branch is handed it +(:func:`capture_branch_hook` / :func:`bound_branch_hook`): its commands are +reported with the path of the ``AC_parallel`` step, the branch's 1-based +index as that step's ``run``, and the callback is never entered by two +branches at once. Any other thread started during the run (a scheduler, a +tool's own worker) does not inherit it, and its commands are not reported. Nothing about the run changes: what it returns, records and logs is the same with and without a hook, and a callback that raises is logged by its exception type and otherwise ignored. With no hook registered the executor pays one lookup per @@ -32,6 +36,7 @@ *before* each action of the list it was passed with, with that action alone, and is not handed down to nested bodies -- its callers count top-level steps. """ +import threading from contextlib import contextmanager from typing import Any, Callable, Iterator, List, NamedTuple, Optional, Tuple @@ -78,12 +83,21 @@ def advance(self, position: int, action: Any) -> None: class _Observation: """One registered callback and the stack of action lists running under it.""" - __slots__ = ("callback", "frames", "started") + __slots__ = ("callback", "frames", "started", "lock") - def __init__(self, callback: ResultHook) -> None: + def __init__(self, callback: ResultHook, lock: Optional[threading.RLock] = None) -> None: self.callback = callback self.frames: List[_Frame] = [] self.started = 0 + # Shared with the run's AC_parallel branches, which report concurrently. + self.lock = lock if lock is not None else threading.RLock() + + +class BranchHook(NamedTuple): + """What an ``AC_parallel`` branch needs to report to the run's hook.""" + callback: ResultHook + lock: threading.RLock + path: StepPath _ACTIVE: "ThreadBoundVar[Optional[_Observation]]" = ThreadBoundVar("autocontrol_result_hook", None) @@ -111,6 +125,35 @@ def observe_results(callback: ResultHook) -> Iterator[None]: _ACTIVE.reset(token) +def capture_branch_hook() -> Optional[BranchHook]: + """On the thread running ``AC_parallel``: the hook its branches report to, if any.""" + observation = _ACTIVE.get() + if observation is None or not observation.frames: + return None + path = tuple(StepPosition(frame.run, frame.position, frame.command) + for frame in observation.frames) + return BranchHook(observation.callback, observation.lock, path) + + +@contextmanager +def bound_branch_hook(hook: Optional[BranchHook], index: int) -> Iterator[None]: + """On a branch thread: report to ``hook`` as branch ``index`` (0-based) of its step.""" + if hook is None: + yield + return + observation = _Observation(hook.callback, hook.lock) + for position in hook.path: + frame = _Frame(position.run) + frame.position, frame.command = position.position, position.command + observation.frames.append(frame) + observation.frames[-1].started = index # the branch's own list runs as index + 1 + token = _ACTIVE.set(observation) + try: + yield + finally: + _ACTIVE.reset(token) + + def enter_list() -> Optional[_Frame]: """Executor: an action list starts; ``None`` when no hook is registered.""" observation = _ACTIVE.get() @@ -141,10 +184,12 @@ def report_result(action: Any, result: Any) -> None: for frame in observation.frames) arguments = action[1] if isinstance(action, list) and len(action) > 1 else None try: - observation.callback(_command_of(action), arguments, result, path) + with observation.lock: + observation.callback(_command_of(action), arguments, result, path) except Exception as error: # noqa: BLE001 # reason: an observer must not fail the run it watches # The type only: the message could quote the result it was handed. autocontrol_logger.warning("result hook raised %s; ignored", type(error).__name__) -__all__ = ["ResultHook", "StepPath", "StepPosition", "observe_results"] +__all__ = ["BranchHook", "ResultHook", "StepPath", "StepPosition", "bound_branch_hook", + "capture_branch_hook", "observe_results"] diff --git a/test/unit_test/headless/test_executor_result_hook.py b/test/unit_test/headless/test_executor_result_hook.py index f5fb86263..6233bac7f 100644 --- a/test/unit_test/headless/test_executor_result_hook.py +++ b/test/unit_test/headless/test_executor_result_hook.py @@ -188,13 +188,45 @@ def spawn(value=None): assert [entry[0] for entry in seen] == ["AC_fake_spawn"] -def test_a_parallel_branch_runs_on_its_own_thread_and_is_not_reported(runner): +def test_a_parallel_branch_reports_under_its_step_with_its_index_as_run(runner): seen, hook = _recorder() record = execute_action( - [["AC_parallel", {"branches": [[["AC_get_var", {"name": "missing", "default": 5}]]]}]], + [["AC_parallel", {"branches": [[["AC_get_var", {"name": "missing", "default": 5}]], + [["AC_get_var", {"name": "missing", "default": 6}]]]}]], result_callback=hook) - assert [entry[0] for entry in seen] == ["AC_parallel"] - assert seen[0][2] is list(record.values())[0], "what the branch answered is in the block's result" + branch = {entry[2]: entry[3] for entry in seen if entry[0] == "AC_get_var"} + step = StepPosition(1, 1, "AC_parallel") + assert branch == {5: (step, StepPosition(1, 1, "AC_get_var")), + 6: (step, StepPosition(2, 1, "AC_get_var"))} + assert seen[-1][0] == "AC_parallel" and seen[-1][3] == (step,) + assert seen[-1][2] is list(record.values())[0], "what the branches answered is in the block's result" + + +def test_parallel_branches_never_enter_the_callback_at_once(runner): + inside, overlaps = [0], [] + gate = threading.Lock() + + def hook(command, arguments, result, path): + with gate: + inside[0] += 1 + overlaps.append(inside[0]) + threading.Event().wait(0.02) # long enough for another branch to arrive + with gate: + inside[0] -= 1 + + branches = [[["AC_get_var", {"name": "missing", "default": index}]] for index in range(4)] + execute_action([["AC_parallel", {"branches": branches}]], result_callback=hook) + assert len(overlaps) == 5, "four branch commands and the block itself" + assert max(overlaps) == 1 + + +def test_a_branch_without_a_hook_registers_none(runner): + seen = [] + execute_action([["AC_parallel", {"branches": [[["AC_get_var", {"name": "m", "default": 1}]]]}]]) + assert result_hook.capture_branch_hook() is None + with result_hook.bound_branch_hook(None, 0): + result_hook.report_result(["AC_fake_echo", {"value": 1}], 1) + assert seen == [] def test_no_hook_means_no_frame_and_no_call(runner, monkeypatch): diff --git a/test/unit_test/headless/test_script_builder_one_time_reveal.py b/test/unit_test/headless/test_script_builder_one_time_reveal.py index 2e38560bd..b1bf69836 100644 --- a/test/unit_test/headless/test_script_builder_one_time_reveal.py +++ b/test/unit_test/headless/test_script_builder_one_time_reveal.py @@ -134,13 +134,14 @@ def test_a_block_that_returns_its_body_record_does_not_offer_a_value_twice(tmp_p assert values[0].value not in shown -def test_a_value_only_a_parallel_branch_produced_is_taken_from_the_block_result(): - """A branch runs on its own thread, which the hook does not follow; its record is in the result.""" +def test_a_value_a_parallel_branch_produced_is_offered_once_from_its_branch(): + """The hook follows AC_parallel branches; the block's repeat of the same token is not offered again.""" + from je_auto_control.utils.executor.result_hook import StepPosition record, values, _truncated = _collected( [["AC_parallel", {"branches": [[["AC_lease_secret", {"name": "one-time-par", "ttl": 5}]]]}]]) try: - assert [(value.command, value.name) for value in values] == [ - ("AC_parallel", "results[0].AC_lease_secret.token")] + assert [(value.command, value.name) for value in values] == [("AC_lease_secret", "token")] + assert values[0].path == (StepPosition(1, 1, "AC_parallel"), StepPosition(1, 1, "AC_lease_secret")) assert values[0].value not in json.dumps(displayable_record(record), default=str) finally: execute_action([["AC_revoke_lease", {"token": values[0].value}]]) From 7771037fbbdf2d49b9d6dde86c6bb860350e9780 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 03:18:49 +0800 Subject: [PATCH 053/161] Drop the capability-probe Progress item; the probes it described are gone --- Progress.md | 2 -- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Progress.md b/Progress.md index 8b068dfd9..1109d3a19 100644 --- a/Progress.md +++ b/Progress.md @@ -170,8 +170,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` PySide6 6.11.2(`[gui]` 要求 6.12.0)。共用環境的升級需要使用者同意,沒有動;不影響 CI。 - **free-threaded**:呼叫者身分、綁定的裝置、自愈的執行標記與 stop token 都改成只在設定它的執行緒上有效(`utils/thread_bound.py`)。 這台機器沒有 free-threaded 直譯器:驗證用的是模擬繼承與真的 `-X thread_inherit_context=1`(3.14.7,GIL 開著);`free-threaded-scope` job(3.14t)是第一次真的跑。 -- **能力探測**:Windows 的鎖定工作站、session 0、低完整性與擷取失敗分支只用假資料判斷;macOS 的三個 preflight 呼叫只對假物件跑過, - pyobjc 的 `Quartz` 有沒有 `CGPreflightListenEventAccess` 未知(沒有的話 `recording`/`stop_shortcut` 回 `unknown`)。 - **Windows 的版面鍵名**(`slash` 等 8 個)只在美式配置上實際呼叫過。 - **設定同步在 Windows 的路徑長度**:`LongPathsEnabled=0` 的機器上,`test_sync_workspace_surfaces.py` 的長紀錄名稱案例 (64+64 字元的 `scripts/…json`)在 `cache/.incoming-*/files/` 下組成 265 字元的路徑,`FileNotFoundError` 後回報 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 6ab15a13d..de15c6bdc 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -190,3 +190,10 @@ - **Tests:** `test_executor_result_hook.py`: branch commands reported under the step with runs 1 and 2; four branches with a 20 ms callback never overlap (5 calls, peak 1); no hook binds nothing. `test_script_builder_one_time_reveal.py`: the branch token is offered once with its branch path. Hook, redaction, Script Builder, executor and flow-control suites: 219 passed, 1 skipped; doc, budget, strict-tier and thread-scope gates: 79 passed; strict Sphinx clean. - **Files:** `utils/executor/{result_hook.py,flow_control.py}`, the two tests, both `new_features_doc.rst` and `operations_layer_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** none for this; the dialog itself still has not been shown on a real screen (`Progress.md` › GUI). + +## U-20261112-10 · 2026-11-12 · The capability-probe Progress item described deleted code · #snapshot #capabilities #macos + +- **What:** The `Progress.md` › 雜項 bullet "能力探測" said the Windows locked-workstation / session 0 / low-integrity / capture-failure branches and three macOS preflight calls had run only against fakes, and that it was unknown whether pyobjc's `Quartz` has `CGPreflightListenEventAccess`. Those branches lived in `wrapper/capability_probes.py` (c134d367f), which no longer exists on `dev`: it went away in the 1.1.0 merge (`538a23096`), and `wrapper/capabilities.py::probe_capabilities` now reports `unverified` for Windows and macOS input and capture without calling any OS API. No code makes those calls, so the bullet is removed. +- **For whoever brings a macOS probe back:** `pyobjc-framework-Quartz==12.2.2` (the version `pyobjc==12.2.2` in `pyproject.toml` resolves to) declares `CGPreflightListenEventAccess`, `CGPreflightPostEventAccess` and `CGPreflightScreenCaptureAccess`, each with signature `B` (no arguments, returns bool), together with the matching `CGRequest…Access`, in `Quartz/CoreGraphics/_metadata.py`. Read from the downloaded wheel, not run; the functions exist only on macOS 10.15 and later. +- **Not covered here:** Windows session and integrity checks elsewhere (`session_guard`, `input_reach`, `agent_runtime/presence_*_windows.py`) stay under the deferred native acceptance items in `Progress.md`. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index cbe96ff10..052ec4050 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-10 | 2026-11-12 | The capability-probe Progress item described deleted code | #snapshot #capabilities #macos | [2026-11-b](2026-11-b.md) | | U-20261112-09 | 2026-11-12 | The result hook follows AC_parallel branches | #done #executor #gui | [2026-11-b](2026-11-b.md) | | U-20261112-08 | 2026-11-12 | Strict tier for the two new MCP modules; Windows Qt stub nulls | #incident #typing #ci | [2026-11-b](2026-11-b.md) | | U-20261112-07 | 2026-11-12 | Build only the first start-up tab; the others when first selected | #done #gui #performance | [2026-11-b](2026-11-b.md) | From e091b0f7f3ac913a88063e201d2a8716dd08563e Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 03:24:05 +0800 Subject: [PATCH 054/161] Refuse config-sync asset paths Windows cannot create, before staging Without LongPathsEnabled the first file past 259 characters failed as a bare FileNotFoundError, reported only as an incomplete generation. --- CHANGELOG.md | 5 +++ Progress.md | 4 --- architecture_explore.md | 14 ++++---- docs/guides/en/usage.md | 2 +- docs/guides/zh-CN/usage.md | 2 +- docs/guides/zh-TW/usage.md | 2 +- docs/updates/2026-11-b.md | 7 ++++ docs/updates/README.md | 1 + je_auto_control/utils/config_sync/assets.py | 35 +++++++++++++++++++ test/unit_test/headless/test_sync_assets.py | 19 ++++++++++ .../headless/test_sync_workspace_surfaces.py | 5 +++ 11 files changed, 82 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9b53e3a8..f5f595dec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- `sync_assets` (and `AC_sync_assets`, `materialize` of `AC_sync_workspace`) refuses up front, + with a `ConfigSyncError` naming the length, a generation whose published paths would pass + 259 characters on Windows without `LongPathsEnabled`; it used to fail on the first such file + with a generic "could not publish a complete generation". + - The executor result hook (`result_callback`, `observe_results`) now follows `AC_parallel` branches: a branch command is reported under the `AC_parallel` step with the branch's 1-based index as `run`, and branches never call the callback concurrently. The Script diff --git a/Progress.md b/Progress.md index 1109d3a19..0c6983af8 100644 --- a/Progress.md +++ b/Progress.md @@ -171,10 +171,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **free-threaded**:呼叫者身分、綁定的裝置、自愈的執行標記與 stop token 都改成只在設定它的執行緒上有效(`utils/thread_bound.py`)。 這台機器沒有 free-threaded 直譯器:驗證用的是模擬繼承與真的 `-X thread_inherit_context=1`(3.14.7,GIL 開著);`free-threaded-scope` job(3.14t)是第一次真的跑。 - **Windows 的版面鍵名**(`slash` 等 8 個)只在美式配置上實際呼叫過。 -- **設定同步在 Windows 的路徑長度**:`LongPathsEnabled=0` 的機器上,`test_sync_workspace_surfaces.py` 的長紀錄名稱案例 - (64+64 字元的 `scripts/…json`)在 `cache/.incoming-*/files/` 下組成 265 字元的路徑,`FileNotFoundError` 後回報 - `asset transfer could not publish a complete generation`(`utils/config_sync/assets.py`);CI 的暫存根目錄較短所以會過。 - 真的安裝把快取放在深一點的目錄時也會撞到。`TODO`:Windows 上改用 `\\?\` 長路徑,或在超出前以明確錯誤拒絕該紀錄名稱。 - **狀態機 `on_enter` 的單一動作寫法**以前一直被拒絕、從沒執行過(已修,U-20261009-24):依賴「它不會跑」的既有狀態機現在會跑它。 --- diff --git a/architecture_explore.md b/architecture_explore.md index 651a13954..d644b5f94 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,557 | +| 程式碼總行數 | 233,592 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,12 +537,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 31,951 行。 +> 6 個套件、約 31,986 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | -| `utils/config_sync/` | 8,542 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | +| `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | | `utils/remote_desktop/` | 16,717 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | @@ -935,7 +935,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cv2_utils/template_detection.py` | 182 | Locate a template image on screen, in the coordinates the mouse takes. | | `utils/cv2_utils/video_recording.py` | 76 | Internal image/capture utilities. | -#### `utils/config_sync/`(8,542 行)— 持久化、因果模型與本機重送 +#### `utils/config_sync/`(8,577 行)— 持久化、因果模型與本機重送 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -961,7 +961,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/config_sync/causal_routes.py` | 53 | 可選 signaling 的獨立第三版 GET/PUT 路由與 full-resync 拒絕回應。 | | `utils/config_sync/causal_wire.py` | 65 | 共用既有 HTTP egress/redirect 限制的第三版 transport,嚴格區分過期版本與操作 ID 衝突。 | | `utils/config_sync/asset_models.py` | 130 | 可攜資產名稱、精確大小/SHA-256 與第一版不可變 manifest。 | -| `utils/config_sync/assets.py` | 270 | 整版暫存驗證後一次發布不可變目錄;精確重驗快取與取消清理。 | +| `utils/config_sync/assets.py` | 305 | 整版暫存驗證後一次發布不可變目錄;精確重驗快取與取消清理。 | | `utils/config_sync/asset_commands.py` | 52 | 私有本機 manifest/資產版本命令,共用即時 roots 與取消檢查。 | | `utils/config_sync/outbox_batch.py` | 106 | Atomically enqueue a bounded namespace batch while checking current generation and pending resync barriers. | | `utils/config_sync/blob_models.py` | 86 | Bounded content-addressed chunk descriptors and portable profile asset references contain no local paths. | @@ -1553,8 +1553,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,069 | -| **總計** | **1,515** | **232,812** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,104 | +| **總計** | **1,515** | **232,847** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/guides/en/usage.md b/docs/guides/en/usage.md index 5c7cf66b9..09327d2e6 100644 --- a/docs/guides/en/usage.md +++ b/docs/guides/en/usage.md @@ -142,7 +142,7 @@ Experimental `self_heal_run(SelfHealRequest(...))` defaults to locating. Choose Captured self-healing rows now include an optional `journal_path` alongside run/step IDs. Experimental `inspect_heal_source(path, run_id, step_id)`, `AC_self_heal_source` and MCP `ac_self_heal_source` read only the original step’s sanitized lifecycle snapshots. In **Self-Healing**, select a row and choose **Actions → Inspect original step** to open the background reader. Switching targets waits for the older reader to stop and retains the requester’s context; closing cancels pending work. Run History’s reader also accepts an optional step ID. Run/step filtering precedes the output limit, the whole file is validated, current path roots are rechecked around progress callbacks, and cancellation returns no partial result. Legacy or uncaptured rows have no original-source link; inspection never replays a command. -Experimental causal synchronization provides `CausalBucket`, `CausalConfigStore`, `SyncActor`, conflict-preserving entry versions and a durable local `SyncOutbox`. The dedicated authenticated `GET/PUT /config/{user_id}/causal` protocol (version 3) validates peer registration, acknowledgements, retirement/full-sync epochs and collection in the same CAS transaction as retry receipts. Collected deletions retain permanent minimal fences; legacy writers cannot overwrite upgraded accounts. Private `AC_config_store_get` / `AC_config_store_commit` and matching MCP/Builder commands read and commit causal JSON with an explicit `_actor`. Pure merge/peer commands and private outbox commands remain available. The explicit `CausalSyncClient` and `AC_config_causal_fetch`, `AC_config_causal_commit`, `AC_sync_outbox_flush` (matching MCP/Builder commands) now deliver v3 HTTP requests: uncertain sends reuse the frozen request; only definite stale-base errors rebase within a bounded budget. `CausalReceipt` confirms the original receipt and latest complete snapshot atomically in the outbox. Command credentials use a live `options.secret_env` reference. `CausalSyncClient.control` and private `AC_sync_peer_control` / `ac_sync_peer_control` / Builder Data commands durably register, acknowledge, collect, retire and perform full resync. `SyncControlRequest(operation_id=...)` makes completed RPC retries idempotent; full resync requires explicit `discard_pending=True` before atomically adopting a new generation and archiving pending old edits. Local `status` reads no credential or network. Run `python -m examples.causal_peer_control` for the temporary loopback workflow; explicit local asset generations are available through `AssetManifest`, `DirectoryAssetTransport`, `build_asset_manifest`, `sync_assets` and private `AC_sync_asset_manifest` / `AC_sync_assets` (MCP/Builder). All assets stage and pass SHA-256/size checks before one directory publication; damaged caches are refused and scripts stay inert. `python -m examples.sync_assets` uses temporary directories only. Seven experimental adapters now capture selected scripts, locators, hotkeys, triggers, address-book entries, JSON settings and saved native GUI preferences into durable causal profiles. `SyncBindings` replaces explicit secrets and machine values with named references; `materialize_sync_profile` publishes a complete inert native-format generation. Private `AC_sync_adapter_snapshot`, `AC_sync_adapter_apply`, `AC_sync_adapter_resolve`, `AC_sync_profile_materialize` and matching MCP/Builder commands share the workflow. `python -m examples.sync_adapters` uses temporary files only. Private absolute path bindings accept high-entropy directory names while recognized credential formats remain refused. Native numeric definitions reject out-of-range values, including extreme JSON integers, with typed errors before storage. `WorkspaceSettingsSyncAdapter` captures only theme, font size, navigation visibility/width from native GUI INI files and publishes an inert `workspace.ini`; explicitly copy it to a separate working file before opening a new GUI. `python -m examples.sync_workspace` stays Qt-free. `SyncWorkspace` now coordinates selected sources, durable offline capture, causal HTTP, exact conflict review and full-resync source baselines. Private `AC_sync_workspace` / `ac_sync_workspace` / Builder Data share status/capture/sync/review/resolve/preferences/materialize and explicit peer controls; all require DRIVE. Runtime network credentials use `options.secret_env`. `python -m examples.sync_workspace_http` demonstrates two temporary sources over loopback, conflict resolution, restart and no replay of retired edits. Received definitions remain inert. Referenced asset transport is described below; explicit native working-copy loading is described below; `ConfigSyncClient` retains its timestamp merge. See the [causal/outbox guide](../../source/Eng/doc/causal_sync/causal_sync_doc.rst) and `python -m examples.causal_sync`. +Experimental causal synchronization provides `CausalBucket`, `CausalConfigStore`, `SyncActor`, conflict-preserving entry versions and a durable local `SyncOutbox`. The dedicated authenticated `GET/PUT /config/{user_id}/causal` protocol (version 3) validates peer registration, acknowledgements, retirement/full-sync epochs and collection in the same CAS transaction as retry receipts. Collected deletions retain permanent minimal fences; legacy writers cannot overwrite upgraded accounts. Private `AC_config_store_get` / `AC_config_store_commit` and matching MCP/Builder commands read and commit causal JSON with an explicit `_actor`. Pure merge/peer commands and private outbox commands remain available. The explicit `CausalSyncClient` and `AC_config_causal_fetch`, `AC_config_causal_commit`, `AC_sync_outbox_flush` (matching MCP/Builder commands) now deliver v3 HTTP requests: uncertain sends reuse the frozen request; only definite stale-base errors rebase within a bounded budget. `CausalReceipt` confirms the original receipt and latest complete snapshot atomically in the outbox. Command credentials use a live `options.secret_env` reference. `CausalSyncClient.control` and private `AC_sync_peer_control` / `ac_sync_peer_control` / Builder Data commands durably register, acknowledge, collect, retire and perform full resync. `SyncControlRequest(operation_id=...)` makes completed RPC retries idempotent; full resync requires explicit `discard_pending=True` before atomically adopting a new generation and archiving pending old edits. Local `status` reads no credential or network. Run `python -m examples.causal_peer_control` for the temporary loopback workflow; explicit local asset generations are available through `AssetManifest`, `DirectoryAssetTransport`, `build_asset_manifest`, `sync_assets` and private `AC_sync_asset_manifest` / `AC_sync_assets` (MCP/Builder). All assets stage and pass SHA-256/size checks before one directory publication; damaged caches are refused and scripts stay inert. On Windows without `LongPathsEnabled`, a generation whose published paths would pass 259 characters is refused up front with a `ConfigSyncError` that names the length. `python -m examples.sync_assets` uses temporary directories only. Seven experimental adapters now capture selected scripts, locators, hotkeys, triggers, address-book entries, JSON settings and saved native GUI preferences into durable causal profiles. `SyncBindings` replaces explicit secrets and machine values with named references; `materialize_sync_profile` publishes a complete inert native-format generation. Private `AC_sync_adapter_snapshot`, `AC_sync_adapter_apply`, `AC_sync_adapter_resolve`, `AC_sync_profile_materialize` and matching MCP/Builder commands share the workflow. `python -m examples.sync_adapters` uses temporary files only. Private absolute path bindings accept high-entropy directory names while recognized credential formats remain refused. Native numeric definitions reject out-of-range values, including extreme JSON integers, with typed errors before storage. `WorkspaceSettingsSyncAdapter` captures only theme, font size, navigation visibility/width from native GUI INI files and publishes an inert `workspace.ini`; explicitly copy it to a separate working file before opening a new GUI. `python -m examples.sync_workspace` stays Qt-free. `SyncWorkspace` now coordinates selected sources, durable offline capture, causal HTTP, exact conflict review and full-resync source baselines. Private `AC_sync_workspace` / `ac_sync_workspace` / Builder Data share status/capture/sync/review/resolve/preferences/materialize and explicit peer controls; all require DRIVE. Runtime network credentials use `options.secret_env`. `python -m examples.sync_workspace_http` demonstrates two temporary sources over loopback, conflict resolution, restart and no replay of retired edits. Received definitions remain inert. Referenced asset transport is described below; explicit native working-copy loading is described below; `ConfigSyncClient` retains its timestamp merge. See the [causal/outbox guide](../../source/Eng/doc/causal_sync/causal_sync_doc.rst) and `python -m examples.causal_sync`. The lazy **Workspace Sync** tab exposes local status/capture, network synchronization and peer controls, exact causal review/resolution, and complete inert publication through **Actions**. Paste an explicit private workspace descriptor; credentials are environment variable names. Sync never applies received preferences automatically. Select `workspace`, review its current heads, then choose **Apply reviewed GUI preferences** to update theme, font and navigation in the running window. `SyncWorkspace.preferences(observed=change_ids)` and the existing AC/MCP/Builder `preferences` operation return four canonical values only when the exact reviewed heads remain conflict-free; missing/deleted values use safe defaults. Workers preserve caller context, refresh DRIVE authority, support cancellation and discard stale results on close. The view shows revision/pending/conflict/reference counts and the last successful sync revision; no connection starts when opened. diff --git a/docs/guides/zh-CN/usage.md b/docs/guides/zh-CN/usage.md index e8e0ea736..68446b8af 100644 --- a/docs/guides/zh-CN/usage.md +++ b/docs/guides/zh-CN/usage.md @@ -136,7 +136,7 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" 已捕获的自愈记录新增可选的 `journal_path`,搭配 run/step ID。实验性 `inspect_heal_source(path, run_id, step_id)`、`AC_self_heal_source` 与 MCP `ac_self_heal_source` 只读取原始步骤经清理的生命周期快照。在 **Self-Healing** 选取记录后,使用 **动作 → 查看原始步骤** 打开后台读取器;切换目标时会等待旧读取停止并保留请求者上下文,关闭则取消待处理工作;Run History 读取器也可选填步骤 ID。先筛选 run/step 再应用输出上限,整份日志仍会验证,进度通知前后重查路径根目录,取消不返回部分结果。旧记录或未经动作日志捕获的操作没有来源链接;查阅不会重放命令。 -实验性因果同步提供 `CausalBucket`、`CausalConfigStore`、`SyncActor`、保留冲突的 entry 版本与持久化本机 `SyncOutbox`。独立且经过验证的 `GET/PUT /config/{user_id}/causal` 第三版协议,在保存重发收据的同一个 CAS 事务内验证设备注册、确认、退休/完整同步 epoch 与删除回收。回收后保留永久的最小删除凭据;旧版写入不能覆盖已升级账号。私有 `AC_config_store_get`/`AC_config_store_commit` 与对应 MCP/Builder 命令可读取及提交带显式 `_actor` 的因果 JSON;纯数据合并/peer 与私有 outbox 命令仍可使用。显式的 `CausalSyncClient` 与 `AC_config_causal_fetch`、`AC_config_causal_commit`、`AC_sync_outbox_flush`(含 MCP/Builder)已提供第三版 HTTP 投递:结果不明时重发固定请求,只有明确的过期版本才在有界预算内重新合并。`CausalReceipt` 在 outbox 原子确认原收据与最新完整快照;命令凭据使用实时的 `options.secret_env` 引用。`CausalSyncClient.control` 与私有 `AC_sync_peer_control`/`ac_sync_peer_control`/Builder Data 命令可持久化注册、确认、回收、退休与完整重同步。`SyncControlRequest(operation_id=...)` 让已完成 RPC 的重试保持幂等;完整重同步须明确提供 `discard_pending=True`,收到收据后才原子采用新世代并归档待送旧编辑。本机 `status` 不读取凭据或网络。`python -m examples.causal_peer_control` 提供暂存 loopback 工作流;明确的本机资产版本可通过 `AssetManifest`、`DirectoryAssetTransport`、`build_asset_manifest`、`sync_assets` 与私有 `AC_sync_asset_manifest`/`AC_sync_assets`(MCP/Builder)操作。全部资产先暂存并通过 SHA-256/大小验证,再一次发布完整目录;受损缓存拒绝使用,脚本保持未执行。`python -m examples.sync_assets` 只使用暂存目录。七种实验性 adapter 已将显式选定的脚本、locator、热键、触发器、通讯录、JSON 设置与已保存的原生 GUI 偏好设置保存为持久化因果 profile。`SyncBindings` 将显式指定的秘密与机器值换成具名引用;`materialize_sync_profile` 发布完整且未启用的原生格式版本。私有 `AC_sync_adapter_snapshot`、`AC_sync_adapter_apply`、`AC_sync_adapter_resolve`、`AC_sync_profile_materialize` 与对应 MCP/Builder 命令提供相同流程。`python -m examples.sync_adapters` 仅使用临时文件。私有绝对路径绑定接受高熵目录名称,仍拒绝可识别的凭证格式。原生数值定义会在存储前以分类错误拒绝超出范围的值,包括超大 JSON 整数。`WorkspaceSettingsSyncAdapter` 仅读取原生 GUI INI 的主题、字号、导航显示/宽度,并发布未启用的 `workspace.ini`;显式复制为独立工作文件后,才能交给新 GUI 使用。`python -m examples.sync_workspace` 不导入 Qt。`SyncWorkspace` 已整合明确来源、持久离线捕捉、因果 HTTP、精确冲突审阅与完整重同步来源基线。私有 `AC_sync_workspace`/`ac_sync_workspace`/Builder Data 共用 status/capture/sync/review/resolve/preferences/materialize 与明确 peer 控制,全部需要 DRIVE;网络凭据使用 `options.secret_env`。`python -m examples.sync_workspace_http` 以两组临时来源与 loopback 演示冲突解决、重启及退休编辑不重放。接收数据保持未启用。引用资产传输见下方;明确的原生工作副本加载见下方,`ConfigSyncClient` 保留时间戳合并。参阅[因果/outbox 指南](../../source/Zh/doc/causal_sync/causal_sync_doc.rst)与 `python -m examples.causal_sync`。 +实验性因果同步提供 `CausalBucket`、`CausalConfigStore`、`SyncActor`、保留冲突的 entry 版本与持久化本机 `SyncOutbox`。独立且经过验证的 `GET/PUT /config/{user_id}/causal` 第三版协议,在保存重发收据的同一个 CAS 事务内验证设备注册、确认、退休/完整同步 epoch 与删除回收。回收后保留永久的最小删除凭据;旧版写入不能覆盖已升级账号。私有 `AC_config_store_get`/`AC_config_store_commit` 与对应 MCP/Builder 命令可读取及提交带显式 `_actor` 的因果 JSON;纯数据合并/peer 与私有 outbox 命令仍可使用。显式的 `CausalSyncClient` 与 `AC_config_causal_fetch`、`AC_config_causal_commit`、`AC_sync_outbox_flush`(含 MCP/Builder)已提供第三版 HTTP 投递:结果不明时重发固定请求,只有明确的过期版本才在有界预算内重新合并。`CausalReceipt` 在 outbox 原子确认原收据与最新完整快照;命令凭据使用实时的 `options.secret_env` 引用。`CausalSyncClient.control` 与私有 `AC_sync_peer_control`/`ac_sync_peer_control`/Builder Data 命令可持久化注册、确认、回收、退休与完整重同步。`SyncControlRequest(operation_id=...)` 让已完成 RPC 的重试保持幂等;完整重同步须明确提供 `discard_pending=True`,收到收据后才原子采用新世代并归档待送旧编辑。本机 `status` 不读取凭据或网络。`python -m examples.causal_peer_control` 提供暂存 loopback 工作流;明确的本机资产版本可通过 `AssetManifest`、`DirectoryAssetTransport`、`build_asset_manifest`、`sync_assets` 与私有 `AC_sync_asset_manifest`/`AC_sync_assets`(MCP/Builder)操作。全部资产先暂存并通过 SHA-256/大小验证,再一次发布完整目录;受损缓存拒绝使用,脚本保持未执行。在未启用 `LongPathsEnabled` 的 Windows 上,发布路径会超过 259 字符的版本会先以 `ConfigSyncError` 拒绝,并说明所需长度。`python -m examples.sync_assets` 只使用暂存目录。七种实验性 adapter 已将显式选定的脚本、locator、热键、触发器、通讯录、JSON 设置与已保存的原生 GUI 偏好设置保存为持久化因果 profile。`SyncBindings` 将显式指定的秘密与机器值换成具名引用;`materialize_sync_profile` 发布完整且未启用的原生格式版本。私有 `AC_sync_adapter_snapshot`、`AC_sync_adapter_apply`、`AC_sync_adapter_resolve`、`AC_sync_profile_materialize` 与对应 MCP/Builder 命令提供相同流程。`python -m examples.sync_adapters` 仅使用临时文件。私有绝对路径绑定接受高熵目录名称,仍拒绝可识别的凭证格式。原生数值定义会在存储前以分类错误拒绝超出范围的值,包括超大 JSON 整数。`WorkspaceSettingsSyncAdapter` 仅读取原生 GUI INI 的主题、字号、导航显示/宽度,并发布未启用的 `workspace.ini`;显式复制为独立工作文件后,才能交给新 GUI 使用。`python -m examples.sync_workspace` 不导入 Qt。`SyncWorkspace` 已整合明确来源、持久离线捕捉、因果 HTTP、精确冲突审阅与完整重同步来源基线。私有 `AC_sync_workspace`/`ac_sync_workspace`/Builder Data 共用 status/capture/sync/review/resolve/preferences/materialize 与明确 peer 控制,全部需要 DRIVE;网络凭据使用 `options.secret_env`。`python -m examples.sync_workspace_http` 以两组临时来源与 loopback 演示冲突解决、重启及退休编辑不重放。接收数据保持未启用。引用资产传输见下方;明确的原生工作副本加载见下方,`ConfigSyncClient` 保留时间戳合并。参阅[因果/outbox 指南](../../source/Zh/doc/causal_sync/causal_sync_doc.rst)与 `python -m examples.causal_sync`。 延迟创建的 **工作区同步** 页面通过 **Actions** 提供本机状态/采集、网络同步与设备控制、精确因果查看/解决冲突,以及完整未启用发布。粘贴明确的私有工作区配置,凭据只填环境变量名称。同步不会自动应用收到的偏好设置。选择 `workspace`、查看当前版本后,再执行“应用已查看的 GUI 偏好设置”,才会更新当前窗口的主题、字号及导航面板。`SyncWorkspace.preferences(observed=change_ids)` 与现有 AC/MCP/Builder 的 `preferences` 操作,仅在已查看版本完全匹配且无冲突时返回四个标准值;缺少或删除的值采用安全默认值。Worker 保留调用者 context、重新验证 DRIVE 权限,支持取消并在关闭后丢弃旧结果。页面显示修订版、待发送/冲突/引用数与最近成功同步版本;打开页面不会启动连接。 diff --git a/docs/guides/zh-TW/usage.md b/docs/guides/zh-TW/usage.md index 7aff9fc7a..8994585bd 100644 --- a/docs/guides/zh-TW/usage.md +++ b/docs/guides/zh-TW/usage.md @@ -136,7 +136,7 @@ python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" 已擷取的自癒紀錄新增可選的 `journal_path`,搭配 run/step ID。實驗性 `inspect_heal_source(path, run_id, step_id)`、`AC_self_heal_source` 與 MCP `ac_self_heal_source` 只讀取原始步驟經清理的生命週期快照。在 **Self-Healing** 選取紀錄後,使用 **動作 → 檢視原始步驟** 開啟背景讀取器;切換目標時會等待舊讀取停止並保留請求者脈絡,關閉則取消待處理工作;Run History 讀取器也可選填步驟 ID。先篩選 run/step 再套用輸出上限,整份日誌仍會驗證,進度通知前後重查路徑根目錄,取消不回傳部分結果。舊紀錄或未經動作日誌擷取的操作沒有來源連結;查閱不會重播指令。 -實驗性因果同步提供 `CausalBucket`、`CausalConfigStore`、`SyncActor`、保留衝突的 entry 版本與持久化本機 `SyncOutbox`。獨立且經驗證的 `GET/PUT /config/{user_id}/causal` 第三版協定,在保存重送收據的同一個 CAS 交易內驗證裝置註冊、確認、退休/完整同步 epoch 與刪除回收。回收後保留永久的最小刪除憑證;舊版寫入不能覆蓋已升級帳號。私有 `AC_config_store_get`/`AC_config_store_commit` 與對應 MCP/Builder 命令可讀取及提交帶明確 `_actor` 的因果 JSON;純資料合併/peer 與私有 outbox 命令仍可使用。明確的 `CausalSyncClient` 與 `AC_config_causal_fetch`、`AC_config_causal_commit`、`AC_sync_outbox_flush`(含 MCP/Builder)已提供第三版 HTTP 投遞:結果不明時重送固定請求,只有明確的過期版本才在有界預算內重合併。`CausalReceipt` 在 outbox 原子確認原收據與最新完整快照;命令憑證使用即時的 `options.secret_env` 參照。`CausalSyncClient.control` 與私有 `AC_sync_peer_control`/`ac_sync_peer_control`/Builder Data 命令可持久化註冊、確認、回收、退休與完整重同步。`SyncControlRequest(operation_id=...)` 讓已完成 RPC 的重試保持冪等;完整重同步須明確提供 `discard_pending=True`,收到收據後才原子採用新世代並封存待送舊編輯。本機 `status` 不讀取憑證或網路。`python -m examples.causal_peer_control` 提供暫存 loopback 工作流;明確的本機資產版本可透過 `AssetManifest`、`DirectoryAssetTransport`、`build_asset_manifest`、`sync_assets` 與私有 `AC_sync_asset_manifest`/`AC_sync_assets`(MCP/Builder)操作。全部資產先暫存並通過 SHA-256/大小驗證,再一次發布完整目錄;受損快取拒絕使用,腳本保持未執行。`python -m examples.sync_assets` 只使用暫存目錄。七種實驗性 adapter 已將明確選定的腳本、locator、熱鍵、觸發器、通訊錄、JSON 設定與已保存的原生 GUI 偏好設定保存為持久化因果 profile。`SyncBindings` 將明確指定的秘密與機器值換成具名參照;`materialize_sync_profile` 發布完整且未啟用的原生格式版本。私有 `AC_sync_adapter_snapshot`、`AC_sync_adapter_apply`、`AC_sync_adapter_resolve`、`AC_sync_profile_materialize` 與對應 MCP/Builder 命令提供相同流程。`python -m examples.sync_adapters` 僅使用暫存檔。私有絕對路徑綁定接受高熵目錄名稱,仍拒絕可辨識的憑證格式。原生數值定義會在儲存前以分類錯誤拒絕超出範圍的值,包含超大 JSON 整數。`WorkspaceSettingsSyncAdapter` 僅讀取原生 GUI INI 的主題、字級、導覽顯示/寬度,並發布未啟用的 `workspace.ini`;明確複製為獨立工作檔後,才能交給新 GUI 使用。`python -m examples.sync_workspace` 不匯入 Qt。`SyncWorkspace` 已整合明確來源、持久離線捕捉、因果 HTTP、精確衝突檢視與完整重同步來源基準。私有 `AC_sync_workspace`/`ac_sync_workspace`/Builder Data 共用 status/capture/sync/review/resolve/preferences/materialize 與明確 peer 控制,全部需要 DRIVE;網路憑證使用 `options.secret_env`。`python -m examples.sync_workspace_http` 以兩組暫存來源與 loopback 示範衝突解決、重啟及退休編輯不重播。接收資料保持未啟用。引用資產傳輸見下方;明確的原生工作副本載入見下方,`ConfigSyncClient` 保留時間戳合併。參閱[因果/outbox 指南](../../source/Zh/doc/causal_sync/causal_sync_doc.rst)與 `python -m examples.causal_sync`。 +實驗性因果同步提供 `CausalBucket`、`CausalConfigStore`、`SyncActor`、保留衝突的 entry 版本與持久化本機 `SyncOutbox`。獨立且經驗證的 `GET/PUT /config/{user_id}/causal` 第三版協定,在保存重送收據的同一個 CAS 交易內驗證裝置註冊、確認、退休/完整同步 epoch 與刪除回收。回收後保留永久的最小刪除憑證;舊版寫入不能覆蓋已升級帳號。私有 `AC_config_store_get`/`AC_config_store_commit` 與對應 MCP/Builder 命令可讀取及提交帶明確 `_actor` 的因果 JSON;純資料合併/peer 與私有 outbox 命令仍可使用。明確的 `CausalSyncClient` 與 `AC_config_causal_fetch`、`AC_config_causal_commit`、`AC_sync_outbox_flush`(含 MCP/Builder)已提供第三版 HTTP 投遞:結果不明時重送固定請求,只有明確的過期版本才在有界預算內重合併。`CausalReceipt` 在 outbox 原子確認原收據與最新完整快照;命令憑證使用即時的 `options.secret_env` 參照。`CausalSyncClient.control` 與私有 `AC_sync_peer_control`/`ac_sync_peer_control`/Builder Data 命令可持久化註冊、確認、回收、退休與完整重同步。`SyncControlRequest(operation_id=...)` 讓已完成 RPC 的重試保持冪等;完整重同步須明確提供 `discard_pending=True`,收到收據後才原子採用新世代並封存待送舊編輯。本機 `status` 不讀取憑證或網路。`python -m examples.causal_peer_control` 提供暫存 loopback 工作流;明確的本機資產版本可透過 `AssetManifest`、`DirectoryAssetTransport`、`build_asset_manifest`、`sync_assets` 與私有 `AC_sync_asset_manifest`/`AC_sync_assets`(MCP/Builder)操作。全部資產先暫存並通過 SHA-256/大小驗證,再一次發布完整目錄;受損快取拒絕使用,腳本保持未執行。在未啟用 `LongPathsEnabled` 的 Windows 上,發布路徑會超過 259 字元的版本會先以 `ConfigSyncError` 拒絕,並說明所需長度。`python -m examples.sync_assets` 只使用暫存目錄。七種實驗性 adapter 已將明確選定的腳本、locator、熱鍵、觸發器、通訊錄、JSON 設定與已保存的原生 GUI 偏好設定保存為持久化因果 profile。`SyncBindings` 將明確指定的秘密與機器值換成具名參照;`materialize_sync_profile` 發布完整且未啟用的原生格式版本。私有 `AC_sync_adapter_snapshot`、`AC_sync_adapter_apply`、`AC_sync_adapter_resolve`、`AC_sync_profile_materialize` 與對應 MCP/Builder 命令提供相同流程。`python -m examples.sync_adapters` 僅使用暫存檔。私有絕對路徑綁定接受高熵目錄名稱,仍拒絕可辨識的憑證格式。原生數值定義會在儲存前以分類錯誤拒絕超出範圍的值,包含超大 JSON 整數。`WorkspaceSettingsSyncAdapter` 僅讀取原生 GUI INI 的主題、字級、導覽顯示/寬度,並發布未啟用的 `workspace.ini`;明確複製為獨立工作檔後,才能交給新 GUI 使用。`python -m examples.sync_workspace` 不匯入 Qt。`SyncWorkspace` 已整合明確來源、持久離線捕捉、因果 HTTP、精確衝突檢視與完整重同步來源基準。私有 `AC_sync_workspace`/`ac_sync_workspace`/Builder Data 共用 status/capture/sync/review/resolve/preferences/materialize 與明確 peer 控制,全部需要 DRIVE;網路憑證使用 `options.secret_env`。`python -m examples.sync_workspace_http` 以兩組暫存來源與 loopback 示範衝突解決、重啟及退休編輯不重播。接收資料保持未啟用。引用資產傳輸見下方;明確的原生工作副本載入見下方,`ConfigSyncClient` 保留時間戳合併。參閱[因果/outbox 指南](../../source/Zh/doc/causal_sync/causal_sync_doc.rst)與 `python -m examples.causal_sync`。 延遲建立的 **工作區同步** 分頁透過 **Actions** 提供本機狀態/擷取、網路同步與裝置控制、精確因果檢視/解決衝突,以及完整未啟用發布。貼上明確的私人工作區設定,憑證只填環境變數名稱。同步不會自動套用收到的偏好設定。選取 `workspace`、檢視目前版本後,再執行「套用已檢視的 GUI 偏好設定」,才會更新目前視窗的主題、字級及導覽面板。`SyncWorkspace.preferences(observed=change_ids)` 與既有 AC/MCP/Builder 的 `preferences` 操作,僅在已檢視版本完全相符且無衝突時回傳四個標準值;缺少或刪除的值採安全預設。Worker 保留呼叫者 context、重驗 DRIVE 權限,支援取消並在關閉後捨棄舊結果。畫面顯示修訂版、待送/衝突/參照數與最近成功同步版本;開啟分頁不會啟動連線。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index de15c6bdc..fe96f44f7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -197,3 +197,10 @@ - **For whoever brings a macOS probe back:** `pyobjc-framework-Quartz==12.2.2` (the version `pyobjc==12.2.2` in `pyproject.toml` resolves to) declares `CGPreflightListenEventAccess`, `CGPreflightPostEventAccess` and `CGPreflightScreenCaptureAccess`, each with signature `B` (no arguments, returns bool), together with the matching `CGRequest…Access`, in `Quartz/CoreGraphics/_metadata.py`. Read from the downloaded wheel, not run; the functions exist only on macOS 10.15 and later. - **Not covered here:** Windows session and integrity checks elsewhere (`session_guard`, `input_reach`, `agent_runtime/presence_*_windows.py`) stay under the deferred native acceptance items in `Progress.md`. - **Open items:** none. + +## U-20261112-11 · 2026-11-12 · Refuse asset paths Windows cannot create before staging · #done #config-sync #windows + +- **What:** Closes the `TODO` added to `Progress.md` › 雜項 earlier today (commit `7158d9a5`). On Windows with `LongPathsEnabled=0` (this machine), `test_sync_workspace_surfaces.py`'s 64 + 64-character record name staged a 265-character path under `cache/.incoming-*` and failed with `FileNotFoundError`, reported only as "asset transfer could not publish a complete generation". `utils/config_sync/assets.py` now checks first: `_path_limit()` reads `HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled` (259 when it is not 1 or cannot be read; no limit off Windows), and `_require_paths_fit` measures every published path (`generation-/files/`, longer than the staging one) and raises `ConfigSyncError` naming the length, the limit and both remedies before the cache root is created. Of the two options the item named, this is the explicit refusal; `\?\` paths were not adopted, because every reader of the returned paths would have to use them too. +- **Test:** `test_sync_assets.py` +2 (refused before anything is created under a patched limit; no limit means no check). The long case of `test_workspace_command_mcp_builder_capture_review_and_materialize` now skips with the measured lengths on a host that cannot hold its path, instead of failing; CI's shorter temp root still runs it. Sync asset / workspace suites: 55 passed, 7 skipped. +- **Files:** `utils/config_sync/assets.py`, the two tests, the three `docs/guides/*/usage.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 052ec4050..a4fdd7e48 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-11 | 2026-11-12 | Refuse asset paths Windows cannot create before staging | #done #config-sync #windows | [2026-11-b](2026-11-b.md) | | U-20261112-10 | 2026-11-12 | The capability-probe Progress item described deleted code | #snapshot #capabilities #macos | [2026-11-b](2026-11-b.md) | | U-20261112-09 | 2026-11-12 | The result hook follows AC_parallel branches | #done #executor #gui | [2026-11-b](2026-11-b.md) | | U-20261112-08 | 2026-11-12 | Strict tier for the two new MCP modules; Windows Qt stub nulls | #incident #typing #ci | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/config_sync/assets.py b/je_auto_control/utils/config_sync/assets.py index 135b52ba6..46fa8b267 100644 --- a/je_auto_control/utils/config_sync/assets.py +++ b/je_auto_control/utils/config_sync/assets.py @@ -8,6 +8,7 @@ from itertools import islice import os from pathlib import Path +import sys from tempfile import TemporaryDirectory from typing import BinaryIO, Callable, ContextManager, Iterable, Iterator, Optional, Protocol @@ -20,6 +21,8 @@ _CHUNK_BYTES = 64 * 1024 _MANIFEST = 'manifest.json' +#: MAX_PATH (260) less the terminating NUL: what Windows creates without long-path support. +_WINDOWS_MAX_PATH = 259 _Cancelled = Optional[Callable[[], bool]] @@ -103,6 +106,7 @@ def _sync_assets(manifest: AssetManifest, transport: AssetTransport, *, raise ConfigSyncError('asset transfer requires a validated manifest') root = Path(transport.target_root).resolve() destination = root / ('generation-' + manifest.digest) + _require_paths_fit(destination, manifest) try: if destination.exists() or destination.is_symlink(): return _verified_result(destination, manifest, True, cancelled) @@ -131,6 +135,37 @@ def _sync_assets(manifest: AssetManifest, transport: AssetTransport, *, raise ConfigSyncError('asset transfer could not publish a complete generation') from error +def _path_limit() -> Optional[int]: + """The longest path this host can create, or ``None`` when it has no such limit.""" + if sys.platform != 'win32': + return None + try: + import winreg + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\FileSystem') as key: + enabled, _kind = winreg.QueryValueEx(key, 'LongPathsEnabled') + except OSError: + return _WINDOWS_MAX_PATH + return None if enabled == 1 else _WINDOWS_MAX_PATH + + +def _require_paths_fit(destination: Path, manifest: AssetManifest) -> None: + """Refuse up front a generation whose files the host could not create. + + Without this, Windows without long-path support failed the first file past + MAX_PATH with ``FileNotFoundError``, reported only as an incomplete generation. + The published paths are the longest: ``generation-`` is longer than + the ``.incoming-*`` staging directory. + """ + limit = _path_limit() + if limit is None or not manifest.files: + return + longest = max(len(str(destination / 'files' / asset.path)) for asset in manifest.files) + if longest > limit: + raise ConfigSyncError( + f'asset cache paths would reach {longest} characters, over the {limit} this Windows host ' + 'allows; move the sync cache to a shorter directory or enable LongPathsEnabled') + + @contextmanager def _staging_directory(root: Path, manifest: AssetManifest, staging: _AssetStaging | None) -> Iterator[Path]: if staging is None: diff --git a/test/unit_test/headless/test_sync_assets.py b/test/unit_test/headless/test_sync_assets.py index 471a50ba2..bf2bbc0d0 100644 --- a/test/unit_test/headless/test_sync_assets.py +++ b/test/unit_test/headless/test_sync_assets.py @@ -153,3 +153,22 @@ def open(self, _asset): with pytest.raises(CancelledError): ac.sync_assets(manifest, interrupted) assert not list(InterruptedTransport.target_root.glob('generation-*')) + + +def test_paths_the_host_cannot_create_are_refused_before_anything_is_staged(tmp_path, monkeypatch): + # Windows without LongPathsEnabled stops at 259 characters; the first file past it + # used to fail as a bare FileNotFoundError reported as an incomplete generation. + from je_auto_control.utils.config_sync import assets + _source, manifest, transport = asset_bundle(tmp_path) + monkeypatch.setattr(assets, '_path_limit', lambda: len(str(tmp_path)) + 20) + with pytest.raises(ac.ConfigSyncError, match='LongPathsEnabled') as refused: + ac.sync_assets(manifest, transport) + assert 'characters' in str(refused.value) + assert not (tmp_path / 'received').exists(), 'refused before the cache root was even created' + + +def test_a_host_without_a_path_limit_is_not_checked(tmp_path, monkeypatch): + from je_auto_control.utils.config_sync import assets + _source, manifest, transport = asset_bundle(tmp_path) + monkeypatch.setattr(assets, '_path_limit', lambda: None) + assert ac.sync_assets(manifest, transport).file_count == len(manifest.files) diff --git a/test/unit_test/headless/test_sync_workspace_surfaces.py b/test/unit_test/headless/test_sync_workspace_surfaces.py index d2004fc44..7c14b0a86 100644 --- a/test/unit_test/headless/test_sync_workspace_surfaces.py +++ b/test/unit_test/headless/test_sync_workspace_surfaces.py @@ -26,6 +26,11 @@ def tool(): @pytest.mark.parametrize('entry_id', ['login.json', 'flows/login.json', 'x' * 64 + '/' + 'y' * 64 + '.json']) def test_workspace_command_mcp_builder_capture_review_and_materialize(tmp_path, monkeypatch, entry_id): from je_auto_control.gui.script_builder.step_model import action_to_step, step_to_action + from je_auto_control.utils.config_sync import assets + limit = assets._path_limit() + published = tmp_path / 'cache' / ('generation-' + '0' * 64) / 'files' / 'scripts' / entry_id + if limit is not None and len(str(published)) > limit: + pytest.skip(f'this host creates paths up to {limit} characters; the cache would need {len(str(published))}') monkeypatch.setenv('AUTOCONTROL_ALLOWED_PATH_ROOTS', str(tmp_path)) config = configuration(tmp_path, entry_id) arguments = {'configuration': config, 'operation': 'capture'} From f406b80636c8c8ef6059beb4141064971084b6c4 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 15:38:37 +0800 Subject: [PATCH 055/161] Move the finished on_enter note out of Progress; CHANGELOG records it --- Progress.md | 1 - docs/updates/2026-11-b.md | 5 +++++ docs/updates/README.md | 1 + 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Progress.md b/Progress.md index 0c6983af8..2cf825757 100644 --- a/Progress.md +++ b/Progress.md @@ -171,7 +171,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` - **free-threaded**:呼叫者身分、綁定的裝置、自愈的執行標記與 stop token 都改成只在設定它的執行緒上有效(`utils/thread_bound.py`)。 這台機器沒有 free-threaded 直譯器:驗證用的是模擬繼承與真的 `-X thread_inherit_context=1`(3.14.7,GIL 開著);`free-threaded-scope` job(3.14t)是第一次真的跑。 - **Windows 的版面鍵名**(`slash` 等 8 個)只在美式配置上實際呼叫過。 -- **狀態機 `on_enter` 的單一動作寫法**以前一直被拒絕、從沒執行過(已修,U-20261009-24):依賴「它不會跑」的既有狀態機現在會跑它。 --- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index fe96f44f7..733c8b183 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -204,3 +204,8 @@ - **Test:** `test_sync_assets.py` +2 (refused before anything is created under a patched limit; no limit means no check). The long case of `test_workspace_command_mcp_builder_capture_review_and_materialize` now skips with the measured lengths on a host that cannot hold its path, instead of failing; CI's shorter temp root still runs it. Sync asset / workspace suites: 55 passed, 7 skipped. - **Files:** `utils/config_sync/assets.py`, the two tests, the three `docs/guides/*/usage.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** none. + +## U-20261113-01 · 2026-11-13 · Move the finished on_enter note out of Progress · #docs #executor + +- **What:** `Progress.md` › 雜項 still carried "a state machine's single-action `on_enter` was always rejected and never ran (fixed, U-20261009-24); a machine that relied on it not running now runs it". That is a finished fix with a compatibility effect, not open work, and `CHANGELOG.md` already records it under 1.0.0 (variable-scope entry) and 1.1.0. The bullet is removed; no code changed. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index a4fdd7e48..d49859fc0 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261113-01 | 2026-11-13 | Move the finished on_enter note out of Progress | #docs #executor | [2026-11-b](2026-11-b.md) | | U-20261112-11 | 2026-11-12 | Refuse asset paths Windows cannot create before staging | #done #config-sync #windows | [2026-11-b](2026-11-b.md) | | U-20261112-10 | 2026-11-12 | The capability-probe Progress item described deleted code | #snapshot #capabilities #macos | [2026-11-b](2026-11-b.md) | | U-20261112-09 | 2026-11-12 | The result hook follows AC_parallel branches | #done #executor #gui | [2026-11-b](2026-11-b.md) | From d1bee2e90dea0274aa9202e5f3794304b7f67f09 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 15:38:57 +0800 Subject: [PATCH 056/161] Number the on_enter note entry for the day it was written --- docs/updates/2026-11-b.md | 2 +- docs/updates/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 733c8b183..662b40d5d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -205,7 +205,7 @@ - **Files:** `utils/config_sync/assets.py`, the two tests, the three `docs/guides/*/usage.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** none. -## U-20261113-01 · 2026-11-13 · Move the finished on_enter note out of Progress · #docs #executor +## U-20261112-12 · 2026-11-12 · Move the finished on_enter note out of Progress · #docs #executor - **What:** `Progress.md` › 雜項 still carried "a state machine's single-action `on_enter` was always rejected and never ran (fixed, U-20261009-24); a machine that relied on it not running now runs it". That is a finished fix with a compatibility effect, not open work, and `CHANGELOG.md` already records it under 1.0.0 (variable-scope entry) and 1.1.0. The bullet is removed; no code changed. - **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index d49859fc0..077d11f90 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,7 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| -| U-20261113-01 | 2026-11-13 | Move the finished on_enter note out of Progress | #docs #executor | [2026-11-b](2026-11-b.md) | +| U-20261112-12 | 2026-11-12 | Move the finished on_enter note out of Progress | #docs #executor | [2026-11-b](2026-11-b.md) | | U-20261112-11 | 2026-11-12 | Refuse asset paths Windows cannot create before staging | #done #config-sync #windows | [2026-11-b](2026-11-b.md) | | U-20261112-10 | 2026-11-12 | The capability-probe Progress item described deleted code | #snapshot #capabilities #macos | [2026-11-b](2026-11-b.md) | | U-20261112-09 | 2026-11-12 | The result hook follows AC_parallel branches | #done #executor #gui | [2026-11-b](2026-11-b.md) | From 0c4fb3b7dfcb4dcbb0e7abe00f376faf44df19e1 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 17:28:35 +0800 Subject: [PATCH 057/161] Record bringing the shared venv to the pinned pillow and PySide6 --- Progress.md | 2 -- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Progress.md b/Progress.md index 2cf825757..cfa83d17e 100644 --- a/Progress.md +++ b/Progress.md @@ -166,8 +166,6 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` `TODO` — 小項目,各自獨立 -- **本機共用 `.venv` 落後 `pyproject.toml` 一個釘選**(U-20261112-01 之後):pillow 12.3.0(要求 `==13.0.0`)、 - PySide6 6.11.2(`[gui]` 要求 6.12.0)。共用環境的升級需要使用者同意,沒有動;不影響 CI。 - **free-threaded**:呼叫者身分、綁定的裝置、自愈的執行標記與 stop token 都改成只在設定它的執行緒上有效(`utils/thread_bound.py`)。 這台機器沒有 free-threaded 直譯器:驗證用的是模擬繼承與真的 `-X thread_inherit_context=1`(3.14.7,GIL 開著);`free-threaded-scope` job(3.14t)是第一次真的跑。 - **Windows 的版面鍵名**(`slash` 等 8 個)只在美式配置上實際呼叫過。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 662b40d5d..bb9d58819 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -209,3 +209,10 @@ - **What:** `Progress.md` › 雜項 still carried "a state machine's single-action `on_enter` was always rejected and never ran (fixed, U-20261009-24); a machine that relied on it not running now runs it". That is a finished fix with a compatibility effect, not open work, and `CHANGELOG.md` already records it under 1.0.0 (variable-scope entry) and 1.1.0. The bullet is removed; no code changed. - **Open items:** none. + +## U-20261112-13 · 2026-11-12 · Bring the shared .venv to the pinned pillow and PySide6 · #done #tooling + +- **What:** Closes the `Progress.md` › 雜項 line left by U-20261112-01; the maintainer approved the upgrade on 2026-11-12. Compared first with `pip install --dry-run`: pillow 12.3.0 → 13.0.0 (`pyproject.toml` pins `==13.0.0`), PySide6 / PySide6_Addons / PySide6_Essentials / shiboken6 6.11.2 → 6.12.0 (the `[gui]` pin), plus two packages PySide6 6.12 now requires, `PySide6_Pdf` and `PySide6_WebEngine` 6.12.0.140. Nothing else changed; `pip check` reports no conflict for these packages. +- **Evidence:** GUI, imaging, theme, navigation, remote-desktop and WebRTC test files on the upgraded env: 3,099 passed, 15 skipped, 1 failed (`test_a11y_window_audit.py::test_restoring_duplicate_titles_moves_each_window_once`, the order-dependent `KeyError` that fails the same way on the pre-session tree, U-20261112-07). +- **Note:** CI still installs `PySide6==6.11.2` for the `pytest-headless` and `typing-extras` jobs, so the shared env is now newer than CI there; the typing-extras exempt list was measured against 6.11.2. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 077d11f90..3e95607b4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-13 | 2026-11-12 | Bring the shared .venv to the pinned pillow and PySide6 | #done #tooling | [2026-11-b](2026-11-b.md) | | U-20261112-12 | 2026-11-12 | Move the finished on_enter note out of Progress | #docs #executor | [2026-11-b](2026-11-b.md) | | U-20261112-11 | 2026-11-12 | Refuse asset paths Windows cannot create before staging | #done #config-sync #windows | [2026-11-b](2026-11-b.md) | | U-20261112-10 | 2026-11-12 | The capability-probe Progress item described deleted code | #snapshot #capabilities #macos | [2026-11-b](2026-11-b.md) | From 65116dbc486867e585f69897921a7e22052d8ce9 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Thu, 12 Nov 2026 17:33:45 +0800 Subject: [PATCH 058/161] Require an explicit allowance before reading the iOS pasteboard facebook-wda reads it by bringing WebDriverAgent to the front through Siri and relaunching the app afterwards, which a script should not trigger by accident. --- CHANGELOG.md | 7 ++++ Progress.md | 2 - architecture_explore.md | 8 ++-- docs/source/Eng/doc/mobile/mobile_doc.rst | 6 ++- docs/source/Zh/doc/mobile/mobile_doc.rst | 5 ++- docs/updates/2026-11-b.md | 7 ++++ docs/updates/README.md | 1 + je_auto_control/android/apps.py | 5 ++- je_auto_control/ios/apps.py | 16 ++++++-- je_auto_control/wrapper/mobile_commands.py | 11 +++-- je_auto_control/wrapper/mobile_extensions.py | 8 +++- .../headless/test_mobile_app_lifecycle.py | 41 +++++++++++++++++++ 12 files changed, 96 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5f595dec..78fb51b5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- Reading the iOS pasteboard (`WdaExtension.get_clipboard`, `AC_ios_get_clipboard`, + `ac_ios_get_clipboard`) now needs `allow_app_switch=True`: facebook-wda brings WebDriverAgent + to the front through Siri for about 3 s and relaunches the app that was in front. Without it + the call raises `DeviceUnsupportedError` and sends nothing. Android accepts and ignores the + flag; an adapter registered through `register_mobile_extension` is called without it unless + it is set. + - `sync_assets` (and `AC_sync_assets`, `materialize` of `AC_sync_workspace`) refuses up front, with a `ConfigSyncError` naming the length, a generation whose published paths would pass 259 characters on Windows without `LongPathsEnabled`; it used to fail on the first such file diff --git a/Progress.md b/Progress.md index cfa83d17e..8b8709e10 100644 --- a/Progress.md +++ b/Progress.md @@ -89,8 +89,6 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD - Android:`input draganddrop` 是否存在、`monkey` 啟動輸出、`pidof`/`pm path` 的結束碼、`dumpsys activity activities` 的格式、`pkill -INT screenrecord` 能否收尾 MP4。 ADBKeyBoard 的送達無法由裝置確認,是從 IME 被選取推定的。 - 已知限制:iOS 捏合忽略 `x`/`y`/`span`;iOS 滑動忽略 `duration_s`(WDA 的 drag duration 是按住時間,不能設移動時間);iOS `app_state` 不會回 `not_installed`;iOS 的安裝/檔案/錄影沒有 adapter(只有 `MobileExtension` 協定與註冊點); - `DECIDE`:iOS 讀剪貼簿(`AC_ios_get_clipboard`、`WdaExtension.get_clipboard`)在 facebook-wda 1.5.4 會請 Siri 把 WDA 帶到前景約 3 秒、 - 再重新啟動原本在前景的 App——已寫進文件與能力說明,但是否該改成要明確啟用才讀,請維護者決定。 Mobile 分頁的 probe/run 已由 TabTask 在背景執行;真實 SDK 的逾時、取消與裝置回應仍待實機驗收。`AC_android_shell` 刻意不做成 MCP 工具,**請維護者確認**。 - 沒有 `examples/` 的實機腳本以外的 smoke;Xcode/WDA 的建置與簽章只寫成前置條件。 diff --git a/architecture_explore.md b/architecture_explore.md index d644b5f94..37c89ccae 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,592 | +| 程式碼總行數 | 233,610 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1540,7 +1540,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,324 | -| `wrapper/` | 25 | 5,996 | +| `wrapper/` | 25 | 6,005 | | `windows/` | 24 | 2,270 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | @@ -1553,8 +1553,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,104 | -| **總計** | **1,515** | **232,847** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,113 | +| **總計** | **1,515** | **232,865** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/mobile/mobile_doc.rst b/docs/source/Eng/doc/mobile/mobile_doc.rst index b6e2f29c8..3188abf1f 100644 --- a/docs/source/Eng/doc/mobile/mobile_doc.rst +++ b/docs/source/Eng/doc/mobile/mobile_doc.rst @@ -330,8 +330,10 @@ reason:: - Set; reading is allowed by WDA only while WDA itself is in front. ``facebook-wda`` 1.5.4's ``get_clipboard`` asks Siri to open WebDriverAgentRunner, waits 3 s, reads, and relaunches the app that was - in front, so the app under test leaves the foreground meanwhile. A - build without ``get_clipboard`` raises ``DeviceUnsupportedError``. + in front, so the app under test leaves the foreground meanwhile. The + read therefore needs ``allow_app_switch=True`` (``get_clipboard`` and + ``AC_ios_get_clipboard``); without it, or on a build without + ``get_clipboard``, it raises ``DeviceUnsupportedError`` and sends nothing. * - ``recording`` - ``adb shell screenrecord`` (180 s at most), stopped with ``SIGINT`` so the file is finalised, then pulled and removed from the device. A diff --git a/docs/source/Zh/doc/mobile/mobile_doc.rst b/docs/source/Zh/doc/mobile/mobile_doc.rst index 81bbe9908..28da139d5 100644 --- a/docs/source/Zh/doc/mobile/mobile_doc.rst +++ b/docs/source/Zh/doc/mobile/mobile_doc.rst @@ -305,8 +305,9 @@ Device matrix 的裝置規格可以寫 ``app_id``\ :第一個步驟之前會 Android 上 ``adb`` 碰不到剪貼簿。 - 可寫入;WDA 只在 WDA 自己位於前景時才允許讀取。\ ``facebook-wda`` 1.5.4 的 ``get_clipboard`` 會請 Siri 開啟 WebDriverAgentRunner、等 3 秒、讀取, - 再重新啟動原本在前景的 App,期間受測 App 離開前景。沒有 ``get_clipboard`` - 的版本丟 ``DeviceUnsupportedError``\ 。 + 再重新啟動原本在前景的 App,期間受測 App 離開前景。因此讀取需要 + ``allow_app_switch=True``\ (\ ``get_clipboard`` 與 ``AC_ios_get_clipboard``\ ); + 沒有給、或版本沒有 ``get_clipboard`` 時丟 ``DeviceUnsupportedError``\ ,不送任何東西。 * - ``recording`` - ``adb shell screenrecord``\ (最長 180 秒),以 ``SIGINT`` 停止好讓檔案 收尾,再拉回主機並從裝置刪除。錄影是裝置端的狀態:關閉 session 不會 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index bb9d58819..96af8f51e 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -216,3 +216,10 @@ - **Evidence:** GUI, imaging, theme, navigation, remote-desktop and WebRTC test files on the upgraded env: 3,099 passed, 15 skipped, 1 failed (`test_a11y_window_audit.py::test_restoring_duplicate_titles_moves_each_window_once`, the order-dependent `KeyError` that fails the same way on the pre-session tree, U-20261112-07). - **Note:** CI still installs `PySide6==6.11.2` for the `pytest-headless` and `typing-extras` jobs, so the shared env is now newer than CI there; the typing-extras exempt list was measured against 6.11.2. - **Open items:** none. + +## U-20261112-14 · 2026-11-12 · Reading the iOS pasteboard needs an explicit allowance · #done #mobile #ios + +- **What:** Resolves the `DECIDE` added in U-20261112-04; the maintainer chose on 2026-11-12 to require an opt-in. facebook-wda 1.5.4's `get_clipboard` asks Siri to open WebDriverAgentRunner, waits 3 s, reads and relaunches the app that was in front. `WdaExtension.get_clipboard(*, allow_app_switch=False)` now raises `DeviceUnsupportedError` (reason: the app switch; alternative: `allow_app_switch=True` or reading the screen) and sends nothing unless the flag is set; the iOS clipboard capability text says so. The `get_clipboard` mobile operation gained a `bool` parameter `allow_app_switch` (default `False`), so `AC_ios_get_clipboard` / `AC_android_get_clipboard`, the generated MCP tools and the Script Builder all offer it. `MobileExtension.get_clipboard` and `AndroidExtension.get_clipboard` accept and ignore it; the command passes it only when set, so an adapter registered before the flag existed is still called without a keyword. Setting the pasteboard is unchanged. +- **Tests:** `test_mobile_app_lifecycle.py` +2 (refused with nothing sent, then read with the allowance; both commands declare the flag and an old adapter is called without it). Mobile, iOS, Android, RBAC catalogue, Builder schema and MCP surface files: 632 passed. Typing on win32 / linux / darwin and strict Sphinx clean. +- **Files:** `ios/apps.py`, `android/apps.py`, `wrapper/mobile_extensions.py`, `wrapper/mobile_commands.py`, `test_mobile_app_lifecycle.py`, both `mobile_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** not run against a real device (`Progress.md` › 行動裝置). diff --git a/docs/updates/README.md b/docs/updates/README.md index 3e95607b4..9167c8fdb 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261112-14 | 2026-11-12 | Reading the iOS pasteboard needs an explicit allowance | #done #mobile #ios | [2026-11-b](2026-11-b.md) | | U-20261112-13 | 2026-11-12 | Bring the shared .venv to the pinned pillow and PySide6 | #done #tooling | [2026-11-b](2026-11-b.md) | | U-20261112-12 | 2026-11-12 | Move the finished on_enter note out of Progress | #docs #executor | [2026-11-b](2026-11-b.md) | | U-20261112-11 | 2026-11-12 | Refuse asset paths Windows cannot create before staging | #done #config-sync #windows | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/android/apps.py b/je_auto_control/android/apps.py index 8477bfbf4..864eb7659 100644 --- a/je_auto_control/android/apps.py +++ b/je_auto_control/android/apps.py @@ -178,8 +178,9 @@ def _clipboard_device(self) -> UIAutomatorDevice: alternative="type the text with type_text instead of pasting it") return ui_device - def get_clipboard(self) -> str: - """The device clipboard's text.""" + def get_clipboard(self, *, allow_app_switch: bool = False) -> str: + """The device clipboard's text; uiautomator2 reads it without switching apps.""" + del allow_app_switch # nothing to allow on Android return _read_clipboard(self._clipboard_device()) def set_clipboard(self, text: str) -> None: diff --git a/je_auto_control/ios/apps.py b/je_auto_control/ios/apps.py index a48c120de..abb96788f 100644 --- a/je_auto_control/ios/apps.py +++ b/je_auto_control/ios/apps.py @@ -20,6 +20,8 @@ NEEDS_ADAPTER = ("WebDriverAgent has no API for this; it needs a host-side adapter " "(for example tidevice, pymobiledevice3 or Appium) registered with " "register_mobile_extension('ios', ...)") +_PASTEBOARD_SWITCH = ("reading the pasteboard brings WebDriverAgent to the front through Siri " + "for about 3 s and then relaunches the app that was in front") _NO_PASTEBOARD_READ = ("this facebook-wda build cannot read the pasteboard " "(WebDriverAgent only allows it while WDA itself is in front)") @@ -85,8 +87,8 @@ def capability(self, feature: str) -> DeviceCapability: if feature == "clipboard": return DeviceCapability( feature, STATE_AVAILABLE, - "set; reading brings WebDriverAgent to the front through Siri for about " - "3 s and then relaunches the app that was in front") + "set; reading needs allow_app_switch=True, because it brings WebDriverAgent " + "to the front through Siri for about 3 s and then relaunches the app that was in front") if feature in ("install", "files", "recording"): return DeviceCapability(feature, STATE_NEEDS_DEPENDENCY, NEEDS_ADAPTER) return DeviceCapability(feature, STATE_UNSUPPORTED, f"unknown feature {feature!r}") @@ -121,14 +123,20 @@ def set_clipboard(self, text: str) -> None: """Put ``text`` on the device pasteboard.""" _set_pasteboard(self._device_source(), text) - def get_clipboard(self) -> str: - """The pasteboard's text, where this facebook-wda build can read it. + def get_clipboard(self, *, allow_app_switch: bool = False) -> str: + """The pasteboard's text, only when the caller accepts the app switch it costs. WebDriverAgent reads the pasteboard only while it is in front, so facebook-wda 1.5.4's ``get_clipboard`` asks Siri to open WebDriverAgentRunner, waits 3 s, reads, and relaunches the app that was in front: the app under test leaves the foreground meanwhile. + Without ``allow_app_switch=True`` nothing is sent to the device and + :class:`DeviceUnsupportedError` says why. """ + if not allow_app_switch: + raise DeviceUnsupportedError( + "reading the iOS pasteboard switches apps; it was not allowed", reason=_PASTEBOARD_SWITCH, + alternative="pass allow_app_switch=True, or read the text from the screen (find_text)") return _get_pasteboard(self._device_source()) diff --git a/je_auto_control/wrapper/mobile_commands.py b/je_auto_control/wrapper/mobile_commands.py index cffcfdeed..d4ac33efe 100644 --- a/je_auto_control/wrapper/mobile_commands.py +++ b/je_auto_control/wrapper/mobile_commands.py @@ -275,8 +275,10 @@ def _pull_file(session: DeviceSession, remote_path: str, local_path: str) -> str return extensions.mobile_extension(session).pull_file(remote_path, local_path) -def _get_clipboard(session: DeviceSession) -> str: - return extensions.mobile_extension(session).get_clipboard() +def _get_clipboard(session: DeviceSession, allow_app_switch: bool = False) -> str: + extension = extensions.mobile_extension(session) + # Only when asked: an adapter registered before the flag existed takes no keyword. + return extension.get_clipboard(allow_app_switch=True) if allow_app_switch else extension.get_clipboard() def _set_clipboard(session: DeviceSession, text: str) -> None: @@ -382,7 +384,10 @@ class _Operation: (Param("remote_path", required=True), Param("local_path", "file_path", True)), "files", "mobile_extension"), _Operation("get_clipboard", "Get Clipboard", "Read the device clipboard's text.", - _get_clipboard, capability="clipboard", api="mobile_extension", read_only=True), + _get_clipboard, (Param("allow_app_switch", "bool", default=False, + description="iOS: let WebDriverAgent come to the front through Siri " + "for about 3 s to read the pasteboard"),), + capability="clipboard", api="mobile_extension", read_only=True), _Operation("set_clipboard", "Set Clipboard", "Put text on the device clipboard.", _set_clipboard, (Param("text", required=True),), "clipboard", "mobile_extension"), diff --git a/je_auto_control/wrapper/mobile_extensions.py b/je_auto_control/wrapper/mobile_extensions.py index 937a9d3bb..13d2c7c19 100644 --- a/je_auto_control/wrapper/mobile_extensions.py +++ b/je_auto_control/wrapper/mobile_extensions.py @@ -56,8 +56,12 @@ def push_file(self, local_path: str, remote_path: str) -> str: def pull_file(self, remote_path: str, local_path: str) -> str: """Copy a device file to the host.""" - def get_clipboard(self) -> str: - """The device clipboard's text.""" + def get_clipboard(self, *, allow_app_switch: bool = False) -> str: + """The device clipboard's text. + + ``allow_app_switch`` lets a backend that must bring another app to the + front to read it (iOS through WebDriverAgent) do so; others ignore it. + """ def set_clipboard(self, text: str) -> None: """Put ``text`` on the device clipboard.""" diff --git a/test/unit_test/headless/test_mobile_app_lifecycle.py b/test/unit_test/headless/test_mobile_app_lifecycle.py index aa913c612..1b5d21fcb 100644 --- a/test/unit_test/headless/test_mobile_app_lifecycle.py +++ b/test/unit_test/headless/test_mobile_app_lifecycle.py @@ -273,3 +273,44 @@ def test_registered_adapter_fills_what_wda_lacks(): assert extension.capability("files").state == "needs_dependency" with pytest.raises(DeviceError): register_mobile_extension("windows", None) + + +class _ReadableWda(FakeWda): + """facebook-wda 1.5.4 has get_clipboard: it switches to WebDriverAgent through Siri to read.""" + + def get_clipboard(self) -> str: + self.calls.append({"op": "get_clipboard"}) + return "pasted 文字" + + +def test_ios_pasteboard_read_needs_an_explicit_allowance(): + wda = _ReadableWda() + extension = mobile_extension(_ios(wda)) + with pytest.raises(DeviceUnsupportedError) as refused: + extension.get_clipboard() + assert "Siri" in refused.value.reason + assert "allow_app_switch=True" in refused.value.alternative + assert wda.calls == [], "nothing was sent to the device" + assert extension.get_clipboard(allow_app_switch=True) == "pasted 文字" + assert [call["op"] for call in wda.calls] == ["get_clipboard"] + assert "allow_app_switch" in extension.capability("clipboard").reason + + +def test_the_clipboard_commands_offer_the_allowance_and_pass_it_only_when_set(monkeypatch): + from je_auto_control.wrapper import mobile_commands + for name in ("AC_ios_get_clipboard", "AC_android_get_clipboard"): + params = {param.name: param for param in mobile_commands._BY_NAME[name].params} + assert params["allow_app_switch"].kind == "bool" + assert params["allow_app_switch"].default is False + seen = [] + + class _OldAdapter: + """Registered before the flag existed: get_clipboard takes no keyword.""" + + def get_clipboard(self): + seen.append("plain") + return "old" + + monkeypatch.setattr(mobile_commands.extensions, "mobile_extension", lambda _session: _OldAdapter()) + assert mobile_commands._get_clipboard(object()) == "old" + assert seen == ["plain"] From 7b9b729c9ebdfc6ce71d75b9e59e7457bbe73b0a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Fri, 13 Nov 2026 07:32:47 +0800 Subject: [PATCH 059/161] Un-maximize before moving a window; match the first comtypes import to its thread Both found by running the Windows checks on a real desktop: a restored layout left windows flagged maximized, and comtypes imported first on a worker put it in an STA (or raised on an MTA thread). --- CHANGELOG.md | 8 +++ Progress.md | 14 +++-- architecture_explore.md | 16 +++--- .../Eng/doc/new_features/v4_features_doc.rst | 6 +- .../Zh/doc/new_features/v4_features_doc.rst | 4 +- docs/updates/2026-11-b.md | 13 +++++ docs/updates/README.md | 1 + .../backends/windows_automation.py | 52 ++++++++++++++++- .../windows/window/windows_window_manage.py | 13 ++++- .../test_accessibility_windows_threads.py | 56 +++++++++++++++++++ .../test_window_lifecycle_contract.py | 17 ++++++ 11 files changed, 181 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78fb51b5d..797def6e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- Windows: `move_window` (used by `restore_window_layout`, `snap_window`, the grid and + cascade layouts, `ac_window_move` and the window backend) un-maximizes a maximized window + first, without activating it. `MoveWindow` alone gave it the new rectangle but left it + flagged maximized. +- Windows accessibility: the first `comtypes` import initialises COM to match the importing + thread. Imported first on a worker it used to put that worker in an STA, and on a thread + already in the MTA it raised `OSError` (`RPC_E_CHANGED_MODE`). + - Reading the iOS pasteboard (`WdaExtension.get_clipboard`, `AC_ios_get_clipboard`, `ac_ios_get_clipboard`) now needs `allow_app_switch=True`: facebook-wda brings WebDriverAgent to the front through Siri for about 3 s and relaunches the app that was in front. Without it diff --git a/Progress.md b/Progress.md index 8b8709e10..c2850139f 100644 --- a/Progress.md +++ b/Progress.md @@ -36,8 +36,11 @@ - **混合 DPI 座標與樣板**:需實測各螢幕上的舊版座標、`screen_region`、視窗版面與樣板, 包含縮放不同的副螢幕、負原點與多螢幕排列;必要時重新錄製,不能以推導代替驗收。 - **舊版存的視窗版面檔要重存**:`save_window_layout` 改存 `GetWindowRect`,舊檔還原會偏右 7 px、縮小 14×7 px。 -- **真的 Win32 行為沒有實測**:`post_key` 在真的編輯框是否只出現一個字、DWM cloak 過濾掉的是哪些視窗、 - `MoveWindow` 對最大化視窗與另一個 DPI 的螢幕是否能原樣還原,都只用假的 `user32` 驗過。 +- **Win32 行為的實測(U-20261113-01,Windows 11、單一 1920×1080 螢幕)只涵蓋自有的原生 `EDIT` 視窗**: + `post_key` 每個字只到一次、DWM cloak 過濾與最大化視窗的還原都已驗;還沒驗的:另一個 DPI 的螢幕上的還原(只有一個螢幕)、 + WinUI(新版記事本)/Chromium 等非原生編輯控制項、零面積過濾(有標題列的視窗被系統夾到 202×56,到不了零)。 + `TODO`:版面檔不存最大化狀態,最大化時存下的視窗還原成螢幕大小的一般視窗;要恢復最大化就得啟用視窗,須先決定可否。 + `TODO`:`post_key_to_window` 拒絕鍵表外的可列印字元(如 `%`),Windows 只送 `WM_CHAR` 其實能送;X11 以 keycode 送,須一起設計。 - **X11/Wayland**:大寫與 Shift 標點的判斷假設 `keysym_to_keycode` 把大寫字母對到小寫的 keycode,沒有對著 X server 跑過。 --- @@ -108,10 +111,9 @@ PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` `TODO` — U-20261009-27、-28、-34、-36、-38、-40 之後還開著的 -- **Windows UIA 後端的執行緒模型完全沒對真的 COM 驗過**:現在每個呼叫執行緒各有一個自動化物件(`accessibility/backends/windows_automation.py`; - 主執行緒 STA、其他執行緒進 MTA),Accessibility 分頁與 A11y Audit 已移出 GUI 執行緒。開發環境沒裝 `comtypes`,CI 也沒有同時有 `comtypes` 與桌面的 job, - 測試全是假 COM 物件。未驗證的假設:MTA 工作執行緒上的 UIA 呼叫可用;焦點事件 callback 不需要 message pump; - `import comtypes` 第一次發生在已經是 MTA 的執行緒上會丟 `OSError`(憑記憶,沒處理)。焦點等待的 cooperative cancellation 已有 headless 回歸測試;真實 COM 訂閱/解除與停止行為仍待原生驗收。 +- **Windows UIA 後端的執行緒模型**已對真的 COM 驗過一次(U-20261113-01,comtypes 1.5.0 裝在暫存目錄、Windows 11):MTA 工作執行緒上的 UIA + 讀取可用、焦點事件不需要 message pump、第一次 `import comtypes` 現在依執行緒的 apartment 初始化。還缺的:CI 仍沒有同時有 `comtypes` 與桌面的 job, + `comtypes` 也不是宣告的相依;`AC_wait_for_focus_change` 被 stop 叫醒的路徑沒在真的 COM 上跑過;`utils/system_volume` 自己的 `comtypes` 匯入不經這條路。 - **Script Builder 的一次性值**:一次執行最多保留 200 個(`MAX_ONE_TIME_VALUES`,留前面的)。 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 diff --git a/architecture_explore.md b/architecture_explore.md index 37c89ccae..2b9170758 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,610 | +| 程式碼總行數 | 233,669 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -202,7 +202,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.3 平台後端 -#### Windows(`windows/`,24 檔/2,270 行) +#### Windows(`windows/`,24 檔/2,279 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -214,7 +214,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `record/win32_input_hook.py` | 258 | 單一一組低階鍵鼠 hook(`WH_KEYBOARD_LL`/`WH_MOUSE_LL`)+訊息迴圈,產生帶時間戳的事件時間軸;停止時以 `PostThreadMessageW(WM_QUIT)` 收掉執行緒,不會每錄一次就漏一條。 | | `record/win32_record.py` | 41 | 把 `win32_input_hook` 的時間軸轉成 action list(含按鍵放開、滾輪與間隔);整形本體與 macOS 共用 `utils/input_macro/recorder_base.py`。 | | `screen/win32_screen.py` | 171 | 螢幕尺寸與像素讀取。**每支 Win32 函式都明寫 argtypes/restype**(HDC 是指標寬度,走預設的 c_int 會截斷,錯誤會沉默地擴散到 GetPixel/ReleaseDC),並持有自己的 user32/gdi32 handle。import 時呼叫 `SetProcessDPIAware()`——**行程層級且不可還原**,實體↔邏輯座標換算請走 `utils/monitor_layout`。 | -| `window/windows_window_manage.py` | 473 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | +| `window/windows_window_manage.py` | 482 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | | `message/window_message.py` | 97 | 直接對視窗送 `WM_*` 訊息(背景輸入)。 | | `interception/_dll.py` | 232 | `interception.dll` 的延遲 ctypes 載入與結構定義。 | | `interception/keyboard.py` | 70 | 經 Interception 驅動的鍵盤輸入(繞過部分反自動化偵測)。 | @@ -463,12 +463,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,859 行。 +> 16 個套件、約 4,909 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a11y_audit/` | 362 | 以無障礙樹 + OCR 進行無障礙與 i18n 稽核 | -| `utils/accessibility/` | 3,324 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | +| `utils/accessibility/` | 3,374 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | | `utils/ax_text/` | 102 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | @@ -1539,9 +1539,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/executor/` | 11 | 10,749 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | -| `utils/accessibility/` | 16 | 3,324 | +| `utils/accessibility/` | 16 | 3,374 | | `wrapper/` | 25 | 6,005 | -| `windows/` | 24 | 2,270 | +| `windows/` | 24 | 2,279 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,113 | -| **總計** | **1,515** | **232,865** | +| **總計** | **1,515** | **232,924** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v4_features_doc.rst b/docs/source/Eng/doc/new_features/v4_features_doc.rst index 257df5f1b..98042d177 100644 --- a/docs/source/Eng/doc/new_features/v4_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v4_features_doc.rst @@ -122,7 +122,11 @@ Window management ``MoveWindow`` positions (Win32 ``GetWindowRect``), so a window comes back exactly where it was. A layout file saved by an earlier version holds the visible frame instead and restores 7 px to the right and 14 x 7 px smaller; - save it again. ``AC_save_window_layout`` / ``AC_restore_window_layout``. + save it again. A window that is maximized when the layout is restored is + un-maximized first, without being activated, so it ends at the saved size + instead of keeping the maximized flag. A window saved while maximized comes + back as a normal window of the screen's size: the maximized state itself is + not stored. ``AC_save_window_layout`` / ``AC_restore_window_layout``. * **Snap / tile** — ``snap_window(title, "left")`` moves a window to a half (left / right / top / bottom), a quarter (the four corners), or ``"max"`` of the primary monitor's *work area* — the screen minus the diff --git a/docs/source/Zh/doc/new_features/v4_features_doc.rst b/docs/source/Zh/doc/new_features/v4_features_doc.rst index 6859a9d6e..8d638837e 100644 --- a/docs/source/Zh/doc/new_features/v4_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v4_features_doc.rst @@ -101,7 +101,9 @@ Builder 項目。視覺與視窗功能的 geometry / IO 操作皆可注入,因 成 JSON;``restore_window_layout(path)`` 再把它們全部移回(方便測試 setup / teardown)。存下的是 ``MoveWindow`` 定位的那個矩形(Win32 ``GetWindowRect``),所以視窗會回到原本的位置。舊版存的版面檔記的是可見 - 外框,還原會右移 7 px、縮小 14 x 7 px,請重新儲存。 + 外框,還原會右移 7 px、縮小 14 x 7 px,請重新儲存。還原時已最大化的視窗會先 + 取消最大化(不啟用它),因此會停在存下的大小,而不是保留最大化狀態。最大化時存下 + 的視窗會以螢幕大小的一般視窗回來:最大化狀態本身沒有存。 ``AC_save_window_layout`` / ``AC_restore_window_layout``。 * **貼齊 / 平鋪** — ``snap_window(title, "left")`` 把視窗移到主螢幕\ *工作區*\ (螢幕扣掉工作列)的一半(left / right / top / bottom)、四分之一(四個角) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 96af8f51e..c4cf3a790 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -223,3 +223,16 @@ - **Tests:** `test_mobile_app_lifecycle.py` +2 (refused with nothing sent, then read with the allowance; both commands declare the flag and an old adapter is called without it). Mobile, iOS, Android, RBAC catalogue, Builder schema and MCP surface files: 632 passed. Typing on win32 / linux / darwin and strict Sphinx clean. - **Files:** `ios/apps.py`, `android/apps.py`, `wrapper/mobile_extensions.py`, `wrapper/mobile_commands.py`, `test_mobile_app_lifecycle.py`, both `mobile_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** not run against a real device (`Progress.md` › 行動裝置). + +## U-20261113-01 · 2026-11-13 · Windows desktop acceptance on a self-owned window; two fixes · #done #windows #accessibility + +- **Scope:** the maintainer resumed the Windows desktop checks on 2026-11-13. Run on this machine (Windows 11 Pro 26200, one 1920×1080 screen at 100 %, Python 3.14.7) against a window the check started itself: a native top-level window with a single-line `EDIT` child in its own process. No other application was driven. `comtypes==1.5.0` was installed into a scratch directory with `pip --target` for the UIA part; the shared `.venv` was not changed. Focus changed only for the two focus checks. +- **`post_key`:** `post_key_to_window` of `a`, `B`, `1` left `aB1` in the edit (each character once), VK_BACK removed one, the foreground window did not change. Found: a printable character outside the key table (`%`) is refused as an unknown key name (`Progress.md` TODO). +- **`list_windows` filters:** the window is listed, absent while it cloaks itself (`DWMWA_CLOAK`) and listed again after; `is_window_cloaked` agrees. On this desktop the cloak filter drops `DummyDWMListenerWindow` ×5, `ThumbnailDeviceHelperWnd`, `Windows.UI.Core.CoreWindow` and `EdgeUiInputTopWndClass` (class names only). The zero-size filter could not be reached: Windows keeps a captioned window at 202×56. +- **Layout restore — fixed:** a layout saved at 150,160 600×300 and restored onto the maximized window gave the right rectangle but left `IsZoomed` true. `windows_window_manage.move_window` now calls `ShowWindow(SW_SHOWNOACTIVATE)` first on a maximized window; re-run: rectangle 150,160–750,460, not maximized. A layout saved while maximized (-11,-11 1942×1030) restores as a screen-sized normal window: the state itself is not stored (`Progress.md` TODO). +- **`focus_window`:** returned the window's handle and it became the foreground window. +- **UIA threading:** `list_elements` and `get_value` (raw role `ControlType_50004`, value `hello uia`) work on the main thread (STA) and on a worker (MTA). `wait_for_focus_change` delivered an event without a message pump on both, 0.08 s and 0.02 s after the focus moved, and removed its handler. +- **First `comtypes` import — fixed:** confirmed what the module's notes guessed: `import comtypes` first on a thread already in the MTA raises `OSError` 0x80010106; and imported first on a worker (the backend's availability probe) it put the worker in an STA, not the MTA the design wants. `windows_automation.import_comtypes_client()` sets `sys.coinit_flags` for that first import from `CoGetApartmentType` (MTA if the thread is MTA, STA if STA, otherwise main → STA and worker → MTA), only when comtypes is not imported yet and nobody set the flags, and removes it afterwards. Fresh-process re-runs: worker first → `mta`; worker already MTA → `mta`, no error; worker already STA → `existing`; main then worker → `sta` / `mta`. +- **Tests:** `test_window_lifecycle_contract.py` +2 (a maximized window is restored with command 4 before `MoveWindow`; a normal one is not), `test_accessibility_windows_threads.py` +6 (flags per apartment type, the uninitialised rule on main and worker, the first import sees the flags and leaves none, flags set elsewhere are kept). Accessibility and window test files: 1,043 passed, 5 skipped, 1 failed (the order-dependent `test_a11y_window_audit.py` `KeyError`, U-20261112-07). +- **Files:** `windows/window/windows_window_manage.py`, `utils/accessibility/backends/windows_automation.py`, the two tests, both `v4_features_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** `Progress.md` › 桌面行為驗收 (second-DPI screen, non-native edit controls, maximized state in layouts, `post_key` characters outside the key table) and › GUI (no CI job with comtypes and a desktop, stop during a real focus wait, `system_volume`'s own import). diff --git a/docs/updates/README.md b/docs/updates/README.md index 9167c8fdb..6cd912de1 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261113-01 | 2026-11-13 | Windows desktop acceptance on a self-owned window; two fixes | #done #windows #accessibility | [2026-11-b](2026-11-b.md) | | U-20261112-14 | 2026-11-12 | Reading the iOS pasteboard needs an explicit allowance | #done #mobile #ios | [2026-11-b](2026-11-b.md) | | U-20261112-13 | 2026-11-12 | Bring the shared .venv to the pinned pillow and PySide6 | #done #tooling | [2026-11-b](2026-11-b.md) | | U-20261112-12 | 2026-11-12 | Move the finished on_enter note out of Progress | #docs #executor | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/accessibility/backends/windows_automation.py b/je_auto_control/utils/accessibility/backends/windows_automation.py index a24d28f23..d5094838e 100644 --- a/je_auto_control/utils/accessibility/backends/windows_automation.py +++ b/je_auto_control/utils/accessibility/backends/windows_automation.py @@ -127,9 +127,59 @@ def __set__(self, instance: Any, value: Any) -> None: self._slot(instance).value = value +#: ``CoGetApartmentType`` answers: the thread is in the multi-threaded apartment. +_APTTYPE_MTA = 1 + + +def _current_apartment_type() -> Optional[int]: + """This thread's ``APTTYPE``; ``None`` when COM is not initialised on it, or there is no COM.""" + if sys.platform != "win32": + return None + import ctypes + ole32 = ctypes.WinDLL("ole32") + kind, qualifier = ctypes.c_int(), ctypes.c_int() + result = int(ole32.CoGetApartmentType(ctypes.byref(kind), ctypes.byref(qualifier))) & 0xFFFFFFFF + return int(kind.value) if result == _S_OK else None + + +def coinit_flags_for_this_thread(apartment_type: Optional[int] = None) -> int: + """The flags ``comtypes`` must initialise COM with on this thread when it is imported here. + + ``comtypes`` calls ``CoInitializeEx(sys.coinit_flags)`` on the thread that + imports it, single-threaded by default. Measured with comtypes 1.5.0 on + Windows 11 (U-20261113-01): imported first on a worker, it put that worker + in a single-threaded apartment, so the worker never joined the MTA this + module intends; imported first on a thread already in the MTA, it raised + ``OSError`` 0x80010106 (``RPC_E_CHANGED_MODE``). The flags therefore follow + the apartment the thread is already in, and otherwise this module's rule. + """ + kind = _current_apartment_type() if apartment_type is None else apartment_type + if kind is None: + on_main = threading.current_thread() is threading.main_thread() + return COINIT_APARTMENTTHREADED if on_main else COINIT_MULTITHREADED + return COINIT_MULTITHREADED if kind == _APTTYPE_MTA else COINIT_APARTMENTTHREADED + + +def import_comtypes_client() -> Any: + """Import ``comtypes.client`` so that its import-time COM initialisation fits this thread. + + Only the first import initialises anything. ``sys.coinit_flags`` is set for + it, and removed again, only when no one else has set it. + """ + chosen = "comtypes" not in sys.modules and not hasattr(sys, "coinit_flags") + if chosen: + setattr(sys, "coinit_flags", coinit_flags_for_this_thread()) + try: + import comtypes.client + finally: + if chosen and hasattr(sys, "coinit_flags"): + delattr(sys, "coinit_flags") + return comtypes.client + + def _is_available() -> bool: try: - import comtypes.client # noqa: F401 # reason: probe import + import_comtypes_client() return True except ImportError: return False diff --git a/je_auto_control/windows/window/windows_window_manage.py b/je_auto_control/windows/window/windows_window_manage.py index 9f3ef7132..bf607de4e 100644 --- a/je_auto_control/windows/window/windows_window_manage.py +++ b/je_auto_control/windows/window/windows_window_manage.py @@ -93,6 +93,7 @@ def _load_dwmapi() -> Any: WM_CLOSE = 0x0010 SW_RESTORE = 9 +_SW_SHOWNOACTIVATE = 4 _DWMWA_CLOAKED = 14 @@ -308,9 +309,17 @@ def show_window(hwnd: int, cmd_show: int) -> bool: def move_window(hwnd: int, x: int, y: int, width: int, height: int, repaint: bool = True) -> bool: """ - 搬移與調整視窗大小 (一次設定座標與寬高) - Move and resize a window in one call. + 搬移與調整視窗大小 (一次設定座標與寬高);最大化的視窗先還原(不啟用) + Move and resize a window in one call; a maximized window is restored first. + + ``MoveWindow`` on a maximized window gives it the requested rectangle but + leaves it maximized (measured on Windows 11, U-20261113-01): the caption + still shows Restore and the next restore jumps back to the old size. It is + therefore restored first with ``SW_SHOWNOACTIVATE``, which does not take + the foreground. """ + if _user32.IsZoomed(int(hwnd)): + _user32.ShowWindow(int(hwnd), _SW_SHOWNOACTIVATE) return bool(_user32.MoveWindow(int(hwnd), int(x), int(y), int(width), int(height), bool(repaint))) diff --git a/test/unit_test/headless/test_accessibility_windows_threads.py b/test/unit_test/headless/test_accessibility_windows_threads.py index cba73814a..4f03485fe 100644 --- a/test/unit_test/headless/test_accessibility_windows_threads.py +++ b/test/unit_test/headless/test_accessibility_windows_threads.py @@ -391,3 +391,59 @@ def test_a_per_thread_attribute_is_one_value_per_thread_and_per_instance(): assert first.slot == "main" assert second.slot is None assert isinstance(_Holder.slot, PerThread) + + +# --- the first comtypes import -------------------------------------------------- +# Measured with comtypes 1.5.0 (U-20261113-01): imported first on a worker it put +# the worker in an STA; imported first on a thread already in the MTA it raised +# OSError 0x80010106. Its import-time CoInitializeEx must follow the thread. + +@pytest.mark.parametrize("apartment_type, flags", [ + (1, windows_automation.COINIT_MULTITHREADED), # APTTYPE_MTA + (0, windows_automation.COINIT_APARTMENTTHREADED), # APTTYPE_STA + (3, windows_automation.COINIT_APARTMENTTHREADED), # APTTYPE_MAINSTA +]) +def test_an_initialised_thread_keeps_its_apartment(apartment_type, flags): + assert windows_automation.coinit_flags_for_this_thread(apartment_type) == flags + + +def test_an_uninitialised_thread_follows_the_module_rule(monkeypatch): + monkeypatch.setattr(windows_automation, "_current_apartment_type", lambda: None) + assert windows_automation.coinit_flags_for_this_thread() == windows_automation.COINIT_APARTMENTTHREADED + seen = [] + worker = threading.Thread(target=lambda: seen.append(windows_automation.coinit_flags_for_this_thread())) + worker.start() + worker.join(10) + assert seen == [windows_automation.COINIT_MULTITHREADED] + + +def _fake_comtypes_import(monkeypatch): + import builtins + real_import, seen = builtins.__import__, [] + + def fake(name, *args, **kwargs): + if name.startswith("comtypes"): + seen.append(getattr(sys, "coinit_flags", "unset")) + fake_package = types.SimpleNamespace(client="client-module") + return fake_package + return real_import(name, *args, **kwargs) + monkeypatch.delitem(sys.modules, "comtypes", raising=False) + monkeypatch.setattr(builtins, "__import__", fake) + return seen + + +def test_the_first_import_sees_the_threads_flags_and_leaves_none_behind(monkeypatch): + monkeypatch.delattr(sys, "coinit_flags", raising=False) + monkeypatch.setattr(windows_automation, "coinit_flags_for_this_thread", lambda: 0) + seen = _fake_comtypes_import(monkeypatch) + assert windows_automation.import_comtypes_client() == "client-module" + assert seen == [0] + assert not hasattr(sys, "coinit_flags") + + +def test_flags_someone_else_chose_are_left_alone(monkeypatch): + monkeypatch.setattr(sys, "coinit_flags", 2, raising=False) + seen = _fake_comtypes_import(monkeypatch) + windows_automation.import_comtypes_client() + assert seen == [2] + assert sys.coinit_flags == 2 diff --git a/test/unit_test/headless/test_window_lifecycle_contract.py b/test/unit_test/headless/test_window_lifecycle_contract.py index 738f78021..a93edce52 100644 --- a/test/unit_test/headless/test_window_lifecycle_contract.py +++ b/test/unit_test/headless/test_window_lifecycle_contract.py @@ -474,3 +474,20 @@ def test_a_short_poll_still_polls_at_its_own_pace(clock): w.wait_for_window("never", timeout=1.0, poll=0.25) assert clock.sleeps[0] == pytest.approx(0.25) assert sum(clock.sleeps) == pytest.approx(1.0) + + +@windows_only +@pytest.mark.parametrize("zoomed", [True, False]) +def test_moving_a_maximized_window_restores_it_first_without_activating(monkeypatch, zoomed): + """Measured on Windows 11: MoveWindow alone left a maximized window flagged maximized.""" + from je_auto_control.windows.window import windows_window_manage + calls = [] + fake = types.SimpleNamespace( + IsZoomed=lambda hwnd: int(zoomed), + ShowWindow=lambda hwnd, command: calls.append(("show", command)), + SetForegroundWindow=lambda hwnd: calls.append(("foreground",)), + MoveWindow=lambda hwnd, x, y, w, h, repaint: calls.append(("move", x, y, w, h)) or 1) + monkeypatch.setattr(windows_window_manage, "_user32", fake) + assert windows_window_manage.move_window(7, 150, 160, 600, 300) + expected = [("show", 4)] if zoomed else [] # SW_SHOWNOACTIVATE + assert calls == expected + [("move", 150, 160, 600, 300)] From 2b0d918a94ed1186a21c315ed2b64aff5af9da3d Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Fri, 13 Nov 2026 08:10:38 +0800 Subject: [PATCH 060/161] Fix the PR checks: libEGL in the image, cleaners keep their own cancellation PySide6 6.12 needs libEGL.so.1, which the container lacked since 2026-11-02, and two WebRTC cleaners swallowed their own cancellation while cancelling a child (SonarCloud S7497). The macos-15 capability gate passed on this PR. --- CHANGELOG.md | 4 ++ Progress.md | 10 ---- architecture_explore.md | 16 +++--- docker/Dockerfile | 2 + docs/updates/2026-11-b.md | 14 ++++++ docs/updates/README.md | 2 + .../utils/remote_desktop/webrtc_file_tasks.py | 2 +- .../utils/remote_desktop/webrtc_host_media.py | 9 +++- .../remote_desktop/webrtc_peer_cleanup.py | 14 +++++- .../test_webrtc_cancel_propagation.py | 49 +++++++++++++++++++ 10 files changed, 101 insertions(+), 21 deletions(-) create mode 100644 test/unit_test/headless/test_webrtc_cancel_propagation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 797def6e9..e3b4349f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- WebRTC cleanup that cancels a child task (viewer video retirement, peer teardown) no longer + swallows its own cancellation when it is cancelled while waiting for that child. +- The container image installs `libegl1`: PySide6 6.12's QtGui loads `libEGL.so.1` at import. + - Windows: `move_window` (used by `restore_window_layout`, `snap_window`, the grid and cascade layouts, `ac_window_move` and the window backend) un-maximizes a maximized window first, without activating it. `MoveWindow` alone gave it the new rectangle but left it diff --git a/Progress.md b/Progress.md index c2850139f..9460b3052 100644 --- a/Progress.md +++ b/Progress.md @@ -97,16 +97,6 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD --- -## macos-15 上的 TCC 權限還沒被 gate 驗過 - -`TODO` — 2026-11-01 把所有 macOS 方格從 `macos-14` 改成 `macos-15`(U-20261101-02), -`test/verify/macos_verify.py` 的 `EXPECTED` 沿用 2026-08-19 在 macos-14 上的實測(螢幕錄製與輔助使用兩個 -TCC 權限都給)。`platform-smoke.yml` 的 `macos-capabilities` 只在推送到 `main` 與對 `main` 的 PR 上執行,所以下一個 dev→main -PR 才會確認 macos-15 是否給一樣的權限;若不同,依 `--measure` 重新實測後更新 `EXPECTED` 與 -`docs/CAPABILITY_MATRIX.md`,不要直接放寬 gate。 - ---- - ## GUI:留下的缺口 `TODO` — U-20261009-27、-28、-34、-36、-38、-40 之後還開著的 diff --git a/architecture_explore.md b/architecture_explore.md index 2b9170758..1bef560de 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,669 | +| 程式碼總行數 | 233,688 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 31,986 行。 +> 6 個套件、約 32,005 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,717 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,736 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,717 行/77 檔) +#### `utils/remote_desktop/`(16,736 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -830,7 +830,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_viewer.py` | 736 | WebRTC 檢視端:接收視訊並送出輸入。 | | `webrtc_retirement.py` | 186 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | | `webrtc_media_owners.py` | 249 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | -| `webrtc_peer_cleanup.py` | 154 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | +| `webrtc_peer_cleanup.py` | 166 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | | `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | | `viewer.py` | 743 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | @@ -861,7 +861,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | | `lan_discovery.py` | 378 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | -| `webrtc_host_media.py` | 250 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | +| `webrtc_host_media.py` | 257 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | | `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | @@ -1535,7 +1535,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 150 | 40,657 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,717 | +| `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,749 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,113 | -| **總計** | **1,515** | **232,924** | +| **總計** | **1,515** | **232,943** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docker/Dockerfile b/docker/Dockerfile index 4ac766b41..10018d6f4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -27,6 +27,7 @@ ARG DEBIAN_FRONTEND=noninteractive # - xvfb + xauth: virtual X server so the host can capture a "screen". # - x11-utils + xdotool: useful for diagnostics, optional. # - libgl1: PySide6 + opencv-python hard-require libGL.so.1 at import. +# - libegl1: PySide6 6.12's QtGui also loads libEGL.so.1 at import. # - libglib2.0-0: opencv-python needs libgthread-2.0.so.0 from glib. # - libxkbcommon-x11-0 + libdbus-1-3 + libxcb-*: Qt platform plugins. # - libusb-1.0-0: USB enumeration via pyusb / libusb. @@ -34,6 +35,7 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates \ libdbus-1-3 \ + libegl1 \ libgl1 \ libglib2.0-0 \ libusb-1.0-0 \ diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c4cf3a790..9c5946395 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -236,3 +236,17 @@ - **Tests:** `test_window_lifecycle_contract.py` +2 (a maximized window is restored with command 4 before `MoveWindow`; a normal one is not), `test_accessibility_windows_threads.py` +6 (flags per apartment type, the uninitialised rule on main and worker, the first import sees the flags and leaves none, flags set elsewhere are kept). Accessibility and window test files: 1,043 passed, 5 skipped, 1 failed (the order-dependent `test_a11y_window_audit.py` `KeyError`, U-20261112-07). - **Files:** `windows/window/windows_window_manage.py`, `utils/accessibility/backends/windows_automation.py`, the two tests, both `v4_features_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** `Progress.md` › 桌面行為驗收 (second-DPI screen, non-native edit controls, maximized state in layouts, `post_key` characters outside the key table) and › GUI (no CI job with comtypes and a desktop, stop during a real focus wait, `system_volume`'s own import). + +## U-20261113-02 · 2026-11-13 · macos-15 grants what the capability gate expects · #done #macos #ci + +- **What:** Closes `Progress.md` › "macos-15 上的 TCC 權限還沒被 gate 驗過". The `macos-capabilities` job of `platform-smoke.yml` runs only on pushes to `main` and pull requests into it, so the first dev→main PR after the move from `macos-14` to `macos-15` (U-20261101-02) was needed: PR #552, opened 2026-11-12. Its run ("What a real macOS runner permits", job 131571286607, image `macos-15-arm64` 20261104.0514.1) reported **13/13 probes match** `test/verify/macos_verify.py`'s `EXPECTED`, which was measured on macos-14 on 2026-08-19 (screen recording and accessibility both granted). `EXPECTED` and `docs/CAPABILITY_MATRIX.md` therefore stay as they are. +- **Also observed in that run:** recorder, window management, click-state readback, minimised-window-by-id and `grab_logical` (1024×768 points at 1x, one display) all "works". That is a 1x single-display runner; the Retina and second-display questions in `Progress.md` › macOS stay open. +- **Open items:** none for this. + +## U-20261113-03 · 2026-11-13 · PR #552: container libEGL and three asyncio cancellation findings · #incident #ci #remote + +- **Container:** "Headless pytest inside the image" (`docker.yml`) has failed on every PR since it last passed on 2026-11-02: the test step installs `dev_requirements.txt`, which pins `PySide6==6.12.0`, and Qt 6.12's QtGui loads `libEGL.so.1`, which the `python:3.12-slim` runtime image did not carry. `test_core_panel_ownership.py` imports `QtWidgets` at module level, so collection failed. `docker/Dockerfile` now installs `libegl1` next to `libgl1`, with the same kind of comment. Not built locally (no Docker here); the PR's container job is the check. +- **SonarCloud (gate: new reliability rating 3 > 1):** three python:S7497 findings in code from 2026-11-11. `webrtc_host_media.py` (`_retire_live_video`) and `webrtc_peer_cleanup.py` (`_cancel_task`) cancelled a child task and then caught every `CancelledError` from awaiting it, which also swallowed the cleaning task's own cancellation if it arrived during the wait. Both now re-raise when the running task itself is being cancelled (`asyncio.current_task().cancelling() > 0`, Python ≥ 3.11), and still absorb the child's. `asyncio.wait` was tried first but the tests' fake tasks are not futures. `webrtc_file_tasks.py` (`_observe_sender`) already keeps the first cancellation and re-raises it once the worker has exited, so it is marked `# NOSONAR python:S7497` with that reason. +- **Tests:** `test_webrtc_cancel_propagation.py` (new, 2): a cancelled child is awaited and absorbed; the cleaner cancelled mid-wait ends cancelled (fails on the previous code). WebRTC / media / remote-desktop files: 1,218 passed, 18 skipped. `test_docker_artifacts.py`: 28 passed. Typing on win32 / linux / darwin clean. +- **Files:** `docker/Dockerfile`, `utils/remote_desktop/{webrtc_host_media.py,webrtc_peer_cleanup.py,webrtc_file_tasks.py}`, the new test, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 6cd912de1..82a36d0be 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,8 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261113-03 | 2026-11-13 | PR #552: container libEGL and three asyncio cancellation findings | #incident #ci #remote | [2026-11-b](2026-11-b.md) | +| U-20261113-02 | 2026-11-13 | macos-15 grants what the capability gate expects | #done #macos #ci | [2026-11-b](2026-11-b.md) | | U-20261113-01 | 2026-11-13 | Windows desktop acceptance on a self-owned window; two fixes | #done #windows #accessibility | [2026-11-b](2026-11-b.md) | | U-20261112-14 | 2026-11-12 | Reading the iOS pasteboard needs an explicit allowance | #done #mobile #ios | [2026-11-b](2026-11-b.md) | | U-20261112-13 | 2026-11-12 | Bring the shared .venv to the pinned pillow and PySide6 | #done #tooling | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py b/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py index e46ace60c..476bb9efc 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py +++ b/je_auto_control/utils/remote_desktop/webrtc_file_tasks.py @@ -112,7 +112,7 @@ async def _observe_sender(worker: asyncio.Future[Optional[BaseException]], stop: while not worker.done(): try: await asyncio.shield(worker) - except asyncio.CancelledError as error: + except asyncio.CancelledError as error: # NOSONAR python:S7497 # reason: re-raised below once the worker exits if interruption is None: interruption = error stop.set() diff --git a/je_auto_control/utils/remote_desktop/webrtc_host_media.py b/je_auto_control/utils/remote_desktop/webrtc_host_media.py index 3b01541cf..18b914886 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host_media.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host_media.py @@ -26,6 +26,12 @@ ) + +def _being_cancelled() -> bool: + """Whether the running task itself has a pending cancellation (not just a child's).""" + task = asyncio.current_task() + return task is not None and task.cancelling() > 0 + class MediaNegotiationMixin: """Media-track half of :class:`WebRTCDesktopHost`. @@ -241,7 +247,8 @@ async def _retire_live_video(self, peer, task) -> None: try: await task except asyncio.CancelledError: - pass + if _being_cancelled(): + raise # this task's own cancellation, not the child's finally: if task.done() and self._viewer_video_task is task: self._viewer_video_task = None diff --git a/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py b/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py index 674814aa5..ddfa65c0c 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py +++ b/je_auto_control/utils/remote_desktop/webrtc_peer_cleanup.py @@ -21,12 +21,24 @@ async def _wait_steps(*steps: Coroutine[Any, Any, object]) -> None: raise result +def _being_cancelled() -> bool: + """Whether the running task itself has a pending cancellation (not just a child's).""" + task = asyncio.current_task() + return task is not None and task.cancelling() > 0 + + async def _cancel_task(task: asyncio.Task[Any]) -> None: + """Cancel ``task`` and wait for it; a cancellation of the caller itself still propagates. + + ``except CancelledError: pass`` alone also swallowed the caller's own + cancellation when it arrived during the wait. + """ task.cancel() try: await task except asyncio.CancelledError: - pass + if _being_cancelled(): + raise async def _close_peer(owner: WebRTCDesktopHost | WebRTCDesktopViewer, diff --git a/test/unit_test/headless/test_webrtc_cancel_propagation.py b/test/unit_test/headless/test_webrtc_cancel_propagation.py new file mode 100644 index 000000000..19c239d7c --- /dev/null +++ b/test/unit_test/headless/test_webrtc_cancel_propagation.py @@ -0,0 +1,49 @@ +"""Cancelling a child task during cleanup must not swallow the cleaner's own cancellation. + +``except asyncio.CancelledError: pass`` around ``await child`` also caught the +cancellation of the task doing the waiting (SonarCloud python:S7497 on #552): +cancelled mid-cleanup, that task carried on as if nothing had happened. +""" +import asyncio + +import pytest + +pytest.importorskip("aiortc", exc_type=ImportError) + +from je_auto_control.utils.remote_desktop import webrtc_peer_cleanup # noqa: E402 # reason: optional media dependencies + + +async def _slow_to_stop(release: asyncio.Event) -> None: + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + await release.wait() # cleanup that takes a while + raise + + +def test_a_cancelled_child_is_waited_for_and_its_cancellation_absorbed(): + async def drive(): + release = asyncio.Event() + release.set() + child = asyncio.create_task(_slow_to_stop(release)) + await asyncio.sleep(0) + await webrtc_peer_cleanup._cancel_task(child) + return child.cancelled() + assert asyncio.run(drive()) is True + + +def test_the_cleaners_own_cancellation_propagates(): + async def drive(): + release = asyncio.Event() + child = asyncio.create_task(_slow_to_stop(release)) + await asyncio.sleep(0) + cleaner = asyncio.create_task(webrtc_peer_cleanup._cancel_task(child)) + await asyncio.sleep(0.01) # the cleaner now waits on the child + cleaner.cancel() + release.set() + try: + await cleaner + except asyncio.CancelledError: + return "cancelled" + return "finished" + assert asyncio.run(drive()) == "cancelled" From cfe70af5c2f54f8a5f0f5a7f494deb187dbb5775 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Fri, 13 Nov 2026 09:33:02 +0800 Subject: [PATCH 061/161] Test against the PySide6 the package pins The dependabot bump to 6.12.0 moved pyproject, dev.toml and dev_requirements.txt but left the workflows' tooling lines on 6.11.2, so only the container job ran 6.12.0 on Linux, and it segfaults at interpreter exit after "shared QObject was deleted directly". With the pin aligned, the Ubuntu square runs 6.12.0 under gdb and records where. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/dev.yml | 2 +- .github/workflows/quality.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index 90f072a30..bb4c97a0d 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -79,7 +79,7 @@ jobs: shell: bash # The same line as quality.yml (test_dev_release.py compares them). # Quoted: `--only-binary :all:` puts a colon-space inside the scalar. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.11.2 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" # No path argument: the paths come from `testpaths` in pyproject.toml, # and an argument would drop the flow_control tests. Linux runs under a diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index a45ba6d95..d81dc1c9f 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -149,7 +149,7 @@ jobs: shell: bash # Quoted: `--only-binary :all:` puts a colon-space inside the # scalar, which YAML reads as a mapping and refuses. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.11.2 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" - name: Verify native diagnostics runner (Linux) if: runner.os == 'Linux' @@ -277,7 +277,7 @@ jobs: python-version: "3.12" cache: "pip" - run: pip install -e ".[gui,webrtc]" # NOSONAR githubactions:S8541,githubactions:S8544 # reason: installs the checked-out project itself, there is no upstream version to lock and the build must run - - run: "pip install --only-binary :all: mypy==2.4.0 PySide6==6.11.2 aiortc==1.15.0 av==17.1.0 aioice==0.10.2 pyee==14.0.0 pylibsrtp==1.0.0" + - run: "pip install --only-binary :all: mypy==2.4.0 PySide6==6.12.0 aiortc==1.15.0 av==17.1.0 aioice==0.10.2 pyee==14.0.0 pylibsrtp==1.0.0" - name: The ordinary contract does not change when the extras are installed run: python test/verify/typing_contract_verify.py - name: The package against the real PySide6 / aiortc / av types From 120d9cb509500eb6e28fd73bb95423083715468e Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Fri, 13 Nov 2026 09:39:29 +0800 Subject: [PATCH 062/161] Let post_key_to_window send any printable character Windows' key table has no punctuation, so "%" was refused although WM_CHAR needs no key code; a character beyond the BMP now goes as its two UTF-16 units. X11 sent the table keycode with no modifier, so "%" and "Z" typed "5" and "z": the character now picks the key its keymap binds and adds Shift when it sits on the shifted level. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++ Progress.md | 4 +- architecture_explore.md | 16 +++---- docs/CAPABILITY_MATRIX.md | 7 +++- docs/updates/2026-11-b.md | 9 ++++ docs/updates/README.md | 1 + .../windows/window/windows_window_manage.py | 5 ++- .../wrapper/auto_control_window.py | 11 +++-- .../wrapper/window_backends/x11_backend.py | 38 ++++++++++++++++- test/unit_test/headless/_xlib_stub.py | 5 +++ .../headless/test_window_backend_x11.py | 42 ++++++++++++++++--- .../test_window_lifecycle_contract.py | 19 +++++++++ 12 files changed, 141 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3b4349f6..a4cdf3829 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- `post_key_to_window` (`AC_post_key_to_window`, `ac_post_key_to_window`) accepts any + printable character, not only those in the platform's key table: on Windows `"%"` and other + punctuation used to raise `unknown key name`, and a character beyond the BMP is now posted + as its two UTF-16 units. On X11 a character is sent as the key the keymap binds it to, with + Shift when it is on the shifted level, so `"%"` and `"Z"` no longer arrive as `5` and `z`. + - WebRTC cleanup that cancels a child task (viewer video retirement, peer teardown) no longer swallows its own cancellation when it is cancelled while waiting for that child. - The container image installs `libegl1`: PySide6 6.12's QtGui loads `libEGL.so.1` at import. diff --git a/Progress.md b/Progress.md index 9460b3052..d409a16ae 100644 --- a/Progress.md +++ b/Progress.md @@ -40,8 +40,8 @@ `post_key` 每個字只到一次、DWM cloak 過濾與最大化視窗的還原都已驗;還沒驗的:另一個 DPI 的螢幕上的還原(只有一個螢幕)、 WinUI(新版記事本)/Chromium 等非原生編輯控制項、零面積過濾(有標題列的視窗被系統夾到 202×56,到不了零)。 `TODO`:版面檔不存最大化狀態,最大化時存下的視窗還原成螢幕大小的一般視窗;要恢復最大化就得啟用視窗,須先決定可否。 - `TODO`:`post_key_to_window` 拒絕鍵表外的可列印字元(如 `%`),Windows 只送 `WM_CHAR` 其實能送;X11 以 keycode 送,須一起設計。 -- **X11/Wayland**:大寫與 Shift 標點的判斷假設 `keysym_to_keycode` 把大寫字母對到小寫的 keycode,沒有對著 X server 跑過。 +- **X11/Wayland**:大寫與 Shift 標點的判斷假設 `keysym_to_keycode` 把大寫字母對到小寫的 keycode,沒有對著 X server 跑過; + `post_key_to_window` 依 keymap 的 Shift 層加 `ShiftMask`(U-20261113-04)也只對 stub keymap 測過。 --- diff --git a/architecture_explore.md b/architecture_explore.md index 1bef560de..e70b3f938 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,688 | +| 程式碼總行數 | 233,730 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -197,12 +197,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `wrapper/auto_control_screen.py` | 111 | 螢幕 API:`screen_size`、`screenshot`(可指定區域)、`get_pixel`。 | | `wrapper/auto_control_image.py` | 89 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | | `wrapper/auto_control_record.py` | 124 | 錄製 API:`record`/`stop_record`/`record_to_json`(支援 stop event 與逾時)。 | -| `wrapper/auto_control_window.py` | 332 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | -| `wrapper/window_backends/` | 1,114 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | +| `wrapper/auto_control_window.py` | 337 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | +| `wrapper/window_backends/` | 1,148 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | ### 5.3 平台後端 -#### Windows(`windows/`,24 檔/2,279 行) +#### Windows(`windows/`,24 檔/2,282 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -214,7 +214,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `record/win32_input_hook.py` | 258 | 單一一組低階鍵鼠 hook(`WH_KEYBOARD_LL`/`WH_MOUSE_LL`)+訊息迴圈,產生帶時間戳的事件時間軸;停止時以 `PostThreadMessageW(WM_QUIT)` 收掉執行緒,不會每錄一次就漏一條。 | | `record/win32_record.py` | 41 | 把 `win32_input_hook` 的時間軸轉成 action list(含按鍵放開、滾輪與間隔);整形本體與 macOS 共用 `utils/input_macro/recorder_base.py`。 | | `screen/win32_screen.py` | 171 | 螢幕尺寸與像素讀取。**每支 Win32 函式都明寫 argtypes/restype**(HDC 是指標寬度,走預設的 c_int 會截斷,錯誤會沉默地擴散到 GetPixel/ReleaseDC),並持有自己的 user32/gdi32 handle。import 時呼叫 `SetProcessDPIAware()`——**行程層級且不可還原**,實體↔邏輯座標換算請走 `utils/monitor_layout`。 | -| `window/windows_window_manage.py` | 482 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | +| `window/windows_window_manage.py` | 485 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | | `message/window_message.py` | 97 | 直接對視窗送 `WM_*` 訊息(背景輸入)。 | | `interception/_dll.py` | 232 | `interception.dll` 的延遲 ctypes 載入與結構定義。 | | `interception/keyboard.py` | 70 | 經 Interception 驅動的鍵盤輸入(繞過部分反自動化偵測)。 | @@ -1540,8 +1540,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,374 | -| `wrapper/` | 25 | 6,005 | -| `windows/` | 24 | 2,279 | +| `wrapper/` | 25 | 6,044 | +| `windows/` | 24 | 2,282 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,113 | -| **總計** | **1,515** | **232,943** | +| **總計** | **1,515** | **232,985** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/CAPABILITY_MATRIX.md b/docs/CAPABILITY_MATRIX.md index ccc2ea95f..763f86a8c 100644 --- a/docs/CAPABILITY_MATRIX.md +++ b/docs/CAPABILITY_MATRIX.md @@ -499,7 +499,12 @@ shown up came out of it, and both were wrong in the first implementation: `post_key_to_window` and `post_click_to_window` work on X11 and are asserted to arrive *flagged synthetic*, because that is what they are: `XSendEvent` traffic, which GTK and Qt discard by design. They are the X11 counterpart of -Win32's `PostMessage`, which carries the same best-effort caveat. macOS has no +Win32's `PostMessage`, which carries the same best-effort caveat. A +one-character key is sent as text: on Windows as `WM_CHAR` (any printable +character, including ones the key table has no entry for, such as `%`), on X11 +as the key the server's keymap binds the character to, with Shift in the +event's state when it is on the shifted level; a character the keymap does not +bind is not sent and the call answers `False`. macOS has no equivalent at all — an event goes to whatever has focus — so the backend refuses rather than reporting a success that went somewhere else. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 9c5946395..2f688151a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -250,3 +250,12 @@ - **Tests:** `test_webrtc_cancel_propagation.py` (new, 2): a cancelled child is awaited and absorbed; the cleaner cancelled mid-wait ends cancelled (fails on the previous code). WebRTC / media / remote-desktop files: 1,218 passed, 18 skipped. `test_docker_artifacts.py`: 28 passed. Typing on win32 / linux / darwin clean. - **Files:** `docker/Dockerfile`, `utils/remote_desktop/{webrtc_host_media.py,webrtc_peer_cleanup.py,webrtc_file_tasks.py}`, the new test, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** none. + +## U-20261113-04 · 2026-11-13 · `post_key_to_window` takes any printable character · #done #windows #x11 + +- **What:** Closes the `Progress.md` › 桌面行為驗收 TODO found in U-20261113-01: `post_key_to_window(title, "%")` raised `unknown key name` on Windows, whose key table has no punctuation at all (``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~`` are all missing), although `post_key` sends a character as `WM_CHAR` and needs no key code for it. `_resolve_key` now returns `(0, character)` for a printable one-character key the table does not have, and refuses only multi-character names it cannot resolve. +- **Windows:** `post_key` posts a character as its UTF-16 code units, so a character beyond the BMP (`😀`) is two `WM_CHAR`s instead of one out-of-range `wParam`. Re-run on the self-owned `EDIT` fixture of U-20261113-01: `%`, `!`, `a`, `é`, `中`, `😀`, `~` left exactly `%!aé中😀~`, foreground unchanged. +- **X11 (designed with it, as the TODO asked):** the backend used to drop the character and send the table's keycode with `state=0`, so `"%"` (keycode of the 5 key) arrived as `5` and `"Z"` as `z`. It now looks the character's keysym up (its code point in Latin-1, `0x01000000 + code point` beyond), sends the key `keysym_to_keycode` binds it to, and sets `ShiftMask` when `keycode_to_keysym(code, 0)` is not the keysym but level 1 is. A character the keymap does not bind falls back to the given keycode; with none, nothing is sent and the answer is `False`. Tested against the stub keymap only, not an X server (`Progress.md` › X11/Wayland already lists the same assumption for `write()`). +- **Tests:** `test_window_lifecycle_contract.py` +4 (`%`, `é`, `中` posted as text with keycode 0; an astral character as two units), `test_window_backend_x11.py` +6 net (Shift for `%` / `Z`, none for `5` / `z`, a Unicode keysym, nothing sent for an unbound character with no keycode; the old "character is dropped" test now checks the fallback). `_xlib_stub.py` gained `keycode_to_keysym`. Window and X11 test files: 266 passed, 1 skipped. +- **Files:** `wrapper/auto_control_window.py`, `windows/window/windows_window_manage.py`, `wrapper/window_backends/x11_backend.py`, the tests and stub, `docs/CAPABILITY_MATRIX.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** X11 behaviour against a real X server (`Progress.md` › X11/Wayland). diff --git a/docs/updates/README.md b/docs/updates/README.md index 82a36d0be..2290c0634 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261113-04 | 2026-11-13 | `post_key_to_window` takes any printable character | #done #windows #x11 | [2026-11-b](2026-11-b.md) | | U-20261113-03 | 2026-11-13 | PR #552: container libEGL and three asyncio cancellation findings | #incident #ci #remote | [2026-11-b](2026-11-b.md) | | U-20261113-02 | 2026-11-13 | macos-15 grants what the capability gate expects | #done #macos #ci | [2026-11-b](2026-11-b.md) | | U-20261113-01 | 2026-11-13 | Windows desktop acceptance on a self-owned window; two fixes | #done #windows #accessibility | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/windows/window/windows_window_manage.py b/je_auto_control/windows/window/windows_window_manage.py index bf607de4e..93ed284d4 100644 --- a/je_auto_control/windows/window/windows_window_manage.py +++ b/je_auto_control/windows/window/windows_window_manage.py @@ -454,7 +454,10 @@ def post_key(hwnd: int, keycode: int, character: str = "") -> bool: """ target = get_focused_control(hwnd) if character: - return bool(_user32.PostMessageW(target, WM_CHAR, ord(character[0]), 1)) + # WM_CHAR carries UTF-16 code units: a character beyond the BMP is two. + units = character[0].encode("utf-16-le") + return all([bool(_user32.PostMessageW(target, WM_CHAR, int.from_bytes(units[i:i + 2], "little"), 1)) + for i in range(0, len(units), 2)]) down, up = _key_lparams(keycode) posted = bool(_user32.PostMessageW(target, WM_KEYDOWN, int(keycode), down)) return bool(_user32.PostMessageW(target, WM_KEYUP, int(keycode), up)) and posted diff --git a/je_auto_control/wrapper/auto_control_window.py b/je_auto_control/wrapper/auto_control_window.py index 519a6c847..4eff407a9 100644 --- a/je_auto_control/wrapper/auto_control_window.py +++ b/je_auto_control/wrapper/auto_control_window.py @@ -170,6 +170,9 @@ def post_key_to_window(title_substring: str, key: int | str, measured on Character Map, the frame swallowed the key and the focused edit accepted it. + A one-character ``key`` is sent as text, so any printable character works, + including ones the key table has no entry for (``"%"`` on Windows). + **This is best effort, not input.** ``PostMessage`` returning true means the message reached a queue, not that the application acted on it: games, anything reading raw input, and applications that check whether they are in @@ -214,12 +217,14 @@ def _resolve_key(key: int | str) -> Tuple[int, str]: keycode = keyboard_keys_table.get(name) if keycode is None: keycode = keyboard_keys_table.get(resolve_key_name(name, keyboard_keys_table)) - if keycode is None: - raise AutoControlActionException(f"unknown key name: {name!r}") # A one-character key is text: edit controls take their content from # WM_CHAR, so posting only the virtual-key messages types nothing. character = name if len(name) == 1 and name.isprintable() else "" - return int(keycode), character + if keycode is None and not character: + raise AutoControlActionException(f"unknown key name: {name!r}") + # A character the table has no key for ("%" on Windows, "é") is still + # text: the backend sends it as a character, with no key code to go by. + return int(keycode or 0), character def _mouse_button_name(button: str) -> str: diff --git a/je_auto_control/wrapper/window_backends/x11_backend.py b/je_auto_control/wrapper/window_backends/x11_backend.py index 50ba19602..feaedcb73 100644 --- a/je_auto_control/wrapper/window_backends/x11_backend.py +++ b/je_auto_control/wrapper/window_backends/x11_backend.py @@ -40,6 +40,15 @@ #: Button names the project uses, in X11's button numbering. _BUTTONS = {"left": 1, "middle": 2, "right": 3} +#: Keysyms above this are Unicode characters, ``0x01000000`` plus the code point (``keysymdef.h``). +_UNICODE_KEYSYM_BASE = 0x01000000 + + +def _character_keysym(character: str) -> int: + """The keysym X names a character by: its code point in Latin-1, the Unicode range beyond.""" + point = ord(character[0]) + return point if 0x20 <= point <= 0x7E or 0xA0 <= point <= 0xFF else _UNICODE_KEYSYM_BASE | point + def _is_linux() -> bool: return sys.platform in ("linux", "linux2") @@ -336,11 +345,21 @@ def post_key(self, window_id: int, keycode: int, Win32's ``PostMessage`` — best-effort, and useful mainly for the older toolkits that do accept it. For input that always lands, focus the window and use the ordinary keyboard API. + + X11 has no "type this character" event, so a ``character`` is sent as + the key the server's keymap binds it to, with Shift held in the + event's state when it sits on the key's shifted level: ``"%"`` is the + 5 key with Shift, ``"Z"`` the z key with Shift. A character the keymap + does not bind falls back to ``keycode``; with no keycode either, + nothing is sent and the answer is ``False``. """ from Xlib import X, protocol - del character # X11 addresses keys by keycode; the character is Win32's try: + detail, state = self._key_for(int(keycode), character) + if not detail: + autocontrol_logger.info("post_key(%s): the keymap binds no key to %r", window_id, character) + return False window = self._window(window_id) for factory, mask in ((protocol.event.KeyPress, X.KeyPressMask), (protocol.event.KeyRelease, X.KeyReleaseMask)): @@ -348,7 +367,7 @@ def post_key(self, window_id: int, keycode: int, factory(time=X.CurrentTime, root=self._root(), window=window, same_screen=1, child=X.NONE, root_x=0, root_y=0, event_x=0, event_y=0, - state=0, detail=int(keycode)), + state=state, detail=detail), propagate=True, event_mask=mask) self._display().flush() return True @@ -356,6 +375,21 @@ def post_key(self, window_id: int, keycode: int, autocontrol_logger.info("post_key(%s) failed: %r", window_id, error) return False + def _key_for(self, keycode: int, character: str) -> Tuple[int, int]: + """``(keycode, modifier state)`` that types ``character``; ``(keycode, 0)`` when it is unbound.""" + if not character: + return keycode, 0 + from Xlib import X + + display = self._display() + keysym = _character_keysym(character) + bound = int(display.keysym_to_keycode(keysym)) + if not bound: + return keycode, 0 + shifted = (display.keycode_to_keysym(bound, 0) != keysym + and display.keycode_to_keysym(bound, 1) == keysym) + return bound, (X.ShiftMask if shifted else 0) + def post_click(self, window_id: int, button: str, x: int, y: int) -> bool: """Send one click to the window without focusing it. diff --git a/test/unit_test/headless/_xlib_stub.py b/test/unit_test/headless/_xlib_stub.py index a6fce2d1a..c451c0a9e 100644 --- a/test/unit_test/headless/_xlib_stub.py +++ b/test/unit_test/headless/_xlib_stub.py @@ -188,6 +188,7 @@ def __init__(self) -> None: self.closed = False self.events = [] self.keycodes = {} # keysym -> keycode + self.keymap = {} # keycode -> keysyms by shift level (0 plain, 1 Shift) self._windows = {} self.root = Window(self, 1) self._windows[1] = self.root @@ -217,6 +218,10 @@ def close(self) -> None: def keysym_to_keycode(self, keysym: int) -> int: return self.keycodes.get(keysym, 0) + def keycode_to_keysym(self, keycode: int, index: int) -> int: + levels = self.keymap.get(keycode, ()) + return levels[index] if index < len(levels) else 0 + def pending_events(self) -> int: return len(self.events) diff --git a/test/unit_test/headless/test_window_backend_x11.py b/test/unit_test/headless/test_window_backend_x11.py index 3c4fa23ac..045a5ee8a 100644 --- a/test/unit_test/headless/test_window_backend_x11.py +++ b/test/unit_test/headless/test_window_backend_x11.py @@ -448,16 +448,48 @@ def test_posting_a_key_sends_a_press_and_a_release(backend, display): _X["KeyReleaseMask"]] -def test_a_posted_key_is_addressed_by_keycode_not_by_character(backend, - display): - # X11 has no "type this character" event; the character is Win32's idea - # and is dropped rather than guessed at. +def test_a_character_the_keymap_does_not_bind_falls_back_to_the_keycode(backend, + display): + # X11 has no "type this character" event: the character only chooses a + # key, and with no key bound to it the given keycode is what is sent. backend.post_key(50, keycode=38, character="Z") press = display.window(50).sent[0][0] - assert press.fields["detail"] == 38 + assert (press.fields["detail"], press.fields["state"]) == (38, 0) assert "character" not in press.fields +def _us_keymap(display): + """The 5 key (keycode 14) types ``5`` / ``%``, the z key (52) ``z`` / ``Z``.""" + display.keymap = {14: (0x35, 0x25), 52: (0x7A, 0x5A)} + display.keycodes = {0x35: 14, 0x25: 14, 0x7A: 52, 0x5A: 52} + + +@pytest.mark.parametrize("character, detail, shifted", [ + ("%", 14, True), ("5", 14, False), ("Z", 52, True), ("z", 52, False), +]) +def test_a_character_is_sent_as_its_key_with_shift_when_it_is_the_shifted_level( + backend, display, character, detail, shifted): + # Before, "%" went out as the 5 key with no modifier and typed "5". + _us_keymap(display) + assert backend.post_key(50, keycode=0, character=character) is True + press, release = (event for event, _mask, _p in display.window(50).sent) + expected_state = _X["ShiftMask"] if shifted else 0 + assert (press.fields["detail"], press.fields["state"]) == (detail, expected_state) + assert (release.fields["detail"], release.fields["state"]) == (detail, expected_state) + + +def test_a_character_beyond_latin1_is_looked_up_by_its_unicode_keysym(backend, display): + display.keymap = {60: (0x010020AC, 0)} + display.keycodes = {0x010020AC: 60} + assert backend.post_key(50, keycode=0, character="€") is True + assert display.window(50).sent[0][0].fields["detail"] == 60 + + +def test_a_character_with_no_key_and_no_keycode_sends_nothing(backend, display): + assert backend.post_key(50, keycode=0, character="%") is False + assert display.window(50).sent == [] + + def test_a_posted_key_is_marked_as_propagating(backend, display): # Synthetic events are what XSendEvent delivers; propagate lets the # toolkit that does accept them see it on an ancestor. diff --git a/test/unit_test/headless/test_window_lifecycle_contract.py b/test/unit_test/headless/test_window_lifecycle_contract.py index a93edce52..ed93fc708 100644 --- a/test/unit_test/headless/test_window_lifecycle_contract.py +++ b/test/unit_test/headless/test_window_lifecycle_contract.py @@ -149,6 +149,25 @@ def test_an_unknown_key_name_is_still_refused(monkeypatch): w.post_key_to_window("Editor", "no_such_key") +@pytest.mark.parametrize("name", ["%", "é", "中"]) +def test_a_character_the_table_has_no_key_for_is_posted_as_text(monkeypatch, name): + """Windows' table has no punctuation, so ``"%"`` raised although ``WM_CHAR`` types it.""" + from je_auto_control.wrapper import platform_wrapper + backend = _PostBackend() + monkeypatch.setattr(w, "get_backend", lambda: backend) + monkeypatch.setattr(platform_wrapper, "keyboard_keys_table", {"return": 13}, raising=False) + assert w.post_key_to_window("Editor", name) is True + assert backend.posted == [(11, 0, name)] + + +@windows_only +def test_a_character_beyond_the_bmp_is_posted_as_its_two_utf16_units(queue): + from je_auto_control.windows.window import windows_window_manage as module + assert module.post_key(5, 0, "\U0001F600") is True + assert [(message, w_param) for message, w_param, _l in queue.messages] == [ + (WM_CHAR, 0xD83D), (WM_CHAR, 0xDE00)] + + # --- focus / show / z-order -------------------------------------------------- class _FocusBackend: From e9493af232d46882d1cba2c5b87783af2d4a0891 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Fri, 13 Nov 2026 18:33:36 +0800 Subject: [PATCH 063/161] Record a backtrace when the container test run crashes The image's run passes every test and then segfaults at interpreter exit after Qt's "shared QObject was deleted directly", with nothing else in the log. The Ubuntu jobs on the same PySide6 6.12.0 (Python 3.11 and 3.14) do not; the image is Python 3.12. Run it like those jobs, under gdb through ci_native_diagnostics, with faulthandler kept on through shutdown. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/docker.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 53e8615ca..095ddf2d1 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -68,6 +68,10 @@ jobs: cache-from: type=gha # Mount the repo so pytest can read tests + write the artifact. + # Under gdb through the same runner the pytest-headless jobs use, and + # with faulthandler on for the whole process: a crash after pytest has + # finished (interpreter shutdown) otherwise leaves nothing but + # "Segmentation fault" in the log. - name: Run headless tests under Xvfb run: | docker run --rm \ @@ -76,8 +80,10 @@ jobs: --entrypoint /bin/sh \ autocontrol:ci -c " pip install --no-cache-dir -r dev_requirements.txt && + apt-get update && apt-get install -y --no-install-recommends gdb && xvfb-run -a -s '-screen 0 1280x800x24' \ - python -m pytest -q --tb=short + python scripts/ci_native_diagnostics.py --artifact-dir /tmp/autocontrol-native --native -- \ + python -X faulthandler -m pytest -q --tb=short " - name: Smoke test the entrypoint (rest mode) From e78d968f194ba882165100b2c46d9e8ecb1f9057 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Fri, 13 Nov 2026 18:42:37 +0800 Subject: [PATCH 064/161] Keep the maximized state in saved layouts; restore it only on request A layout saved while a window was maximized held the maximized rectangle and came back as a screen-sized normal window. It now stores the restored rectangle with "maximized": true. Maximizing activates the window on Windows, so restore stays non-activating and re-maximizes only with maximize=True. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++ Progress.md | 2 +- architecture_explore.md | 30 +++---- .../Eng/doc/new_features/v4_features_doc.rst | 9 +- .../Zh/doc/new_features/v4_features_doc.rst | 6 +- docs/updates/2026-11-b.md | 11 +++ docs/updates/README.md | 1 + je_auto_control/actions.pyi | 2 +- .../gui/script_builder/command_schema.py | 6 +- .../utils/executor/action_executor.py | 9 +- .../utils/window_capture/window_capture.py | 61 +++++++++++--- .../windows/window/windows_window_manage.py | 83 ++++++++++++++++++- .../unit_test/headless/test_window_capture.py | 57 +++++++++++++ .../test_window_lifecycle_contract.py | 68 ++++++++++++++- 14 files changed, 309 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4cdf3829..1aec971ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- `save_window_layout` stores a maximized window with `"maximized": true` and its restored + rectangle; it used to store the maximized rectangle, which restored as a screen-sized normal + window. `restore_window_layout(..., maximize=True)` (`AC_restore_window_layout`'s + `maximize`) maximizes those windows again, activating each on Windows; without it nothing is + activated. A custom `mover` receives `maximize=True` for those entries only when it is set. + - `post_key_to_window` (`AC_post_key_to_window`, `ac_post_key_to_window`) accepts any printable character, not only those in the platform's key table: on Windows `"%"` and other punctuation used to raise `unknown key name`, and a character beyond the BMP is now posted diff --git a/Progress.md b/Progress.md index d409a16ae..1ec1e9f60 100644 --- a/Progress.md +++ b/Progress.md @@ -38,8 +38,8 @@ - **舊版存的視窗版面檔要重存**:`save_window_layout` 改存 `GetWindowRect`,舊檔還原會偏右 7 px、縮小 14×7 px。 - **Win32 行為的實測(U-20261113-01,Windows 11、單一 1920×1080 螢幕)只涵蓋自有的原生 `EDIT` 視窗**: `post_key` 每個字只到一次、DWM cloak 過濾與最大化視窗的還原都已驗;還沒驗的:另一個 DPI 的螢幕上的還原(只有一個螢幕)、 + 工作列在左或上時最大化視窗存下的還原矩形(工作區座標換算只有單元測試,U-20261113-05)、 WinUI(新版記事本)/Chromium 等非原生編輯控制項、零面積過濾(有標題列的視窗被系統夾到 202×56,到不了零)。 - `TODO`:版面檔不存最大化狀態,最大化時存下的視窗還原成螢幕大小的一般視窗;要恢復最大化就得啟用視窗,須先決定可否。 - **X11/Wayland**:大寫與 Shift 標點的判斷假設 `keysym_to_keycode` 把大寫字母對到小寫的 keycode,沒有對著 X server 跑過; `post_key_to_window` 依 keymap 的 Shift 層加 `ShiftMask`(U-20261113-04)也只對 stub keymap 測過。 diff --git a/architecture_explore.md b/architecture_explore.md index e70b3f938..8af06fbc1 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,730 | +| 程式碼總行數 | 233,851 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -202,7 +202,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.3 平台後端 -#### Windows(`windows/`,24 檔/2,282 行) +#### Windows(`windows/`,24 檔/2,363 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -214,7 +214,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `record/win32_input_hook.py` | 258 | 單一一組低階鍵鼠 hook(`WH_KEYBOARD_LL`/`WH_MOUSE_LL`)+訊息迴圈,產生帶時間戳的事件時間軸;停止時以 `PostThreadMessageW(WM_QUIT)` 收掉執行緒,不會每錄一次就漏一條。 | | `record/win32_record.py` | 41 | 把 `win32_input_hook` 的時間軸轉成 action list(含按鍵放開、滾輪與間隔);整形本體與 macOS 共用 `utils/input_macro/recorder_base.py`。 | | `screen/win32_screen.py` | 171 | 螢幕尺寸與像素讀取。**每支 Win32 函式都明寫 argtypes/restype**(HDC 是指標寬度,走預設的 c_int 會截斷,錯誤會沉默地擴散到 GetPixel/ReleaseDC),並持有自己的 user32/gdi32 handle。import 時呼叫 `SetProcessDPIAware()`——**行程層級且不可還原**,實體↔邏輯座標換算請走 `utils/monitor_layout`。 | -| `window/windows_window_manage.py` | 485 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | +| `window/windows_window_manage.py` | 566 | 視窗列舉/聚焦/關閉/最小化/幾何/所屬行程 PID/投遞式輸入(`auto_control_window` 的實作)。**每支 Win32 函式都明寫 argtypes/restype**,並持有自己的 user32 handle,避免把原型外溢到別的模組;hwnd 一律是 int。 | | `message/window_message.py` | 97 | 直接對視窗送 `WM_*` 訊息(背景輸入)。 | | `interception/_dll.py` | 232 | `interception.dll` 的延遲 ctypes 載入與結構定義。 | | `interception/keyboard.py` | 70 | 經 Interception 驅動的鍵盤輸入(繞過部分反自動化偵測)。 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,543 行。 +> 25 個套件、約 19,546 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -304,7 +304,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,749 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,752 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | | `utils/input_macro/` | 477 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | @@ -706,7 +706,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.16 系統、視窗與剪貼簿 -> 16 個套件、約 2,710 行。 +> 16 個套件、約 2,745 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -722,7 +722,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/shell_open/` | 99 | Open files with their registered applications and delegate URLs to WebRunner. | | `utils/system_volume/` | 212 | 讀取與控制系統主音量與靜音狀態 | | `utils/trash/` | 93 | 把檔案移到系統資源回收筒(可復原刪除) | -| `utils/window_capture/` | 379 | 逐視窗截圖、視窗版面儲存/還原、貼齊與排列 | +| `utils/window_capture/` | 414 | 逐視窗截圖、視窗版面儲存/還原、貼齊與排列 | | `utils/window_geometry/` | 87 | 視窗客戶區幾何(外框內縮、client→screen 對映) | | `utils/window_layout/` | 137 | 視窗拼貼/版面規劃器(左右半、四象限、網格、層疊) | | `utils/window_zorder/` | 77 | 視窗 z 序控制(最上層/移到最前/送到最後) | @@ -744,11 +744,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | | `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,749 行)— 執行核心 +#### `utils/executor/`(10,752 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `action_executor.py` | 8,676 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | +| `action_executor.py` | 8,679 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | | `flow_control.py` | 726 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | | `flow_data_commands.py` | 272 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | | `action_schema.py` | 225 | action list 的結構驗證:形狀、參數型別、未知指令拒絕。單一走訪同時支援兩種消費方式:`validate_actions()` 遇到第一個問題就拋、`unknown_command_names()` 收齊全部不認得的名字(REST `/execute` 用它回 400)。 | @@ -1341,7 +1341,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | screenshot | `_screenshot_tab.py` | 179 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 159 | 樣板裁切、定位、定位全部、定位並點擊。 | | record | `_record_tab.py` | 162 | 錄製/停止/回放/存檔/載入。 | -| script_builder | `script_builder/` | 6,909 | **視覺化腳本編輯器**:`command_schema.py`(5,549 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | +| script_builder | `script_builder/` | 6,911 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | | flow_editor | `flow_editor/` | 490 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | | script | `_script_tab.py` | 183 | 載入/執行單檔或整個目錄、內建編輯器執行。 | | recording_editor | `recording_editor_tab.py` | 262 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | @@ -1533,15 +1533,15 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 150 | 40,657 | +| `gui/` | 150 | 40,659 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | -| `utils/executor/` | 11 | 10,749 | +| `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,060 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,374 | | `wrapper/` | 25 | 6,044 | -| `windows/` | 24 | 2,282 | +| `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | @@ -1553,8 +1553,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,113 | -| **總計** | **1,515** | **232,985** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,148 | +| **總計** | **1,515** | **233,106** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v4_features_doc.rst b/docs/source/Eng/doc/new_features/v4_features_doc.rst index 98042d177..7685c4387 100644 --- a/docs/source/Eng/doc/new_features/v4_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v4_features_doc.rst @@ -124,9 +124,12 @@ Window management visible frame instead and restores 7 px to the right and 14 x 7 px smaller; save it again. A window that is maximized when the layout is restored is un-maximized first, without being activated, so it ends at the saved size - instead of keeping the maximized flag. A window saved while maximized comes - back as a normal window of the screen's size: the maximized state itself is - not stored. ``AC_save_window_layout`` / ``AC_restore_window_layout``. + instead of keeping the maximized flag. A window saved while maximized is + stored with ``"maximized": true`` and its restored rectangle, and by default + comes back as a normal window at that rectangle. ``restore_window_layout(path, + maximize=True)`` maximizes those windows again, which on Windows activates + each one; nothing is activated without it. + ``AC_save_window_layout`` / ``AC_restore_window_layout`` (``maximize``). * **Snap / tile** — ``snap_window(title, "left")`` moves a window to a half (left / right / top / bottom), a quarter (the four corners), or ``"max"`` of the primary monitor's *work area* — the screen minus the diff --git a/docs/source/Zh/doc/new_features/v4_features_doc.rst b/docs/source/Zh/doc/new_features/v4_features_doc.rst index 8d638837e..92c565cd9 100644 --- a/docs/source/Zh/doc/new_features/v4_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v4_features_doc.rst @@ -103,8 +103,10 @@ Builder 項目。視覺與視窗功能的 geometry / IO 操作皆可注入,因 ``GetWindowRect``),所以視窗會回到原本的位置。舊版存的版面檔記的是可見 外框,還原會右移 7 px、縮小 14 x 7 px,請重新儲存。還原時已最大化的視窗會先 取消最大化(不啟用它),因此會停在存下的大小,而不是保留最大化狀態。最大化時存下 - 的視窗會以螢幕大小的一般視窗回來:最大化狀態本身沒有存。 - ``AC_save_window_layout`` / ``AC_restore_window_layout``。 + 的視窗會記為 ``"maximized": true`` 並存它還原後的矩形,預設以該矩形的一般視窗 + 回來;``restore_window_layout(path, maximize=True)`` 會再把它們最大化,在 Windows + 上會逐一啟用這些視窗,不加這個選項就不會啟用任何視窗。 + ``AC_save_window_layout`` / ``AC_restore_window_layout``(``maximize``)。 * **貼齊 / 平鋪** — ``snap_window(title, "left")`` 把視窗移到主螢幕\ *工作區*\ (螢幕扣掉工作列)的一半(left / right / top / bottom)、四分之一(四個角) 或 ``"max"``,貼齊後視窗底部不會被工作列蓋住。``arrange_grid`` 與 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 2f688151a..7858a267a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -259,3 +259,14 @@ - **Tests:** `test_window_lifecycle_contract.py` +4 (`%`, `é`, `中` posted as text with keycode 0; an astral character as two units), `test_window_backend_x11.py` +6 net (Shift for `%` / `Z`, none for `5` / `z`, a Unicode keysym, nothing sent for an unbound character with no keycode; the old "character is dropped" test now checks the fallback). `_xlib_stub.py` gained `keycode_to_keysym`. Window and X11 test files: 266 passed, 1 skipped. - **Files:** `wrapper/auto_control_window.py`, `windows/window/windows_window_manage.py`, `wrapper/window_backends/x11_backend.py`, the tests and stub, `docs/CAPABILITY_MATRIX.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** X11 behaviour against a real X server (`Progress.md` › X11/Wayland). + +## U-20261113-05 · 2026-11-13 · Saved layouts keep the maximized state; restoring it is opt-in · #done #windows + +- **What:** Closes the `Progress.md` › 桌面行為驗收 TODO from U-20261113-01: a layout saved while a window was maximized stored the maximized rectangle (-11,-11 1942×1030 there) and restored it as a screen-sized normal window. Re-maximizing a window on Windows always activates it, so the maintainer decided on 2026-11-13: store the state, keep restore non-activating by default, and make re-maximizing an explicit option. +- **Save:** `save_window_layout` writes `"maximized": true` for a maximized window, with its *restored* rectangle: `WINDOWPLACEMENT.rcNormalPosition`, converted from workspace to screen coordinates by the window's monitor's work-area offset (none for a `WS_EX_TOOLWINDOW`). The key is written only when true, so an older file, and a normal window, read as not maximized. +- **Restore:** by default the window is moved to that rectangle (`move_window` already un-maximizes with `SW_SHOWNOACTIVATE`) and stays normal. `restore_window_layout(..., maximize=True)` then maximizes those entries' windows through the new `windows_window_manage.maximize_window` (`ShowWindow(SW_MAXIMIZE)` + the foreground request `show_window` already makes), and counts one as restored only when it is maximized afterwards. A custom `mover` is called with `maximize=True` only for those entries and only when the option is set, so five-argument movers keep working without it. Surfaces: `AC_restore_window_layout`'s `maximize`, the Script Builder field, `actions.pyi` (edited by hand: regenerating on Python 3.14 rewrites every `Optional[...]` as `X | None`). +- **New Win32 helpers:** `is_window_maximized`, `get_normal_window_rect`, `maximize_window` in `windows/window/windows_window_manage.py`, with explicit prototypes (`HMONITOR` is pointer-width). +- **Native check (self-owned fixture of U-20261113-01, this machine):** saved at 150,160 600×300 then maximized: the entry was 150,160 600×300 with `maximized: true`. Default restore onto the maximized window: 150,160–750,460, not maximized, foreground unchanged. `maximize=True`: maximized, count 1; Windows refused the foreground request (the fixture was not brought forward) but the window was maximized, and `SW_RESTORE` afterwards returned it to 150,160 600×300. The workspace-offset path is only unit-tested: the taskbar here is at the bottom, where workspace and screen coordinates agree. +- **Tests:** `test_window_capture.py` +5 (saved entry shape, default restore passes no option, `maximize=True` only for maximized entries, a five-argument mover still works, the executor passes `maximize` through), `test_window_lifecycle_contract.py` +7 (a maximized window saved at its restored rectangle; workspace→screen for taskbar left / top / bottom and a tool window; the mover maximizes only when asked). Window, layout, audit, contract and stub tests: 173 passed. +- **Files:** `utils/window_capture/window_capture.py`, `windows/window/windows_window_manage.py`, `utils/executor/action_executor.py`, `gui/script_builder/command_schema.py`, `actions.pyi`, the two tests, both `v4_features_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** restore on a second monitor with another DPI and with a taskbar on the left or top (`Progress.md` › 桌面行為驗收, one screen here). diff --git a/docs/updates/README.md b/docs/updates/README.md index 2290c0634..0880d210e 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261113-05 | 2026-11-13 | Saved layouts keep the maximized state; restoring it is opt-in | #done #windows | [2026-11-b](2026-11-b.md) | | U-20261113-04 | 2026-11-13 | `post_key_to_window` takes any printable character | #done #windows #x11 | [2026-11-b](2026-11-b.md) | | U-20261113-03 | 2026-11-13 | PR #552: container libEGL and three asyncio cancellation findings | #incident #ci #remote | [2026-11-b](2026-11-b.md) | | U-20261113-02 | 2026-11-13 | macos-15 grants what the capability gate expects | #done #macos #ci | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/actions.pyi b/je_auto_control/actions.pyi index 90df4a412..bacab8c78 100644 --- a/je_auto_control/actions.pyi +++ b/je_auto_control/actions.pyi @@ -2946,7 +2946,7 @@ def AC_rest_api_status() -> Dict[str, Any]: def AC_rest_api_stop() -> Dict[str, Any]: ... -def AC_restore_window_layout(layout: Union[List[Dict[str, Any]], str]) -> Dict[str, Any]: +def AC_restore_window_layout(layout: Union[List[Dict[str, Any]], str], maximize: bool = ...) -> Dict[str, Any]: """Executor adapter: move windows back to a saved layout (list or path).""" def AC_retry_after(response: Any) -> Dict[str, Any]: diff --git a/je_auto_control/gui/script_builder/command_schema.py b/je_auto_control/gui/script_builder/command_schema.py index dd70ccdac..69c7643a9 100644 --- a/je_auto_control/gui/script_builder/command_schema.py +++ b/je_auto_control/gui/script_builder/command_schema.py @@ -1561,8 +1561,10 @@ def _add_window_specs(specs: List[CommandSpec]) -> None: ), CommandSpec( "AC_restore_window_layout", "Window", "Restore Window Layout", - fields=(FieldSpec("layout", FieldType.FILE_PATH),), - description="Move windows back to a saved layout file.", + fields=(FieldSpec("layout", FieldType.FILE_PATH), + FieldSpec("maximize", FieldType.BOOL, optional=True, default=False)), + description="Move windows back to a saved layout file; maximize re-maximizes " + "windows saved maximized, activating each.", ), CommandSpec( "AC_tile_rect", "Window", "Tile Rect (compute)", diff --git a/je_auto_control/utils/executor/action_executor.py b/je_auto_control/utils/executor/action_executor.py index 5146dd515..8a2592e54 100644 --- a/je_auto_control/utils/executor/action_executor.py +++ b/je_auto_control/utils/executor/action_executor.py @@ -2462,11 +2462,14 @@ def _save_window_layout(path: Optional[str] = None) -> Dict[str, Any]: return {"count": len(layout), "path": path, "layout": layout} -def _restore_window_layout(layout: List[Dict[str, Any]] | str +def _restore_window_layout(layout: List[Dict[str, Any]] | str, maximize: bool = False ) -> Dict[str, Any]: - """Executor adapter: move windows back to a saved layout (list or path).""" + """Executor adapter: move windows back to a saved layout (list or path). + + ``maximize`` re-maximizes windows saved maximized, which activates each one. + """ from je_auto_control.utils.window_capture import restore_window_layout - return {"restored": restore_window_layout(layout)} + return {"restored": restore_window_layout(layout, maximize=bool(maximize))} def _region_color_stats(region: Optional[List[int] | str] = None, diff --git a/je_auto_control/utils/window_capture/window_capture.py b/je_auto_control/utils/window_capture/window_capture.py index c978cd62b..08cdd4379 100644 --- a/je_auto_control/utils/window_capture/window_capture.py +++ b/je_auto_control/utils/window_capture/window_capture.py @@ -29,6 +29,8 @@ GeometryProvider = Callable[[str], Optional[Rect]] WindowLister = Callable[[], List[Tuple[int, str]]] WindowMover = Callable[[str, int, int, int, int], bool] +#: A :data:`WindowMover` that also takes ``maximize=True`` (only ever passed for a maximized entry). +LayoutMover = Callable[..., bool] SizeProvider = Callable[[], Tuple[int, int]] AreaProvider = Callable[[], Tuple[int, int, int, int]] @@ -148,17 +150,24 @@ def save_window_layout(path: Optional[str | Path] = None, *, saving and restoring leaves a window exactly where it was. A layout file written before this held the visible frame instead and still restores 7 px off; save it again. + + A maximized window is saved with ``"maximized": true`` and its *restored* + rectangle, not the screen-sized one it has while maximized; an entry + without the key (every entry in an older file) is a normal window. """ layout: List[Dict[str, Any]] = [] for hwnd, title in (lister or _default_lister)(): # By handle, which the lister already has: looking the window up # again by title substring read another window's geometry whenever # one title contained another or two windows shared a title. - rect = geometry(title) if geometry is not None else _handle_geometry(hwnd) + rect, maximized = (geometry(title), False) if geometry is not None else _handle_layout(hwnd) if rect is None: continue - layout.append({"title": title, "x": rect[0], "y": rect[1], - "width": rect[2], "height": rect[3]}) + entry: Dict[str, Any] = {"title": title, "x": rect[0], "y": rect[1], + "width": rect[2], "height": rect[3]} + if maximized: + entry["maximized"] = True + layout.append(entry) if path is not None: Path(path).write_text(json.dumps(layout, indent=2), encoding="utf-8") return layout @@ -179,12 +188,27 @@ def _default_mover(title: str, x: int, y: int, return bool(wm.move_window(int(hit[0]), x, y, width, height)) -def _handle_geometry(hwnd: int) -> Optional[Rect]: - """The rectangle a layout stores for ``hwnd``: the one the mover takes.""" - return _win32_window_rect(int(hwnd)) if sys.platform == "win32" else None +def _handle_layout(hwnd: int) -> Tuple[Optional[Rect], bool]: + """What a layout stores for ``hwnd``: the rectangle the mover takes, and whether it is maximized. + For a maximized window that is its restored rectangle: ``GetWindowRect`` + gives the maximized one, which restored as a screen-sized normal window. + """ + if sys.platform != "win32": + return None, False + import ctypes + rect = _win32_window_rect(int(hwnd)) + if rect is None or not ctypes.windll.user32.IsZoomed(int(hwnd)): # type: ignore[attr-defined] # reason: win32-only ctypes + return rect, False + from je_auto_control.windows.window import windows_window_manage as wm + normal = wm.get_normal_window_rect(int(hwnd)) + if normal is None: + return rect, True + left, top, right, bottom = normal + return (left, top, right - left, bottom - top), True -def _exact_title_mover() -> WindowMover: + +def _exact_title_mover() -> LayoutMover: """A mover that gives each saved entry a different window of that exact title. It matched by title substring, so every entry whose title another @@ -193,7 +217,7 @@ def _exact_title_mover() -> WindowMover: """ used: set = set() - def move(title: str, x: int, y: int, width: int, height: int) -> bool: + def move(title: str, x: int, y: int, width: int, height: int, maximize: bool = False) -> bool: if sys.platform != "win32": return False from je_auto_control.wrapper.auto_control_window import list_windows @@ -201,18 +225,25 @@ def move(title: str, x: int, y: int, width: int, height: int) -> bool: for hwnd, name in list_windows(titled_only=True): if name == title and hwnd not in used: used.add(hwnd) - return bool(wm.move_window(int(hwnd), x, y, width, height)) + moved = bool(wm.move_window(int(hwnd), x, y, width, height)) + return moved and (not maximize or wm.maximize_window(int(hwnd))) return False return move def restore_window_layout(layout: List[Dict[str, Any]] | str | Path, *, - mover: Optional[WindowMover] = None) -> int: + mover: Optional[LayoutMover] = None, maximize: bool = False) -> int: """Move each window back to its saved geometry; return the count moved. ``layout`` is a list from :func:`save_window_layout`, or a path to the JSON it wrote. ``mover`` is injectable for tests. + + Nothing is activated by default: a window saved maximized is put back at + its restored rectangle as a normal window. With ``maximize=True`` it is + maximized again after the move, which on Windows also activates it, one + window at a time -- there is no maximize that leaves the foreground alone. + A ``mover`` is then called with ``maximize=True`` for those entries. """ entries: List[Dict[str, Any]] = ( json.loads(Path(layout).read_text(encoding="utf-8")) @@ -222,9 +253,13 @@ def restore_window_layout(layout: List[Dict[str, Any]] | str | Path, *, restored = 0 for entry in entries: title = entry.get("title") - if title and move(title, int(entry["x"]), int(entry["y"]), - int(entry["width"]), int(entry["height"])): - restored += 1 + if not title: + continue + rect = (int(entry["x"]), int(entry["y"]), int(entry["width"]), int(entry["height"])) + if maximize and entry.get("maximized"): + restored += bool(move(title, *rect, maximize=True)) + else: + restored += bool(move(title, *rect)) return restored diff --git a/je_auto_control/windows/window/windows_window_manage.py b/je_auto_control/windows/window/windows_window_manage.py index 93ed284d4..b77d8c744 100644 --- a/je_auto_control/windows/window/windows_window_manage.py +++ b/je_auto_control/windows/window/windows_window_manage.py @@ -71,6 +71,29 @@ _user32.IsWindow.restype = wintypes.BOOL _user32.MapVirtualKeyW.argtypes = [wintypes.UINT, wintypes.UINT] _user32.MapVirtualKeyW.restype = wintypes.UINT +_user32.IsZoomed.argtypes = [wintypes.HWND] +_user32.IsZoomed.restype = wintypes.BOOL + + +class _WindowPlacement(ctypes.Structure): + _fields_ = [("length", wintypes.UINT), ("flags", wintypes.UINT), ("showCmd", wintypes.UINT), + ("ptMinPosition", wintypes.POINT), ("ptMaxPosition", wintypes.POINT), + ("rcNormalPosition", wintypes.RECT)] + + +class _MonitorInfo(ctypes.Structure): + _fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT), + ("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD)] + + +_user32.GetWindowPlacement.argtypes = [wintypes.HWND, ctypes.POINTER(_WindowPlacement)] +_user32.GetWindowPlacement.restype = wintypes.BOOL +_user32.MonitorFromWindow.argtypes = [wintypes.HWND, wintypes.DWORD] +_user32.MonitorFromWindow.restype = wintypes.HMONITOR +_user32.GetMonitorInfoW.argtypes = [wintypes.HMONITOR, ctypes.POINTER(_MonitorInfo)] +_user32.GetMonitorInfoW.restype = wintypes.BOOL +_user32.GetWindowLongW.argtypes = [wintypes.HWND, ctypes.c_int] +_user32.GetWindowLongW.restype = wintypes.LONG def _load_dwmapi() -> Any: @@ -94,6 +117,7 @@ def _load_dwmapi() -> Any: WM_CLOSE = 0x0010 SW_RESTORE = 9 _SW_SHOWNOACTIVATE = 4 +_SW_MAXIMIZE = 3 _DWMWA_CLOAKED = 14 @@ -189,6 +213,63 @@ def get_window_rect(hwnd: int) -> Optional[Tuple[int, int, int, int]]: return (int(rect.left), int(rect.top), int(rect.right), int(rect.bottom)) +def is_window_maximized(hwnd: int) -> bool: + """ + 視窗是否最大化 + Whether the window is maximized + """ + return bool(_user32.IsZoomed(int(hwnd))) + + +_MONITOR_DEFAULTTONEAREST = 2 +_GWL_EXSTYLE = -20 +_WS_EX_TOOLWINDOW = 0x00000080 + + +def get_normal_window_rect(hwnd: int) -> Optional[Tuple[int, int, int, int]]: + """ + 視窗「還原」時的矩形(螢幕座標),查不到回 None + The rectangle the window has when restored, in screen coordinates; None if unavailable + + 最大化或最小化的視窗,``GetWindowRect`` 給的是目前的樣子;還原後的大小只在 + ``WINDOWPLACEMENT.rcNormalPosition``。那是工作區座標(扣掉工作列等),除了 + 工具視窗以外都要加回所在螢幕工作區相對螢幕的位移。 + + For a maximized window ``GetWindowRect`` is the maximized rectangle; the + restored one is only in ``WINDOWPLACEMENT.rcNormalPosition``, which is in + workspace coordinates (the work area's origin, past a taskbar on the top or + left) for any window but a tool window, so the offset of its monitor's work + area is added back. + + :return: (left, top, right, bottom) + """ + placement = _WindowPlacement() + placement.length = ctypes.sizeof(_WindowPlacement) + if not _user32.GetWindowPlacement(int(hwnd), byref(placement)): + return None + normal = placement.rcNormalPosition + dx = dy = 0 + if not _user32.GetWindowLongW(int(hwnd), _GWL_EXSTYLE) & _WS_EX_TOOLWINDOW: + info = _MonitorInfo() + info.cbSize = ctypes.sizeof(_MonitorInfo) + monitor = _user32.MonitorFromWindow(int(hwnd), _MONITOR_DEFAULTTONEAREST) + if monitor and _user32.GetMonitorInfoW(monitor, byref(info)): + dx = info.rcWork.left - info.rcMonitor.left + dy = info.rcWork.top - info.rcMonitor.top + return (int(normal.left) + dx, int(normal.top) + dy, int(normal.right) + dx, int(normal.bottom) + dy) + + +def maximize_window(hwnd: int) -> bool: + """ + 最大化視窗;會啟用它(Windows 沒有不啟用的最大化)。回傳之後是否為最大化 + Maximize a window, which activates it (Windows has no non-activating maximize) + + :return: whether the window is maximized afterwards + """ + show_window(int(hwnd), _SW_MAXIMIZE) + return is_window_maximized(hwnd) + + def get_window_process_id(hwnd: int) -> int: """ 視窗所屬行程的 PID,查不到回 0 @@ -318,7 +399,7 @@ def move_window(hwnd: int, x: int, y: int, width: int, height: int, therefore restored first with ``SW_SHOWNOACTIVATE``, which does not take the foreground. """ - if _user32.IsZoomed(int(hwnd)): + if is_window_maximized(hwnd): _user32.ShowWindow(int(hwnd), _SW_SHOWNOACTIVATE) return bool(_user32.MoveWindow(int(hwnd), int(x), int(y), int(width), int(height), diff --git a/test/unit_test/headless/test_window_capture.py b/test/unit_test/headless/test_window_capture.py index c9029249e..9a335495c 100644 --- a/test/unit_test/headless/test_window_capture.py +++ b/test/unit_test/headless/test_window_capture.py @@ -149,3 +149,60 @@ def test_saved_entries_are_all_restorable(): layout, mover=lambda title, *rect: moved.append(title) or True) assert restored == len(layout) == 2 assert moved == ["Editor", "Browser"] + + +# --- maximized windows in a layout ------------------------------------------- + +def test_a_maximized_window_is_saved_with_its_restored_rectangle(monkeypatch): + from je_auto_control.utils.window_capture import window_capture as module + states = {1: ((150, 160, 600, 300), True), 2: ((0, 0, 80, 40), False)} + monkeypatch.setattr(module, "_handle_layout", lambda hwnd: states[hwnd]) + layout = save_window_layout(lister=lambda: [(1, "Max"), (2, "Normal")]) + assert layout == [ + {"title": "Max", "x": 150, "y": 160, "width": 600, "height": 300, "maximized": True}, + {"title": "Normal", "x": 0, "y": 0, "width": 80, "height": 40}, + ] + + +def _recording_mover(calls): + def mover(title, x, y, width, height, **options): + calls.append((title, (x, y, width, height), options)) + return True + return mover + + +_MAXIMIZED_LAYOUT = [ + {"title": "Max", "x": 1, "y": 2, "width": 3, "height": 4, "maximized": True}, + {"title": "Normal", "x": 5, "y": 6, "width": 7, "height": 8}, +] + + +def test_restore_leaves_a_maximized_entry_normal_unless_asked(): + """Maximizing activates the window, so it is never done without ``maximize=True``.""" + calls = [] + assert restore_window_layout(_MAXIMIZED_LAYOUT, mover=_recording_mover(calls)) == 2 + assert [options for _title, _rect, options in calls] == [{}, {}] + + +def test_restore_with_maximize_asks_only_for_the_entries_saved_maximized(): + calls = [] + assert restore_window_layout(_MAXIMIZED_LAYOUT, mover=_recording_mover(calls), maximize=True) == 2 + assert calls == [("Max", (1, 2, 3, 4), {"maximize": True}), ("Normal", (5, 6, 7, 8), {})] + + +def test_a_five_argument_mover_still_restores_a_layout_without_maximize(): + """Movers written before the option keep working as long as it is not used.""" + moved = [] + count = restore_window_layout(_MAXIMIZED_LAYOUT, + mover=lambda title, x, y, w, h: moved.append(title) or True) + assert (count, moved) == (2, ["Max", "Normal"]) + + +def test_the_executor_command_passes_maximize_through(monkeypatch): + from je_auto_control.utils import window_capture + from je_auto_control.utils.executor import action_executor + seen = {} + monkeypatch.setattr(window_capture, "restore_window_layout", + lambda layout, maximize=False: seen.update(layout=layout, maximize=maximize) or 1) + assert action_executor._restore_window_layout([], maximize=True) == {"restored": 1} + assert seen == {"layout": [], "maximize": True} diff --git a/test/unit_test/headless/test_window_lifecycle_contract.py b/test/unit_test/headless/test_window_lifecycle_contract.py index ed93fc708..7a57e734e 100644 --- a/test/unit_test/headless/test_window_lifecycle_contract.py +++ b/test/unit_test/headless/test_window_lifecycle_contract.py @@ -333,6 +333,7 @@ class _Window: def __init__(self, x, y, width, height): self.rect = (x, y, width, height) + self.maximized = 0 def win32(self): """``ctypes.windll`` reading this window: the DWM frame is inside the rect.""" @@ -350,7 +351,8 @@ def frame_bounds(_hwnd, _attribute, reference, _size): return 0 return types.SimpleNamespace( - user32=types.SimpleNamespace(IsIconic=lambda hwnd: 0, GetWindowRect=get_window_rect), + user32=types.SimpleNamespace(IsIconic=lambda hwnd: 0, IsZoomed=lambda hwnd: self.maximized, + GetWindowRect=get_window_rect), dwmapi=types.SimpleNamespace(DwmGetWindowAttribute=frame_bounds)) @@ -377,6 +379,70 @@ def test_a_window_capture_still_takes_the_visible_frame(monkeypatch): assert window_capture._win32_window_rect(1) == (100, 50, 800, 600) +@windows_only +def test_a_maximized_window_is_saved_at_its_restored_rectangle(monkeypatch): + """Saved maximized, the layout held the screen-sized rectangle and restored it as a normal window.""" + from je_auto_control.windows.window import windows_window_manage as module + window = _Window(-11, -11, 1942, 1030) + window.maximized = 1 + monkeypatch.setattr(ctypes, "windll", window.win32()) + monkeypatch.setattr(module, "get_normal_window_rect", lambda hwnd: (150, 160, 750, 460)) + assert window_capture.save_window_layout(lister=lambda: [(1, "Editor")]) == [ + {"title": "Editor", "x": 150, "y": 160, "width": 600, "height": 300, "maximized": True}] + + +class _Placement: + """``user32`` as far as ``get_normal_window_rect`` uses it.""" + + def __init__(self, normal, work_offset, tool_window=False): + self.normal, self.work_offset, self.tool_window = normal, work_offset, tool_window + + def GetWindowPlacement(self, hwnd, reference): # noqa: N802 # reason: Win32 name + rect = reference._obj.rcNormalPosition + rect.left, rect.top, rect.right, rect.bottom = self.normal + return 1 + + def GetWindowLongW(self, hwnd, index): # noqa: N802 # reason: Win32 name + return 0x80 if self.tool_window else 0 + + def MonitorFromWindow(self, hwnd, flags): # noqa: N802 # reason: Win32 name + return 77 + + def GetMonitorInfoW(self, monitor, reference): # noqa: N802 # reason: Win32 name + info = reference._obj + info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right, info.rcMonitor.bottom = 0, 0, 1920, 1080 + dx, dy = self.work_offset + info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom = dx, dy, 1920, 1080 + return 1 + + +@windows_only +@pytest.mark.parametrize("work_offset, tool_window, expected", [ + ((0, 0), False, (100, 50, 900, 650)), # taskbar at the bottom: workspace == screen + ((48, 0), False, (148, 50, 948, 650)), # taskbar on the left: add the work area's offset + ((0, 40), False, (100, 90, 900, 690)), # taskbar on top + ((48, 0), True, (100, 50, 900, 650)), # a tool window's placement is already in screen coordinates +]) +def test_the_restored_rectangle_is_converted_from_workspace_coordinates(monkeypatch, work_offset, tool_window, + expected): + from je_auto_control.windows.window import windows_window_manage as module + monkeypatch.setattr(module, "_user32", _Placement((100, 50, 900, 650), work_offset, tool_window)) + assert module.get_normal_window_rect(5) == expected + + +@windows_only +@pytest.mark.parametrize("maximize, expected", [(False, ["move"]), (True, ["move", "maximize"])]) +def test_the_layout_mover_maximizes_only_when_asked(monkeypatch, maximize, expected): + from je_auto_control.windows.window import windows_window_manage as module + calls = [] + monkeypatch.setattr(w, "list_windows", lambda titled_only=True: [(11, "Editor")]) + monkeypatch.setattr(module, "move_window", lambda *args: calls.append("move") or True) + monkeypatch.setattr(module, "maximize_window", lambda hwnd: calls.append("maximize") or True) + move = window_capture._exact_title_mover() + assert move("Editor", 1, 2, 3, 4, maximize=maximize) is True + assert calls == expected + + @windows_only def test_a_minimised_window_is_not_saved(monkeypatch): fake = _Window(-32000, -32000, 160, 28).win32() From 1d372dba6d0415645cdf990c0ba72c9a89a91ce4 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 02:38:16 +0800 Subject: [PATCH 065/161] Fix the layout regressions CI caught; record the container crash Reading IsZoomed through ctypes.windll broke the Linux squares that fake sys.platform, so it now goes through a seam the tests stub. The executor read the maximize flag with bool(), which turns "false" into True; it uses the shared flag parser like every other adapter. The duplicate-title restore test only passed when an earlier test had imported the Windows window package, so it stands one in itself. The container job's intermittent PySide6 6.12 segfault on Python 3.12 is recorded in Progress.md with the options that need a decision, and the test step runs pytest verbosely so a crash names its test. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/docker.yml | 4 ++-- Progress.md | 13 +++++++++++++ architecture_explore.md | 10 +++++----- docs/updates/2026-11-b.md | 9 +++++++++ docs/updates/README.md | 1 + je_auto_control/utils/executor/action_executor.py | 2 +- .../utils/window_capture/window_capture.py | 9 +++++++-- test/unit_test/headless/test_a11y_window_audit.py | 11 +++++++++-- 8 files changed, 47 insertions(+), 12 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 095ddf2d1..ff125e613 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -71,7 +71,7 @@ jobs: # Under gdb through the same runner the pytest-headless jobs use, and # with faulthandler on for the whole process: a crash after pytest has # finished (interpreter shutdown) otherwise leaves nothing but - # "Segmentation fault" in the log. + # "Segmentation fault" in the log. -v so a crash mid-suite names its test. - name: Run headless tests under Xvfb run: | docker run --rm \ @@ -83,7 +83,7 @@ jobs: apt-get update && apt-get install -y --no-install-recommends gdb && xvfb-run -a -s '-screen 0 1280x800x24' \ python scripts/ci_native_diagnostics.py --artifact-dir /tmp/autocontrol-native --native -- \ - python -X faulthandler -m pytest -q --tb=short + python -X faulthandler -m pytest -v --tb=short " - name: Smoke test the entrypoint (rest mode) diff --git a/Progress.md b/Progress.md index 1ec1e9f60..306daddee 100644 --- a/Progress.md +++ b/Progress.md @@ -208,6 +208,19 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD --- +## PySide6 6.12 在容器(Python 3.12)的 headless 測試間歇 segfault + +`TODO` — `docker.yml` 的「Headless pytest inside the image」在 PySide6 6.12.0 上 4 次跑 3 次 SIGSEGV(U-20261114-01)。 +同一個 6.12.0 在 Ubuntu 3.11/3.14 的 pytest-headless(也在 gdb 下)都沒有;Windows 本機 3.14 也沒有。 +- 兩次在測試全部跑完後的直譯器結束:`Py_FinalizeEx` → `PySide::runCleanupFunctions` → `destroyQCoreApplication` + → `BindingManager::visitAllPyObjects` → `QObject::~QObject`,前一行是 Qt 的 `shared QObject was deleted directly`。 +- 一次在測試中段(約 46%)主執行緒的 `Shiboken::BindingManager::runDeletionInMainThread()` → QtWidgets。 +- 還不知道:是 Python 3.12 本身還是映像(slim、`dev_requirements.txt` 的套件組合)造成;是哪個測試留下了被兩邊刪除的物件。 + 上游查無相同回報。`docker.yml` 現在以 gdb 跑、`-X faulthandler`、`-v`,下次中段崩潰會有測試名稱。 +- 可選的處置(須維護者決定):繼續定位;容器暫時固定 PySide6 6.11.2;或把映像換成 3.11/3.14。 + +--- + ## Agent 電腦接管與任務自動化 `WIP` — **依使用者恢復目標繼續交付;個別原生/真機/24 小時驗收仍暫緩。** diff --git a/architecture_explore.md b/architecture_explore.md index 8af06fbc1..2cacb3c66 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,851 | +| 程式碼總行數 | 233,856 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -706,7 +706,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.16 系統、視窗與剪貼簿 -> 16 個套件、約 2,745 行。 +> 16 個套件、約 2,750 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -722,7 +722,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/shell_open/` | 99 | Open files with their registered applications and delegate URLs to WebRunner. | | `utils/system_volume/` | 212 | 讀取與控制系統主音量與靜音狀態 | | `utils/trash/` | 93 | 把檔案移到系統資源回收筒(可復原刪除) | -| `utils/window_capture/` | 414 | 逐視窗截圖、視窗版面儲存/還原、貼齊與排列 | +| `utils/window_capture/` | 419 | 逐視窗截圖、視窗版面儲存/還原、貼齊與排列 | | `utils/window_geometry/` | 87 | 視窗客戶區幾何(外框內縮、client→screen 對映) | | `utils/window_layout/` | 137 | 視窗拼貼/版面規劃器(左右半、四象限、網格、層疊) | | `utils/window_zorder/` | 77 | 視窗 z 序控制(最上層/移到最前/送到最後) | @@ -1553,8 +1553,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,148 | -| **總計** | **1,515** | **233,106** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | +| **總計** | **1,515** | **233,111** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 7858a267a..67cd80620 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -270,3 +270,12 @@ - **Tests:** `test_window_capture.py` +5 (saved entry shape, default restore passes no option, `maximize=True` only for maximized entries, a five-argument mover still works, the executor passes `maximize` through), `test_window_lifecycle_contract.py` +7 (a maximized window saved at its restored rectangle; workspace→screen for taskbar left / top / bottom and a tool window; the mover maximizes only when asked). Window, layout, audit, contract and stub tests: 173 passed. - **Files:** `utils/window_capture/window_capture.py`, `windows/window/windows_window_manage.py`, `utils/executor/action_executor.py`, `gui/script_builder/command_schema.py`, `actions.pyi`, the two tests, both `v4_features_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** restore on a second monitor with another DPI and with a taskbar on the left or top (`Progress.md` › 桌面行為驗收, one screen here). + +## U-20261114-01 · 2026-11-14 · PR #552: CI tested PySide6 6.11.2, the container crashes on 6.12.0, two test regressions · #incident #ci #gui + +- **Pin drift:** the dependabot bump to `PySide6==6.12.0` (`3076a0cf6`) changed `pyproject.toml`, `dev.toml` and `dev_requirements.txt` but not the tooling lines of `dev.yml` / `quality.yml` (pytest-headless and typing-extras), which stayed on 6.11.2. Only the container job installed 6.12.0 on Linux. All three lines now pin 6.12.0 (`cfe70af5`). With it, the Ubuntu dev square (3.14) and the PR's Ubuntu 3.11 / 3.14 and macOS / Windows squares ran 6.12.0 with no crash. +- **Container crash (corrects U-20261113-03's "open items: none"):** with `libegl1` the image's run reached the end and then died with exit 139 after Qt's `QObject: shared QObject was deleted directly`. `docker.yml` now runs it like the pytest-headless jobs, under gdb through `scripts/ci_native_diagnostics.py --native` with `-X faulthandler`, and with `-v`. Four runs on 6.12.0: one passed (`120d9cb5`); two crashed at interpreter exit in `Py_FinalizeEx` → `PySide::destroyQCoreApplication` → `BindingManager::visitAllPyObjects` → `QObject::~QObject`; one crashed at about 46 % of the suite in the main thread's `Shiboken::BindingManager::runDeletionInMainThread()` → QtWidgets. No upstream report matches either stack. Cause not found; `Progress.md` › "PySide6 6.12 在容器(Python 3.12)的 headless 測試間歇 segfault" holds it and the options. +- **Two regressions from U-20261113-05, caught by every pytest-headless square:** `_handle_layout` called `ctypes.windll` directly, so `test_a11y_window_audit.py::test_a_saved_layout_reads_each_window_by_its_handle`, which fakes `sys.platform == "win32"` on Linux and stubs `_win32_window_rect`, raised `AttributeError`. The read is now `_win32_is_maximized`, a seam like `_win32_window_rect`, and that test stubs it. `_restore_window_layout` read its flag with `bool()`, which `test_executor_flags.py` forbids (`"false"` is truthy); it uses `as_bool()`. The local check before that commit ran only the window and layout test files, not the full suite. +- **Also fixed:** `test_restoring_duplicate_titles_moves_each_window_once` (the order-dependent `KeyError` noted in U-20261112-07 and U-20261113-01) looked up `sys.modules["je_auto_control.windows.window"]`, present only when an earlier test had imported it; it now stands in a package when none is loaded, and passes alone. +- **Files:** `.github/workflows/{dev.yml,quality.yml,docker.yml}`, `utils/window_capture/window_capture.py`, `utils/executor/action_executor.py`, `test_a11y_window_audit.py`, `Progress.md`. +- **Open items:** the container crash (`Progress.md`). diff --git a/docs/updates/README.md b/docs/updates/README.md index 0880d210e..12bfb25aa 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-01 | 2026-11-14 | PR #552: CI tested PySide6 6.11.2, the container crashes on 6.12.0, two test regressions | #incident #ci #gui | [2026-11-b](2026-11-b.md) | | U-20261113-05 | 2026-11-13 | Saved layouts keep the maximized state; restoring it is opt-in | #done #windows | [2026-11-b](2026-11-b.md) | | U-20261113-04 | 2026-11-13 | `post_key_to_window` takes any printable character | #done #windows #x11 | [2026-11-b](2026-11-b.md) | | U-20261113-03 | 2026-11-13 | PR #552: container libEGL and three asyncio cancellation findings | #incident #ci #remote | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/executor/action_executor.py b/je_auto_control/utils/executor/action_executor.py index 8a2592e54..98995b129 100644 --- a/je_auto_control/utils/executor/action_executor.py +++ b/je_auto_control/utils/executor/action_executor.py @@ -2469,7 +2469,7 @@ def _restore_window_layout(layout: List[Dict[str, Any]] | str, maximize: bool = ``maximize`` re-maximizes windows saved maximized, which activates each one. """ from je_auto_control.utils.window_capture import restore_window_layout - return {"restored": restore_window_layout(layout, maximize=bool(maximize))} + return {"restored": restore_window_layout(layout, maximize=_as_bool(maximize))} def _region_color_stats(region: Optional[List[int] | str] = None, diff --git a/je_auto_control/utils/window_capture/window_capture.py b/je_auto_control/utils/window_capture/window_capture.py index 08cdd4379..8a5a6d82f 100644 --- a/je_auto_control/utils/window_capture/window_capture.py +++ b/je_auto_control/utils/window_capture/window_capture.py @@ -87,6 +87,12 @@ def _win32_window_rect(hwnd: int) -> Optional[Rect]: rect.right - rect.left, rect.bottom - rect.top) +def _win32_is_maximized(hwnd: int) -> bool: + """``IsZoomed``: whether the window is maximized.""" + import ctypes + return bool(ctypes.windll.user32.IsZoomed(hwnd)) # type: ignore[attr-defined] # reason: win32-only ctypes + + def _win32_work_area() -> Optional[Rect]: """The primary monitor's work area as ``(x, y, width, height)``, or ``None``.""" import ctypes @@ -196,9 +202,8 @@ def _handle_layout(hwnd: int) -> Tuple[Optional[Rect], bool]: """ if sys.platform != "win32": return None, False - import ctypes rect = _win32_window_rect(int(hwnd)) - if rect is None or not ctypes.windll.user32.IsZoomed(int(hwnd)): # type: ignore[attr-defined] # reason: win32-only ctypes + if rect is None or not _win32_is_maximized(int(hwnd)): return rect, False from je_auto_control.windows.window import windows_window_manage as wm normal = wm.get_normal_window_rect(int(hwnd)) diff --git a/test/unit_test/headless/test_a11y_window_audit.py b/test/unit_test/headless/test_a11y_window_audit.py index 6f14181d2..a04031ca0 100644 --- a/test/unit_test/headless/test_a11y_window_audit.py +++ b/test/unit_test/headless/test_a11y_window_audit.py @@ -60,6 +60,7 @@ def test_a_saved_layout_reads_each_window_by_its_handle(monkeypatch): monkeypatch.setattr(sys, "platform", "win32") real = {1: (0, 0, 800, 600), 2: (900, 50, 400, 300)} monkeypatch.setattr(window_capture, "_win32_window_rect", lambda hwnd: real[hwnd]) + monkeypatch.setattr(window_capture, "_win32_is_maximized", lambda hwnd: False) layout = window_capture.save_window_layout(lister=lambda: [(1, "Editor - a"), (2, "Editor")]) assert [(entry["title"], entry["x"]) for entry in layout] == [("Editor - a", 0), ("Editor", 900)] @@ -72,8 +73,14 @@ def test_restoring_duplicate_titles_moves_each_window_once(monkeypatch): moved = [] fake_wm = types.SimpleNamespace(move_window=lambda hwnd, *rect: moved.append(hwnd) or True) monkeypatch.setitem(sys.modules, "je_auto_control.windows.window.windows_window_manage", fake_wm) - monkeypatch.setattr(sys.modules["je_auto_control.windows.window"], "windows_window_manage", - fake_wm, raising=False) + # Run alone (or first) nothing has imported the package yet, and on + # Linux / macOS it cannot be: stand one in rather than depend on order. + package = sys.modules.get("je_auto_control.windows.window") + if package is None: + package = types.ModuleType("je_auto_control.windows.window") + package.__path__ = [] + monkeypatch.setitem(sys.modules, "je_auto_control.windows.window", package) + monkeypatch.setattr(package, "windows_window_manage", fake_wm, raising=False) count = window_capture.restore_window_layout([ {"title": "Editor", "x": 0, "y": 0, "width": 1, "height": 1}, {"title": "Editor", "x": 5, "y": 5, "width": 1, "height": 1}, From 5575f6a9318870c1ad11174ce16c0a49086c9655 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 04:01:25 +0800 Subject: [PATCH 066/161] Pin PySide6 6.11.2 again: 6.12.0 crashes every CI platform at exit On 1d372dba every pytest-headless square passed its tests and then died at interpreter exit (Linux abort in malloc, macOS abort, Windows access violations): a double free while destroyQCoreApplication releases a Python closure holding the last reference to a widget Qt has already deleted. CI never showed it on 6.11.2. Changing the tab close buttons' slot moved the crash rather than removing it, so the closure is still unknown. Dependabot skips 6.12.0 only, so a later 6.12 release is still proposed. --- .github/dependabot.yml | 5 +++++ .github/workflows/dev.yml | 2 +- .github/workflows/quality.yml | 4 ++-- CHANGELOG.md | 4 ++++ Progress.md | 11 ++++++----- dev.toml | 2 +- dev_requirements.txt | 2 +- docs/updates/2026-11-b.md | 8 ++++++++ docs/updates/README.md | 1 + pyproject.toml | 2 +- requirements.txt | 2 +- 11 files changed, 31 insertions(+), 12 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c40004304..c105727cc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,3 +14,8 @@ updates: - "/.github/requirements" schedule: interval: "daily" + ignore: + # 6.12.0 crashes the test process at interpreter exit on every platform + # (Progress.md, "PySide6 6.12"); a later 6.12 release may be proposed. + - dependency-name: "pyside6" + versions: ["6.12.0"] diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index bb4c97a0d..90f072a30 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -79,7 +79,7 @@ jobs: shell: bash # The same line as quality.yml (test_dev_release.py compares them). # Quoted: `--only-binary :all:` puts a colon-space inside the scalar. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.11.2 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" # No path argument: the paths come from `testpaths` in pyproject.toml, # and an argument would drop the flow_control tests. Linux runs under a diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index d81dc1c9f..a45ba6d95 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -149,7 +149,7 @@ jobs: shell: bash # Quoted: `--only-binary :all:` puts a colon-space inside the # scalar, which YAML reads as a mapping and refuses. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.11.2 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" - name: Verify native diagnostics runner (Linux) if: runner.os == 'Linux' @@ -277,7 +277,7 @@ jobs: python-version: "3.12" cache: "pip" - run: pip install -e ".[gui,webrtc]" # NOSONAR githubactions:S8541,githubactions:S8544 # reason: installs the checked-out project itself, there is no upstream version to lock and the build must run - - run: "pip install --only-binary :all: mypy==2.4.0 PySide6==6.12.0 aiortc==1.15.0 av==17.1.0 aioice==0.10.2 pyee==14.0.0 pylibsrtp==1.0.0" + - run: "pip install --only-binary :all: mypy==2.4.0 PySide6==6.11.2 aiortc==1.15.0 av==17.1.0 aioice==0.10.2 pyee==14.0.0 pylibsrtp==1.0.0" - name: The ordinary contract does not change when the extras are installed run: python test/verify/typing_contract_verify.py - name: The package against the real PySide6 / aiortc / av types diff --git a/CHANGELOG.md b/CHANGELOG.md index 1aec971ff..7d8d3223b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- The `gui` extra and the development and CI pins are back on `PySide6==6.11.2`. 6.12.0 crashed + the test process at interpreter exit on every CI platform (a double free while + `destroyQCoreApplication` tears down Python-held widgets); Dependabot now skips 6.12.0. + - `save_window_layout` stores a maximized window with `"maximized": true` and its restored rectangle; it used to store the maximized rectangle, which restored as a screen-sized normal window. `restore_window_layout(..., maximize=True)` (`AC_restore_window_layout`'s diff --git a/Progress.md b/Progress.md index 306daddee..3644df033 100644 --- a/Progress.md +++ b/Progress.md @@ -208,16 +208,17 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD --- -## PySide6 6.12 在容器(Python 3.12)的 headless 測試間歇 segfault +## PySide6 6.12:headless 測試跑完後直譯器結束時崩潰(全平台) -`TODO` — `docker.yml` 的「Headless pytest inside the image」在 PySide6 6.12.0 上 4 次跑 3 次 SIGSEGV(U-20261114-01)。 -同一個 6.12.0 在 Ubuntu 3.11/3.14 的 pytest-headless(也在 gdb 下)都沒有;Windows 本機 3.14 也沒有。 +`TODO` — 維護者 2026-11-14 決定全面固定回 PySide6 6.11.2(U-20261114-03;dependabot 忽略 6.12.0),待之後的 6.12.x 或找出 closure 後再升級並重驗。先在容器看到(U-20261114-01:`docker.yml` 4 次 3 次 SIGSEGV);到 `1d372dba`(PR #552,2026-11-14)已是**每一格**:全部測試通過後,Ubuntu 3.14 exit 255(glibc `malloc_consolidate` abort)、macOS 3.11 `Fatal Python error: Aborted`、Windows 3.11/3.14 access violation、3.13 `Aborted`,Windows 3.12 在 `test_gui_offthread_sites.py` 中段 abort。本機 Windows 3.14 的完整套件沒有重現。 +- Ubuntu 的 gdb 堆疊(dev run 43484575781):`destroyQCoreApplication` → `visitAllPyObjects` → 某個 QObject 的 `~QObject` 釋放接在它訊號上的 Python 函式 → `func_dealloc` → closure cell → 一個 widget 的 wrapper 歸零 → `~QWidget` → `~QScrollBar` → `free()` 重複釋放;前一行是 `shared QObject was deleted directly`。即 closure 握有最後一個參考的 widget,在結束時被 shiboken 與 Qt 各刪一次。是哪個 closure 還不知道。 +- 試過把分頁關閉鈕的 lambda(握住頁面)換成 bound method,或改用 Qt 內建關閉鈕:`test_gui_lazy_registry.py` 的探針在 `os._exit` 10/10 崩潰(HEAD 13/13 正常),已還原;這條路徑本身就是「把 Python 建的 widget 放進分頁列在結束時崩潰」那一項。 - 兩次在測試全部跑完後的直譯器結束:`Py_FinalizeEx` → `PySide::runCleanupFunctions` → `destroyQCoreApplication` → `BindingManager::visitAllPyObjects` → `QObject::~QObject`,前一行是 Qt 的 `shared QObject was deleted directly`。 - 一次在測試中段(約 46%)主執行緒的 `Shiboken::BindingManager::runDeletionInMainThread()` → QtWidgets。 -- 還不知道:是 Python 3.12 本身還是映像(slim、`dev_requirements.txt` 的套件組合)造成;是哪個測試留下了被兩邊刪除的物件。 +- 不是 Python 3.12 或容器映像特有(每個平台與版本都有);還不知道是哪個測試留下了被兩邊刪除的物件。 上游查無相同回報。`docker.yml` 現在以 gdb 跑、`-X faulthandler`、`-v`,下次中段崩潰會有測試名稱。 -- 可選的處置(須維護者決定):繼續定位;容器暫時固定 PySide6 6.11.2;或把映像換成 3.11/3.14。 +- 升級回 6.12 前要做的:在 PR 上跑完整矩陣(含 `docker.yml`)確認結束時不再崩潰;或先找出握住 widget 的 closure(上面的分頁關閉鈕實驗顯示改動它會改變崩潰點,不是單純移除)。 --- diff --git a/dev.toml b/dev.toml index 2a6375fc2..c286f70cf 100644 --- a/dev.toml +++ b/dev.toml @@ -85,7 +85,7 @@ find = { namespaces = false } ] [project.optional-dependencies] -gui = ["PySide6==6.12.0"] +gui = ["PySide6==6.11.2"] webrtc = ["aiortc>=1.14.0", "av>=14.0.0"] signaling = ["fastapi>=0.115", "starlette>=1.0.1", "uvicorn>=0.32"] discovery = ["zeroconf>=0.149.16"] diff --git a/dev_requirements.txt b/dev_requirements.txt index 0520862cb..697da8fca 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -4,7 +4,7 @@ build twine sphinx sphinx-rtd-theme -PySide6==6.12.0 +PySide6==6.11.2 mss==10.2.0 defusedxml==0.7.1 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 67cd80620..d4bcfd1c4 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -279,3 +279,11 @@ - **Also fixed:** `test_restoring_duplicate_titles_moves_each_window_once` (the order-dependent `KeyError` noted in U-20261112-07 and U-20261113-01) looked up `sys.modules["je_auto_control.windows.window"]`, present only when an earlier test had imported it; it now stands in a package when none is loaded, and passes alone. - **Files:** `.github/workflows/{dev.yml,quality.yml,docker.yml}`, `utils/window_capture/window_capture.py`, `utils/executor/action_executor.py`, `test_a11y_window_audit.py`, `Progress.md`. - **Open items:** the container crash (`Progress.md`). + +## U-20261114-03 · 2026-11-14 · PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit · #decision #ci #gui + +- **Evidence:** on `1d372dba` (PR #552) every pytest-headless square passed all its tests and then died at interpreter exit: Ubuntu 3.14 exit 255 (glibc `malloc_consolidate(): unaligned fastbin chunk`), macOS 3.11 `Fatal Python error: Aborted` (134), Windows 3.11 and 3.14 access violation, 3.13 `Aborted`; Windows 3.12 aborted mid-suite in `test_gui_offthread_sites.py`. The macOS jobs of the PR run were never picked up by a runner (capacity), so they say nothing. Ubuntu's gdb stack: `destroyQCoreApplication` → `visitAllPyObjects` → a QObject's `~QObject` frees a Python function connected to its signal → closure cell → the last reference to a widget's wrapper → `~QWidget` → `~QScrollBar` → `free()` of memory Qt already freed. CI never showed this on 6.11.2. +- **Tried:** the tab close buttons' lambda holds the page, so it was replaced by a bound method and, separately, by Qt's own close button. Both made `test_gui_lazy_registry.py`'s whole-window probe crash at `os._exit` 10 of 10 times (HEAD: 13 of 13 clean), so both were reverted; the closure responsible is still unknown. +- **Decision (maintainer, 2026-11-14):** pin `PySide6==6.11.2` again in `pyproject.toml`, `dev.toml`, `requirements.txt`, `dev_requirements.txt` and the `dev.yml` / `quality.yml` tool lines; Dependabot ignores 6.12.0 only, so a later 6.12 release is still proposed. The shared local `.venv` stays on 6.12.0 (not replaced); CI is the check for 6.11.2. +- **Files:** the six pinned files, `.github/dependabot.yml`, `CHANGELOG.md`, `Progress.md`. +- **Open items:** retrying 6.12.x (`Progress.md` › PySide6 6.12). diff --git a/docs/updates/README.md b/docs/updates/README.md index 12bfb25aa..d42540c55 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-03 | 2026-11-14 | PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit | #decision #ci #gui | [2026-11-b](2026-11-b.md) | | U-20261114-01 | 2026-11-14 | PR #552: CI tested PySide6 6.11.2, the container crashes on 6.12.0, two test regressions | #incident #ci #gui | [2026-11-b](2026-11-b.md) | | U-20261113-05 | 2026-11-13 | Saved layouts keep the maximized state; restoring it is opt-in | #done #windows | [2026-11-b](2026-11-b.md) | | U-20261113-04 | 2026-11-13 | `post_key_to_window` takes any printable character | #done #windows #x11 | [2026-11-b](2026-11-b.md) | diff --git a/pyproject.toml b/pyproject.toml index ff4e5e830..dc5023c1b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -110,7 +110,7 @@ find = { namespaces = false } ] [project.optional-dependencies] -gui = ["PySide6==6.12.0"] +gui = ["PySide6==6.11.2"] webrtc = ["aiortc>=1.14.0", "av>=14.0.0"] signaling = ["fastapi>=0.115", "starlette>=1.0.1", "uvicorn>=0.32"] discovery = ["zeroconf>=0.149.16"] diff --git a/requirements.txt b/requirements.txt index b51e3948b..8ae22da1b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,4 @@ je_auto_control>=1.0.4 # replaced that entry. A direct requirement does. pillow>=12.3.0 mss==10.2.0 -PySide6==6.12.0 +PySide6==6.11.2 From a4ebadf2be25554395fa823faf6746e7f2b7a5a6 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 04:11:30 +0800 Subject: [PATCH 067/161] Redesign the GUI shell: adaptive building blocks and window breakpoints The tabs had fixed layouts: one combo box sized to its longest command made Mobile need 1,464 px, and narrow windows only scrolled sideways. gui/adaptive adds wrapping rows, stacking boxes, cards, page headers, a fit pass the workspace runs on every page, and vector check boxes and radio buttons (Fusion's outline vanished on the dark theme). The window now classifies its width: below 800 px the navigation becomes a rail that opens the feature list as a drawer, and below 1,200 px the execution details open as a drawer. The saved navigation preference is the user's, never the width's. test_gui_page_widths.py holds every page to 72 average characters; four pages are listed until they are reworked. --- CHANGELOG.md | 13 + Progress.md | 5 + README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 29 +- .../doc/new_features/v224_features_doc.rst | 88 ++++++ docs/source/Eng/eng_index.rst | 1 + .../Zh/doc/new_features/v224_features_doc.rst | 75 ++++++ docs/source/Zh/zh_index.rst | 1 + docs/updates/2026-11-b.md | 12 + docs/updates/README.md | 1 + je_auto_control/gui/adaptive/__init__.py | 9 + je_auto_control/gui/adaptive/breakpoints.py | 46 ++++ je_auto_control/gui/adaptive/flow_layout.py | 105 ++++++++ je_auto_control/gui/adaptive/glyphs.py | 52 ++++ je_auto_control/gui/adaptive/overlay.py | 102 +++++++ je_auto_control/gui/adaptive/responsive.py | 119 +++++++++ je_auto_control/gui/adaptive/style.py | 102 +++++++ je_auto_control/gui/adaptive/surfaces.py | 160 +++++++++++ je_auto_control/gui/adaptive_window.py | 179 +++++++++++++ .../gui/language_wrapper/english.py | 53 ++++ .../gui/language_wrapper/japanese.py | 53 ++++ .../language_wrapper/simplified_chinese.py | 53 ++++ .../language_wrapper/traditional_chinese.py | 53 ++++ je_auto_control/gui/main_window.py | 47 ++-- je_auto_control/gui/navigation.py | 4 + je_auto_control/gui/theme.py | 66 ++++- je_auto_control/gui/workspace.py | 68 ++++- je_auto_control/gui/workspace_details.py | 2 + test/unit_test/headless/test_gui_adaptive.py | 250 ++++++++++++++++++ .../headless/test_gui_adaptive_window.py | 197 ++++++++++++++ .../headless/test_gui_page_widths.py | 95 +++++++ .../headless/test_gui_workspace_navigation.py | 19 +- 34 files changed, 2022 insertions(+), 43 deletions(-) create mode 100644 docs/source/Eng/doc/new_features/v224_features_doc.rst create mode 100644 docs/source/Zh/doc/new_features/v224_features_doc.rst create mode 100644 je_auto_control/gui/adaptive/__init__.py create mode 100644 je_auto_control/gui/adaptive/breakpoints.py create mode 100644 je_auto_control/gui/adaptive/flow_layout.py create mode 100644 je_auto_control/gui/adaptive/glyphs.py create mode 100644 je_auto_control/gui/adaptive/overlay.py create mode 100644 je_auto_control/gui/adaptive/responsive.py create mode 100644 je_auto_control/gui/adaptive/style.py create mode 100644 je_auto_control/gui/adaptive/surfaces.py create mode 100644 je_auto_control/gui/adaptive_window.py create mode 100644 test/unit_test/headless/test_gui_adaptive.py create mode 100644 test/unit_test/headless/test_gui_adaptive_window.py create mode 100644 test/unit_test/headless/test_gui_page_widths.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d8d3223b..7703db241 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ the test process at interpreter exit on every CI platform (a double free while `destroyQCoreApplication` tears down Python-held widgets); Dependabot now skips 6.12.0. +- GUI: `prepare_application` installs `AdaptiveStyle` (Fusion with check boxes and radio + buttons drawn from the palette) instead of plain Fusion, and the workspace inserts a + `PageHeader` at the top of every tab laid out by a vertical box layout and runs + `fit_to_width` on it, which changes its combo boxes' size-adjust policy and its form + layouts' row-wrap policy. Code that embeds a tab and reads its layout's first item, or + relies on a combo box sizing to its longest entry, sees the difference. +- GUI: below 800 px the main window hides the docked navigation and shows a rail; between + 800 and 1,199 px the execution details open as a drawer. `AutoControlGUIUI._sidebar_action` + (Ctrl+B) is now the window's own checkable action rather than the dock's `toggleViewAction()`, + and the dock's toggle is hidden from the dock area's context menu. The saved + `workspace/navigation_visible` is the user's preference, not whether the dock happened to be + shown when the window closed. + - `save_window_layout` stores a maximized window with `"maximized": true` and its restored rectangle; it used to store the maximized rectangle, which restored as a screen-sized normal window. `restore_window_layout(..., maximize=True)` (`AC_restore_window_layout`'s diff --git a/Progress.md b/Progress.md index 3644df033..c782fdc33 100644 --- a/Progress.md +++ b/Progress.md @@ -533,6 +533,11 @@ H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深 F 還缺: - **F2 其餘**:Diagnostics 以外面板的執行詳情,以及各面板的空白/錯誤/permission states 尚未全面交付。 +- **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: + 設計系統(`gui/adaptive/`、主題 token 與字階)、每頁頁首與 fit pass、視窗斷點(圖示欄、導覽與詳情抽屜)已交付(U-20261114-02)。仍缺: + 51 個分頁逐頁改用 `Card`/`FlowLayout`/`ResponsiveBox` 重排(目前多數頁只套上群組框的卡片樣式,頁首標題與頁內第一個群組標題重複); + `test_gui_page_widths.py` 的 `WIDE_PAGES`(script_builder、flakiness、audit_log、usb_share)降到 72 字元內後移除; + 所有截圖都是 offscreen 平台加 Windows 字型,尚未在真實螢幕、混合 DPI 與 Linux/macOS 字型上目視審閱。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/README.md b/README.md index 0325dcee1..04cd78e93 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ Of the three tabs open at start, only Record is built then; Script Builder and R View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there; other pages explicitly say when details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. +Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. + WebRTC statistics polling starts in the background and discards late samples after it stops. Windows, macOS, X11 and Wayland use different backends. Available features depend on system permissions and optional dependencies; Windows ARM64 has additional limitations. See the installation guide before choosing a deployment target. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 48550666d..ad4780ff5 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -45,6 +45,8 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态;其他分页尚未提供时会明确显示。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 +每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 + WebRTC 统计轮询在后台启动,停止后会丢弃延迟到达的样本。 Windows、macOS、X11 与 Wayland 使用不同后端,实际功能取决于系统权限与可选依赖。Windows ARM64 另有限制,部署前请先阅读安装文件。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 15ab42f25..26eec4106 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -45,6 +45,8 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態;其他分頁尚未提供時會明確顯示。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 +每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 + WebRTC 統計輪詢在背景啟動,停止後會捨棄晚到的樣本。 Windows、macOS、X11 與 Wayland 使用不同後端,實際功能取決於系統權限與選配依賴。Windows ARM64 另有限制,部署前請先閱讀安裝文件。 diff --git a/architecture_explore.md b/architecture_explore.md index 2cacb3c66..3ab6301e5 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,527 | -| 程式碼總行數 | 233,856 | +| Python 模組總數(含周邊子專案) | 1,536 | +| 程式碼總行數 | 235,073 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1295,13 +1295,22 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | -| `main_window.py` | 450 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | +| `main_window.py` | 463 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合,窄視窗時改為抽屜,由 `adaptive_window.py` 安排)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | -| `navigation.py` | 208 | `NavigationPanel`:搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。 | -| `theme.py` | 183 | 設計 token(`ThemeTokens`:顏色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表與對應的 `QPalette`;不載入圖檔或字型檔。 | -| `workspace.py` | 466 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情。 | -| `workspace_details.py` | 95 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | +| `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | +| `theme.py` | 233 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | +| `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | +| `adaptive/flow_layout.py` | 105 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | +| `adaptive/responsive.py` | 119 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行),工作區放入每頁時跑一次。 | +| `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | +| `adaptive/style.py` | 102 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | +| `adaptive/glyphs.py` | 52 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | +| `adaptive/overlay.py` | 102 | A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed. `OverlayDrawer`:Escape 或點擊遮罩關閉。 | +| `adaptive_window.py` | 179 | Rearrange the main window's navigation and details panes as the window's width class changes. `AdaptiveWindowLayout`:expanded 兩側停靠;medium 詳情改抽屜;compact 導覽改圖示欄+抽屜。「想要停靠導覽」與寬度是否允許分開記錄,窄視窗不會改寫使用者偏好。 | +| `workspace.py` | 528 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | +| `workspace_details.py` | 97 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 166 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 131 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | @@ -1326,7 +1335,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 7,983 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,195 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1533,7 +1542,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 150 | 40,659 | +| `gui/` | 159 | 41,876 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1554,7 +1563,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,515** | **233,111** | +| **總計** | **1,524** | **234,328** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v224_features_doc.rst b/docs/source/Eng/doc/new_features/v224_features_doc.rst new file mode 100644 index 000000000..f26a85ef6 --- /dev/null +++ b/docs/source/Eng/doc/new_features/v224_features_doc.rst @@ -0,0 +1,88 @@ +Adaptive GUI: Page Headers, Cards and Controls That Shrink +========================================================== + +The GUI is being redesigned around one set of adaptive building blocks, so +every page looks the same and fits a small window. This page describes what +is in place: the building blocks, the window's own breakpoints, and what every +page gets from them. Reworking each page onto the blocks follows in later +releases. + +The window adapts to its width +------------------------------ + +============ ================== ========================================= +Window width Navigation Execution details +============ ================== ========================================= +1,200 px + docked on the left a column on the right +800-1,199 px docked on the left a drawer over the tabs, from the right +below 800 px a rail of icons a drawer over the tabs, from the right +============ ================== ========================================= + +In the narrowest layout the rail's menu button, **Ctrl+B** or **Ctrl+K** opens +the feature list as a drawer over the tabs; choosing a feature, **Escape** or a +click on the dimmed area closes it. The rail's last button toggles the +execution details. A width must move 24 px past a boundary before the layout +changes back, so dragging the window edge near one does not make it flicker. + +**View → Navigation Panel** (**Ctrl+B**) still records whether you want the +docked list. That preference is kept apart from the width: a window narrowed +below 800 px hides the dock without changing it, and widening the window brings +the dock back only if you had it shown. It is saved on close as before. + +What every page gets +-------------------- + +* **A page header.** Each tab opens with its title and a one-line description + of what it is for, in the active language. The description comes from the + ``_subtitle`` string (``tab_mobile_subtitle`` for Mobile); a page + whose language has no such string shows only the title. +* **Cards.** Group boxes are drawn as raised cards with their title above + them, and new pages are built from ``Card`` directly. +* **Visible check boxes and radio buttons.** Fusion outlines them with a shade + of the window colour, which all but disappears in the dark theme; they are + now drawn in code from the palette (accent fill, check mark, ring and dot), + so they follow the theme without any image file. +* **Controls that shrink.** When a page is first shown it goes through a fit + pass: drop-down lists stop sizing themselves to their longest entry (Mobile + needed 1,464 px for one command label), form labels move above their field + when both do not fit, and long notes wrap. + +Building blocks +--------------- + +They live in ``je_auto_control.gui.adaptive``: + +``breakpoints`` + ``classify(width, previous)`` returns ``WidthClass.COMPACT`` (below 800 + px), ``MEDIUM`` or ``EXPANDED`` (from 1,200 px). A width must move 24 px + past a boundary before the class changes back, so resizing near one does + not flicker. Qt-free. +``flow_layout.FlowLayout`` + A row that wraps onto the next line instead of widening its page; its + minimum width is its widest single item. +``responsive.ResponsiveBox`` + Two or more parts side by side when there is room, stacked below a width + you choose. +``responsive.fit_to_width`` + The fit pass described above. The workspace runs it on every page it + shows; a control already fitted is left alone. +``surfaces`` + ``Card``, ``PageHeader``, ``EmptyState`` and ``retranslate_surfaces``. They + carry a ``role`` property (``card``, ``pageTitle``, ``hint`` ...) that the + theme's style sheet targets, so the look stays in ``gui/theme.py``. +``style.AdaptiveStyle`` + The Fusion proxy that paints the two indicators. + ``prepare_application`` installs it. + +Titles, section titles and hints are sized from the body text size +(``type_scale_rules``), so **View → Text Size** scales them too. + +The width check +--------------- + +``test/unit_test/headless/test_gui_page_widths.py`` opens every registered tab +the way the window does and reads its minimum width, in average characters of +the window's label font so the same limit holds on Windows and Linux fonts. A +page may need at most 72 characters (about 460 px in 10 pt Segoe UI). Four +pages are still over it and listed with a ceiling each (Script Builder, +Flaky Tests, Audit Log, USB Sharing); the list only shrinks. diff --git a/docs/source/Eng/eng_index.rst b/docs/source/Eng/eng_index.rst index 571ec9575..795e9088e 100644 --- a/docs/source/Eng/eng_index.rst +++ b/docs/source/Eng/eng_index.rst @@ -250,6 +250,7 @@ Comprehensive guides for all AutoControl features. doc/new_features/v221_features_doc doc/new_features/v222_features_doc doc/new_features/v223_features_doc + doc/new_features/v224_features_doc doc/mobile/mobile_doc doc/ocr_backends/ocr_backends_doc doc/observability/observability_doc diff --git a/docs/source/Zh/doc/new_features/v224_features_doc.rst b/docs/source/Zh/doc/new_features/v224_features_doc.rst new file mode 100644 index 000000000..c20054beb --- /dev/null +++ b/docs/source/Zh/doc/new_features/v224_features_doc.rst @@ -0,0 +1,75 @@ +自適應 GUI:頁首、卡片與會縮小的控制項 +====================================== + +GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一致,也放得進小視窗。 +本頁說明目前已完成的部分:元件、視窗本身的斷點,以及每個分頁因此得到的改變。 +各分頁逐頁改用這些元件,會在之後的版本陸續交付。 + +視窗依寬度調整 +-------------- + +.. list-table:: + :header-rows: 1 + + * - 視窗寬度 + - 導覽 + - 執行詳情 + * - 1,200 px 以上 + - 停靠在左側 + - 右側一欄 + * - 800-1,199 px + - 停靠在左側 + - 從右側覆蓋在分頁上的抽屜 + * - 800 px 以下 + - 圖示欄 + - 從右側覆蓋在分頁上的抽屜 + +最窄時,按圖示欄的選單鈕、**Ctrl+B** 或 **Ctrl+K** 會以抽屜開啟功能清單; +選擇功能、按 **Escape** 或點擊變暗的區域即關閉。圖示欄最後一個按鈕切換執行詳情。 +寬度須越過邊界 24 px 才會切回,在邊界附近拖曳視窗邊緣不會閃動。 + +**View → Navigation Panel**(**Ctrl+B**)仍記錄你是否想要停靠的清單。這個偏好與寬度分開: +視窗縮到 800 px 以下會隱藏停靠面板但不改動偏好,再放寬時只有原本顯示才會出現。關閉視窗時照舊儲存。 + +每個分頁都有的 +-------------- + +* **頁首。** 每個分頁開頭顯示標題與一行用途說明(依目前語言)。說明取自 + ``_subtitle`` 字串(Mobile 為 ``tab_mobile_subtitle``);該語言沒有這個字串時只顯示標題。 +* **卡片。** 群組框改畫成浮起的卡片、標題在上方;新頁面直接使用 ``Card``。 +* **看得見的核取方塊與選項按鈕。** Fusion 以視窗色的深淺描邊,深色主題下幾乎看不見; + 現在改由程式依調色盤繪製(強調色填色、勾號、外圈與圓點),隨主題變化,不需要圖檔。 +* **會縮小的控制項。** 分頁第一次顯示時會經過一次調整:下拉選單不再以最長項目決定寬度 + (Mobile 曾因一個指令名稱需要 1,464 px)、表單放不下時標籤移到欄位上方、長說明自動換行。 + +元件 +---- + +位於 ``je_auto_control.gui.adaptive``: + +``breakpoints`` + ``classify(width, previous)`` 回傳 ``WidthClass.COMPACT`` (800 px 以下)、 + ``MEDIUM`` 或 ``EXPANDED`` (1,200 px 起)。寬度須越過邊界 24 px 才會切回, + 在邊界附近調整大小不會閃動。不匯入 Qt。 +``flow_layout.FlowLayout`` + 放不下時換到下一行、而不撐寬頁面的列;最小寬度等於最寬的單一項目。 +``responsive.ResponsiveBox`` + 空間足夠時並排、低於指定寬度時上下堆疊。 +``responsive.fit_to_width`` + 上述的調整。工作區顯示每個分頁時都會執行;已調整過的控制項不會重複處理。 +``surfaces`` + ``Card``、``PageHeader``、``EmptyState`` 與 ``retranslate_surfaces``。它們帶有 + ``role`` 屬性(例如 ``card``、``pageTitle``、``hint``),由主題樣式表指定外觀,樣式集中在 ``gui/theme.py``。 +``style.AdaptiveStyle`` + 繪製這兩種指示器的 Fusion 代理樣式,由 ``prepare_application`` 安裝。 + +標題、區段標題與提示文字的大小依內文字級計算(``type_scale_rules``), +**View → Text Size** 也會一併縮放它們。 + +寬度檢查 +-------- + +``test/unit_test/headless/test_gui_page_widths.py`` 以視窗的方式開啟每個已註冊分頁並讀取最小寬度, +單位是視窗標籤字型的平均字元寬,使 Windows 與 Linux 字型適用同一個上限。 +每頁最多 72 字元(10 pt Segoe UI 約 460 px)。目前仍有四個分頁超過,各自列出上限 +(Script Builder、Flaky Tests、Audit Log、USB Sharing);這份清單只減不增。 diff --git a/docs/source/Zh/zh_index.rst b/docs/source/Zh/zh_index.rst index 989d106f1..b814e522e 100644 --- a/docs/source/Zh/zh_index.rst +++ b/docs/source/Zh/zh_index.rst @@ -250,6 +250,7 @@ AutoControl 所有功能的完整使用指南。 doc/new_features/v221_features_doc doc/new_features/v222_features_doc doc/new_features/v223_features_doc + doc/new_features/v224_features_doc doc/mobile/mobile_doc doc/ocr_backends/ocr_backends_doc doc/observability/observability_doc diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d4bcfd1c4..64ddb3080 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -280,6 +280,18 @@ - **Files:** `.github/workflows/{dev.yml,quality.yml,docker.yml}`, `utils/window_capture/window_capture.py`, `utils/executor/action_executor.py`, `test_a11y_window_audit.py`, `Progress.md`. - **Open items:** the container crash (`Progress.md`). +## U-20261114-02 · 2026-11-14 · GUI redesign, stage 1: adaptive building blocks, page headers, cards, window breakpoints and the width gate · #migration #gui + +- **Decision (maintainer, 2026-11-14):** redo the whole GUI as a visual redesign with an adaptive layout; when the window is narrow the navigation and details panes become overlays. Delivered in stages; this is the first. Open items in `Progress.md` › F2 GUI 重製. +- **Measured before:** every tab opened offscreen and its `minimumSizeHint` read. Without fonts (Windows offscreen draws boxes) 16 of 51 tabs needed more than 600 px; with `QT_QPA_FONTDIR` pointing at the Windows fonts, Mobile needed 1,464 px because of one combo box sized to its longest command label. +- **New `gui/adaptive/`:** `breakpoints` (Qt-free `classify`: compact below 800 px, expanded from 1,200, 24 px hysteresis), `FlowLayout`, `ResponsiveBox`, `fit_to_width` (combo boxes `AdjustToMinimumContentsLengthWithIcon` at 14 characters plus a `StyleChange` event, since only that clears their cached minimum size hint; form layouts `WrapLongRows`; labels over 40 characters wrap), `Card` / `PageHeader` / `EmptyState` with a `role` property, `AdaptiveStyle` (vector check boxes and radio buttons from the palette: Fusion's outline was invisible on the dark theme). +- **Shell:** the workspace gives every page a header (title plus `_subtitle`, 51 new strings in each of the four languages) and runs the fit pass when it seats a page; `retranslate` re-reads the surfaces. The theme gained status colours, a large radius, card and role rules, group boxes drawn as cards, and `type_scale_rules` (titles and hints follow View → Text Size). +- **Window breakpoints:** `gui/adaptive_window.py` (`AdaptiveWindowLayout`) classifies the window on every resize. Expanded (≥1,200 px): navigation dock and details column as before. Medium: the details move into an `OverlayDrawer` from the right (`WorkspaceShell.set_details_overlay`), keeping their open state both ways. Compact (<800 px): the dock hides, a vertical `QToolBar` rail (menu, search, details; icons drawn by `adaptive/glyphs.py` in the theme's text colour) appears, and the menu button, Ctrl+B or Ctrl+K open a second `NavigationPanel` in a left drawer that closes on a choice, Escape or a click on the scrim. `_sidebar_action` is now the window's own action, and `navigation_preferred` is saved instead of the dock's visibility, so a compact spell never overwrites the user's choice. The navigation panel gained a brand title. +- **After:** with fonts, no tab needs more than 600 px; 9 need more than 420 (Script Builder 818, Flaky Tests 559, Audit Log 504, USB Sharing 492 the widest). `test_gui_page_widths.py` holds every page to 72 average characters of the label font (about 460 px in 10 pt Segoe UI; the unit keeps the limit the same on Linux fonts) and lists the four still over it with ceilings, shrink-only. Full build of every tab in the probe: about 6 s. +- **Tests:** `test_gui_adaptive_window.py` (9: each width class, drawers keep state across a breakpoint, Ctrl+B / Ctrl+K per class, the preference surviving a compact spell, no flip-flop near 1,200 px, rail icons per theme, scrim clicks, glyphs); `test_gui_workspace_navigation.py`'s 640×420 check now expects the rail and a 560 px+ workspace instead of the docked list; `test_gui_adaptive.py` (21: width classes, flow wrapping, stacking, the fit pass, missing subtitles, header placement, language switch, indicator pixels, type scale), `test_gui_page_widths.py` (3). GUI, workspace, theme and language tests: 1,511 passed, 25 skipped. Strict Sphinx build clean. +- **Files:** `gui/adaptive/*` and `gui/adaptive_window.py` (new), `gui/navigation.py`, `gui/theme.py`, `gui/workspace.py`, `gui/workspace_details.py`, `gui/main_window.py`, the four `language_wrapper` catalogues, the two tests, `README.md` and both translations, `docs/source/{Eng,Zh}/doc/new_features/v224_features_doc.rst` and both indexes, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** per-tab rework, the four wide pages, review on a real screen (`Progress.md` › F2 GUI 重製). + ## U-20261114-03 · 2026-11-14 · PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit · #decision #ci #gui - **Evidence:** on `1d372dba` (PR #552) every pytest-headless square passed all its tests and then died at interpreter exit: Ubuntu 3.14 exit 255 (glibc `malloc_consolidate(): unaligned fastbin chunk`), macOS 3.11 `Fatal Python error: Aborted` (134), Windows 3.11 and 3.14 access violation, 3.13 `Aborted`; Windows 3.12 aborted mid-suite in `test_gui_offthread_sites.py`. The macOS jobs of the PR run were never picked up by a runner (capacity), so they say nothing. Ubuntu's gdb stack: `destroyQCoreApplication` → `visitAllPyObjects` → a QObject's `~QObject` frees a Python function connected to its signal → closure cell → the last reference to a widget's wrapper → `~QWidget` → `~QScrollBar` → `free()` of memory Qt already freed. CI never showed this on 6.11.2. diff --git a/docs/updates/README.md b/docs/updates/README.md index d42540c55..30067374a 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -59,6 +59,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| | U-20261114-03 | 2026-11-14 | PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit | #decision #ci #gui | [2026-11-b](2026-11-b.md) | +| U-20261114-02 | 2026-11-14 | GUI redesign, stage 1: adaptive building blocks, page headers, cards, window breakpoints and the width gate | #migration #gui | [2026-11-b](2026-11-b.md) | | U-20261114-01 | 2026-11-14 | PR #552: CI tested PySide6 6.11.2, the container crashes on 6.12.0, two test regressions | #incident #ci #gui | [2026-11-b](2026-11-b.md) | | U-20261113-05 | 2026-11-13 | Saved layouts keep the maximized state; restoring it is opt-in | #done #windows | [2026-11-b](2026-11-b.md) | | U-20261113-04 | 2026-11-13 | `post_key_to_window` takes any printable character | #done #windows #x11 | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/adaptive/__init__.py b/je_auto_control/gui/adaptive/__init__.py new file mode 100644 index 000000000..96c1acdd3 --- /dev/null +++ b/je_auto_control/gui/adaptive/__init__.py @@ -0,0 +1,9 @@ +"""Adaptive layout building blocks shared by the window and every page. + +``breakpoints`` is Qt-free; the rest needs PySide6 and is imported from the +submodules directly (``from je_auto_control.gui.adaptive.surfaces import Card``), +so importing this package loads no Qt. +""" +from je_auto_control.gui.adaptive.breakpoints import WidthClass, classify + +__all__ = ["WidthClass", "classify"] diff --git a/je_auto_control/gui/adaptive/breakpoints.py b/je_auto_control/gui/adaptive/breakpoints.py new file mode 100644 index 000000000..b721cbac3 --- /dev/null +++ b/je_auto_control/gui/adaptive/breakpoints.py @@ -0,0 +1,46 @@ +"""Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. + +Qt-free: the window asks :func:`classify` on every resize and rearranges its +panes only when the answer changes. +""" +from enum import Enum +from typing import Optional + + +class WidthClass(str, Enum): + """How much horizontal room the window has.""" + + COMPACT = "compact" # one pane: navigation and details become overlays + MEDIUM = "medium" # navigation docked, details slide over the workspace + EXPANDED = "expanded" # navigation, workspace and details side by side + + +#: Window widths (logical pixels) at which the next class begins. +MEDIUM_FROM = 800 +EXPANDED_FROM = 1200 +#: How far past a boundary the width must move before the class changes back. +HYSTERESIS = 24 + +_ORDER = (WidthClass.COMPACT, WidthClass.MEDIUM, WidthClass.EXPANDED) + + +def _plain(width: int) -> WidthClass: + if width >= EXPANDED_FROM: + return WidthClass.EXPANDED + if width >= MEDIUM_FROM: + return WidthClass.MEDIUM + return WidthClass.COMPACT + + +def classify(width: int, previous: Optional[WidthClass] = None, hysteresis: int = HYSTERESIS) -> WidthClass: + """Width class for ``width``, sticking with ``previous`` until the width is ``hysteresis`` past a boundary.""" + if width < 0 or hysteresis < 0: + raise ValueError("width and hysteresis must not be negative") + plain = _plain(width) + if previous is None or plain is previous: + return plain + # Shrinking leaves a class only once the width is that far below its start; + # growing enters the next only once the width is that far above it. + sticky = _plain(width + hysteresis) if _ORDER.index(plain) < _ORDER.index(previous) \ + else _plain(max(0, width - hysteresis)) + return previous if sticky is previous else plain diff --git a/je_auto_control/gui/adaptive/flow_layout.py b/je_auto_control/gui/adaptive/flow_layout.py new file mode 100644 index 000000000..24dff1783 --- /dev/null +++ b/je_auto_control/gui/adaptive/flow_layout.py @@ -0,0 +1,105 @@ +"""A layout that places items left to right and wraps them onto the next line when the row is full.""" +from typing import List, Optional + +from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt +from PySide6.QtWidgets import QHBoxLayout, QLayout, QLayoutItem, QWidget + + +class FlowLayout(QLayout): + """Rows of widgets that wrap instead of forcing the page wider. + + The minimum width is the widest single item, so a row of fields and + buttons never makes its page scroll sideways; it gets taller instead. + """ + + def __init__(self, parent: Optional[QWidget] = None, spacing: int = 8) -> None: + super().__init__(parent) + self._items: List[QLayoutItem] = [] + self.setSpacing(spacing) + self.setContentsMargins(0, 0, 0, 0) + + def addItem(self, item: QLayoutItem) -> None: # noqa: N802 # reason: Qt override + """Append an item (called by ``addWidget``).""" + self._items.append(item) + + def count(self) -> int: + """Number of items held.""" + return len(self._items) + + def itemAt(self, index: int) -> Optional[QLayoutItem]: # noqa: N802 # reason: Qt override + """The item at ``index``, or ``None`` past the end.""" + return self._items[index] if 0 <= index < len(self._items) else None + + def takeAt(self, index: int) -> Optional[QLayoutItem]: # noqa: N802 # reason: Qt override + """Remove and return the item at ``index``.""" + return self._items.pop(index) if 0 <= index < len(self._items) else None + + def expandingDirections(self) -> Qt.Orientation: # noqa: N802 # reason: Qt override + """A flow grows in neither direction by itself.""" + return Qt.Orientation(0) + + def hasHeightForWidth(self) -> bool: # noqa: N802 # reason: Qt override + """Its height depends on the width it is given.""" + return True + + def heightForWidth(self, width: int) -> int: # noqa: N802 # reason: Qt override + """Height needed to lay every item out within ``width``.""" + return self._arrange(QRect(0, 0, width, 0), apply=False) + + def setGeometry(self, rect: QRect) -> None: # noqa: N802 # reason: Qt override + """Place the items inside ``rect``.""" + super().setGeometry(rect) + self._arrange(rect, apply=True) + + def sizeHint(self) -> QSize: # noqa: N802 # reason: Qt override + """Everything on one line.""" + width = sum(item.sizeHint().width() for item in self._visible()) + width += self.spacing() * max(0, len(self._visible()) - 1) + height = max((item.sizeHint().height() for item in self._visible()), default=0) + return QSize(width, height).grownBy(self.contentsMargins()) + + def minimumSize(self) -> QSize: # noqa: N802 # reason: Qt override + """The largest single item: the layout never needs more width than that.""" + size = QSize() + for item in self._visible(): + size = size.expandedTo(item.minimumSize()) + return size.grownBy(self.contentsMargins()) + + def _visible(self) -> List[QLayoutItem]: + return [item for item in self._items if (widget := item.widget()) is None or not widget.isHidden()] + + def _arrange(self, rect: QRect, *, apply: bool) -> int: + margins: QMargins = self.contentsMargins() + area = rect.marginsRemoved(margins) + x, y, line_height = area.x(), area.y(), 0 + spacing = self.spacing() + for item in self._visible(): + hint = item.sizeHint() + width = min(hint.width(), max(item.minimumSize().width(), area.width())) + if x > area.x() and x + width > area.right() + 1: + x, y, line_height = area.x(), y + line_height + spacing, 0 + if apply: + height = item.heightForWidth(width) if item.hasHeightForWidth() else hint.height() + item.setGeometry(QRect(QPoint(x, y), QSize(width, height))) + line_height = max(line_height, item.heightForWidth(width) if item.hasHeightForWidth() else hint.height()) + x += width + spacing + return y + line_height - rect.y() + margins.bottom() + + +def field_pair(label: QWidget, field: QWidget, spacing: int = 6) -> QWidget: + """A label and its field kept together on one line, so a flow row wraps between pairs, not inside one.""" + pair = QWidget() + layout = QHBoxLayout(pair) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(spacing) + layout.addWidget(label) + layout.addWidget(field, 1) + return pair + + +def flow_of(*widgets: QWidget, spacing: int = 12) -> FlowLayout: + """A :class:`FlowLayout` holding ``widgets`` in order.""" + flow = FlowLayout(spacing=spacing) + for widget in widgets: + flow.addWidget(widget) + return flow diff --git a/je_auto_control/gui/adaptive/glyphs.py b/je_auto_control/gui/adaptive/glyphs.py new file mode 100644 index 000000000..eaafd2e5a --- /dev/null +++ b/je_auto_control/gui/adaptive/glyphs.py @@ -0,0 +1,52 @@ +"""Small line icons drawn in code, so the navigation rail ships no image files and follows the theme.""" +from typing import Callable, Dict + +from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtGui import QColor, QIcon, QPainter, QPen, QPixmap + +_Painter = Callable[[QPainter, float], None] + + +def _menu(painter: QPainter, side: float) -> None: + for fraction in (0.3, 0.5, 0.7): + painter.drawLine(QPointF(side * 0.2, side * fraction), QPointF(side * 0.8, side * fraction)) + + +def _search(painter: QPainter, side: float) -> None: + painter.drawEllipse(QRectF(side * 0.2, side * 0.2, side * 0.42, side * 0.42)) + painter.drawLine(QPointF(side * 0.57, side * 0.57), QPointF(side * 0.8, side * 0.8)) + + +def _details(painter: QPainter, side: float) -> None: + painter.drawRoundedRect(QRectF(side * 0.18, side * 0.22, side * 0.64, side * 0.56), side * 0.06, side * 0.06) + painter.drawLine(QPointF(side * 0.58, side * 0.22), QPointF(side * 0.58, side * 0.78)) + + +GLYPHS: Dict[str, _Painter] = {"menu": _menu, "search": _search, "details": _details} + + +def glyph_pixmap(name: str, colour: str, side: int = 20, scale: float = 1.0) -> QPixmap: + """The glyph ``name`` stroked in ``colour`` on a transparent ``side``-pixel square at ``scale``.""" + paint = GLYPHS[name] + pixmap = QPixmap(round(side * scale), round(side * scale)) + pixmap.setDevicePixelRatio(scale) + pixmap.fill(Qt.GlobalColor.transparent) + pen = QPen(QColor(colour), max(1.5, side / 12)) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + painter = QPainter(pixmap) + try: + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + painter.setPen(pen) + painter.setBrush(Qt.BrushStyle.NoBrush) + paint(painter, float(side)) + finally: + painter.end() + return pixmap + + +def glyph_icon(name: str, colour: str, side: int = 20) -> QIcon: + """An icon holding the glyph at 1x, 2x and 3x, which Qt picks by screen scale.""" + icon = QIcon() + for scale in (1.0, 2.0, 3.0): + icon.addPixmap(glyph_pixmap(name, colour, side, scale)) + return icon diff --git a/je_auto_control/gui/adaptive/overlay.py b/je_auto_control/gui/adaptive/overlay.py new file mode 100644 index 000000000..d1e5ae908 --- /dev/null +++ b/je_auto_control/gui/adaptive/overlay.py @@ -0,0 +1,102 @@ +"""A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed.""" +from typing import Optional + +from PySide6.QtCore import QEvent, QObject, QRect, Qt, Signal +from PySide6.QtGui import QColor, QKeySequence, QMouseEvent, QPainter, QPaintEvent, QShortcut +from PySide6.QtWidgets import QFrame, QVBoxLayout, QWidget + +#: Widest a drawer gets, and the share of the host it may cover when the host is narrower. +DRAWER_WIDTH = 320 +DRAWER_SHARE = 0.85 + + +class OverlayDrawer(QWidget): + """Cover ``host`` with a dimming scrim and show one panel along its left or right edge. + + Escape or a click on the scrim closes it; :attr:`closed` then fires. The + drawer keeps its geometry matched to the host's as the host is resized. + """ + + closed = Signal() + + def __init__(self, host: QWidget, side: Qt.Edge = Qt.Edge.LeftEdge, object_name: str = "") -> None: + super().__init__(host) + self._host = host + self.side = side + self.panel = QFrame(self) + if object_name: + self.panel.setObjectName(object_name) + self.panel.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self._content = QVBoxLayout(self.panel) + self._content.setContentsMargins(0, 0, 0, 0) + escape = QShortcut(QKeySequence(Qt.Key.Key_Escape), self) + escape.setContext(Qt.ShortcutContext.WidgetWithChildrenShortcut) + escape.activated.connect(self.close_drawer) + host.installEventFilter(self) + self.hide() + + @property + def is_open(self) -> bool: + """Whether the drawer is showing.""" + return not self.isHidden() + + def set_content(self, widget: Optional[QWidget]) -> None: + """Make ``widget`` the panel's only content (``None`` empties it); the previous one is detached, not deleted.""" + while self._content.count(): + item = self._content.takeAt(0) + previous = item.widget() if item is not None else None + if previous is not None and previous is not widget: + previous.setParent(None) + if widget is not None: + self._content.addWidget(widget) + widget.show() + + def content(self) -> Optional[QWidget]: + """The widget the panel holds, or ``None``.""" + item = self._content.itemAt(0) + return item.widget() if item is not None else None + + def open_drawer(self) -> None: + """Show the drawer above everything else in the host.""" + self._fit() + self.show() + self.raise_() + + def close_drawer(self) -> None: + """Hide the drawer and report it.""" + if self.isHidden(): + return + self.hide() + self.closed.emit() + + def panel_rect(self, width: int, height: int) -> QRect: + """Where the panel goes inside a host of ``width`` x ``height``.""" + panel_width = min(DRAWER_WIDTH, int(width * DRAWER_SHARE)) + left = 0 if self.side == Qt.Edge.LeftEdge else width - panel_width + return QRect(left, 0, panel_width, height) + + def _fit(self) -> None: + self.setGeometry(self._host.rect()) + self.panel.setGeometry(self.panel_rect(self._host.width(), self._host.height())) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 # reason: Qt override + """Follow the host's size while open.""" + if watched is self._host and event.type() == QEvent.Type.Resize and self.is_open: + self._fit() + return False + + def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 # reason: Qt override + """A click on the dimmed area outside the panel dismisses the drawer.""" + if not self.panel.geometry().contains(event.position().toPoint()): + self.close_drawer() + event.accept() + return + super().mousePressEvent(event) + + def paintEvent(self, _event: QPaintEvent) -> None: # noqa: N802 # reason: Qt override + """Dim the host behind the panel.""" + painter = QPainter(self) + try: + painter.fillRect(self.rect(), QColor(0, 0, 0, 96)) + finally: + painter.end() diff --git a/je_auto_control/gui/adaptive/responsive.py b/je_auto_control/gui/adaptive/responsive.py new file mode 100644 index 000000000..1062880c0 --- /dev/null +++ b/je_auto_control/gui/adaptive/responsive.py @@ -0,0 +1,119 @@ +"""Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide.""" +from typing import Optional + +from PySide6.QtCore import QCoreApplication, QEvent, QObject +from PySide6.QtGui import QResizeEvent +from PySide6.QtWidgets import QBoxLayout, QComboBox, QFormLayout, QLabel, QLayout, QSizePolicy, QTabWidget, QWidget + +#: Below this many logical pixels a :class:`ResponsiveBox` stacks its parts. +DEFAULT_STACK_BELOW = 720 +#: Characters a combo box shows at its minimum; longer entries are elided, not sized for. +COMBO_MINIMUM_CHARACTERS = 14 +_FITTED = "_adaptive_fitted" + + +class ResponsiveBox(QWidget): + """Parts side by side when there is room, one above the other when there is not. + + ``stretches`` sets each part's share of the width when side by side; stacked, + they share the height the same way. + """ + + def __init__(self, *parts: QWidget, stack_below: int = DEFAULT_STACK_BELOW, + stretches: tuple = (), spacing: int = 12, parent: Optional[QWidget] = None) -> None: + super().__init__(parent) + self.stack_below = stack_below + self._layout = QBoxLayout(QBoxLayout.Direction.LeftToRight, self) + self._layout.setContentsMargins(0, 0, 0, 0) + self._layout.setSpacing(spacing) + for index, part in enumerate(parts): + stretch = stretches[index] if index < len(stretches) else 1 + self._layout.addWidget(part, stretch) + + @property + def stacked(self) -> bool: + """Whether the parts are currently one above the other.""" + return self._layout.direction() == QBoxLayout.Direction.TopToBottom + + def minimumSizeHint(self): # noqa: N802 # reason: Qt override + """Never ask for more width than the widest part needs on its own.""" + hint = super().minimumSizeHint() + items = (self._layout.itemAt(index) for index in range(self._layout.count())) + widest = max((item.minimumSize().width() for item in items if item is not None), default=0) + hint.setWidth(widest) + return hint + + def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 # reason: Qt override + """Switch between side by side and stacked as the width crosses ``stack_below``.""" + self.arrange(event.size().width()) + super().resizeEvent(event) + + def arrange(self, width: int) -> None: + """Lay the parts out for ``width`` pixels.""" + direction = QBoxLayout.Direction.TopToBottom if width < self.stack_below \ + else QBoxLayout.Direction.LeftToRight + if self._layout.direction() != direction: + self._layout.setDirection(direction) + + +def _fit_combo(combo: QComboBox) -> None: + combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) + combo.setMinimumContentsLength(COMBO_MINIMUM_CHARACTERS) + combo.setSizePolicy(QSizePolicy.Policy.Expanding, combo.sizePolicy().verticalPolicy()) + # The two setters above clear the cached size hint but not the cached + # minimum size hint; only a style or font change does, so send one. + QCoreApplication.sendEvent(combo, QEvent(QEvent.Type.StyleChange)) + + +def _fit_layout(layout: Optional[QLayout]) -> None: + if layout is None: + return + if isinstance(layout, QFormLayout): + layout.setRowWrapPolicy(QFormLayout.RowWrapPolicy.WrapLongRows) + layout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) + for index in range(layout.count()): + item = layout.itemAt(index) + if item is not None: + _fit_layout(item.layout()) + + +def fit_to_width(root: QWidget) -> int: + """Let every control under ``root`` shrink with the window; return how many were adjusted. + + Combo boxes stop sizing themselves to their longest entry, form layouts + move a label above its field when both do not fit, long labels wrap and + nested tab widgets scroll their tab bar. Run once, after the page is + built; a control already fitted is left alone, so calling it again is cheap. + """ + adjusted = 0 + widgets = [root, *root.findChildren(QWidget)] + for widget in widgets: + if widget.property(_FITTED): + continue + widget.setProperty(_FITTED, True) + _fit_layout(widget.layout()) + if isinstance(widget, QComboBox): + _fit_combo(widget) + elif isinstance(widget, QLabel) and not widget.wordWrap() and len(widget.text()) > 40: + widget.setWordWrap(True) + elif isinstance(widget, QTabWidget): + widget.setUsesScrollButtons(True) + else: + continue + adjusted += 1 + return adjusted + + +class WidthWatcher(QObject): + """Call ``callback(width)`` whenever ``target`` is resized.""" + + def __init__(self, target: QWidget, callback) -> None: + super().__init__(target) + self._callback = callback + target.installEventFilter(self) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 # reason: Qt override + """Report the new width of the watched widget.""" + if event.type() == QEvent.Type.Resize and isinstance(watched, QWidget): + self._callback(watched.width()) + return False diff --git a/je_auto_control/gui/adaptive/style.py b/je_auto_control/gui/adaptive/style.py new file mode 100644 index 000000000..0b550d09c --- /dev/null +++ b/je_auto_control/gui/adaptive/style.py @@ -0,0 +1,102 @@ +"""Fusion with check boxes and radio buttons drawn from the palette's accent. + +Fusion outlines both indicators with a shade of the window colour, which on the +dark theme all but disappears (an unchecked radio button showed no ring at all). +Styling ``::indicator`` in the style sheet would fix the outline but drop the +check mark, which a style sheet can only draw from an image file. This proxy +paints both in code instead, from the widget's palette, so they follow the theme. +""" +from typing import Any, Optional + +from PySide6.QtCore import QPointF, QRectF, Qt +from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen +from PySide6.QtWidgets import QProxyStyle, QStyle, QStyleOption, QWidget + +_INDICATORS = (QStyle.PrimitiveElement.PE_IndicatorCheckBox, QStyle.PrimitiveElement.PE_IndicatorRadioButton) + + +def _state(option: QStyleOption) -> tuple: + flags = option.state + checked = bool(flags & QStyle.StateFlag.State_On) + partial = bool(flags & QStyle.StateFlag.State_NoChange) + enabled = bool(flags & QStyle.StateFlag.State_Enabled) + hovered = bool(flags & QStyle.StateFlag.State_MouseOver) + return checked, partial, enabled, hovered + + +def _colours(option: QStyleOption, checked: bool, enabled: bool, hovered: bool) -> tuple: + palette = option.palette + accent = palette.highlight().color() + base = palette.base().color() + outline = palette.placeholderText().color() + if hovered and enabled: + outline = accent + if not enabled: + accent = QColor(outline) + accent.setAlpha(140) + return (accent if checked else outline), (accent if checked else base), palette.highlightedText().color() + + +def _square(rect: QRectF) -> QRectF: + side = min(rect.width(), rect.height()) - 2 + return QRectF(rect.center().x() - side / 2, rect.center().y() - side / 2, side, side) + + +def paint_indicator(painter: QPainter, option: QStyleOption, radio: bool) -> None: + """Draw one check box or radio indicator into ``option.rect``.""" + checked, partial, enabled, hovered = _state(option) + border, fill, mark = _colours(option, checked or partial, enabled, hovered) + box = _square(QRectF(option.rect)) + painter.save() + try: + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + painter.setPen(QPen(border, 1.5)) + if radio: + painter.setBrush(option.palette.base().color()) + painter.drawEllipse(box) + if checked: + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(fill) + inner = box.width() * 0.25 + painter.drawEllipse(box.adjusted(inner, inner, -inner, -inner)) + return + painter.setBrush(fill) + painter.drawRoundedRect(box, 3, 3) + pen = QPen(mark, max(1.6, box.width() / 8)) + pen.setCapStyle(Qt.PenCapStyle.RoundCap) + pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) + painter.setPen(pen) + painter.setBrush(Qt.BrushStyle.NoBrush) + left, top, side = box.left(), box.top(), box.width() + if partial: + painter.drawLine(QPointF(left + side * 0.28, top + side / 2), QPointF(left + side * 0.72, top + side / 2)) + elif checked: + path = QPainterPath(QPointF(left + side * 0.24, top + side * 0.52)) + path.lineTo(QPointF(left + side * 0.43, top + side * 0.70)) + path.lineTo(QPointF(left + side * 0.76, top + side * 0.32)) + painter.drawPath(path) + finally: + painter.restore() + + +class AdaptiveStyle(QProxyStyle): + """Fusion, with theme-coloured vector check boxes and radio buttons.""" + + def __init__(self, base: str = "Fusion") -> None: + super().__init__(base) + + def drawPrimitive(self, element: QStyle.PrimitiveElement, option: QStyleOption, # noqa: N802 # reason: Qt override + painter: QPainter, widget: Optional[QWidget] = None) -> None: + """Paint the two indicators here; leave every other element to Fusion.""" + if element in _INDICATORS: + paint_indicator(painter, option, element == QStyle.PrimitiveElement.PE_IndicatorRadioButton) + return + super().drawPrimitive(element, option, painter, widget) + + def pixelMetric(self, metric: QStyle.PixelMetric, option: Any = None, # noqa: N802 # reason: Qt override + widget: Optional[QWidget] = None) -> int: + """Slightly larger indicators than Fusion's 13 px, easier to hit and to see.""" + if metric in (QStyle.PixelMetric.PM_IndicatorWidth, QStyle.PixelMetric.PM_IndicatorHeight, + QStyle.PixelMetric.PM_ExclusiveIndicatorWidth, QStyle.PixelMetric.PM_ExclusiveIndicatorHeight): + return 16 + return super().pixelMetric(metric, option, widget) diff --git a/je_auto_control/gui/adaptive/surfaces.py b/je_auto_control/gui/adaptive/surfaces.py new file mode 100644 index 000000000..5f769b70d --- /dev/null +++ b/je_auto_control/gui/adaptive/surfaces.py @@ -0,0 +1,160 @@ +"""Cards, page headers and empty states: the shared surfaces every page is built from. + +They carry a ``role`` property the theme's style sheet targets +(``QFrame[role="card"]``, ``QLabel[role="pageTitle"]`` ...), so the look lives +in :mod:`je_auto_control.gui.theme` and a page only says what each part is. +""" +from typing import Optional + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QBoxLayout, QFrame, QLabel, QLayout, QVBoxLayout, QWidget + +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper + +#: Property naming what a widget is to the style sheet. +ROLE = "role" +_HEADER_NAME = "AdaptivePageHeader" + + +def set_role(widget: QWidget, role: str) -> QWidget: + """Tag ``widget`` for the style sheet and re-polish it so the change shows.""" + widget.setProperty(ROLE, role) + style = widget.style() + style.unpolish(widget) + style.polish(widget) + return widget + + +def optional_text(key: str) -> str: + """``key`` in the active language, or ``""`` when no language defines it.""" + if not key: + return "" + text = language_wrapper.translate(key, "") + return "" if text == key else text + + +def _label(role: str, wrap: bool = True) -> QLabel: + label = QLabel() + label.setTextFormat(Qt.TextFormat.PlainText) + label.setWordWrap(wrap) + set_role(label, role) + return label + + +class Card(QFrame): + """A raised panel with an optional title, holding one group of related controls.""" + + def __init__(self, title_key: str = "", parent: Optional[QWidget] = None, *, + title_default: str = "") -> None: + super().__init__(parent) + set_role(self, "card") + self._title_key, self._title_default = title_key, title_default + self._outer = QVBoxLayout(self) + self._outer.setContentsMargins(16, 14, 16, 16) + self._outer.setSpacing(10) + self.title = _label("sectionTitle") + self.title.setVisible(bool(title_key)) + self._outer.addWidget(self.title) + self.retranslate() + + @property + def body(self) -> QVBoxLayout: + """The layout the card's controls go into.""" + return self._outer + + def add(self, item: "QWidget | QLayout", stretch: int = 0) -> "Card": + """Append a widget or a layout to the card; returns the card for chaining.""" + if isinstance(item, QLayout): + self._outer.addLayout(item, stretch) + else: + self._outer.addWidget(item, stretch) + return self + + def retranslate(self) -> None: + """Re-read the title in the active language.""" + if self._title_key: + self.title.setText(language_wrapper.translate(self._title_key, self._title_default or self._title_key)) + + +class PageHeader(QWidget): + """Page title and a one-line description of what the page is for.""" + + def __init__(self, title_key: str, subtitle_key: str = "", parent: Optional[QWidget] = None) -> None: + super().__init__(parent) + self.setObjectName(_HEADER_NAME) + self._title_key, self._subtitle_key = title_key, subtitle_key + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 4) + layout.setSpacing(2) + self.title = _label("pageTitle") + self.subtitle = _label("pageSubtitle") + layout.addWidget(self.title) + layout.addWidget(self.subtitle) + self.retranslate() + + def retranslate(self) -> None: + """Re-read both lines in the active language; a subtitle with no text is hidden.""" + translate = language_wrapper.translate + self.title.setText(translate(self._title_key, self._title_key)) + subtitle = optional_text(self._subtitle_key) + self.subtitle.setText(subtitle) + self.subtitle.setVisible(bool(subtitle)) + + +class EmptyState(QWidget): + """Centred message shown in place of an empty list or table.""" + + def __init__(self, message_key: str, hint_key: str = "", parent: Optional[QWidget] = None) -> None: + super().__init__(parent) + self._message_key, self._hint_key = message_key, hint_key + layout = QVBoxLayout(self) + layout.setContentsMargins(24, 24, 24, 24) + layout.setSpacing(4) + self.message = _label("emptyMessage") + self.hint = _label("hint") + for label in (self.message, self.hint): + label.setAlignment(Qt.AlignmentFlag.AlignHCenter) + layout.addWidget(label) + self.retranslate() + + def retranslate(self) -> None: + """Re-read the message and hint in the active language.""" + translate = language_wrapper.translate + self.message.setText(translate(self._message_key, self._message_key)) + hint = optional_text(self._hint_key) + self.hint.setText(hint) + self.hint.setVisible(bool(hint)) + + +def page_header(page: QWidget) -> Optional[PageHeader]: + """The header :func:`add_page_header` gave ``page``, or ``None``.""" + found = page.findChild(PageHeader, _HEADER_NAME, Qt.FindChildOption.FindDirectChildrenOnly) + return found if isinstance(found, PageHeader) else None + + +def add_page_header(page: QWidget, title_key: str, subtitle_key: str = "") -> Optional[PageHeader]: + """Put a :class:`PageHeader` at the top of ``page``; ``None`` when its layout cannot take one. + + Only a page laid out by a box layout gets a header (anything else would have + to be re-laid out, which is the page's own business). Calling it again + returns the header already there. + """ + existing = page_header(page) + if existing is not None: + return existing + layout = page.layout() + if not isinstance(layout, QBoxLayout) or layout.direction() != QBoxLayout.Direction.TopToBottom: + return None + header = PageHeader(title_key, subtitle_key, page) + layout.insertWidget(0, header) + return header + + +def retranslate_surfaces(root: QWidget) -> None: + """Re-read every card title, page header and empty state under ``root`` in the active language.""" + for header in root.findChildren(PageHeader): + header.retranslate() + for card in root.findChildren(Card): + card.retranslate() + for empty in root.findChildren(EmptyState): + empty.retranslate() diff --git a/je_auto_control/gui/adaptive_window.py b/je_auto_control/gui/adaptive_window.py new file mode 100644 index 000000000..d09c85fb6 --- /dev/null +++ b/je_auto_control/gui/adaptive_window.py @@ -0,0 +1,179 @@ +"""Rearrange the main window's navigation and details panes as the window's width class changes. + +Expanded windows dock both panes beside the tabs. Medium ones keep the +navigation docked but open the details as a drawer. Compact ones replace the +docked navigation with a narrow rail of icons; its menu button and ``Ctrl+K`` +open the navigation as a drawer over the tabs. Whether the user wants the +docked navigation is remembered separately from whether the width allows it, +so a narrow spell never overwrites the saved preference. +""" +from typing import Callable, Optional + +from PySide6.QtCore import QEvent, QObject, QSize, Qt, Signal +from PySide6.QtGui import QAction +from PySide6.QtWidgets import QDockWidget, QMainWindow, QSizePolicy, QToolBar, QWidget + +from je_auto_control.gui.adaptive.breakpoints import WidthClass, classify +from je_auto_control.gui.adaptive.glyphs import glyph_icon +from je_auto_control.gui.adaptive.overlay import OverlayDrawer +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper +from je_auto_control.gui.navigation import NavigationPanel +from je_auto_control.gui.workspace import WorkspaceShell + + +def _t(key: str, default: str) -> str: + return language_wrapper.translate(key, default) + + +class AdaptiveWindowLayout(QObject): + """Owns the navigation rail and drawer and decides where each pane goes for the window's width.""" + + #: Emitted with the new :class:`WidthClass` value whenever the window crosses a breakpoint. + width_class_changed = Signal(str) + #: Emitted whenever the navigation appears or disappears, docked or in its drawer. + navigation_shown_changed = Signal(bool) + + def __init__(self, window: QMainWindow, dock: QDockWidget, workspace: WorkspaceShell, + make_panel: Callable[[], NavigationPanel], *, navigation_preferred: bool) -> None: + super().__init__(window) + self._window, self._dock, self._workspace = window, dock, workspace + self.navigation_preferred = navigation_preferred + self.width_class: Optional[WidthClass] = None + self.rail = self._build_rail(window) + self.panel = make_panel() + self.drawer = OverlayDrawer(workspace, Qt.Edge.LeftEdge, "NavigationOverlay") + self.drawer.set_content(self.panel) + self.drawer.closed.connect(self._report_navigation) + self.panel.feature_activated.connect(self._on_feature_chosen) + dock.visibilityChanged.connect(self._on_dock_visibility) + window.installEventFilter(self) + self.update(window.width()) + + # --- the rail --------------------------------------------------------------- + + def _build_rail(self, window: QMainWindow) -> QToolBar: + rail = QToolBar(window) + rail.setObjectName("NavigationRail") + rail.setMovable(False) + rail.setFloatable(False) + rail.setOrientation(Qt.Orientation.Vertical) + rail.setIconSize(QSize(20, 20)) + rail.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) + rail.toggleViewAction().setVisible(False) + self.menu_action = QAction(rail) + self.menu_action.triggered.connect(self.toggle_navigation) + self.search_action = QAction(rail) + self.search_action.triggered.connect(self.reveal_search) + self.details_action = QAction(rail) + # Bound methods rather than lambdas over ``self``: a closure freed while Qt + # tears the window down at exit can drop a last reference shiboken then + # double-deletes (see ScrollableTabs._install_close_button). + self.details_action.triggered.connect(self._toggle_details) + rail.addAction(self.menu_action) + rail.addAction(self.search_action) + spacer = QWidget(rail) + spacer.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding) + rail.addWidget(spacer) + rail.addAction(self.details_action) + window.addToolBar(Qt.ToolBarArea.LeftToolBarArea, rail) + rail.hide() + self.retranslate() + return rail + + def set_glyph_colour(self, colour: str) -> None: + """Redraw the rail's icons in ``colour`` (called when the theme changes).""" + for action, name in ((self.menu_action, "menu"), (self.search_action, "search"), + (self.details_action, "details")): + action.setIcon(glyph_icon(name, colour)) + + def retranslate(self) -> None: + """Re-read the rail's tooltips and the drawer panel's texts in the active language.""" + for action, key, default in ( + (self.menu_action, "menu_view_sidebar", "Navigation Panel"), + (self.search_action, "menu_view_search", "Search Features..."), + (self.details_action, "workspace_details_title", "Execution details")): + text = _t(key, default) + action.setText(text) + action.setToolTip(text) + panel = getattr(self, "panel", None) + if panel is not None: + panel.retranslate() + + # --- width classes ------------------------------------------------------------ + + @property + def compact(self) -> bool: + """Whether the window is in its one-pane arrangement.""" + return self.width_class is WidthClass.COMPACT + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 # reason: Qt override + """Re-classify the window on every resize.""" + if watched is self._window and event.type() == QEvent.Type.Resize: + self.update(self._window.width()) + return False + + def update(self, width: int) -> None: + """Rearrange the panes if ``width`` puts the window in a different class.""" + new = classify(max(0, width), self.width_class) + if new is self.width_class: + return + self.width_class = new + compact = new is WidthClass.COMPACT + self.rail.setVisible(compact) + self._dock.setVisible(self.navigation_preferred and not compact) + if not compact: + self.drawer.hide() + self._workspace.set_details_overlay(new is not WidthClass.EXPANDED) + self.width_class_changed.emit(new.value) + self._report_navigation() + + # --- navigation ---------------------------------------------------------------- + + def navigation_shown(self) -> bool: + """Whether the feature list is on screen, docked or in its drawer.""" + return self.drawer.is_open if self.compact else not self._dock.isHidden() + + def set_navigation_preferred(self, visible: bool) -> None: + """Record whether the docked navigation is wanted; show or hide it if the width allows docking.""" + self.navigation_preferred = visible + if not self.compact: + self._dock.setVisible(visible) + self._report_navigation() + + def toggle_navigation(self) -> None: + """``Ctrl+B``: open or close the drawer when compact, otherwise show or hide the docked panel.""" + if self.compact: + if self.drawer.is_open: + self.drawer.close_drawer() + else: + self.drawer.open_drawer() + self.panel.tree.setFocus() + self._report_navigation() + return + self.set_navigation_preferred(self._dock.isHidden()) + + def reveal_search(self) -> NavigationPanel: + """Show the feature list wherever it lives at this width and return the panel whose search to focus.""" + if self.compact: + self.drawer.open_drawer() + self.panel.focus_search() + self._report_navigation() + return self.panel + self.set_navigation_preferred(True) + docked = self._dock.widget() + if isinstance(docked, NavigationPanel): + docked.focus_search() + return docked + return self.panel + + def _toggle_details(self) -> None: + self._workspace.set_details_visible(not self._workspace.details_visible()) + + def _on_dock_visibility(self, _visible: bool) -> None: + self._report_navigation() + + def _on_feature_chosen(self, _key: str) -> None: + self.drawer.close_drawer() + + def _report_navigation(self) -> None: + self.navigation_shown_changed.emit(self.navigation_shown()) diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index 842d3e54e..c1f523b7f 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -2081,3 +2081,56 @@ 'workspace_phase_cancelled': 'Cancelled', 'workspace_phase_error': 'Error', 'workspace_phase_unavailable': 'Unavailable'}) + +english_word_dict.update({ + 'tab_auto_click_subtitle': 'Click or type repeatedly at a fixed interval until stopped or a count is reached.', + 'tab_screenshot_subtitle': 'Capture the screen or a region, and read the colour of any pixel.', + 'tab_image_detect_subtitle': 'Find a template image on screen and act on where it appears.', + 'tab_record_subtitle': 'Record mouse and keyboard input, then play it back as an action list.', + 'tab_script_builder_subtitle': 'Compose an action script step by step and run it.', + 'tab_flow_editor_subtitle': 'Draw a script as connected nodes and export it as an action list.', + 'tab_script_subtitle': 'Load an action JSON file and run it in the background.', + 'tab_recording_editor_subtitle': 'Trim, filter and rescale a recorded action list before replaying it.', + 'tab_variables_subtitle': 'Inspect, seed and clear the variables scripts read at run time.', + 'tab_secrets_subtitle': 'Unlock the vault and manage the secrets scripts reference by name.', + 'tab_vlm_subtitle': 'Describe a UI element in words and let a vision model find it.', + 'tab_self_healing_subtitle': 'Compare a failing locator against a fixed frame and review the repaired step.', + 'tab_ocr_reader_subtitle': 'Read the text in a screen region, or search it with a pattern.', + 'tab_accessibility_subtitle': "Browse the operating system's UI tree and act on elements by role and name.", + 'tab_live_hud_subtitle': 'Watch the pointer position, the colour under it and the latest log lines.', + 'tab_llm_planner_subtitle': 'Describe a task in plain language, preview the planned actions, then run them.', + 'tab_computer_use_subtitle': 'Run a model-driven agent that sees the screen and operates it step by step.', + 'tab_agent_tasks_subtitle': 'Queue, watch and review tasks the agent runtime carries out.', + 'tab_scheduler_subtitle': 'Run action files on an interval or a cron schedule.', + 'tab_hotkeys_subtitle': 'Bind global hotkeys to action files.', + 'tab_triggers_subtitle': 'Run a script when an image, window, pixel or file changes.', + 'tab_webhooks_subtitle': 'Run a script when an HTTP request arrives.', + 'tab_email_triggers_subtitle': 'Run a script when matching mail reaches an IMAP mailbox.', + 'tab_test_suite_subtitle': 'Run a test suite and manage the tests quarantined as flaky.', + 'tab_assertions_subtitle': 'Check one screen-state assertion and see whether it passes.', + 'tab_data_source_subtitle': 'Preview the rows a data-driven run will read.', + 'tab_flakiness_subtitle': 'Rank scripts that fail only some of the time, from run history.', + 'tab_a11y_audit_subtitle': 'Find accessibility and localisation defects in the live UI tree.', + 'tab_device_matrix_subtitle': 'Run one action list on many devices at once and compare the results.', + 'tab_mobile_subtitle': 'Probe an Android or iOS device and run one mobile command on it.', + 'tab_media_checks_subtitle': 'Assert that audio is playing or that video is moving.', + 'tab_run_history_subtitle': 'Browse past runs, their artifacts and their action journals.', + 'tab_profiler_subtitle': 'See which actions took the most time.', + 'tab_window_manager_subtitle': 'List open windows, then focus, move or close them.', + 'tab_plugins_subtitle': 'Load extra action commands from a folder of your own.', + 'tab_webrunner_subtitle': 'Drive a web browser through the WebRunner bridge.', + 'tab_dag_runner_subtitle': 'Edit, validate and run a graph of dependent jobs across hosts.', + 'tab_chatops_subtitle': 'Try chat slash commands locally before connecting them to Slack.', + 'tab_trace_replay_subtitle': 'Step back and forth through a recorded run, frame by frame.', + 'tab_remote_desktop_subtitle': "Share this screen or connect to another machine's.", + 'tab_presence_subtitle': 'See who is watching a shared screen right now.', + 'tab_rest_api_subtitle': 'Start the local HTTP API, see how to authenticate and manage its users.', + 'tab_admin_console_subtitle': 'Manage many remote AutoControl endpoints from one place.', + 'tab_audit_log_subtitle': 'Browse the audit log and verify that its chain is intact.', + 'tab_inspector_subtitle': 'Watch live statistics of a remote desktop connection.', + 'tab_usb_devices_subtitle': 'List the USB devices attached to this machine and watch for changes.', + 'tab_usb_browser_subtitle': 'Browse the USB devices a remote host offers.', + 'tab_usb_share_subtitle': 'Share a local USB device with a remote session, or use one it shares.', + 'tab_diagnostics_subtitle': 'Check what this machine can automate and why a feature is unavailable.', + 'tab_config_sync_subtitle': 'Synchronise workspace settings and scripts with other machines.', + 'tab_report_subtitle': 'Turn recorded test results into HTML, JSON or XML reports.'}) diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index 84f87937e..cb7a5ca3a 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -1973,3 +1973,56 @@ 'workspace_phase_cancelled': 'キャンセル済み', 'workspace_phase_error': 'エラー', 'workspace_phase_unavailable': '利用不可'}) + +japanese_word_dict.update({ + 'tab_auto_click_subtitle': '停止するか回数に達するまで、一定間隔でクリックや入力を繰り返します。', + 'tab_screenshot_subtitle': '画面全体または領域をキャプチャし、任意のピクセルの色を読み取ります。', + 'tab_image_detect_subtitle': '画面上でテンプレート画像を探し、見つかった位置で操作します。', + 'tab_record_subtitle': 'マウスとキーボードの入力を記録し、アクションリストとして再生します。', + 'tab_script_builder_subtitle': 'アクションスクリプトを一手順ずつ組み立てて実行します。', + 'tab_flow_editor_subtitle': 'スクリプトをノードのつながりとして描き、アクションリストに書き出します。', + 'tab_script_subtitle': 'アクション JSON ファイルを読み込み、バックグラウンドで実行します。', + 'tab_recording_editor_subtitle': '再生する前に、記録したアクションリストを切り詰め、絞り込み、拡大縮小します。', + 'tab_variables_subtitle': 'スクリプトが実行時に読む変数を確認、設定、消去します。', + 'tab_secrets_subtitle': '保管庫を解錠し、スクリプトが名前で参照するシークレットを管理します。', + 'tab_vlm_subtitle': 'UI 要素を言葉で説明し、ビジョンモデルに探させます。', + 'tab_self_healing_subtitle': '失敗したロケーターを固定フレームと比較し、修復した手順を確認します。', + 'tab_ocr_reader_subtitle': '画面領域の文字を読み取るか、パターンで検索します。', + 'tab_accessibility_subtitle': 'OS の UI ツリーを参照し、ロールと名前で要素を操作します。', + 'tab_live_hud_subtitle': 'ポインターの位置、その下の色、最新のログを表示します。', + 'tab_llm_planner_subtitle': 'やりたいことを普通の言葉で書き、計画されたアクションを確認してから実行します。', + 'tab_computer_use_subtitle': '画面を見ながら一手順ずつ操作するモデル駆動のエージェントを実行します。', + 'tab_agent_tasks_subtitle': 'エージェントランタイムが実行するタスクをキューに入れ、監視し、確認します。', + 'tab_scheduler_subtitle': '一定間隔または cron スケジュールでアクションファイルを実行します。', + 'tab_hotkeys_subtitle': 'グローバルホットキーをアクションファイルに割り当てます。', + 'tab_triggers_subtitle': '画像、ウィンドウ、ピクセル、ファイルが変化したときにスクリプトを実行します。', + 'tab_webhooks_subtitle': 'HTTP リクエストを受け取ったときにスクリプトを実行します。', + 'tab_email_triggers_subtitle': '条件に合うメールが IMAP メールボックスに届いたときにスクリプトを実行します。', + 'tab_test_suite_subtitle': 'テストスイートを実行し、不安定として隔離したテストを管理します。', + 'tab_assertions_subtitle': '画面状態のアサーションを一つ確認し、合否を表示します。', + 'tab_data_source_subtitle': 'データ駆動の実行が読み込む行をプレビューします。', + 'tab_flakiness_subtitle': '実行履歴から、ときどき失敗するスクリプトを順位付けします。', + 'tab_a11y_audit_subtitle': '実際の UI ツリーからアクセシビリティとローカライズの不具合を探します。', + 'tab_device_matrix_subtitle': '一つのアクションリストを複数のデバイスで同時に実行し、結果を比べます。', + 'tab_mobile_subtitle': 'Android または iOS デバイスを調べ、モバイルコマンドを一つ実行します。', + 'tab_media_checks_subtitle': '音声が再生中か、映像が動いているかをアサートします。', + 'tab_run_history_subtitle': '過去の実行、その成果物とアクションジャーナルを参照します。', + 'tab_profiler_subtitle': 'どのアクションに最も時間がかかったかを確認します。', + 'tab_window_manager_subtitle': '開いているウィンドウを一覧にし、前面に出す、移動する、閉じることができます。', + 'tab_plugins_subtitle': '自分のフォルダーから追加のアクションコマンドを読み込みます。', + 'tab_webrunner_subtitle': 'WebRunner ブリッジを通じて Web ブラウザーを操作します。', + 'tab_dag_runner_subtitle': 'ホストをまたぐ依存ジョブのグラフを編集、検証、実行します。', + 'tab_chatops_subtitle': 'Slack につなぐ前に、チャットのスラッシュコマンドをローカルで試します。', + 'tab_trace_replay_subtitle': '記録した実行をコマ送りで前後に確認します。', + 'tab_remote_desktop_subtitle': 'この画面を共有するか、別のマシンの画面に接続します。', + 'tab_presence_subtitle': '共有中の画面をいま誰が見ているかを表示します。', + 'tab_rest_api_subtitle': 'ローカル HTTP API を起動し、認証方法を確認してユーザーを管理します。', + 'tab_admin_console_subtitle': '複数のリモート AutoControl エンドポイントを一か所で管理します。', + 'tab_audit_log_subtitle': '監査ログを参照し、チェーンが改ざんされていないことを検証します。', + 'tab_inspector_subtitle': 'リモートデスクトップ接続の統計をリアルタイムで表示します。', + 'tab_usb_devices_subtitle': 'このマシンに接続された USB デバイスを一覧にし、抜き差しを監視します。', + 'tab_usb_browser_subtitle': 'リモートホストが提供する USB デバイスを参照します。', + 'tab_usb_share_subtitle': 'ローカルの USB デバイスをリモートセッションと共有するか、相手が共有するものを使います。', + 'tab_diagnostics_subtitle': 'このマシンで何を自動化できるか、機能が使えない理由は何かを確認します。', + 'tab_config_sync_subtitle': 'ワークスペースの設定とスクリプトを他のマシンと同期します。', + 'tab_report_subtitle': '記録したテスト結果から HTML、JSON、XML のレポートを作成します。'}) diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index b66f45941..30284cecd 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1915,3 +1915,56 @@ 'workspace_phase_cancelled': '已取消', 'workspace_phase_error': '错误', 'workspace_phase_unavailable': '无法使用'}) + +simplified_chinese_word_dict.update({ + 'tab_auto_click_subtitle': '以固定间隔重复点击或输入,直到停止或达到次数。', + 'tab_screenshot_subtitle': '截取整个屏幕或区域,并读取任一像素的颜色。', + 'tab_image_detect_subtitle': '在屏幕上查找模板图片,并对找到的位置执行操作。', + 'tab_record_subtitle': '录制鼠标与键盘输入,再以动作列表回放。', + 'tab_script_builder_subtitle': '逐步组合动作脚本并执行。', + 'tab_flow_editor_subtitle': '以相连的节点绘制脚本,并导出为动作列表。', + 'tab_script_subtitle': '加载动作 JSON 文件并在后台执行。', + 'tab_recording_editor_subtitle': '回放前裁剪、筛选录制的动作列表或调整其比例。', + 'tab_variables_subtitle': '查看、预设与清除脚本运行时读取的变量。', + 'tab_secrets_subtitle': '解锁保管库,管理脚本以名称引用的机密。', + 'tab_vlm_subtitle': '用文字描述界面元素,由视觉模型找出它。', + 'tab_self_healing_subtitle': '以固定画面比对失效的定位器,并查看修复后的步骤。', + 'tab_ocr_reader_subtitle': '读取屏幕区域内的文字,或以模式搜索。', + 'tab_accessibility_subtitle': '浏览操作系统的界面树,按角色与名称操作元素。', + 'tab_live_hud_subtitle': '实时查看光标位置、其下的颜色与最新的日志。', + 'tab_llm_planner_subtitle': '以自然语言描述任务,预览规划的动作后再执行。', + 'tab_computer_use_subtitle': '运行能看到屏幕并逐步操作的模型代理。', + 'tab_agent_tasks_subtitle': '排入、监视与审阅代理运行环境处理的任务。', + 'tab_scheduler_subtitle': '按间隔或 cron 计划执行动作文件。', + 'tab_hotkeys_subtitle': '将全局快捷键绑定到动作文件。', + 'tab_triggers_subtitle': '在图片、窗口、像素或文件变化时执行脚本。', + 'tab_webhooks_subtitle': '在收到 HTTP 请求时执行脚本。', + 'tab_email_triggers_subtitle': '在符合条件的邮件到达 IMAP 邮箱时执行脚本。', + 'tab_test_suite_subtitle': '运行测试套件,并管理被隔离的不稳定测试。', + 'tab_assertions_subtitle': '检查一项画面状态断言,查看是否通过。', + 'tab_data_source_subtitle': '预览数据驱动运行将读取的数据行。', + 'tab_flakiness_subtitle': '根据运行记录找出时好时坏的脚本并排序。', + 'tab_a11y_audit_subtitle': '在实时界面树中找出无障碍与本地化缺陷。', + 'tab_device_matrix_subtitle': '在多台设备上同时运行同一动作列表并比较结果。', + 'tab_mobile_subtitle': '探测 Android 或 iOS 设备,并在其上运行一个移动指令。', + 'tab_media_checks_subtitle': '断言音频正在播放或视频正在变动。', + 'tab_run_history_subtitle': '浏览过去的运行、产出物与动作日志。', + 'tab_profiler_subtitle': '查看哪些动作耗时最多。', + 'tab_window_manager_subtitle': '列出打开的窗口,并聚焦、移动或关闭它们。', + 'tab_plugins_subtitle': '从自己的文件夹加载额外的动作指令。', + 'tab_webrunner_subtitle': '通过 WebRunner 桥接操作网页浏览器。', + 'tab_dag_runner_subtitle': '编辑、验证并运行跨主机的依赖作业图。', + 'tab_chatops_subtitle': '连接 Slack 前,先在本地试用聊天斜杠指令。', + 'tab_trace_replay_subtitle': '逐帧来回查看录下的运行过程。', + 'tab_remote_desktop_subtitle': '共享本机画面,或连接到其他电脑的画面。', + 'tab_presence_subtitle': '查看当前谁在观看共享的画面。', + 'tab_rest_api_subtitle': '启动本地 HTTP API、查看认证方式并管理用户。', + 'tab_admin_console_subtitle': '在同一处管理多个远程 AutoControl 端点。', + 'tab_audit_log_subtitle': '浏览审计日志并验证其哈希链未被篡改。', + 'tab_inspector_subtitle': '实时查看远程桌面连接的统计数据。', + 'tab_usb_devices_subtitle': '列出本机连接的 USB 设备,并监视插拔变化。', + 'tab_usb_browser_subtitle': '浏览远程主机提供的 USB 设备。', + 'tab_usb_share_subtitle': '将本机 USB 设备共享给远程会话,或使用对方共享的设备。', + 'tab_diagnostics_subtitle': '检查本机能自动化哪些功能,以及某项功能为何无法使用。', + 'tab_config_sync_subtitle': '与其他电脑同步工作区设置与脚本。', + 'tab_report_subtitle': '将记录的测试结果生成为 HTML、JSON 或 XML 报告。'}) diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index 4f088a189..db0957b06 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1923,3 +1923,56 @@ 'workspace_phase_cancelled': '已取消', 'workspace_phase_error': '錯誤', 'workspace_phase_unavailable': '無法使用'}) + +traditional_chinese_word_dict.update({ + 'tab_auto_click_subtitle': '以固定間隔重複點擊或輸入,直到停止或達到次數。', + 'tab_screenshot_subtitle': '擷取整個螢幕或區域,並讀取任一像素的顏色。', + 'tab_image_detect_subtitle': '在螢幕上尋找樣板圖片,並對找到的位置執行動作。', + 'tab_record_subtitle': '錄製滑鼠與鍵盤輸入,再以動作清單回放。', + 'tab_script_builder_subtitle': '逐步組合動作腳本並執行。', + 'tab_flow_editor_subtitle': '以相連的節點繪製腳本,並匯出為動作清單。', + 'tab_script_subtitle': '載入動作 JSON 檔並在背景執行。', + 'tab_recording_editor_subtitle': '回放前裁切、篩選錄製的動作清單或調整其比例。', + 'tab_variables_subtitle': '檢視、預設與清除腳本執行時讀取的變數。', + 'tab_secrets_subtitle': '解鎖保管庫,管理腳本以名稱引用的機密。', + 'tab_vlm_subtitle': '用文字描述介面元素,由視覺模型找出它。', + 'tab_self_healing_subtitle': '以固定畫面比對失效的定位器,並檢視修復後的步驟。', + 'tab_ocr_reader_subtitle': '讀取螢幕區域內的文字,或以樣式搜尋。', + 'tab_accessibility_subtitle': '瀏覽作業系統的介面樹,依角色與名稱操作元素。', + 'tab_live_hud_subtitle': '即時查看游標位置、其下的顏色與最新的記錄。', + 'tab_llm_planner_subtitle': '以一般語言描述工作,預覽規劃的動作後再執行。', + 'tab_computer_use_subtitle': '執行能看見螢幕並逐步操作的模型代理。', + 'tab_agent_tasks_subtitle': '排入、監看與審閱代理執行環境處理的工作。', + 'tab_scheduler_subtitle': '依間隔或 cron 排程執行動作檔。', + 'tab_hotkeys_subtitle': '將全域快捷鍵綁定到動作檔。', + 'tab_triggers_subtitle': '在圖片、視窗、像素或檔案變化時執行腳本。', + 'tab_webhooks_subtitle': '在收到 HTTP 請求時執行腳本。', + 'tab_email_triggers_subtitle': '在符合條件的郵件到達 IMAP 信箱時執行腳本。', + 'tab_test_suite_subtitle': '執行測試套件,並管理被隔離的不穩定測試。', + 'tab_assertions_subtitle': '檢查一項畫面狀態斷言,查看是否通過。', + 'tab_data_source_subtitle': '預覽資料驅動執行將讀取的資料列。', + 'tab_flakiness_subtitle': '依執行記錄找出時好時壞的腳本並排序。', + 'tab_a11y_audit_subtitle': '在即時介面樹中找出無障礙與在地化缺陷。', + 'tab_device_matrix_subtitle': '在多台裝置上同時執行同一動作清單並比較結果。', + 'tab_mobile_subtitle': '探測 Android 或 iOS 裝置,並在其上執行一個行動指令。', + 'tab_media_checks_subtitle': '斷言音訊正在播放或影像正在變動。', + 'tab_run_history_subtitle': '瀏覽過去的執行、產出物與動作日誌。', + 'tab_profiler_subtitle': '查看哪些動作耗時最多。', + 'tab_window_manager_subtitle': '列出開啟中的視窗,並聚焦、移動或關閉它們。', + 'tab_plugins_subtitle': '從自己的資料夾載入額外的動作指令。', + 'tab_webrunner_subtitle': '透過 WebRunner 橋接操作網頁瀏覽器。', + 'tab_dag_runner_subtitle': '編輯、驗證並執行跨主機的相依工作圖。', + 'tab_chatops_subtitle': '連接 Slack 前,先在本機試用聊天斜線指令。', + 'tab_trace_replay_subtitle': '逐格來回檢視錄下的執行過程。', + 'tab_remote_desktop_subtitle': '分享本機畫面,或連線到其他電腦的畫面。', + 'tab_presence_subtitle': '查看目前誰在觀看分享的畫面。', + 'tab_rest_api_subtitle': '啟動本機 HTTP API、查看驗證方式並管理使用者。', + 'tab_admin_console_subtitle': '在同一處管理多個遠端 AutoControl 端點。', + 'tab_audit_log_subtitle': '瀏覽稽核記錄並驗證其雜湊鏈未被竄改。', + 'tab_inspector_subtitle': '即時查看遠端桌面連線的統計資料。', + 'tab_usb_devices_subtitle': '列出本機連接的 USB 裝置,並監看插拔變化。', + 'tab_usb_browser_subtitle': '瀏覽遠端主機提供的 USB 裝置。', + 'tab_usb_share_subtitle': '將本機 USB 裝置分享給遠端連線,或使用對方分享的裝置。', + 'tab_diagnostics_subtitle': '檢查本機能自動化哪些功能,以及某項功能為何無法使用。', + 'tab_config_sync_subtitle': '與其他電腦同步工作區設定與腳本。', + 'tab_report_subtitle': '將記錄的測試結果產生為 HTML、JSON 或 XML 報告。'}) diff --git a/je_auto_control/gui/main_window.py b/je_auto_control/gui/main_window.py index e116a69bc..c18b07b26 100644 --- a/je_auto_control/gui/main_window.py +++ b/je_auto_control/gui/main_window.py @@ -11,10 +11,11 @@ from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) +from je_auto_control.gui.adaptive_window import AdaptiveWindowLayout from je_auto_control.gui.main_widget import AutoControlGUIWidget from je_auto_control.gui.navigation import NavigationPanel from je_auto_control.gui.theme import ( - THEMES, apply_theme, font_rule, prepare_application, theme_named, + THEMES, apply_theme, font_rule, prepare_application, theme_named, type_scale_rules, ) from je_auto_control.gui.workspace_settings import WorkspacePreferences, default_settings from je_auto_control.utils.config_sync.contract import ConfigSyncError @@ -75,9 +76,8 @@ def __init__(self, *, settings: QSettings | None = None) -> None: self.auto_control_gui_widget = AutoControlGUIWidget(parent=self) self.setCentralWidget(self.auto_control_gui_widget) - self._build_navigation() + self._build_navigation(preferences.navigation_visible) self.resizeDocks([self._navigation_dock], [preferences.navigation_width], Qt.Orientation.Horizontal) - self._navigation_dock.setVisible(preferences.navigation_visible) self._navigation_dock.installEventFilter(self) self._view_menu: QMenu | None = None @@ -102,7 +102,8 @@ def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 # reason: Qt ov if event.isAccepted(): for key, value in ( ("theme", self._theme_name), ("font_pt", self._user_font_pt), - ("navigation_visible", not self._navigation_dock.isHidden()), + # The preference, not the dock: a narrow window hides the dock without the user asking. + ("navigation_visible", self._adaptive.navigation_preferred), ("navigation_width", self._navigation_width), ): self._settings.setValue(f"workspace/{key}", value) @@ -117,19 +118,26 @@ def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 # # --- navigation ---------------------------------------------------------- - def _build_navigation(self) -> None: - """Dock the searchable feature list on the left of the workspace.""" + def _build_navigation(self, navigation_preferred: bool) -> None: + """Dock the searchable feature list on the left; narrow windows get a rail and a drawer instead.""" self.navigation = NavigationPanel(self) self.navigation.feature_activated.connect(self.auto_control_gui_widget.activate_tab) self._navigation_dock = QDockWidget(self) self._navigation_dock.setObjectName("NavigationDock") - # Closable enables Qt's toggleViewAction (including Ctrl+B). The empty - # title bar still keeps the navigation panel fixed and button-free. + # The empty title bar keeps the navigation panel fixed and button-free; + # showing and hiding it belongs to the adaptive layout, so Qt's own + # toggle (offered in the dock area's context menu) is hidden. self._navigation_dock.setFeatures(QDockWidget.DockWidgetFeature.DockWidgetClosable) self._navigation_dock.setTitleBarWidget(QWidget(self._navigation_dock)) self._navigation_dock.setWidget(self.navigation) + self._navigation_dock.toggleViewAction().setVisible(False) self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, self._navigation_dock) self.resizeDocks([self._navigation_dock], [260], Qt.Orientation.Horizontal) + self._navigation_dock.setVisible(navigation_preferred) + self._adaptive = AdaptiveWindowLayout(self, self._navigation_dock, self.auto_control_gui_widget, + lambda: NavigationPanel(), navigation_preferred=navigation_preferred) + self._adaptive.panel.feature_activated.connect(self.auto_control_gui_widget.activate_tab) + self._adaptive.set_glyph_colour(theme_named(self._theme_name).text) # Owned by the window, not by a menu: the menu bar is rebuilt on every # language switch, and a shortcut on a per-menu action would be # registered once more each time. @@ -137,8 +145,12 @@ def _build_navigation(self) -> None: self._search_action.setShortcut(QKeySequence("Ctrl+K")) self._search_action.triggered.connect(self._focus_feature_search) self.addAction(self._search_action) - self._sidebar_action = self._navigation_dock.toggleViewAction() + self._sidebar_action = QAction(self) + self._sidebar_action.setCheckable(True) + self._sidebar_action.setChecked(self._adaptive.navigation_shown()) self._sidebar_action.setShortcut(QKeySequence("Ctrl+B")) + self._sidebar_action.triggered.connect(self._adaptive.toggle_navigation) + self._adaptive.navigation_shown_changed.connect(self._sidebar_action.setChecked) self.addAction(self._sidebar_action) self._details_action = QAction(self) self._details_action.setCheckable(True) @@ -149,14 +161,13 @@ def _build_navigation(self) -> None: self._refresh_navigation() def _refresh_navigation(self) -> None: - self.navigation.set_entries( - self.auto_control_gui_widget.list_registered_tabs(), _TAB_CATEGORIES, - ) + entries = self.auto_control_gui_widget.list_registered_tabs() + for panel in (self.navigation, self._adaptive.panel): + panel.set_entries(entries, _TAB_CATEGORIES) def _focus_feature_search(self) -> None: - """Show the navigation panel and put the cursor in its search box (Ctrl+K).""" - self._navigation_dock.setVisible(True) - self.navigation.focus_search() + """Show the feature list (docked, or as a drawer when narrow) and focus its search box (Ctrl+K).""" + self._adaptive.reveal_search() # --- menu construction --------------------------------------------------- @@ -244,6 +255,7 @@ def set_theme(self, name: str) -> None: self._theme_name = tokens.name self._theme_stylesheet = apply_theme(self, tokens) self._apply_font_pt(self._user_font_pt) + self._adaptive.set_glyph_colour(tokens.text) def apply_workspace_preferences(self, values: dict[str, object]) -> None: """Explicitly apply all four canonical preferences on the GUI thread; persist through normal window close.""" @@ -255,7 +267,7 @@ def apply_workspace_preferences(self, values: dict[str, object]) -> None: self.set_theme(cast(str, values['theme'])) self.resizeDocks([self._navigation_dock], [cast(int, values['navigation_width'])], Qt.Orientation.Horizontal) self._navigation_width = cast(int, values['navigation_width']) - self._navigation_dock.setVisible(cast(bool, values['navigation_visible'])) + self._adaptive.set_navigation_preferred(cast(bool, values['navigation_visible'])) for action in self.findChildren(QAction): data = action.data() if not action.isCheckable(): @@ -337,7 +349,7 @@ def _apply_font_pt(self, pt: int) -> None: the theme's; only the size is set here. """ effective = pt if pt > 0 else self._detect_auto_font_pt() - self.setStyleSheet(f"{self._theme_stylesheet}\n{font_rule(effective)}") + self.setStyleSheet(f"{self._theme_stylesheet}\n{font_rule(effective)}\n{type_scale_rules(effective)}") def _on_text_size_selected(self) -> None: action = self.sender() @@ -412,6 +424,7 @@ def _on_language_changed(self, _language: str) -> None: self.setWindowTitle(_t("application_name", "AutoControlGUI")) self.auto_control_gui_widget.retranslate() self.navigation.retranslate() + self._adaptive.retranslate() self._refresh_navigation() self._build_menu_bar() diff --git a/je_auto_control/gui/navigation.py b/je_auto_control/gui/navigation.py index fd3e95432..2aae51620 100644 --- a/je_auto_control/gui/navigation.py +++ b/je_auto_control/gui/navigation.py @@ -79,6 +79,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: layout = QVBoxLayout(self) layout.setContentsMargins(8, 8, 8, 8) layout.setSpacing(8) + self.brand = QLabel(self) + self.brand.setObjectName("NavigationBrand") + layout.addWidget(self.brand) layout.addWidget(self.search) layout.addWidget(self.tree, 1) layout.addWidget(self.empty, 1) @@ -202,6 +205,7 @@ def _on_item_chosen(self, item: QTreeWidgetItem, _column: int = 0) -> None: def retranslate(self) -> None: """Re-read every label from the language wrapper.""" + self.brand.setText(_t("application_name", "AutoControlGUI")) self.search.setPlaceholderText(_t("nav_search_placeholder", "Search features (Ctrl+K)")) self.empty.setText(_t("nav_no_results", "No feature matches this search.")) if self._entries: diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index f1277b969..c53ab0f07 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -31,7 +31,10 @@ class ThemeTokens: selection: str hover: str danger: str + success: str = "#3fb950" + warning: str = "#d29922" radius: int = 6 + radius_large: int = 10 spacing: int = 8 font_family: str = FONT_FAMILY @@ -39,12 +42,12 @@ class ThemeTokens: DARK = ThemeTokens( name="dark", window="#16181d", surface="#1d2026", surface_raised="#262a32", border="#343944", text="#e7e9ee", text_muted="#9aa1ae", accent="#5b9dff", accent_hover="#7ab0ff", accent_text="#0c1220", - selection="#2c4470", hover="#2b303a", danger="#ff6b6b", + selection="#2c4470", hover="#2b303a", danger="#ff6b6b", success="#3fb950", warning="#e3b341", ) LIGHT = ThemeTokens( name="light", window="#f4f5f8", surface="#ffffff", surface_raised="#eceef3", border="#d3d7df", text="#1c2029", text_muted="#5f6775", accent="#2563eb", accent_hover="#1d4fd0", accent_text="#ffffff", - selection="#d4e2ff", hover="#e6e9f0", danger="#c62828", + selection="#d4e2ff", hover="#e6e9f0", danger="#c62828", success="#1a7f37", warning="#9a6700", ) THEMES: Dict[str, ThemeTokens] = {DARK.name: DARK, LIGHT.name: LIGHT} DEFAULT_THEME = DARK.name @@ -60,6 +63,22 @@ def font_rule(point_size: int) -> str: return f"* {{ font-size: {int(point_size)}pt; }}" +def type_scale_rules(point_size: int) -> str: + """Rules sizing page titles, section titles and hints relative to the body text size. + + A ``QLabel[role=...]`` selector outranks the ``*`` of :func:`font_rule`, so + these win whatever order the two are in. + """ + size = int(point_size) + return "\n".join(( + f'QLabel[role="pageTitle"] {{ font-size: {size + 6}pt; }}', + f'QLabel[role="sectionTitle"], QGroupBox {{ font-size: {size + 1}pt; }}', + f'QLabel[role="emptyMessage"] {{ font-size: {size + 2}pt; }}', + f'QLabel[role="hint"], QLabel[role="pageSubtitle"] {{ font-size: {max(size - 1, 8)}pt; }}', + f'#NavigationBrand {{ font-size: {size + 3}pt; }}', + )) + + _TEMPLATE = """ QWidget {{ background-color: {window}; color: {text}; font-family: {font_family}; }} QMainWindow, QDialog, QDockWidget {{ background-color: {window}; }} @@ -77,6 +96,8 @@ def font_rule(point_size: int) -> str: QMenu::separator {{ height: 1px; background: {border}; margin: {half}px {spacing}px; }} QTabWidget::pane {{ border: 1px solid {border}; border-radius: {radius}px; background-color: {surface}; top: -1px; }} +QTabWidget#WorkspaceTabs::pane {{ border: 0; border-top: 1px solid {border}; border-radius: 0; + background-color: {window}; }} QTabBar {{ background: transparent; qproperty-drawBase: 0; }} QTabBar::tab {{ background: transparent; color: {text_muted}; padding: {spacing}px {wide}px; border: 1px solid transparent; border-top-left-radius: {radius}px; border-top-right-radius: {radius}px; @@ -113,9 +134,22 @@ def font_rule(point_size: int) -> str: border-bottom: 1px solid {border}; padding: {half}px {spacing}px; }} QTableCornerButton::section {{ background-color: {surface_raised}; border: 0; }} -QGroupBox {{ border: 1px solid {border}; border-radius: {radius}px; margin-top: {wide}px; - padding: {spacing}px; background-color: transparent; }} -QGroupBox::title {{ subcontrol-origin: margin; left: {spacing}px; padding: 0 {half}px; color: {text_muted}; }} +QGroupBox {{ border: 1px solid {border}; border-radius: {radius_large}px; margin-top: 1.7em; + padding: {half}px {half}px {half}px {half}px; background-color: {surface}; font-weight: 600; }} +QGroupBox::title {{ subcontrol-origin: margin; subcontrol-position: top left; left: {small}px; top: 0; + padding: 0; color: {text}; background: transparent; }} +QGroupBox QLabel, QGroupBox QCheckBox, QGroupBox QRadioButton, QGroupBox QPushButton, +QGroupBox QLineEdit, QGroupBox QComboBox, QGroupBox QAbstractItemView {{ font-weight: normal; }} +QFrame[role="card"] {{ background-color: {surface}; border: 1px solid {border}; border-radius: {radius_large}px; }} +QLabel[role="pageTitle"] {{ font-weight: 600; color: {text}; }} +QLabel[role="pageSubtitle"], QLabel[role="hint"] {{ color: {text_muted}; }} +QLabel[role="sectionTitle"] {{ font-weight: 600; color: {text}; }} +QLabel[role="emptyMessage"] {{ color: {text_muted}; }} +QLabel[role="danger"] {{ color: {danger}; }} +QLabel[role="success"] {{ color: {success}; }} +QLabel[role="warning"] {{ color: {warning}; }} +QPushButton[role="primary"] {{ background-color: {accent}; color: {accent_text}; border-color: {accent}; }} +QPushButton[role="primary"]:hover {{ background-color: {accent_hover}; }} QScrollBar:vertical {{ background: transparent; width: 10px; margin: 0; }} QScrollBar:horizontal {{ background: transparent; height: 10px; margin: 0; }} @@ -133,8 +167,17 @@ def font_rule(point_size: int) -> str: #NavigationPanel {{ background-color: {surface}; border-right: 1px solid {border}; }} #NavigationPanel QTreeWidget {{ background-color: {surface}; border: 0; border-radius: 0; }} +#NavigationPanel QTreeWidget::item {{ padding: {half}px {spacing}px; margin: 1px 0; }} +#NavigationPanel QTreeWidget::item:selected {{ background-color: {selection}; color: {text}; }} #NavigationPanel QLineEdit {{ background-color: {window}; }} +#NavigationBrand {{ font-weight: 600; color: {text}; padding: {half}px {small}px {spacing}px {small}px; }} #NavigationEmpty {{ color: {text_muted}; padding: {wide}px; }} +#NavigationRail {{ background-color: {surface}; border-right: 1px solid {border}; }} +#NavigationRail QToolButton {{ background: transparent; border: 0; border-radius: {radius}px; padding: {half}px; }} +#NavigationRail QToolButton:hover {{ background-color: {hover}; }} +#NavigationRail QToolButton:checked {{ background-color: {selection}; }} +#NavigationOverlay, #DetailsOverlay {{ background-color: {surface}; border: 1px solid {border}; }} +#ExecutionDetails {{ background-color: {surface}; border: 0; border-left: 1px solid {border}; }} """ @@ -174,10 +217,17 @@ def apply_theme(window: Any, tokens: ThemeTokens, point_size: Optional[int] = No if close_rules: sheet = f"{sheet}\n{close_rules}" window.setPalette(_palette(tokens)) - window.setStyleSheet(sheet if point_size is None else f"{sheet}\n{font_rule(point_size)}") + window.setStyleSheet(sheet if point_size is None + else f"{sheet}\n{font_rule(point_size)}\n{type_scale_rules(point_size)}") return sheet def prepare_application(app: Any) -> None: - """Give ``app`` the Fusion style, which follows the palette on every platform.""" - app.setStyle("Fusion") + """Give ``app`` the Fusion style, which follows the palette on every platform. + + Fusion's own check box and radio button outlines all but vanish on the dark + theme, so those two are drawn by + :class:`~je_auto_control.gui.adaptive.style.AdaptiveStyle` instead. + """ + from je_auto_control.gui.adaptive.style import AdaptiveStyle + app.setStyle(AdaptiveStyle("Fusion")) diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index e58176e45..4f49c986e 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -7,6 +7,9 @@ from PySide6.QtWidgets import QAbstractButton, QScrollArea, QTabBar, QTabWidget, QWidget, QSplitter, QVBoxLayout from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.overlay import OverlayDrawer +from je_auto_control.gui.adaptive.responsive import fit_to_width +from je_auto_control.gui.adaptive.surfaces import add_page_header, retranslate_surfaces from je_auto_control.gui.tab_registry import MenuActions, TabEntry, TabRegistry, WidgetFactory from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsPane, ExecutionDetailsSource @@ -172,6 +175,7 @@ def __init__(self, registry: TabRegistry, parent: QWidget | None = None) -> None self.tab_registry = registry self._unbuilt: dict[str, _UnbuiltPage] = {} self.tabs = ScrollableTabs() + self.tabs.setObjectName("WorkspaceTabs") self.tabs.setDocumentMode(True) self.tabs.setUsesScrollButtons(True) self.tabs.setMinimumSize(360, 240) @@ -188,6 +192,10 @@ def __init__(self, registry: TabRegistry, parent: QWidget | None = None) -> None layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._splitter) + # Narrow windows show the details over the tabs instead of beside them. + self._details_drawer = OverlayDrawer(self, Qt.Edge.RightEdge, "DetailsOverlay") + self._details_drawer.closed.connect(self._on_details_drawer_closed) + self._details_overlay = False owner = weakref.ref(self) def closed(page: QWidget) -> None: @@ -203,10 +211,48 @@ def closed(page: QWidget) -> None: def set_details_visible(self, visible: bool) -> None: """Expand or collapse execution details without starting any work.""" + if self._details_overlay: + self.details.setVisible(True) + if visible: + self._details_drawer.open_drawer() + else: + self._details_drawer.hide() + else: + self.details.setVisible(visible) + if visible: + self._splitter.setSizes([max(360, self.width() - 260), 260]) + self.details_visibility_changed.emit(visible) + + def details_visible(self) -> bool: + """Whether execution details are on screen, docked or in their drawer.""" + return self._details_drawer.is_open if self._details_overlay else not self.details.isHidden() + + @property + def details_overlay(self) -> bool: + """Whether details open as a drawer over the tabs rather than as a column beside them.""" + return self._details_overlay + + def set_details_overlay(self, enabled: bool) -> None: + """Move execution details into a right-hand drawer (narrow window) or back beside the tabs.""" + if enabled == self._details_overlay: + return + visible = self.details_visible() + self._details_overlay = enabled + if enabled: + self._details_drawer.set_content(self.details) + if visible: + self._details_drawer.open_drawer() + return + self._details_drawer.hide() + self._details_drawer.set_content(None) + self._splitter.addWidget(self.details) self.details.setVisible(visible) if visible: self._splitter.setSizes([max(360, self.width() - 260), 260]) - self.details_visibility_changed.emit(visible) + + def _on_details_drawer_closed(self) -> None: + """Escape or a click beside the drawer closed it: report the details as hidden.""" + self.details_visibility_changed.emit(False) def _bind_details(self) -> None: if self._details_connection is not None: @@ -258,18 +304,27 @@ def adopt(page: QWidget) -> None: self._unbuilt[key] = page = _UnbuiltPage(key) self.tabs.addTab(page, title) elif default_visible: + self._dress(key, entry.widget) self.tabs.addTab(entry.widget, title) elif isinstance(widget, QWidget): WorkspaceShell._adopt_hidden_tab(self, entry.widget) def _adopt_built_page(self, key: str, page: QWidget) -> None: """Seat a newly built page in its stand-in's tab, or keep it hidden and owned.""" + self._dress(key, page) stand_in = self._unbuilt.pop(key, None) if stand_in is not None and self.tabs.replace_page(stand_in, page): stand_in.deleteLater() return self._adopt_hidden_tab(page) + def _dress(self, key: str, page: QWidget) -> None: + """Give a page its header and let its controls shrink with the window; repeat calls are no-ops.""" + entry = self._find_entry(key) + if entry is not None: + add_page_header(page, entry.title_key, f"{entry.title_key}_subtitle") + fit_to_width(page) + def _drop_unbuilt(self, key: str) -> bool: """Close a start-up tab that was never built; ``False`` when ``key`` has none.""" stand_in = self._unbuilt.pop(key, None) @@ -386,6 +441,7 @@ def show_tab(self, key: str) -> None: target_index += 1 title = language_wrapper.translate(entry.title_key, entry.title_key) page = self.tab_registry.open(key) + self._dress(key, page) self.tabs.insertTab(target_index, page, title) self.tabs.setCurrentWidget(page) self.tabs_changed.emit() @@ -456,10 +512,16 @@ def retranslate(self) -> None: index, language_wrapper.translate(entry.title_key, entry.title_key), ) TranslatableMixin.retranslate(self) - # Child class tabs get their own retranslate if they implement one. + self._retranslate_pages() + + def _retranslate_pages(self) -> None: + """Re-read each built page's shared surfaces, then call its own ``retranslate`` if it has one.""" for entry in self._built_entries(): + if entry.widget is self: + continue + retranslate_surfaces(entry.widget) callback = getattr(entry.widget, "retranslate", None) - if callable(callback) and entry.widget is not self: + if callable(callback): try: callback() except (RuntimeError, AttributeError): diff --git a/je_auto_control/gui/workspace_details.py b/je_auto_control/gui/workspace_details.py index f4a38ffbb..07a753f63 100644 --- a/je_auto_control/gui/workspace_details.py +++ b/je_auto_control/gui/workspace_details.py @@ -46,11 +46,13 @@ class ExecutionDetailsPane(QScrollArea): def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) + self.setObjectName("ExecutionDetails") self.setWidgetResizable(True) self.setMinimumWidth(0) content = QWidget() layout = QVBoxLayout(content) self.title = QLabel() + self.title.setProperty("role", "sectionTitle") self.state = QLabel() self.summary = QLabel() for label in (self.title, self.state, self.summary): diff --git a/test/unit_test/headless/test_gui_adaptive.py b/test/unit_test/headless/test_gui_adaptive.py new file mode 100644 index 000000000..b72854d12 --- /dev/null +++ b/test/unit_test/headless/test_gui_adaptive.py @@ -0,0 +1,250 @@ +"""The adaptive building blocks: width classes, wrapping rows, stacking boxes, the fit pass, surfaces, indicators.""" +import os +import subprocess # nosec B404 # reason: runs a fixed import probe in a child interpreter +import sys + +import pytest + +from je_auto_control.gui.adaptive.breakpoints import ( + EXPANDED_FROM, HYSTERESIS, MEDIUM_FROM, WidthClass, classify, +) + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + + +# --- width classes: no Qt needed --------------------------------------------- + +@pytest.mark.parametrize("width, expected", [ + (0, WidthClass.COMPACT), (MEDIUM_FROM - 1, WidthClass.COMPACT), (MEDIUM_FROM, WidthClass.MEDIUM), + (EXPANDED_FROM - 1, WidthClass.MEDIUM), (EXPANDED_FROM, WidthClass.EXPANDED), (4000, WidthClass.EXPANDED), +]) +def test_a_fresh_width_falls_in_its_plain_class(width, expected): + assert classify(width) is expected + + +def test_shrinking_just_below_a_boundary_keeps_the_wider_class(): + assert classify(EXPANDED_FROM - HYSTERESIS + 1, WidthClass.EXPANDED) is WidthClass.EXPANDED + assert classify(EXPANDED_FROM - HYSTERESIS - 1, WidthClass.EXPANDED) is WidthClass.MEDIUM + assert classify(MEDIUM_FROM - 1, WidthClass.MEDIUM) is WidthClass.MEDIUM + + +def test_growing_just_past_a_boundary_keeps_the_narrower_class(): + assert classify(MEDIUM_FROM + HYSTERESIS - 1, WidthClass.COMPACT) is WidthClass.COMPACT + assert classify(MEDIUM_FROM + HYSTERESIS, WidthClass.COMPACT) is WidthClass.MEDIUM + assert classify(EXPANDED_FROM + 1, WidthClass.MEDIUM) is WidthClass.MEDIUM + + +def test_a_large_jump_skips_straight_to_its_class(): + assert classify(2000, WidthClass.COMPACT) is WidthClass.EXPANDED + assert classify(300, WidthClass.EXPANDED) is WidthClass.COMPACT + + +def test_a_negative_width_is_refused(): + with pytest.raises(ValueError): + classify(-1) + + +def test_importing_the_adaptive_package_loads_no_qt(): + probe = ("import sys, je_auto_control.gui.adaptive as a; " + "assert a.classify(900).value == 'medium'; " + "assert not any(m.startswith('PySide6') for m in sys.modules)") + done = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, # nosec B603 # reason: fixed argv + timeout=60, check=False) + assert done.returncode == 0, done.stderr[-1500:] + + +# --- widgets ------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def qapp(): + widgets = pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + return widgets.QApplication.instance() or widgets.QApplication([]) + + +def _button(text, width): + from PySide6.QtWidgets import QPushButton + button = QPushButton(text) + button.setFixedWidth(width) + return button + + +def test_a_flow_row_wraps_instead_of_widening(qapp): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.adaptive.flow_layout import FlowLayout + host = QWidget() + flow = FlowLayout(host, spacing=10) + for index in range(4): + flow.addWidget(_button(f"b{index}", 100)) + assert flow.minimumSize().width() == 100, "the minimum is the widest single item" + one_line = flow.heightForWidth(430) + assert flow.heightForWidth(220) > one_line, "a narrower row is taller" + assert flow.heightForWidth(100) >= 4 * flow.itemAt(0).sizeHint().height() + host.resize(220, flow.heightForWidth(220)) + flow.setGeometry(host.rect()) + tops = sorted({flow.itemAt(i).geometry().top() for i in range(flow.count())}) + assert len(tops) == 2, "four 100 px buttons in 220 px make two rows" + assert all(flow.itemAt(i).geometry().right() < 220 for i in range(flow.count())) + host.deleteLater() + + +def test_a_hidden_item_takes_no_room_in_a_flow(qapp): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.adaptive.flow_layout import FlowLayout + host = QWidget() + flow = FlowLayout(host) + wide, narrow = _button("wide", 300), _button("narrow", 80) + flow.addWidget(wide) + flow.addWidget(narrow) + wide.hide() + assert flow.minimumSize().width() == 80 + assert flow.takeAt(0) is not None and flow.count() == 1 + assert flow.itemAt(5) is None and flow.takeAt(5) is None + host.deleteLater() + + +def test_field_pairs_wrap_as_units(qapp): + from PySide6.QtWidgets import QLabel, QLineEdit, QWidget + from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of + pairs = [field_pair(QLabel(f"Label {index}"), QLineEdit()) for index in range(3)] + host = QWidget() + flow = flow_of(*pairs) + host.setLayout(flow) + widest = max(pair.minimumSizeHint().width() for pair in pairs) + assert flow.minimumSize().width() == widest + assert flow.count() == 3 and flow.spacing() == 12 + label, field = (pairs[0].layout().itemAt(i).widget() for i in range(2)) + assert isinstance(label, QLabel) and isinstance(field, QLineEdit) + host.deleteLater() + + +def test_a_responsive_box_stacks_below_its_threshold(qapp): + from PySide6.QtWidgets import QLabel + from je_auto_control.gui.adaptive.responsive import ResponsiveBox + left, right = QLabel("list"), QLabel("details") + left.setMinimumWidth(300) + right.setMinimumWidth(200) + box = ResponsiveBox(left, right, stack_below=600, stretches=(2, 1)) + assert box.minimumSizeHint().width() == 300, "never more than the widest part" + box.arrange(900) + assert not box.stacked + box.arrange(500) + assert box.stacked + box.resize(800, 300) + box.show() + qapp.processEvents() + assert not box.stacked, "a resize re-arranges it" + box.deleteLater() + + +def test_the_fit_pass_stops_a_long_combo_from_widening_its_page(qapp): + from PySide6.QtWidgets import QComboBox, QFormLayout, QLabel, QVBoxLayout, QWidget + from je_auto_control.gui.adaptive.responsive import fit_to_width + page = QWidget() + layout = QVBoxLayout(page) + combo = QComboBox() + combo.addItem("A command label that goes on and on " * 4) + form = QFormLayout() + form.addRow("Command", combo) + layout.addLayout(form) + note = QLabel("A long explanatory sentence that would otherwise sit on one very wide line.") + layout.addWidget(note) + before = page.minimumSizeHint().width() + adjusted = fit_to_width(page) + after = page.minimumSizeHint().width() + assert adjusted >= 2 + assert after < before / 2, (before, after) + assert form.rowWrapPolicy() == QFormLayout.RowWrapPolicy.WrapLongRows + assert note.wordWrap() + assert fit_to_width(page) == 0, "a second pass changes nothing" + page.deleteLater() + + +def test_a_missing_subtitle_shows_nothing_rather_than_its_key(qapp): + from je_auto_control.gui.adaptive.surfaces import PageHeader, optional_text + assert optional_text("") == "" + assert optional_text("no_such_key_for_sure") == "" + assert optional_text("tab_mobile_subtitle") + header = PageHeader("tab_mobile", "no_such_key_for_sure") + assert header.title.text() == "Mobile" + assert header.subtitle.isHidden() + header.deleteLater() + + +def test_a_page_header_is_added_once_and_only_to_a_vertical_page(qapp): + from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QVBoxLayout, QWidget + from je_auto_control.gui.adaptive.surfaces import add_page_header, page_header + page = QWidget() + QVBoxLayout(page) + first = add_page_header(page, "tab_mobile", "tab_mobile_subtitle") + assert first is not None and page.layout().itemAt(0).widget() is first + assert add_page_header(page, "tab_mobile") is first + assert page_header(page) is first + for layout_type in (QGridLayout, QHBoxLayout): + other = QWidget() + layout_type(other) + assert add_page_header(other, "tab_mobile") is None + other.deleteLater() + bare = QWidget() + assert add_page_header(bare, "tab_mobile") is None + page.deleteLater() + bare.deleteLater() + + +def test_surfaces_follow_a_language_switch(qapp): + from PySide6.QtWidgets import QWidget, QVBoxLayout + from je_auto_control.gui.adaptive.surfaces import Card, EmptyState, PageHeader, retranslate_surfaces + from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper + page = QWidget() + layout = QVBoxLayout(page) + header = PageHeader("tab_mobile", "tab_mobile_subtitle") + card = Card("tab_variables") + empty = EmptyState("tab_secrets", "tab_secrets_subtitle") + for widget in (header, card, empty): + layout.addWidget(widget) + previous = language_wrapper.language + try: + language_wrapper.reset_language("Traditional_Chinese") + retranslate_surfaces(page) + assert header.subtitle.text() == "探測 Android 或 iOS 裝置,並在其上執行一個行動指令。" + assert card.title.text() == language_wrapper.translate("tab_variables") + assert empty.hint.text() == language_wrapper.translate("tab_secrets_subtitle") + finally: + language_wrapper.reset_language(previous) + page.deleteLater() + assert card.property("role") == "card" + assert not Card().title.isVisibleTo(card), "an untitled card shows no title row" + + +@pytest.mark.parametrize("radio", [False, True]) +def test_indicators_are_drawn_in_the_accent_colour_when_checked(qapp, radio): + from PySide6.QtGui import QColor, QImage, QPainter, QPalette + from PySide6.QtCore import QRect + from PySide6.QtWidgets import QStyle, QStyleOptionButton + from je_auto_control.gui.adaptive.style import AdaptiveStyle + style = AdaptiveStyle() + accent = QColor("#2563eb") + image = QImage(32, 32, QImage.Format.Format_ARGB32) + image.fill(QColor("#ffffff")) + option = QStyleOptionButton() + option.rect = QRect(8, 8, 16, 16) + option.state = QStyle.StateFlag.State_Enabled | QStyle.StateFlag.State_On + palette = QPalette() + palette.setColor(QPalette.ColorRole.Highlight, accent) + palette.setColor(QPalette.ColorRole.Base, QColor("#ffffff")) + option.palette = palette + element = QStyle.PrimitiveElement.PE_IndicatorRadioButton if radio \ + else QStyle.PrimitiveElement.PE_IndicatorCheckBox + painter = QPainter(image) + style.drawPrimitive(element, option, painter, None) + painter.end() + centre = image.pixelColor(16, 16) if radio else image.pixelColor(10, 10) + assert abs(centre.blue() - accent.blue()) < 40 and centre.red() < 120, centre.name() + assert style.pixelMetric(QStyle.PixelMetric.PM_IndicatorWidth) == 16 + + +def test_the_type_scale_grows_titles_with_the_text_size(): + from je_auto_control.gui.theme import type_scale_rules + rules = type_scale_rules(12) + assert 'QLabel[role="pageTitle"] { font-size: 18pt; }' in rules + assert 'QLabel[role="hint"], QLabel[role="pageSubtitle"] { font-size: 11pt; }' in rules + assert "font-size: 8pt" in type_scale_rules(6), "hints never drop below 8 pt" diff --git a/test/unit_test/headless/test_gui_adaptive_window.py b/test/unit_test/headless/test_gui_adaptive_window.py new file mode 100644 index 000000000..06d81c1c9 --- /dev/null +++ b/test/unit_test/headless/test_gui_adaptive_window.py @@ -0,0 +1,197 @@ +"""The window rearranges its panes by width: docked when wide, drawers and a rail when narrow.""" +import os + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + + +@pytest.fixture(scope="module") +def qapp(): + widgets = pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + return widgets.QApplication.instance() or widgets.QApplication([]) + + +@pytest.fixture +def window_factory(qapp, monkeypatch, tmp_path): + from PySide6.QtCore import QSettings + from je_auto_control.gui import main_widget + from je_auto_control.gui.main_window import AutoControlGUIUI + + monkeypatch.setattr(main_widget, "TAB_SPECS", tuple( + spec for spec in main_widget.TAB_SPECS if spec.key in {"record", "variables", "auto_click"} + )) + settings = QSettings(str(tmp_path / "workspace.ini"), QSettings.Format.IniFormat) + windows = [] + + def build(): + window = AutoControlGUIUI(settings=settings) + windows.append(window) + window.resize(1280, 800) + window.show() + qapp.processEvents() + return window + + yield build, settings + for window in windows: + window.close() + window.deleteLater() + + +def _resize(qapp, window, width, height=700): + window.resize(width, height) + for _ in range(3): + qapp.processEvents() + + +def test_a_wide_window_docks_both_panes(window_factory, qapp): + from je_auto_control.gui.adaptive.breakpoints import WidthClass + build, _settings = window_factory + window = build() + layout, shell = window._adaptive, window.auto_control_gui_widget + assert layout.width_class is WidthClass.EXPANDED + assert not layout.rail.isVisible() + assert not window._navigation_dock.isHidden() + assert not shell.details_overlay + shell.set_details_visible(True) + assert shell.details.parentWidget() is shell._splitter + + +def test_a_medium_window_opens_details_as_a_drawer(window_factory, qapp): + build, _settings = window_factory + window = build() + shell = window.auto_control_gui_widget + window._details_action.trigger() + assert shell.details_visible() + _resize(qapp, window, 1000) + assert shell.details_overlay + assert shell.details_visible(), "the details stay open when they move into the drawer" + assert shell._details_drawer.content() is shell.details + assert not window._navigation_dock.isHidden(), "the navigation stays docked at medium width" + shell._details_drawer.close_drawer() # what Escape and a click on the scrim do + assert not shell.details_visible() + assert not window._details_action.isChecked() + window._details_action.trigger() + assert shell._details_drawer.is_open + _resize(qapp, window, 1400) + assert not shell.details_overlay + assert shell.details.parentWidget() is shell._splitter + assert shell.details_visible(), "back in the column, still open" + + +def test_a_compact_window_swaps_the_docked_list_for_a_rail_and_a_drawer(window_factory, qapp): + build, settings = window_factory + window = build() + layout, shell = window._adaptive, window.auto_control_gui_widget + _resize(qapp, window, 600) + assert layout.compact + assert layout.rail.isVisible() + assert window._navigation_dock.isHidden() + assert layout.navigation_preferred, "hiding the dock for width is not the user's choice" + assert not window._sidebar_action.isChecked() + window._sidebar_action.trigger() # Ctrl+B + assert layout.drawer.is_open + assert window._sidebar_action.isChecked() + assert layout.panel.visible_keys() == window.navigation.visible_keys() + layout.panel.feature_activated.emit("variables") + assert shell.current_tab_key() == "variables" + assert not layout.drawer.is_open, "choosing a feature closes the drawer" + window.close() + assert str(settings.value("workspace/navigation_visible")).lower() == "true" + + +def test_ctrl_k_opens_the_list_wherever_it_lives(window_factory, qapp): + build, _settings = window_factory + window = build() + layout = window._adaptive + window._sidebar_action.trigger() + assert window._navigation_dock.isHidden() and not layout.navigation_preferred + window._search_action.trigger() + assert not window._navigation_dock.isHidden(), "a wide window shows the docked list again" + assert layout.navigation_preferred + _resize(qapp, window, 600) + window._search_action.trigger() + assert layout.drawer.is_open + _resize(qapp, window, 1300) + assert not layout.drawer.is_open, "widening the window closes the drawer" + assert not window._navigation_dock.isHidden() + + +def test_a_hidden_preference_survives_a_compact_spell(window_factory, qapp): + build, settings = window_factory + window = build() + window._sidebar_action.trigger() + _resize(qapp, window, 600) + window._sidebar_action.trigger() + window._adaptive.drawer.close_drawer() + _resize(qapp, window, 1300) + assert window._navigation_dock.isHidden(), "the user hid it before the window narrowed" + window.close() + assert str(settings.value("workspace/navigation_visible")).lower() == "false" + + +def test_resizing_near_a_boundary_does_not_flip_back_and_forth(window_factory, qapp): + from je_auto_control.gui.adaptive.breakpoints import WidthClass + build, _settings = window_factory + window = build() + seen = [] + window._adaptive.width_class_changed.connect(seen.append) + for width in (1190, 1210, 1185, 1215, 1100): + _resize(qapp, window, width) + assert seen == [WidthClass.MEDIUM.value] + + +def test_the_rail_icons_follow_the_theme(window_factory, qapp): + build, _settings = window_factory + window = build() + action = window._adaptive.menu_action + before = action.icon().pixmap(20, 20).toImage() + window.set_theme("light") + after = action.icon().pixmap(20, 20).toImage() + assert not action.icon().isNull() + assert before != after + assert action.toolTip() + + +def test_a_drawer_closes_on_a_click_beside_its_panel_only(qapp): + from PySide6.QtCore import QPoint, QPointF, Qt + from PySide6.QtGui import QMouseEvent + from PySide6.QtWidgets import QLabel, QWidget + from je_auto_control.gui.adaptive.overlay import DRAWER_WIDTH, OverlayDrawer + host = QWidget() + host.resize(800, 500) + drawer = OverlayDrawer(host, Qt.Edge.RightEdge, "DetailsOverlay") + content = QLabel("details") + drawer.set_content(content) + closed = [] + drawer.closed.connect(lambda: closed.append(True)) + drawer.open_drawer() + assert drawer.panel.geometry().width() == DRAWER_WIDTH + assert drawer.panel.geometry().right() == 799 + + def click(x): + point = QPointF(QPoint(x, 100)) + return QMouseEvent(QMouseEvent.Type.MouseButtonPress, point, point, Qt.MouseButton.LeftButton, + Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) + drawer.mousePressEvent(click(700)) + assert drawer.is_open and not closed + drawer.mousePressEvent(click(100)) + assert not drawer.is_open and closed == [True] + drawer.close_drawer() + assert closed == [True], "closing a closed drawer reports nothing" + narrow = drawer.panel_rect(300, 200) + assert narrow.width() == int(300 * 0.85) and narrow.right() == 299 + drawer.set_content(None) + assert drawer.content() is None and content.parent() is None + host.deleteLater() + content.deleteLater() + + +def test_the_glyphs_draw_on_transparent_ground(qapp): + from je_auto_control.gui.adaptive.glyphs import GLYPHS, glyph_pixmap + for name in GLYPHS: + image = glyph_pixmap(name, "#ff0000", 20, 2.0).toImage() + assert image.width() == 40 + assert image.pixelColor(0, 0).alpha() == 0 + assert any(image.pixelColor(x, y).red() > 200 and image.pixelColor(x, y).alpha() > 200 + for x in range(40) for y in range(40)), name diff --git a/test/unit_test/headless/test_gui_page_widths.py b/test/unit_test/headless/test_gui_page_widths.py new file mode 100644 index 000000000..2c4011b6c --- /dev/null +++ b/test/unit_test/headless/test_gui_page_widths.py @@ -0,0 +1,95 @@ +"""Every page fits a compact window: no tab forces the workspace to scroll sideways. + +Each tab is opened the way the window opens it (so it has its page header and +has been through the fit pass) and its minimum width is read. Widths are +measured in average characters of the window's own label font, so the same +budget holds on Windows' Segoe UI and Linux's wider fallback fonts alike. + +``WIDE_PAGES`` lists the tabs not yet reworked to fit, each with the most it +may need. The list only shrinks: a listed tab that now fits, or that grew past +its ceiling, fails here. The probe runs in a child interpreter, like the other +whole-window probes, so the tabs' helper threads never outlive it in this one. +""" +import json +import os +import pathlib +import subprocess # nosec B404 # reason: runs this file's own probe with a fixed argv +import sys + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +#: The most a page may need, in average characters of the label font (about 460 px in 10 pt Segoe UI): +#: a compact window's width less the navigation rail and a scroll bar. +BUDGET = 72 +#: Pages still over the budget, with the most each may need until it is reworked. +WIDE_PAGES = { + "script_builder": 134, + "flakiness": 92, + "audit_log": 83, + "usb_share": 81, +} + +_PROBE = r""" +import json, os, sys +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +from PySide6.QtCore import QSettings +from PySide6.QtWidgets import QApplication, QLabel +app = QApplication.instance() or QApplication([]) +from je_auto_control.gui.theme import prepare_application +prepare_application(app) +from je_auto_control.gui.main_window import AutoControlGUIUI +from je_auto_control.gui.tab_registry import TAB_SPECS +window = AutoControlGUIUI(settings=QSettings(sys.argv[1], QSettings.Format.IniFormat)) +window.show() +app.processEvents() +workspace = window.auto_control_gui_widget +probe = QLabel("x", workspace) +probe.ensurePolished() +unit = probe.fontMetrics().horizontalAdvance("abcdefghijklmnopqrstuvwxyz") / 26 +widths = {} +for spec in TAB_SPECS: + workspace.activate_tab(spec.key) + app.processEvents() + page = workspace.tabs.currentWidget() + widths[spec.key] = page.minimumSizeHint().width() / unit if workspace.current_tab_key() == spec.key else -1 +sys.stdout.write(json.dumps({"unit": unit, "widths": widths})) +sys.stdout.flush() +os._exit(0) +""" + + +@pytest.fixture(scope="module") +def measured(tmp_path_factory): + root = pathlib.Path(__file__).resolve().parents[3] + env = dict(os.environ, PYTHONPATH=str(root), QT_QPA_PLATFORM="offscreen") + if sys.platform == "win32": + # The offscreen platform finds no fonts on Windows unless pointed at them, + # and then measures every label as a row of boxes. + env.setdefault("QT_QPA_FONTDIR", str(pathlib.Path(os.environ.get("WINDIR", r"C:\Windows")) / "Fonts")) + settings = tmp_path_factory.mktemp("widths") / "gui.ini" + done = subprocess.run([sys.executable, "-c", _PROBE, str(settings)], # nosec B603 # nosemgrep # reason: fixed argv, no shell + capture_output=True, text=True, timeout=240, env=env, cwd=str(root), check=False) + assert done.returncode == 0, done.stderr[-2000:] + return json.loads(done.stdout) + + +def test_every_tab_was_opened(measured): + assert measured["unit"] > 0 + assert [key for key, width in measured["widths"].items() if width < 0] == [] + + +def test_every_page_fits_a_compact_window(measured): + over = {key: round(width) for key, width in measured["widths"].items() + if width > BUDGET and key not in WIDE_PAGES} + assert over == {}, f"pages wider than {BUDGET} characters: {over}" + + +def test_the_list_of_wide_pages_only_shrinks(measured): + widths = measured["widths"] + assert set(WIDE_PAGES) <= set(widths), "a listed page is no longer registered" + fits = sorted(key for key in WIDE_PAGES if widths[key] <= BUDGET) + assert fits == [], f"these now fit; remove them from WIDE_PAGES: {fits}" + grew = {key: round(widths[key]) for key in WIDE_PAGES if widths[key] > WIDE_PAGES[key]} + assert grew == {}, f"these grew past their ceiling: {grew}" diff --git a/test/unit_test/headless/test_gui_workspace_navigation.py b/test/unit_test/headless/test_gui_workspace_navigation.py index b9149b3ea..cdfa27b86 100644 --- a/test/unit_test/headless/test_gui_workspace_navigation.py +++ b/test/unit_test/headless/test_gui_workspace_navigation.py @@ -182,7 +182,12 @@ def test_a_search_survives_the_list_being_refreshed(panel): window.resize(640, 420) app.processEvents() -report["small"] = [window.width(), window.height(), workspace.width(), navigation.isVisible()] +report["small"] = [window.width(), window.height(), workspace.width(), navigation.isVisible(), + window._adaptive.rail.isVisible()] +window._search_action.trigger() +app.processEvents() +report["small_search"] = [window._adaptive.drawer.is_open, window._adaptive.panel.search.hasFocus() + or window._adaptive.panel.search.isVisible(), window._sidebar_action.isChecked()] sys.stdout.write(json.dumps(report)) sys.stdout.flush() os._exit(0) @@ -226,8 +231,12 @@ def test_rebuilding_the_menus_for_a_language_switch_adds_no_shortcut(window): "Tabs", "Theme", "Text Size"] -def test_the_window_shrinks_to_a_small_screen_with_both_panes_usable(window): - width, height, workspace_width, panel_visible = window["small"] +def test_a_small_window_gives_the_tabs_the_width_and_keeps_the_features_one_key_away(window): + width, height, workspace_width, docked_visible, rail_visible = window["small"] assert (width, height) == (640, 420), "the window refused to shrink" - assert panel_visible - assert workspace_width >= 300 + assert not docked_visible, "below 800 px the docked list gives its width to the tabs" + assert rail_visible + assert workspace_width >= 560 + drawer_open, search_shown, action_checked = window["small_search"] + assert drawer_open and search_shown, "Ctrl+K opens the feature list as a drawer" + assert action_checked From fa887d0df3497f2243ab65ed729f7c9cd162c96f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 05:36:36 +0800 Subject: [PATCH 068/161] Rebuild every tab on the adaptive layout All 51 tabs and their embedded views now group controls on cards, wrap rows instead of widening, and stack side-by-side panes in narrow windows; widgets, signals, menu actions and translation keys are unchanged. Script Builder needed 818 px for its toolbar row and now needs 206, and every page fits the 72-character budget, so the list of wide pages is empty. Pages scrolled even when they fitted: QScrollArea sizes a page holding any height-for-width item from preferred heights. Each tab page now sits in a PageScrollArea that gives it the viewport or its minimum, and FlowLayout keeps its wrapped height as a minimum instead of reporting height-for-width. Flow lines centre their items and give spare width to fields; group-box titles are drawn inside the box like card titles. Also fixes the WebRTC viewer's remote-files section showing a raw key, the English publish button rendering "&" as a mnemonic, and adds the new adaptive modules to the strict typing tier CI asked for. --- CHANGELOG.md | 9 + Progress.md | 11 +- architecture_explore.md | 138 ++++++------- .../doc/new_features/v224_features_doc.rst | 25 ++- .../Zh/doc/new_features/v224_features_doc.rst | 16 +- docs/updates/2026-11-b.md | 11 ++ docs/updates/README.md | 1 + je_auto_control/gui/_auto_click_tab.py | 161 ++++++++------- je_auto_control/gui/_image_detect_tab.py | 25 ++- je_auto_control/gui/_record_tab.py | 10 +- je_auto_control/gui/_report_tab.py | 16 +- je_auto_control/gui/_screenshot_tab.py | 67 +++---- je_auto_control/gui/_script_tab.py | 34 ++-- je_auto_control/gui/a11y_audit_tab.py | 23 ++- je_auto_control/gui/accessibility_tab.py | 21 +- je_auto_control/gui/adaptive/flow_layout.py | 103 ++++++++-- je_auto_control/gui/adaptive/responsive.py | 11 +- je_auto_control/gui/adaptive/style.py | 6 +- je_auto_control/gui/admin_console_tab.py | 28 ++- je_auto_control/gui/agent_observation_view.py | 4 + je_auto_control/gui/agent_tasks_tab.py | 19 +- je_auto_control/gui/agent_transfer_view.py | 5 + je_auto_control/gui/assertions_tab.py | 40 ++-- je_auto_control/gui/audit_log_tab.py | 20 +- je_auto_control/gui/chatops_tab.py | 20 +- je_auto_control/gui/computer_use_tab.py | 14 +- je_auto_control/gui/config_sync_tab.py | 30 ++- je_auto_control/gui/dag_tab.py | 26 +-- je_auto_control/gui/data_source_tab.py | 38 ++-- je_auto_control/gui/device_matrix_tab.py | 24 +-- je_auto_control/gui/diagnostics_tab.py | 10 +- je_auto_control/gui/email_triggers_tab.py | 59 +++--- je_auto_control/gui/flakiness_tab.py | 21 +- je_auto_control/gui/flow_editor/tab.py | 8 +- .../gui/healing_evaluation_panel.py | 18 +- je_auto_control/gui/hotkeys_tab.py | 19 +- je_auto_control/gui/inspector_tab.py | 11 +- .../gui/language_wrapper/english.py | 2 +- je_auto_control/gui/live_hud_tab.py | 8 +- je_auto_control/gui/llm_planner_tab.py | 15 +- je_auto_control/gui/mcp_discovery_view.py | 7 +- je_auto_control/gui/media_checks_tab.py | 41 ++-- je_auto_control/gui/mobile_tab.py | 18 +- je_auto_control/gui/ocr_tab.py | 45 ++--- je_auto_control/gui/plugins_tab.py | 17 +- je_auto_control/gui/presence_tab.py | 6 +- je_auto_control/gui/profiler_tab.py | 7 +- je_auto_control/gui/rbac_users_panel.py | 32 ++- je_auto_control/gui/recording_editor_tab.py | 53 +++-- .../gui/remote_desktop/_helpers.py | 23 ++- .../gui/remote_desktop/advanced_group.py | 25 +-- .../gui/remote_desktop/connection_screen.py | 23 ++- .../gui/remote_desktop/host_panel.py | 134 ++++++------- .../gui/remote_desktop/trusted_group.py | 10 +- .../gui/remote_desktop/viewer_panel.py | 47 ++--- .../gui/remote_desktop/webrtc_dialogs.py | 22 ++- .../gui/remote_desktop/webrtc_host_ui.py | 149 +++++++------- .../gui/remote_desktop/webrtc_known_hosts.py | 45 ++--- .../gui/remote_desktop/webrtc_panel.py | 2 +- .../gui/remote_desktop/webrtc_viewer_ui.py | 186 ++++++++---------- je_auto_control/gui/rest_api_tab.py | 46 ++--- je_auto_control/gui/run_history_tab.py | 45 ++--- je_auto_control/gui/scheduler_tab.py | 21 +- .../gui/script_builder/builder_tab.py | 39 ++-- .../gui/script_builder/step_form_view.py | 4 + je_auto_control/gui/secrets_tab.py | 11 +- je_auto_control/gui/self_healing_tab.py | 8 +- je_auto_control/gui/test_suite_tab.py | 15 +- je_auto_control/gui/theme.py | 7 +- je_auto_control/gui/trace_replay_tab.py | 18 +- je_auto_control/gui/triggers_tab.py | 86 ++++---- je_auto_control/gui/usb_browser_tab.py | 22 +-- je_auto_control/gui/usb_devices_tab.py | 24 +-- je_auto_control/gui/usb_passthrough_panel.py | 38 ++-- je_auto_control/gui/variables_tab.py | 19 +- je_auto_control/gui/vlm_tab.py | 19 +- je_auto_control/gui/webhooks_tab.py | 51 +++-- je_auto_control/gui/webrunner_tab.py | 39 ++-- je_auto_control/gui/window_tab.py | 12 +- je_auto_control/gui/workspace.py | 47 ++++- pyproject.toml | 3 + test/unit_test/headless/test_gui_adaptive.py | 51 +++++ .../headless/test_gui_adaptive_window.py | 31 +++ .../headless/test_gui_page_widths.py | 10 +- 84 files changed, 1484 insertions(+), 1201 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7703db241..e9b87ec1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## [Unreleased] +- GUI: every tab's layout is rebuilt on cards, wrapping rows and side-by-side panes that stack + when narrow; widget objects, attributes, signals, Actions-menu entries and translation keys + are unchanged. Each page's scroll area no longer uses `setWidgetResizable(True)` + (`ScrollableTabs.scroll_area()` returns a `PageScrollArea`, which sizes the page to the + viewport or its minimum), `FlowLayout` no longer reports height-for-width, and group-box + titles are drawn inside the box. The WebRTC viewer's remote-files section showed the raw key + `rd_webrtc_files_group`; it uses `rd_webrtc_remote_files_group`. The English + "Publish & wait for viewer" button read "Publish _wait"; it is "Publish and wait for viewer". + - The `gui` extra and the development and CI pins are back on `PySide6==6.11.2`. 6.12.0 crashed the test process at interpreter exit on every CI platform (a double free while `destroyQCoreApplication` tears down Python-held widgets); Dependabot now skips 6.12.0. diff --git a/Progress.md b/Progress.md index c782fdc33..f5477bfa2 100644 --- a/Progress.md +++ b/Progress.md @@ -534,10 +534,13 @@ F 還缺: - **F2 其餘**:Diagnostics 以外面板的執行詳情,以及各面板的空白/錯誤/permission states 尚未全面交付。 - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: - 設計系統(`gui/adaptive/`、主題 token 與字階)、每頁頁首與 fit pass、視窗斷點(圖示欄、導覽與詳情抽屜)已交付(U-20261114-02)。仍缺: - 51 個分頁逐頁改用 `Card`/`FlowLayout`/`ResponsiveBox` 重排(目前多數頁只套上群組框的卡片樣式,頁首標題與頁內第一個群組標題重複); - `test_gui_page_widths.py` 的 `WIDE_PAGES`(script_builder、flakiness、audit_log、usb_share)降到 72 字元內後移除; - 所有截圖都是 offscreen 平台加 Windows 字型,尚未在真實螢幕、混合 DPI 與 Linux/macOS 字型上目視審閱。 + 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: + - 所有截圖都是 offscreen 平台加 Windows 字型,尚未在真實螢幕、混合 DPI 與 Linux/macOS 字型上目視審閱。 + - 重排時看到、但屬邏輯或字串而未改的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; + Remote Desktop 的走勢圖背景(黑)、統計文字(`#ccaa55`)與大號 ID(`#2070d0`)寫死顏色,淺色主題下不協調; + 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複;Diagnostics 閒置時空的進度列仍佔一行; + Assertions 的種類下拉選單項目與 Email Triggers 的密碼提示字在 `__init__` 設定,切換語言不會更新; + 下拉選單的箭頭貼齊右緣(`theme.py`);Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/architecture_explore.md b/architecture_explore.md index 3ab6301e5..3a844c1ba 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,536 | -| 程式碼總行數 | 235,073 | +| 程式碼總行數 | 235,230 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1299,27 +1299,27 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 233 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 234 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | -| `adaptive/flow_layout.py` | 105 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | -| `adaptive/responsive.py` | 119 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行),工作區放入每頁時跑一次。 | +| `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | +| `adaptive/responsive.py` | 120 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行),工作區放入每頁時跑一次。 | | `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | | `adaptive/style.py` | 102 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | | `adaptive/glyphs.py` | 52 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | | `adaptive/overlay.py` | 102 | A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed. `OverlayDrawer`:Escape 或點擊遮罩關閉。 | | `adaptive_window.py` | 179 | Rearrange the main window's navigation and details panes as the window's width class changes. `AdaptiveWindowLayout`:expanded 兩側停靠;medium 詳情改抽屜;compact 導覽改圖示欄+抽屜。「想要停靠導覽」與寬度是否允許分開記錄,窄視窗不會改寫使用者偏好。 | -| `workspace.py` | 528 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | +| `workspace.py` | 567 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | | `workspace_details.py` | 97 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | -| `agent_transfer_view.py` | 166 | Explicit transfer requests and consent preparation with revision-bound background observations. | +| `agent_transfer_view.py` | 171 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 131 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | -| `config_sync_tab.py` | 413 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | -| `_auto_click_tab.py` | 326 | 獨立自動點擊分頁;快照工作參數,以 TabTask 執行與取消。 | -| `_screenshot_tab.py` | 179 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | -| `_image_detect_tab.py` | 159 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | +| `config_sync_tab.py` | 423 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | +| `_auto_click_tab.py` | 321 | 獨立自動點擊分頁;快照工作參數,以 TabTask 執行與取消。 | +| `_screenshot_tab.py` | 180 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | +| `_image_detect_tab.py` | 158 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | | `_script_tab.py` | 183 | 獨立腳本執行分頁;背景載入與執行,關閉取消並釋放控制項。 | -| `_record_tab.py` | 162 | 獨立錄製/回放檢視;背景工作與共享錄製器狀態,關閉檢視不停止錄製器。 | +| `_record_tab.py` | 166 | 獨立錄製/回放檢視;背景工作與共享錄製器狀態,關閉檢視不停止錄製器。 | | `_report_tab.py` | 106 | 報表分頁 mixin。 | | `_i18n_helpers.py` | 79 | 需要即時語言切換的分頁共用的翻譯註冊 mixin。 | | `_validators.py` | 29 | `int_validator()`/`double_validator()`:以 C locale 驗證的數字輸入框 validator,接受的正是 `int()`/`float()` 讀得懂的寫法(預設 locale 在法文、德文下只收小數逗號)。所有數字 `QLineEdit` 都用它。 | @@ -1346,55 +1346,55 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | 分頁 | 模組 | 行數 | 職責 | | --- | --- | ---: | --- | -| auto_click | `_auto_click_tab.py` | 326 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | -| screenshot | `_screenshot_tab.py` | 179 | 截圖、選區、螢幕尺寸、取像素色。 | -| image_detect | `_image_detect_tab.py` | 159 | 樣板裁切、定位、定位全部、定位並點擊。 | -| record | `_record_tab.py` | 162 | 錄製/停止/回放/存檔/載入。 | -| script_builder | `script_builder/` | 6,911 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | -| flow_editor | `flow_editor/` | 490 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | +| auto_click | `_auto_click_tab.py` | 321 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | +| screenshot | `_screenshot_tab.py` | 180 | 截圖、選區、螢幕尺寸、取像素色。 | +| image_detect | `_image_detect_tab.py` | 158 | 樣板裁切、定位、定位全部、定位並點擊。 | +| record | `_record_tab.py` | 166 | 錄製/停止/回放/存檔/載入。 | +| script_builder | `script_builder/` | 6,928 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | +| flow_editor | `flow_editor/` | 496 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | | script | `_script_tab.py` | 183 | 載入/執行單檔或整個目錄、內建編輯器執行。 | -| recording_editor | `recording_editor_tab.py` | 262 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | -| variables | `variables_tab.py` | 169 | 檢視、灌入、清除 executor 執行期作用域。 | -| secrets | `secrets_tab.py` | 187 | 解鎖保險庫並管理 `${secrets.NAME}`。 | -| vlm | `vlm_tab.py` | 125 | 用文字描述 UI 元素,交由模型定位。 | -| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 941 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | -| ocr_reader | `ocr_tab.py` | 195 | 傾印區域文字或以 regex 搜尋。 | -| accessibility | `accessibility_tab.py` | 192 | 瀏覽 OS UI 樹並依 role/name 點擊。 | -| live_hud | `live_hud_tab.py` | 136 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | -| llm_planner | `llm_planner_tab.py` | 200 | 自然語言描述 → 預覽 → 執行。 | -| computer_use | `computer_use_tab.py` | 179 | 從 GUI 啟動 Anthropic 閉環 agent。 | -| agent_tasks | `agent_tasks_tab.py` | 609 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | -| scheduler | `scheduler_tab.py` | 173 | 註冊間隔式 action JSON 執行。 | -| hotkeys | `hotkeys_tab.py` | 165 | 將全域熱鍵綁到 action 檔。 | -| triggers | `triggers_tab.py` | 382 | 影像/視窗/像素/檔案事件監看。 | -| webhooks | `webhooks_tab.py` | 229 | 將 HTTP 請求綁到 action 腳本。 | -| email_triggers | `email_triggers_tab.py` | 257 | 將 IMAP 信箱綁到 action 腳本。 | -| test_suite | `test_suite_tab.py` | 197 | 執行 QA 套件規格並管理易碎隔離區。 | -| assertions | `assertions_tab.py` | 150 | 執行單一畫面狀態斷言並顯示通過/失敗。 | -| data_source | `data_source_tab.py` | 136 | 預覽無頭資料層載入的資料列。 | -| flakiness | `flakiness_tab.py` | 116 | 依執行歷史排序間歇失敗的腳本。 | -| a11y_audit | `a11y_audit_tab.py` | 133 | 從即時樹找出無障礙/i18n 缺陷。 | +| recording_editor | `recording_editor_tab.py` | 255 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | +| variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | +| secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | +| vlm | `vlm_tab.py` | 126 | 用文字描述 UI 元素,交由模型定位。 | +| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 955 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | +| ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | +| accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | +| live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | +| llm_planner | `llm_planner_tab.py` | 203 | 自然語言描述 → 預覽 → 執行。 | +| computer_use | `computer_use_tab.py` | 185 | 從 GUI 啟動 Anthropic 閉環 agent。 | +| agent_tasks | `agent_tasks_tab.py` | 618 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | +| scheduler | `scheduler_tab.py` | 174 | 註冊間隔式 action JSON 執行。 | +| hotkeys | `hotkeys_tab.py` | 166 | 將全域熱鍵綁到 action 檔。 | +| triggers | `triggers_tab.py` | 384 | 影像/視窗/像素/檔案事件監看。 | +| webhooks | `webhooks_tab.py` | 222 | 將 HTTP 請求綁到 action 腳本。 | +| email_triggers | `email_triggers_tab.py` | 250 | 將 IMAP 信箱綁到 action 腳本。 | +| test_suite | `test_suite_tab.py` | 200 | 執行 QA 套件規格並管理易碎隔離區。 | +| assertions | `assertions_tab.py` | 148 | 執行單一畫面狀態斷言並顯示通過/失敗。 | +| data_source | `data_source_tab.py` | 132 | 預覽無頭資料層載入的資料列。 | +| flakiness | `flakiness_tab.py` | 115 | 依執行歷史排序間歇失敗的腳本。 | +| a11y_audit | `a11y_audit_tab.py` | 138 | 從即時樹找出無障礙/i18n 缺陷。 | | device_matrix | `device_matrix_tab.py` | 139 | 一份 action list 跨多裝置平行執行。 | -| mobile | `mobile_tab.py` | 216 | Android/iOS 裝置工作階段:設定報告、擷取、手勢、輸入與能力矩陣。 | -| media_checks | `media_checks_tab.py` | 136 | 音訊活動與影片動態斷言。 | -| run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 826 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | -| profiler | `profiler_tab.py` | 138 | 視覺化逐動作耗時熱點。 | -| window_manager | `window_tab.py` | 137 | 列出、聚焦、關閉視窗。 | -| plugins | `plugins_tab.py` | 82 | 從使用者目錄載入額外 `AC_` 指令。 | -| webrunner | `webrunner_tab.py` | 204 | 從 GUI 驅動 `je_web_runner`。 | -| dag_runner | `dag_tab.py` | 369 | 編輯、驗證、執行跨主機 DAG。 | -| chatops | `chatops_tab.py` | 144 | 在接上 Slack 前先本機測試 slash 指令。 | -| trace_replay | `trace_replay_tab.py` | 192 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,353 | 見下。 | -| presence | `presence_tab.py` | 164 | 多檢視者在場名單。 | -| rest_api | `rest_api_tab.py` | 260 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | -| admin_console | `admin_console_tab.py` | 318 | 管理多個遠端 AutoControl REST 端點。 | -| audit_log | `audit_log_tab.py` | 191 | 瀏覽並驗證防竄改雜湊鏈。 | -| inspector | `inspector_tab.py` | 128 | WebRTC 檢測器:即時摘要與近期統計取樣。 | -| usb_devices | `usb_devices_tab.py` | 168 | 唯讀列舉 + 熱插拔監看控制。 | -| usb_browser | `usb_browser_tab.py` | 290 | 檢視端 USB 裝置瀏覽器。 | -| usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | -| diagnostics | `diagnostics_tab.py` | 232 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | +| mobile | `mobile_tab.py` | 222 | Android/iOS 裝置工作階段:設定報告、擷取、手勢、輸入與能力矩陣。 | +| media_checks | `media_checks_tab.py` | 129 | 音訊活動與影片動態斷言。 | +| run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 823 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | +| profiler | `profiler_tab.py` | 141 | 視覺化逐動作耗時熱點。 | +| window_manager | `window_tab.py` | 139 | 列出、聚焦、關閉視窗。 | +| plugins | `plugins_tab.py` | 85 | 從使用者目錄載入額外 `AC_` 指令。 | +| webrunner | `webrunner_tab.py` | 203 | 從 GUI 驅動 `je_web_runner`。 | +| dag_runner | `dag_tab.py` | 371 | 編輯、驗證、執行跨主機 DAG。 | +| chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | +| trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,335 | 見下。 | +| presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | +| rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | +| admin_console | `admin_console_tab.py` | 326 | 管理多個遠端 AutoControl REST 端點。 | +| audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | +| inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | +| usb_devices | `usb_devices_tab.py` | 170 | 唯讀列舉 + 熱插拔監看控制。 | +| usb_browser | `usb_browser_tab.py` | 288 | 檢視端 USB 裝置瀏覽器。 | +| usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 770 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | +| diagnostics | `diagnostics_tab.py` | 234 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1403,7 +1403,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,353 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,335 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1415,17 +1415,17 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | | `webrtc_panel_state.py` | 165 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | | `webrtc_panel.py` | 422 | WebRTC 子分頁主體。 | -| `webrtc_dialogs.py` | 520 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | -| `advanced_group.py` | 104 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | -| `trusted_group.py` | 73 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | -| `connection_screen.py` | 667 | Quick Connect —— AnyDesk 風格單畫面入口。 | -| `viewer_panel.py` | 599 | 「控制另一台機器」子分頁。 | -| `webrtc_known_hosts.py` | 346 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | -| `host_panel.py` | 437 | 「分享這台機器」子分頁。 | +| `webrtc_dialogs.py` | 524 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | +| `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | +| `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | +| `connection_screen.py` | 672 | Quick Connect —— AnyDesk 風格單畫面入口。 | +| `viewer_panel.py` | 594 | 「控制另一台機器」子分頁。 | +| `webrtc_known_hosts.py` | 339 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | +| `host_panel.py` | 419 | 「分享這台機器」子分頁。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | | `webrtc_workers.py` | 237 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | | `tab.py` | 179 | 外層容器分頁。 | -| `_helpers.py` | 273 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | +| `_helpers.py` | 294 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | | `remote_screen_window.py` | 140 | 檢視端的彈出視窗。 | | `tray_icon.py` | 106 | WebRTC 主機的系統匣圖示。 | | `annotation_overlay.py` | 174 | 主機端標註的透明最上層覆蓋。 | @@ -1542,7 +1542,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 159 | 41,876 | +| `gui/` | 159 | 42,033 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,7 +1563,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,524** | **234,328** | +| **總計** | **1,524** | **234,485** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v224_features_doc.rst b/docs/source/Eng/doc/new_features/v224_features_doc.rst index f26a85ef6..9bacb1b59 100644 --- a/docs/source/Eng/doc/new_features/v224_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v224_features_doc.rst @@ -3,9 +3,23 @@ Adaptive GUI: Page Headers, Cards and Controls That Shrink The GUI is being redesigned around one set of adaptive building blocks, so every page looks the same and fits a small window. This page describes what -is in place: the building blocks, the window's own breakpoints, and what every -page gets from them. Reworking each page onto the blocks follows in later -releases. +is in place: the building blocks, the window's own breakpoints, and every +page rebuilt on them. + +Every page is rebuilt +--------------------- + +All 51 pages now group their controls on cards, put their main table or result +on a card that takes the remaining height, wrap rows of fields and buttons +instead of widening, and set side-by-side panes (list and details, input and +output) one above the other in a narrow window. Status lines and notes are +muted hints. Nothing a page does changed: its widgets, menu actions and +translations are the same. + +A page scrolls only when the window is smaller than the page can shrink: each +page is given the visible area, or its minimum size where that is larger. (Qt's +default sized a page holding a wrapped label from every control's preferred +height, so pages with a table scrolled in windows they fitted.) The window adapts to its width ------------------------------ @@ -83,6 +97,5 @@ The width check ``test/unit_test/headless/test_gui_page_widths.py`` opens every registered tab the way the window does and reads its minimum width, in average characters of the window's label font so the same limit holds on Windows and Linux fonts. A -page may need at most 72 characters (about 460 px in 10 pt Segoe UI). Four -pages are still over it and listed with a ceiling each (Script Builder, -Flaky Tests, Audit Log, USB Sharing); the list only shrinks. +page may need at most 72 characters (about 460 px in 10 pt Segoe UI). Every +page fits; before the rework Script Builder alone needed 818 px. diff --git a/docs/source/Zh/doc/new_features/v224_features_doc.rst b/docs/source/Zh/doc/new_features/v224_features_doc.rst index c20054beb..9f2567915 100644 --- a/docs/source/Zh/doc/new_features/v224_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v224_features_doc.rst @@ -2,8 +2,17 @@ ====================================== GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一致,也放得進小視窗。 -本頁說明目前已完成的部分:元件、視窗本身的斷點,以及每個分頁因此得到的改變。 -各分頁逐頁改用這些元件,會在之後的版本陸續交付。 +本頁說明目前已完成的部分:元件、視窗本身的斷點,以及以它們重建的每個分頁。 + +每個分頁都已重建 +---------------- + +51 個分頁都把控制項依用途分組在卡片上,主要的表格或結果放在佔滿剩餘高度的卡片; +欄位與按鈕列放不下時換行而不撐寬;並排的面板(清單與詳情、輸入與輸出)在窄視窗改為上下排列。 +狀態列與說明改為淡色提示。分頁的行為不變:控制項、Actions 選單與翻譯都相同。 + +只有視窗小於分頁能縮到的大小時才會捲動:每頁取得可見區域,或在其最小尺寸較大時取最小尺寸。 +(Qt 預設會依每個控制項的偏好高度決定含換行標籤的頁面高度,所以含表格的頁面在放得下的視窗裡也會捲動。) 視窗依寬度調整 -------------- @@ -71,5 +80,4 @@ GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一 ``test/unit_test/headless/test_gui_page_widths.py`` 以視窗的方式開啟每個已註冊分頁並讀取最小寬度, 單位是視窗標籤字型的平均字元寬,使 Windows 與 Linux 字型適用同一個上限。 -每頁最多 72 字元(10 pt Segoe UI 約 460 px)。目前仍有四個分頁超過,各自列出上限 -(Script Builder、Flaky Tests、Audit Log、USB Sharing);這份清單只減不增。 +每頁最多 72 字元(10 pt Segoe UI 約 460 px)。目前每頁都符合;重排前 Script Builder 一頁就需要 818 px。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 64ddb3080..0bfa6e176 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -299,3 +299,14 @@ - **Decision (maintainer, 2026-11-14):** pin `PySide6==6.11.2` again in `pyproject.toml`, `dev.toml`, `requirements.txt`, `dev_requirements.txt` and the `dev.yml` / `quality.yml` tool lines; Dependabot ignores 6.12.0 only, so a later 6.12 release is still proposed. The shared local `.venv` stays on 6.12.0 (not replaced); CI is the check for 6.11.2. - **Files:** the six pinned files, `.github/dependabot.yml`, `CHANGELOG.md`, `Progress.md`. - **Open items:** retrying 6.12.x (`Progress.md` › PySide6 6.12). + +## U-20261114-04 · 2026-11-14 · GUI redesign, stage 2: every tab rebuilt on the adaptive layout · #migration #gui + +- **What:** the 51 tabs' layouts (plus their embedded views: RBAC users, healing evaluation, agent observation / transfer, MCP discovery, the Remote Desktop panels and dialogs, Script Builder's step form) rebuilt on `Card`, `FlowLayout` / `field_pair` and `ResponsiveBox`: groups on cards, the main table or result on a stretching card, rows that wrap, side-by-side panes that stack below 720 px, status lines as hints, inline labels registered for live translation. Auto Click's group titled like the page is gone. Widget objects, attributes, signal connections, `menu_actions()`, `retranslate()`, `dispose()` and translation keys are unchanged; a scan of the diff for removed connections, attributes and keys found only that title and the remote-files key below. +- **Widths (average characters, budget 72):** Script Builder 127 → 32 (its 9-button toolbar was one row), Audit Log 78.5 → 44.1, USB Sharing 76.6 → 39.5 (now also gets a page header), Flaky Tests 87 → under budget, Media Checks 71.8 → 37.8, Triggers 71.0 → 43.0, Image Detection 66.8 → 35.8, Recording Editor 62.0 → 25.5, DAG Runner 60.3 → 42.7, Remote Desktop's WebRTC host 120.3 → 52.6 and viewer 107.7 → 52.6 (inside its own scroll areas). `WIDE_PAGES` in `test_gui_page_widths.py` is empty. +- **Shared fixes found while doing it:** `FlowLayout` no longer reports height-for-width (a page with one scrolled even when it fitted), keeps its wrapped height as its minimum, centres items on a line and gives spare width to items that grow (line edits, fitted combos); each tab page sits in a `PageScrollArea` that gives it the viewport or its minimum, because `setWidgetResizable(True)` sized any page with a wrapped label from preferred heights; container widgets take a `bare` role (no painted background inside cards); group-box titles are drawn inside the box like card titles. +- **Defects fixed on the way:** the WebRTC viewer's remote-files section showed the raw key `rd_webrtc_files_group` (now the existing `rd_webrtc_remote_files_group`); the English "Publish & wait for viewer" rendered as "Publish _wait" (the `&` is a mnemonic); Remote Desktop's security warning, status and drag-and-drop notes used fixed colours (`#555` was unreadable on dark) and now use roles. +- **How:** done in seven parallel batches with one brief (layout only, no shared files), then reviewed, the shared fixes above made here, and rendered as contact sheets in both themes at 600 and 1,360 px. +- **Tests:** batches reported 140 + 216 + 160 + 171 + 293 + 170 + 1,463 tab tests passing (Remote Desktop's count equals its baseline). `test_gui_adaptive.py` +2 (a flow row inside a scroll area does not scroll above its minimum and never overlaps what follows; spare width and centring), `test_gui_adaptive_window.py` +1 (a page with wrapped text scrolls only below its minimum). +- **Files:** 70 modules under `gui/`, `gui/adaptive/{flow_layout,responsive}.py`, `gui/theme.py`, `gui/workspace.py`, `english.py`, the three tests, both `v224_features_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** review on a real screen and other fonts; the pre-existing defects listed in `Progress.md` › F2 GUI 重製. diff --git a/docs/updates/README.md b/docs/updates/README.md index 30067374a..e0c109bf1 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-04 | 2026-11-14 | GUI redesign, stage 2: every tab rebuilt on the adaptive layout | #migration #gui | [2026-11-b](2026-11-b.md) | | U-20261114-03 | 2026-11-14 | PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit | #decision #ci #gui | [2026-11-b](2026-11-b.md) | | U-20261114-02 | 2026-11-14 | GUI redesign, stage 1: adaptive building blocks, page headers, cards, window breakpoints and the width gate | #migration #gui | [2026-11-b](2026-11-b.md) | | U-20261114-01 | 2026-11-14 | PR #552: CI tested PySide6 6.11.2, the container crashes on 6.12.0, two test regressions | #incident #ci #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_auto_click_tab.py b/je_auto_control/gui/_auto_click_tab.py index c585561fa..b6e9f5814 100644 --- a/je_auto_control/gui/_auto_click_tab.py +++ b/je_auto_control/gui/_auto_click_tab.py @@ -6,12 +6,15 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QWidget, QLineEdit, QComboBox, QVBoxLayout, QLabel, - QGridLayout, QHBoxLayout, QRadioButton, QButtonGroup, QMessageBox, + QWidget, QLineEdit, QComboBox, QVBoxLayout, QLabel, QFormLayout, + QHBoxLayout, QRadioButton, QButtonGroup, QMessageBox, QGroupBox, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui._tab_task import TabTask, stop_all_script_runs from je_auto_control.utils.exception.cancellation import cancellation_checkpoint @@ -35,6 +38,20 @@ class _Click: count: int +def _form_panel(rows) -> QWidget: + """A frameless panel holding ``(label, field)`` form rows; a ``None`` label spans the row.""" + panel = QWidget() + panel.setProperty("role", "bare") + form = QFormLayout(panel) + form.setContentsMargins(0, 0, 0, 0) + for label, field in rows: + if label is None: + form.addRow(field) + else: + form.addRow(label, field) + return panel + + def _click(request: _Click) -> None: for _ in range(request.count): cancellation_checkpoint() @@ -59,64 +76,37 @@ def __init__(self, parent: QWidget | None = None) -> None: self._task.error.connect(self._on_error) self._task.finished.connect(self._refresh_status) outer = QVBoxLayout(self) - click_group = self._tr(QGroupBox(), "tab_auto_click") - grid = QGridLayout() - row = 0 + outer.setSpacing(12) + outer.addWidget(self._build_click_card()) + # Start/stop, position probe, hotkey, write, and scroll commands all + # run from the Actions menu; the tab keeps only their inputs. + outer.addWidget(ResponsiveBox(self._build_position_group(), self._build_scroll_group())) + outer.addWidget(ResponsiveBox(self._build_hotkey_group(), self._build_write_group())) + self.status_label = QLabel() + self.status_label.setWordWrap(True) + set_role(self.status_label, "hint") + outer.addWidget(self.status_label) + self._refresh_status() + outer.addStretch() + + self.mouse_radio.toggled.connect(self._update_click_mode) + self._update_click_mode() - grid.addWidget(self._tr(QLabel(), "input_method"), row, 0) + def _build_click_card(self) -> Card: + """The click settings: how and how often on the left, what and where on the right.""" self.mouse_radio = self._tr(QRadioButton(), "mouse_radio") self.keyboard_radio = self._tr(QRadioButton(), "keyboard_radio") self.mouse_radio.setChecked(True) self._input_group = QButtonGroup(self) self._input_group.addButton(self.mouse_radio) self._input_group.addButton(self.keyboard_radio) - h = QHBoxLayout() - h.addWidget(self.mouse_radio) - h.addWidget(self.keyboard_radio) - grid.addLayout(h, row, 1) - - row += 1 - grid.addWidget(self._tr(QLabel(), "interval_time"), row, 0) self.interval_input = QLineEdit("1000") self.interval_input.setValidator(int_validator(1, 999999999)) - grid.addWidget(self.interval_input, row, 1) - - row += 1 - grid.addWidget(self._tr(QLabel(), "cursor_x"), row, 0) - self.cursor_x_input = QLineEdit() - self.cursor_x_input.setValidator(int_validator()) - grid.addWidget(self.cursor_x_input, row, 1) - - row += 1 - grid.addWidget(self._tr(QLabel(), "cursor_y"), row, 0) - self.cursor_y_input = QLineEdit() - self.cursor_y_input.setValidator(int_validator()) - grid.addWidget(self.cursor_y_input, row, 1) - - row += 1 - grid.addWidget(self._tr(QLabel(), "mouse_button"), row, 0) - self.mouse_button_combo = QComboBox() - self.mouse_button_combo.addItems( - list(mouse_keys_table.keys()) if isinstance(mouse_keys_table, dict) else list(mouse_keys_table) - ) - grid.addWidget(self.mouse_button_combo, row, 1) - - row += 1 - grid.addWidget(self._tr(QLabel(), "keyboard_button"), row, 0) - self.keyboard_button_combo = QComboBox() - self.keyboard_button_combo.addItems(list(get_keyboard_keys_table().keys())) - grid.addWidget(self.keyboard_button_combo, row, 1) - - row += 1 - grid.addWidget(self._tr(QLabel(), "click_type"), row, 0) self.click_type_combo = QComboBox() self._click_type_keys = ["single_click", "double_click"] self.click_type_combo.addItems( [self._translate(key) for key in self._click_type_keys] ) - grid.addWidget(self.click_type_combo, row, 1) - - row += 1 self.repeat_until_stopped = self._tr( QRadioButton(), "repeat_until_stopped_radio", ) @@ -127,66 +117,71 @@ def __init__(self, parent: QWidget | None = None) -> None: rg.addButton(self.repeat_until_stopped) rg.addButton(self.repeat_count_times) self.repeat_until_stopped.setChecked(True) - rh = QHBoxLayout() - rh.addWidget(self.repeat_until_stopped) - rh.addWidget(self.repeat_count_times) - rh.addWidget(self.repeat_count_input) - grid.addLayout(rh, row, 0, 1, 2) - - click_group.setLayout(grid) - outer.addWidget(click_group) - - # Start/stop, position probe, hotkey, write, and scroll commands all - # run from the Actions menu; the tab keeps only their inputs. + how = _form_panel(( + (self._tr(QLabel(), "input_method"), flow_of(self.mouse_radio, self.keyboard_radio)), + (self._tr(QLabel(), "interval_time"), self.interval_input), + (self._tr(QLabel(), "click_type"), self.click_type_combo), + (None, flow_of(self.repeat_until_stopped, + field_pair(self.repeat_count_times, self.repeat_count_input))), + )) + return Card().add(ResponsiveBox(how, self._build_target_panel())) + + def _build_target_panel(self) -> QWidget: + """Cursor position and the mouse or keyboard button to press.""" + self.cursor_x_input = QLineEdit() + self.cursor_x_input.setValidator(int_validator()) + self.cursor_y_input = QLineEdit() + self.cursor_y_input.setValidator(int_validator()) + self.mouse_button_combo = QComboBox() + self.mouse_button_combo.addItems( + list(mouse_keys_table.keys()) if isinstance(mouse_keys_table, dict) else list(mouse_keys_table) + ) + self.keyboard_button_combo = QComboBox() + self.keyboard_button_combo.addItems(list(get_keyboard_keys_table().keys())) + return _form_panel(( + (self._tr(QLabel(), "cursor_x"), self.cursor_x_input), + (self._tr(QLabel(), "cursor_y"), self.cursor_y_input), + (self._tr(QLabel(), "mouse_button"), self.mouse_button_combo), + (self._tr(QLabel(), "keyboard_button"), self.keyboard_button_combo), + )) + + def _build_position_group(self) -> QGroupBox: pos_group = self._tr(QGroupBox(), "get_position") - pos_layout = QHBoxLayout() + pos_layout = QHBoxLayout(pos_group) self.pos_label = QLabel() self._pos_label_suffix = " --" self.pos_label.setText( self._translate("current_position") + self._pos_label_suffix, ) pos_layout.addWidget(self.pos_label) - pos_group.setLayout(pos_layout) - outer.addWidget(pos_group) + return pos_group + def _build_hotkey_group(self) -> QGroupBox: hotkey_group = self._tr(QGroupBox(), "hotkey_label") - hk_layout = QHBoxLayout() self.hotkey_input = QLineEdit() self.hotkey_input.setPlaceholderText("ctrl,a") - hk_layout.addWidget(self.hotkey_input) - hotkey_group.setLayout(hk_layout) - outer.addWidget(hotkey_group) + QHBoxLayout(hotkey_group).addWidget(self.hotkey_input) + return hotkey_group + def _build_write_group(self) -> QGroupBox: write_group = self._tr(QGroupBox(), "write_label") - wr_layout = QHBoxLayout() self.write_input = QLineEdit() - wr_layout.addWidget(self.write_input) - write_group.setLayout(wr_layout) - outer.addWidget(write_group) + QHBoxLayout(write_group).addWidget(self.write_input) + return write_group + def _build_scroll_group(self) -> QGroupBox: scroll_group = self._tr(QGroupBox(), "mouse_scroll_label") - sc_layout = QHBoxLayout() self.scroll_value_input = QLineEdit("3") self.scroll_value_input.setValidator(int_validator()) - sc_layout.addWidget(self._tr(QLabel(), "mouse_scroll_label")) - sc_layout.addWidget(self.scroll_value_input) + row = [field_pair(self._tr(QLabel(), "mouse_scroll_label"), self.scroll_value_input)] if special_mouse_keys_table: self.scroll_dir_combo: Optional[QComboBox] = QComboBox() self.scroll_dir_combo.addItems(list(special_mouse_keys_table.keys())) - sc_layout.addWidget(self.scroll_dir_combo) + row.append(self.scroll_dir_combo) else: self.scroll_dir_combo = None - scroll_group.setLayout(sc_layout) - outer.addWidget(scroll_group) - - self.status_label = QLabel() - outer.addWidget(self.status_label) - self._refresh_status() - outer.addStretch() - - self.mouse_radio.toggled.connect(self._update_click_mode) - self._update_click_mode() - + QVBoxLayout(scroll_group).addLayout(flow_of(*row)) + return scroll_group def retranslate(self) -> None: """Re-translate composite labels and combo items that ``_tr`` can't own.""" diff --git a/je_auto_control/gui/_image_detect_tab.py b/je_auto_control/gui/_image_detect_tab.py index 935d46405..284b669e8 100644 --- a/je_auto_control/gui/_image_detect_tab.py +++ b/je_auto_control/gui/_image_detect_tab.py @@ -5,13 +5,14 @@ from typing import Callable, Literal from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QFileDialog, QGridLayout, QLabel, QLineEdit, QMessageBox, + QCheckBox, QComboBox, QFileDialog, QFormLayout, QLabel, QLineEdit, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui._validators import double_validator +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.selector import crop_template_to_file from je_auto_control.utils.exception.exceptions import AutoControlException @@ -49,26 +50,24 @@ def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self._tr_init() layout = QVBoxLayout(self) - grid = QGridLayout() - grid.addWidget(self._tr(QLabel(), "template_image"), 0, 0) + layout.setSpacing(12) + form = QFormLayout() self.img_path_input = QLineEdit() - grid.addWidget(self.img_path_input, 0, 1) - grid.addWidget(self._tr(QLabel(), "threshold_label"), 1, 0) + form.addRow(self._tr(QLabel(), "template_image"), self.img_path_input) self.threshold_input = QLineEdit("0.8") self.threshold_input.setValidator(double_validator(0.0, 1.0, 2)) - grid.addWidget(self.threshold_input, 1, 1) - self.draw_check = self._tr(QCheckBox(), "draw_image_check") - grid.addWidget(self.draw_check, 1, 2) - grid.addWidget(self._tr(QLabel(), "mouse_button"), 2, 0) + form.addRow(self._tr(QLabel(), "threshold_label"), self.threshold_input) self.mouse_button_combo = QComboBox() self.mouse_button_combo.addItems(list(mouse_keys_table)) self.mouse_button_combo.setCurrentText("mouse_left") - grid.addWidget(self.mouse_button_combo, 2, 1) - layout.addLayout(grid) - layout.addWidget(self._tr(QLabel(), "detection_result")) + form.addRow(self._tr(QLabel(), "mouse_button"), self.mouse_button_combo) + self.draw_check = self._tr(QCheckBox(), "draw_image_check") + form.addRow(self.draw_check) + layout.addWidget(Card().add(form)) + result_card = Card().add(set_role(self._tr(QLabel(), "detection_result"), "sectionTitle")) self.detect_result_text = QTextEdit() self.detect_result_text.setReadOnly(True) - layout.addWidget(self.detect_result_text) + layout.addWidget(result_card.add(self.detect_result_text, stretch=1), stretch=1) self._status_key = "" self._task = TabTask(self) self._task.result.connect(self._on_result) diff --git a/je_auto_control/gui/_record_tab.py b/je_auto_control/gui/_record_tab.py index 64562531e..46ff328ea 100644 --- a/je_auto_control/gui/_record_tab.py +++ b/je_auto_control/gui/_record_tab.py @@ -14,6 +14,7 @@ from je_auto_control.gui._tab_task import TabTask, was_stopped from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.wrapper import auto_control_record from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.exception.exceptions import AutoControlException @@ -47,17 +48,20 @@ def __init__(self, parent=None): self._tr_init() self._record_data: list = [] layout = QVBoxLayout(self) + layout.setSpacing(12) # Record/playback/save/load all run from the Actions menu. self._record_status_key = "record_idle" self.record_status_label = QLabel() + self.record_status_label.setWordWrap(True) + set_role(self.record_status_label, "hint") self._apply_record_status_label() - layout.addWidget(self.record_status_label) - layout.addWidget(self._tr(QLabel(), "record_list_label")) + list_card = Card().add(set_role(self._tr(QLabel(), "record_list_label"), "sectionTitle")) self.record_list_text = QTextEdit() self.record_list_text.setReadOnly(True) - layout.addWidget(self.record_list_text) + layout.addWidget(list_card.add(self.record_list_text, stretch=1), stretch=1) + layout.addWidget(self.record_status_label) self._playback_runs = TabTask(self) self._playback_runs.error.connect(self._on_playback_error) self._playback_runs.finished.connect(self._on_playback_finished) diff --git a/je_auto_control/gui/_report_tab.py b/je_auto_control/gui/_report_tab.py index d3ffd3697..2f53bc1dd 100644 --- a/je_auto_control/gui/_report_tab.py +++ b/je_auto_control/gui/_report_tab.py @@ -4,12 +4,13 @@ from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( - QGroupBox, QHBoxLayout, QLabel, QLineEdit, + QFormLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.generate_report.generate_html_report import generate_html_report from je_auto_control.utils.generate_report.generate_json_report import generate_json_report @@ -24,6 +25,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() layout = QVBoxLayout(self) + layout.setSpacing(12) # Enable/disable recording and report generation run from the # Actions menu; the tab keeps only status, name input, and result. @@ -34,17 +36,15 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: tr_group.setLayout(tr_h) layout.addWidget(tr_group) - name_h = QHBoxLayout() - name_h.addWidget(self._tr(QLabel(), "report_name")) + name_form = QFormLayout() self.report_name_input = QLineEdit("autocontrol_report") - name_h.addWidget(self.report_name_input) - layout.addLayout(name_h) + name_form.addRow(self._tr(QLabel(), "report_name"), self.report_name_input) + layout.addWidget(Card().add(name_form)) - layout.addWidget(self._tr(QLabel(), "report_result")) + result_card = Card().add(set_role(self._tr(QLabel(), "report_result"), "sectionTitle")) self.report_result_text = QTextEdit() self.report_result_text.setReadOnly(True) - layout.addWidget(self.report_result_text) - layout.addStretch() + layout.addWidget(result_card.add(self.report_result_text, stretch=1), stretch=1) self._task = TabTask(self) self._task.result.connect(self._on_report_result) self._task.error.connect(self._on_report_error) diff --git a/je_auto_control/gui/_screenshot_tab.py b/je_auto_control/gui/_screenshot_tab.py index 2276843e0..806fef57e 100644 --- a/je_auto_control/gui/_screenshot_tab.py +++ b/je_auto_control/gui/_screenshot_tab.py @@ -3,13 +3,16 @@ from typing import Callable, Literal, Optional from PySide6.QtWidgets import ( - QFileDialog, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, + QFileDialog, QFormLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._validators import int_validator from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.selector import open_region_selector from je_auto_control.wrapper.auto_control_screen import screen_size, screenshot, get_pixel @@ -27,55 +30,53 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() layout = QVBoxLayout(self) + layout.setSpacing(12) + # Screenshot inputs; capture runs from the Actions menu. + layout.addWidget(self._build_screenshot_group()) + # Screen size (read via Actions menu -> Get Screen Size) beside the + # pixel probe inputs; lookup runs from the Actions menu. + layout.addWidget(ResponsiveBox(self._build_size_group(), self._build_pixel_group(), stretches=(1, 2))) + self.ss_result_text = QTextEdit() + self.ss_result_text.setReadOnly(True) + self.ss_result_text.setMaximumHeight(100) + layout.addWidget(Card().add(self.ss_result_text)) + # A stretch factor, so the capped result card keeps its own height. + layout.addStretch(1) + self._task = TabTask(self) + self._task.result.connect(self._on_result) + self._task.error.connect(self._on_error) - # Screen size (read via Actions menu -> Get Screen Size) + def _build_size_group(self) -> QGroupBox: size_group = self._tr(QGroupBox(), "screen_size_label") - sg = QHBoxLayout() self.screen_size_label = QLabel("--") - sg.addWidget(self.screen_size_label) - size_group.setLayout(sg) - layout.addWidget(size_group) + QHBoxLayout(size_group).addWidget(self.screen_size_label) + return size_group - # Screenshot inputs; capture runs from the Actions menu. + def _build_screenshot_group(self) -> QGroupBox: ss_group = self._tr(QGroupBox(), "take_screenshot") - ss_grid = QGridLayout() - ss_grid.addWidget(self._tr(QLabel(), "file_path_label"), 0, 0) + ss_form = QFormLayout(ss_group) self.ss_path_input = QLineEdit() - ss_grid.addWidget(self.ss_path_input, 0, 1) - - ss_grid.addWidget(self._tr(QLabel(), "region_label"), 1, 0) + ss_form.addRow(self._tr(QLabel(), "file_path_label"), self.ss_path_input) self.ss_region_input = QLineEdit() self.ss_region_input.setPlaceholderText("0, 0, 800, 600") - ss_grid.addWidget(self.ss_region_input, 1, 1) - ss_group.setLayout(ss_grid) - layout.addWidget(ss_group) + ss_form.addRow(self._tr(QLabel(), "region_label"), self.ss_region_input) + return ss_group - # Pixel probe inputs; lookup runs from the Actions menu. + def _build_pixel_group(self) -> QGroupBox: px_group = self._tr(QGroupBox(), "get_pixel_label") - px_grid = QGridLayout() - px_grid.addWidget(self._tr(QLabel(), "pixel_x"), 0, 0) + px_layout = QVBoxLayout(px_group) self.pixel_x_input = QLineEdit("0") self.pixel_x_input.setValidator(int_validator()) - px_grid.addWidget(self.pixel_x_input, 0, 1) - px_grid.addWidget(self._tr(QLabel(), "pixel_y"), 0, 2) self.pixel_y_input = QLineEdit("0") self.pixel_y_input.setValidator(int_validator()) - px_grid.addWidget(self.pixel_y_input, 0, 3) + px_layout.addLayout(flow_of(field_pair(self._tr(QLabel(), "pixel_x"), self.pixel_x_input), + field_pair(self._tr(QLabel(), "pixel_y"), self.pixel_y_input))) self.pixel_result_label = QLabel() + self.pixel_result_label.setWordWrap(True) self._pixel_result: tuple[Literal["value", "error", "running"], str] = ("value", "--") self._render_pixel_result() - px_grid.addWidget(self.pixel_result_label, 1, 0, 1, 4) - px_group.setLayout(px_grid) - layout.addWidget(px_group) - - self.ss_result_text = QTextEdit() - self.ss_result_text.setReadOnly(True) - self.ss_result_text.setMaximumHeight(100) - layout.addWidget(self.ss_result_text) - layout.addStretch() - self._task = TabTask(self) - self._task.result.connect(self._on_result) - self._task.error.connect(self._on_error) + px_layout.addWidget(self.pixel_result_label) + return px_group def menu_actions(self) -> list[tuple[str, Callable[[], object]]]: return [ diff --git a/je_auto_control/gui/_script_tab.py b/je_auto_control/gui/_script_tab.py index b7c37a163..0460e9a99 100644 --- a/je_auto_control/gui/_script_tab.py +++ b/je_auto_control/gui/_script_tab.py @@ -12,12 +12,14 @@ from typing import Any, Callable, ContextManager from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, + QFileDialog, QFormLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._tab_task import TabTask, was_stopped from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.manual_run_controls import ManualRunControls, _requested_manual_run from je_auto_control.utils.executor.action_executor import execute_action, execute_files @@ -60,29 +62,23 @@ def __init__(self, parent: QWidget | None = None) -> None: self._tr_init() self._status_key = "" layout = QVBoxLayout(self) - file_h = QHBoxLayout() - file_h.addWidget(self._tr(QLabel(), "file_path_label")) + layout.setSpacing(12) + sources = QFormLayout() self.script_path_input = QLineEdit() - file_h.addWidget(self.script_path_input) - layout.addLayout(file_h) - - dir_h = QHBoxLayout() - dir_h.addWidget(self._tr(QLabel(), "execute_dir_label")) + sources.addRow(self._tr(QLabel(), "file_path_label"), self.script_path_input) self.script_dir_input = QLineEdit() - dir_h.addWidget(self.script_dir_input) - layout.addLayout(dir_h) + sources.addRow(self._tr(QLabel(), "execute_dir_label"), self.script_dir_input) + self.script_history_controls = ManualRunControls() + self.script_history_controls.setProperty("role", "bare") + layout.addWidget(Card().add(sources).add(self.script_history_controls)) - layout.addWidget(self._tr(QLabel(), "script_content")) self.script_editor = QTextEdit() self.script_editor.setPlaceholderText('[["AC_type_keyboard", {"keycode": "a"}]]') - layout.addWidget(self.script_editor) - - self.script_history_controls = ManualRunControls() - layout.addWidget(self.script_history_controls) - layout.addWidget(self._tr(QLabel(), "execution_result")) self.script_result_text = QTextEdit() self.script_result_text.setReadOnly(True) - layout.addWidget(self.script_result_text) + layout.addWidget(ResponsiveBox(self._titled_card("script_content", self.script_editor), + self._titled_card("execution_result", self.script_result_text)), + stretch=1) self._loads = TabTask(self) self._loads.result.connect(self._loaded_script) self._loads.error.connect(self._load_error) @@ -91,6 +87,10 @@ def __init__(self, parent: QWidget | None = None) -> None: self._script_runs.error.connect(self._show_script_error) self._script_runs.finished.connect(self._on_finished) + def _titled_card(self, title_key: str, view: QWidget) -> Card: + """A card with a translated section title over ``view``, which takes the remaining height.""" + return Card().add(set_role(self._tr(QLabel(), title_key), "sectionTitle")).add(view, stretch=1) + def _start_script_run(self, work: Callable[[], Any]) -> None: """Run ``work`` as this tab's one stoppable script run.""" if not self._script_runs.start_script(work): diff --git a/je_auto_control/gui/a11y_audit_tab.py b/je_auto_control/gui/a11y_audit_tab.py index e0807abec..9e910c39e 100644 --- a/je_auto_control/gui/a11y_audit_tab.py +++ b/je_auto_control/gui/a11y_audit_tab.py @@ -10,13 +10,14 @@ from PySide6.QtCore import Qt from PySide6.QtWidgets import ( - QAbstractItemView, QHBoxLayout, QLabel, QLineEdit, + QAbstractItemView, QFormLayout, QHBoxLayout, QLabel, QLineEdit, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -79,16 +80,20 @@ def _build_layout(self) -> None: # Audit/contrast commands run from the Actions menu; the tab keeps # only the inputs, the issue table, and the summary line. root = QVBoxLayout(self) - row = QHBoxLayout() - row.addWidget(QLabel(_t("audit_app"))) - row.addWidget(self._app, stretch=1) - root.addLayout(row) - crow = QHBoxLayout() - crow.addWidget(QLabel(_t("audit_contrast_label"))) + root.setSpacing(12) + colours = QWidget() + colours.setProperty("role", "bare") + crow = QHBoxLayout(colours) + crow.setContentsMargins(0, 0, 0, 0) crow.addWidget(self._fg) crow.addWidget(self._bg) - root.addLayout(crow) - root.addWidget(self._table, stretch=1) + form = QFormLayout() + form.addRow(self._tr(QLabel(), "audit_app"), self._app) + form.addRow(self._tr(QLabel(), "audit_contrast_label"), colours) + root.addWidget(Card().add(form)) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._summary.setWordWrap(True) + set_role(self._summary, "hint") root.addWidget(self._summary) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/accessibility_tab.py b/je_auto_control/gui/accessibility_tab.py index 5f88705e2..a3fc553bd 100644 --- a/je_auto_control/gui/accessibility_tab.py +++ b/je_auto_control/gui/accessibility_tab.py @@ -10,7 +10,7 @@ from PySide6.QtCore import Qt from PySide6.QtWidgets import ( - QAbstractItemView, QHBoxLayout, QHeaderView, QLabel, QLineEdit, + QAbstractItemView, QHeaderView, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -18,6 +18,8 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui._qt_typed import filled_item from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -113,18 +115,17 @@ def _build_layout(self) -> None: # Refresh/click commands run from the Actions menu; the tab keeps # only the filter inputs, the element table, and the status line. root = QVBoxLayout(self) - row = QHBoxLayout() - row.addWidget(self._tr(QLabel(), "a11y_app_label")) + root.setSpacing(12) self._app_filter.setPlaceholderText(_t("a11y_app_placeholder")) - row.addWidget(self._app_filter, stretch=1) - row.addWidget(self._tr(QLabel(), "a11y_window_label")) self._window_filter.setPlaceholderText(_t("a11y_window_placeholder")) - row.addWidget(self._window_filter, stretch=1) - row.addWidget(self._tr(QLabel(), "a11y_name_label")) self._name_filter.setPlaceholderText(_t("a11y_name_placeholder")) - row.addWidget(self._name_filter, stretch=1) - root.addLayout(row) - root.addWidget(self._table, stretch=1) + filters = flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("a11y_app_label", self._app_filter), ("a11y_window_label", self._window_filter), + ("a11y_name_label", self._name_filter)))) + root.addWidget(Card().add(filters)) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/adaptive/flow_layout.py b/je_auto_control/gui/adaptive/flow_layout.py index 24dff1783..e991abba6 100644 --- a/je_auto_control/gui/adaptive/flow_layout.py +++ b/je_auto_control/gui/adaptive/flow_layout.py @@ -1,5 +1,5 @@ """A layout that places items left to right and wraps them onto the next line when the row is full.""" -from typing import List, Optional +from typing import List, Optional, Tuple from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt from PySide6.QtWidgets import QHBoxLayout, QLayout, QLayoutItem, QWidget @@ -15,6 +15,8 @@ class FlowLayout(QLayout): def __init__(self, parent: Optional[QWidget] = None, spacing: int = 8) -> None: super().__init__(parent) self._items: List[QLayoutItem] = [] + #: Height the rows took at the width last laid out; the minimum height until the width changes. + self._wrapped_height = 0 self.setSpacing(spacing) self.setContentsMargins(0, 0, 0, 0) @@ -39,56 +41,115 @@ def expandingDirections(self) -> Qt.Orientation: # noqa: N802 # reason: Qt ove return Qt.Orientation(0) def hasHeightForWidth(self) -> bool: # noqa: N802 # reason: Qt override - """Its height depends on the width it is given.""" - return True + """``False`` on purpose, although the height does depend on the width. + + A page whose layout reports height-for-width is sized by + ``QScrollArea`` from every item's *preferred* height, so a page with a + flow row and a table scrolled even in a window it fitted. The wrapped + height is reported as the minimum height instead (see :meth:`setGeometry`). + """ + return False def heightForWidth(self, width: int) -> int: # noqa: N802 # reason: Qt override """Height needed to lay every item out within ``width``.""" return self._arrange(QRect(0, 0, width, 0), apply=False) def setGeometry(self, rect: QRect) -> None: # noqa: N802 # reason: Qt override - """Place the items inside ``rect``.""" + """Place the items inside ``rect``; ask for a re-layout if the rows now need another height.""" super().setGeometry(rect) - self._arrange(rect, apply=True) + height = self._arrange(rect, apply=True) + if height != self._wrapped_height: + self._wrapped_height = height + # Posts a layout request: the parent reads the new minimum height on + # the next pass, at the same width, so this settles after one round. + self.invalidate() def sizeHint(self) -> QSize: # noqa: N802 # reason: Qt override - """Everything on one line.""" + """Everything on one line, but never shorter than the rows took at the last width laid out.""" width = sum(item.sizeHint().width() for item in self._visible()) width += self.spacing() * max(0, len(self._visible()) - 1) height = max((item.sizeHint().height() for item in self._visible()), default=0) - return QSize(width, height).grownBy(self.contentsMargins()) + hint = QSize(width, height).grownBy(self.contentsMargins()) + return QSize(hint.width(), max(hint.height(), self._wrapped_height)) def minimumSize(self) -> QSize: # noqa: N802 # reason: Qt override - """The largest single item: the layout never needs more width than that.""" + """The largest single item's width, and the height the rows took at the last width laid out.""" size = QSize() for item in self._visible(): size = size.expandedTo(item.minimumSize()) - return size.grownBy(self.contentsMargins()) + size = size.grownBy(self.contentsMargins()) + return QSize(size.width(), max(size.height(), self._wrapped_height)) def _visible(self) -> List[QLayoutItem]: return [item for item in self._items if (widget := item.widget()) is None or not widget.isHidden()] - def _arrange(self, rect: QRect, *, apply: bool) -> int: - margins: QMargins = self.contentsMargins() - area = rect.marginsRemoved(margins) - x, y, line_height = area.x(), area.y(), 0 - spacing = self.spacing() + def _lines(self, area: QRect) -> List[List[Tuple[QLayoutItem, int, int]]]: + """Items grouped into lines that fit ``area``'s width, each with its width and height.""" + lines: List[List[Tuple[QLayoutItem, int, int]]] = [[]] + x, spacing = area.x(), self.spacing() for item in self._visible(): hint = item.sizeHint() width = min(hint.width(), max(item.minimumSize().width(), area.width())) - if x > area.x() and x + width > area.right() + 1: - x, y, line_height = area.x(), y + line_height + spacing, 0 - if apply: - height = item.heightForWidth(width) if item.hasHeightForWidth() else hint.height() - item.setGeometry(QRect(QPoint(x, y), QSize(width, height))) - line_height = max(line_height, item.heightForWidth(width) if item.hasHeightForWidth() else hint.height()) + if lines[-1] and x + width > area.right() + 1: + lines.append([]) + x = area.x() + height = item.heightForWidth(width) if item.hasHeightForWidth() else hint.height() + lines[-1].append((item, width, height)) x += width + spacing - return y + line_height - rect.y() + margins.bottom() + return lines + + def _share_spare_width(self, line: List[Tuple[QLayoutItem, int, int]], + available: int) -> List[Tuple[QLayoutItem, int, int]]: + """Widen the items on ``line`` that can grow sideways (line edits, fitted combos) to fill it.""" + used = sum(width for _item, width, _height in line) + self.spacing() * max(0, len(line) - 1) + growers = [index for index, (item, _w, _h) in enumerate(line) + if item.expandingDirections() & Qt.Orientation.Horizontal] + spare = available - used + widened = list(line) + # An item capped by its maximum width hands what it cannot take to the others. + while spare > 0 and growers: + spare, still_growing = _grow_once(widened, growers, spare) + if still_growing == growers: + break + growers = still_growing + return widened + + def _arrange(self, rect: QRect, *, apply: bool) -> int: + """Lay the items out in ``rect`` (when ``apply``), each centred on its line; return the height used.""" + margins: QMargins = self.contentsMargins() + area = rect.marginsRemoved(margins) + y, spacing = area.y(), self.spacing() + for line in self._lines(area): + line_height = max((height for _item, _width, height in line), default=0) + x = area.x() + for item, width, height in self._share_spare_width(line, area.width()): + if apply: + item.setGeometry(QRect(QPoint(x, y + (line_height - height) // 2), QSize(width, height))) + x += width + spacing + y += line_height + spacing + return max(0, y - spacing) - rect.y() + margins.bottom() + + +def _grow_once(line: List[Tuple[QLayoutItem, int, int]], growers: List[int], spare: int) -> Tuple[int, List[int]]: + """Share ``spare`` pixels among ``growers`` once, in place; return what is left and who can still grow.""" + share, remainder = divmod(spare, len(growers)) + still_growing = [] + for position, index in enumerate(growers): + item, width, height = line[index] + limit = item.maximumSize().width() + new_width = min(width + share + (1 if position < remainder else 0), limit) + spare -= new_width - width + if new_width > width: + line[index] = (item, new_width, item.heightForWidth(new_width) if item.hasHeightForWidth() else height) + if new_width < limit: + still_growing.append(index) + return spare, still_growing def field_pair(label: QWidget, field: QWidget, spacing: int = 6) -> QWidget: """A label and its field kept together on one line, so a flow row wraps between pairs, not inside one.""" pair = QWidget() + pair.setProperty("role", "bare") layout = QHBoxLayout(pair) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(spacing) diff --git a/je_auto_control/gui/adaptive/responsive.py b/je_auto_control/gui/adaptive/responsive.py index 1062880c0..89ea97862 100644 --- a/je_auto_control/gui/adaptive/responsive.py +++ b/je_auto_control/gui/adaptive/responsive.py @@ -1,7 +1,7 @@ """Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide.""" -from typing import Optional +from typing import Callable, Optional, Tuple -from PySide6.QtCore import QCoreApplication, QEvent, QObject +from PySide6.QtCore import QCoreApplication, QEvent, QObject, QSize from PySide6.QtGui import QResizeEvent from PySide6.QtWidgets import QBoxLayout, QComboBox, QFormLayout, QLabel, QLayout, QSizePolicy, QTabWidget, QWidget @@ -20,9 +20,10 @@ class ResponsiveBox(QWidget): """ def __init__(self, *parts: QWidget, stack_below: int = DEFAULT_STACK_BELOW, - stretches: tuple = (), spacing: int = 12, parent: Optional[QWidget] = None) -> None: + stretches: Tuple[int, ...] = (), spacing: int = 12, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self.stack_below = stack_below + self.setProperty("role", "bare") self._layout = QBoxLayout(QBoxLayout.Direction.LeftToRight, self) self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(spacing) @@ -35,7 +36,7 @@ def stacked(self) -> bool: """Whether the parts are currently one above the other.""" return self._layout.direction() == QBoxLayout.Direction.TopToBottom - def minimumSizeHint(self): # noqa: N802 # reason: Qt override + def minimumSizeHint(self) -> QSize: # noqa: N802 # reason: Qt override """Never ask for more width than the widest part needs on its own.""" hint = super().minimumSizeHint() items = (self._layout.itemAt(index) for index in range(self._layout.count())) @@ -107,7 +108,7 @@ def fit_to_width(root: QWidget) -> int: class WidthWatcher(QObject): """Call ``callback(width)`` whenever ``target`` is resized.""" - def __init__(self, target: QWidget, callback) -> None: + def __init__(self, target: QWidget, callback: Callable[[int], None]) -> None: super().__init__(target) self._callback = callback target.installEventFilter(self) diff --git a/je_auto_control/gui/adaptive/style.py b/je_auto_control/gui/adaptive/style.py index 0b550d09c..057baa312 100644 --- a/je_auto_control/gui/adaptive/style.py +++ b/je_auto_control/gui/adaptive/style.py @@ -6,7 +6,7 @@ check mark, which a style sheet can only draw from an image file. This proxy paints both in code instead, from the widget's palette, so they follow the theme. """ -from typing import Any, Optional +from typing import Any, Optional, Tuple from PySide6.QtCore import QPointF, QRectF, Qt from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen @@ -15,7 +15,7 @@ _INDICATORS = (QStyle.PrimitiveElement.PE_IndicatorCheckBox, QStyle.PrimitiveElement.PE_IndicatorRadioButton) -def _state(option: QStyleOption) -> tuple: +def _state(option: QStyleOption) -> Tuple[bool, bool, bool, bool]: flags = option.state checked = bool(flags & QStyle.StateFlag.State_On) partial = bool(flags & QStyle.StateFlag.State_NoChange) @@ -24,7 +24,7 @@ def _state(option: QStyleOption) -> tuple: return checked, partial, enabled, hovered -def _colours(option: QStyleOption, checked: bool, enabled: bool, hovered: bool) -> tuple: +def _colours(option: QStyleOption, checked: bool, enabled: bool, hovered: bool) -> Tuple[QColor, QColor, QColor]: palette = option.palette accent = palette.highlight().color() base = palette.base().color() diff --git a/je_auto_control/gui/admin_console_tab.py b/je_auto_control/gui/admin_console_tab.py index f96145716..81bd45d26 100644 --- a/je_auto_control/gui/admin_console_tab.py +++ b/je_auto_control/gui/admin_console_tab.py @@ -13,6 +13,9 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -112,10 +115,18 @@ def _build_layout(self) -> None: # Add/remove/refresh/thumbnail/broadcast commands run from the # Actions menu; the tab keeps only the inputs, tables, and output. root = QVBoxLayout(self) + root.setSpacing(12) root.addWidget(self._build_add_group()) - root.addWidget(self._table, stretch=1) - root.addWidget(self._build_thumbnails_group(), stretch=1) - root.addWidget(self._build_broadcast_group(), stretch=1) + # Hosts and their thumbnails in one column, the broadcast beside them: + # side by side the page stays one screen tall; stacked it keeps the old order. + hosts = QWidget() + hosts.setProperty("role", "bare") + column = QVBoxLayout(hosts) + column.setContentsMargins(0, 0, 0, 0) + column.setSpacing(12) + column.addWidget(Card().add(self._table, stretch=1), stretch=1) + column.addWidget(self._build_thumbnails_group(), stretch=1) + root.addWidget(ResponsiveBox(hosts, self._build_broadcast_group(), stretches=(3, 2)), stretch=1) def dispose(self) -> None: """Release what the tab holds beyond its widgets: its thumbnail timer and the polls still out. @@ -147,13 +158,10 @@ def _build_thumbnails_group(self) -> QGroupBox: def _build_add_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "admin_add_group") - form = QHBoxLayout(group) - form.addWidget(self._tr(QLabel(), "admin_label")) - form.addWidget(self._label_input) - form.addWidget(self._tr(QLabel(), "admin_url")) - form.addWidget(self._url_input, stretch=1) - form.addWidget(self._tr(QLabel(), "admin_token")) - form.addWidget(self._token_input) + layout = QVBoxLayout(group) + layout.addLayout(flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("admin_label", self._label_input), ("admin_url", self._url_input), + ("admin_token", self._token_input))))) return group def _build_broadcast_group(self) -> QGroupBox: diff --git a/je_auto_control/gui/agent_observation_view.py b/je_auto_control/gui/agent_observation_view.py index 494e088d0..e49cf7711 100644 --- a/je_auto_control/gui/agent_observation_view.py +++ b/je_auto_control/gui/agent_observation_view.py @@ -9,6 +9,7 @@ from PySide6.QtWidgets import (QAbstractItemView, QLabel, QScrollArea, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget) +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.images import observation_image_bytes @@ -45,7 +46,10 @@ def __init__(self, parent: QWidget | None = None) -> None: self._image = _Image() self._image.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) self._image.picked.connect(self.picked.emit) + self.setProperty("role", "bare") self._notice = QLabel() + self._notice.setWordWrap(True) + set_role(self._notice, "danger") scroll = QScrollArea() scroll.setWidgetResizable(False) scroll.setWidget(self._image) diff --git a/je_auto_control/gui/agent_tasks_tab.py b/je_auto_control/gui/agent_tasks_tab.py index 00be069e2..0b14e28ff 100644 --- a/je_auto_control/gui/agent_tasks_tab.py +++ b/je_auto_control/gui/agent_tasks_tab.py @@ -12,6 +12,8 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.task_controller import TaskController, TaskOutcome from je_auto_control.gui.agent_transfer_view import AgentTransferView @@ -77,13 +79,19 @@ def __init__(self, parent: QWidget | None = None) -> None: self._table.cellClicked.connect(self._select) self._status = QLabel() self._task_id.textChanged.connect(self._clear_observation) + self._build_layout() + self.retranslate() + + def _build_layout(self) -> None: layout = QVBoxLayout(self) - layout.addWidget(self._task_id) - layout.addWidget(self._pages) + layout.setSpacing(12) + layout.addWidget(Card().add(self._task_id)) + layout.addWidget(self._pages, stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") layout.addWidget(self._status) - layout.addWidget(self._table) - layout.addWidget(self._output) - self.retranslate() + results = ResponsiveBox(Card().add(self._table, stretch=1), Card().add(self._output, stretch=1)) + layout.addWidget(results, stretch=1) def _setup_fields(self) -> None: self._goal, self._target, self._task_id = QLineEdit(), QLineEdit("local-desktop"), QLineEdit() @@ -161,6 +169,7 @@ def _setup_pages(self) -> None: def _page(self, key: str, fields: tuple) -> None: page = QWidget() + page.setProperty("role", "bare") form = QFormLayout() for label_key, control in fields: label = QLabel() diff --git a/je_auto_control/gui/agent_transfer_view.py b/je_auto_control/gui/agent_transfer_view.py index dd1b0d129..a26169ae8 100644 --- a/je_auto_control/gui/agent_transfer_view.py +++ b/je_auto_control/gui/agent_transfer_view.py @@ -8,6 +8,7 @@ from PySide6 import QtWidgets +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.task_controller import TaskController, TaskOutcome from je_auto_control.utils.agent_runtime.api import manage_agent_transfer @@ -55,7 +56,11 @@ def __init__(self, parent: QtWidgets.QWidget | None = None) -> None: self._result.setReadOnly(True) self._notice = QtWidgets.QLabel() self._notice.setWordWrap(True) + set_role(self._notice, 'hint') self._status = QtWidgets.QLabel() + self._status.setWordWrap(True) + set_role(self._status, 'hint') + self.setProperty('role', 'bare') form = QtWidgets.QFormLayout() for key, control in (('operation', self._operation), ('request', self._request), ('result', self._result)): label = QtWidgets.QLabel() diff --git a/je_auto_control/gui/assertions_tab.py b/je_auto_control/gui/assertions_tab.py index f066d83ad..d3f4c29ff 100644 --- a/je_auto_control/gui/assertions_tab.py +++ b/je_auto_control/gui/assertions_tab.py @@ -8,13 +8,15 @@ from typing import Any, Dict, List, Optional from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QHBoxLayout, QLabel, QLineEdit, + QCheckBox, QComboBox, QFormLayout, QLabel, QLineEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.flow_layout import flow_of +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -60,26 +62,22 @@ def _build_layout(self) -> None: # The run command runs from the Actions menu; the tab keeps only # the assertion form and the result label. root = QVBoxLayout(self) - krow = QHBoxLayout() - krow.addWidget(QLabel(_t("assert_kind"))) - krow.addWidget(self._kind) - krow.addStretch() - root.addLayout(krow) - - self._target_label = QLabel(_t("assert_target")) - root.addWidget(self._target_label) - root.addWidget(self._target) - - self._xy_label = QLabel(_t("assert_pixel_xy")) - root.addWidget(self._xy_label) - root.addWidget(self._xy) - self._rgb_label = QLabel(_t("assert_pixel_rgb")) - root.addWidget(self._rgb_label) - root.addWidget(self._rgb) - - root.addWidget(self._expect) - root.addWidget(self._regex) - root.addWidget(self._result) + root.setSpacing(12) + kind_row = QFormLayout() + kind_row.addRow(self._tr(QLabel(), "assert_kind"), self._kind) + form = Card().add(kind_row) + # Each label sits above its field; the kind decides which pairs show. + self._target_label = self._tr(QLabel(), "assert_target") + self._xy_label = self._tr(QLabel(), "assert_pixel_xy") + self._rgb_label = self._tr(QLabel(), "assert_pixel_rgb") + for widget in (self._target_label, self._target, self._xy_label, self._xy, + self._rgb_label, self._rgb): + form.add(widget) + self._tr(self._expect, "assert_expect_present") + self._tr(self._regex, "assert_regex") + form.add(flow_of(self._expect, self._regex)) + root.addWidget(form) + root.addWidget(Card().add(self._result)) root.addStretch() def dispose(self) -> None: diff --git a/je_auto_control/gui/audit_log_tab.py b/je_auto_control/gui/audit_log_tab.py index f5a6776b2..897d3ff32 100644 --- a/je_auto_control/gui/audit_log_tab.py +++ b/je_auto_control/gui/audit_log_tab.py @@ -3,12 +3,14 @@ from typing import List, Optional, Sequence from PySide6.QtWidgets import ( - QComboBox, QGroupBox, QHBoxLayout, QHeaderView, QLabel, QLineEdit, + QComboBox, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -75,8 +77,11 @@ def _build_layout(self) -> None: # Refresh/verify/clear commands run from the Actions menu; the # tab keeps only the filter inputs, the table, and the status. root = QVBoxLayout(self) + root.setSpacing(12) root.addWidget(self._build_filter_group()) - root.addWidget(self._table, stretch=1) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._verify_status.setWordWrap(True) + set_role(self._verify_status, "hint") root.addWidget(self._verify_status) def menu_actions(self) -> list: @@ -89,13 +94,10 @@ def menu_actions(self) -> list: def _build_filter_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "audit_filter_group") - row = QHBoxLayout(group) - row.addWidget(self._tr(QLabel(), "audit_filter_type")) - row.addWidget(self._type_filter) - row.addWidget(self._tr(QLabel(), "audit_filter_host")) - row.addWidget(self._host_filter) - row.addWidget(self._tr(QLabel(), "audit_filter_limit")) - row.addWidget(self._limit_input) + layout = QVBoxLayout(group) + layout.addLayout(flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("audit_filter_type", self._type_filter), ("audit_filter_host", self._host_filter), + ("audit_filter_limit", self._limit_input))))) return group def _refresh(self) -> None: diff --git a/je_auto_control/gui/chatops_tab.py b/je_auto_control/gui/chatops_tab.py index 2a8b15dd4..688cb6b3e 100644 --- a/je_auto_control/gui/chatops_tab.py +++ b/je_auto_control/gui/chatops_tab.py @@ -7,13 +7,14 @@ from typing import Any, Optional from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QLabel, QLineEdit, QTextEdit, + QFileDialog, QFormLayout, QLabel, QLineEdit, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask, was_stopped +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -58,21 +59,16 @@ def _build_layout(self) -> None: # Browse/send commands run from the Actions menu; the tab keeps # only the root/command inputs and the output log. root = QVBoxLayout(self) - root_row = QHBoxLayout() + root.setSpacing(12) self._root_label = QLabel() - root_row.addWidget(self._root_label) - root_row.addWidget(self._script_root, stretch=1) - root.addLayout(root_row) - - cmd_row = QHBoxLayout() self._cmd_label = QLabel() - cmd_row.addWidget(self._cmd_label) - cmd_row.addWidget(self._command_input, stretch=1) - root.addLayout(cmd_row) + form = QFormLayout() + form.addRow(self._root_label, self._script_root) + form.addRow(self._cmd_label, self._command_input) + root.addWidget(Card().add(form)) self._output_label = QLabel() - root.addWidget(self._output_label) - root.addWidget(self._output, stretch=1) + root.addWidget(Card().add(self._output_label).add(self._output, stretch=1), stretch=1) self._apply_translations() def dispose(self) -> None: diff --git a/je_auto_control/gui/computer_use_tab.py b/je_auto_control/gui/computer_use_tab.py index 4bb49f923..5ffae3454 100644 --- a/je_auto_control/gui/computer_use_tab.py +++ b/je_auto_control/gui/computer_use_tab.py @@ -12,6 +12,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -83,6 +84,7 @@ def _build_layout(self) -> None: # The run command runs from the Actions menu; the tab keeps only # the goal/model/limit inputs, the output view, and the status. root = QVBoxLayout(self) + root.setSpacing(12) form = QFormLayout() self._goal_label = QLabel() self._model_label = QLabel() @@ -94,11 +96,15 @@ def _build_layout(self) -> None: form.addRow(self._max_steps_label, self._max_steps) form.addRow(self._wall_seconds_label, self._wall_seconds) form.addRow(self._max_tokens_label, self._max_tokens) - root.addLayout(form) - root.addWidget(self._status) + root.addWidget(Card().add(form)) self._output_label = QLabel() - root.addWidget(self._output_label) - root.addWidget(self._output, stretch=1) + output = Card() + output.add(self._output_label) + output.add(self._output, stretch=1) + root.addWidget(output, stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") + root.addWidget(self._status) self._apply_translations() def _apply_translations(self) -> None: diff --git a/je_auto_control/gui/config_sync_tab.py b/je_auto_control/gui/config_sync_tab.py index 3ee8b8b66..57b38d095 100644 --- a/je_auto_control/gui/config_sync_tab.py +++ b/je_auto_control/gui/config_sync_tab.py @@ -12,6 +12,8 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui._worker_thread import WorkerHandle, start_worker from je_auto_control.gui.config_sync_worker import ConfigSyncWorker, SyncUIOutcome, SyncUIRequest from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper @@ -70,11 +72,15 @@ def _label(self, key: str) -> QLabel: def _build_form(self) -> QVBoxLayout: layout = QVBoxLayout(self) + layout.setSpacing(12) note = self._label('notice') note.setWordWrap(True) + set_role(note, 'hint') layout.addWidget(note) self._form = QWidget(self) + self._form.setProperty('role', 'bare') form = QFormLayout(self._form) + form.setContentsMargins(0, 0, 0, 0) self._configuration = QPlainTextEdit(self) self._configuration.setMaximumHeight(160) self._tr(self._configuration, 'config_sync_configuration_hint', 'setPlaceholderText') @@ -95,12 +101,13 @@ def _build_form(self) -> QVBoxLayout: self._kind = QComboBox(self) self._kind.addItems(sorted(KINDS)) form.addRow(self._label('kind'), self._kind) - layout.addWidget(self._form) return layout def _build_profile_inputs(self, layout: QVBoxLayout) -> None: self._load_form = QWidget(self) + self._load_form.setProperty('role', 'bare') form = QFormLayout(self._load_form) + form.setContentsMargins(0, 0, 0, 0) self._generation_directory = QLineEdit(self) form.addRow(self._label('generation_directory'), self._generation_directory) self._manifest_digest = QLineEdit(self) @@ -109,37 +116,40 @@ def _build_profile_inputs(self, layout: QVBoxLayout) -> None: form.addRow(self._label('working_root'), self._working_root) self._loaded_scripts = QComboBox(self) form.addRow(self._label('loaded_script'), self._loaded_scripts) - layout.addWidget(self._load_form) notice = self._label('profile_notice') notice.setWordWrap(True) - layout.addWidget(notice) + set_role(notice, 'hint') + profile = Card().add(self._load_form).add(notice) + profile.body.addStretch(1) + layout.addWidget(ResponsiveBox(Card().add(self._form), profile)) def _build_review(self, layout: QVBoxLayout) -> None: self._summary = QLabel(self) self._summary.setTextFormat(Qt.TextFormat.PlainText) self._summary.setWordWrap(True) - layout.addWidget(self._summary) + set_role(self._summary, 'hint') + review = Card().add(self._summary) self._heads = QTableWidget(0, 6, self) self._heads.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) self._heads.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) self._heads.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) self._heads.setMinimumHeight(140) - layout.addWidget(self._heads) + review.add(self._heads, stretch=1) self._value = QPlainTextEdit(self) self._value.setMaximumHeight(130) - layout.addWidget(self._label('resolution_value')) - layout.addWidget(self._value) + review.add(self._label('resolution_value')).add(self._value) self._deleted = QCheckBox(self) self._tr(self._deleted, 'config_sync_deleted') - layout.addWidget(self._deleted) + review.add(self._deleted) + layout.addWidget(review, stretch=1) self._status = QLabel(self) self._status.setTextFormat(Qt.TextFormat.PlainText) self._status.setWordWrap(True) - layout.addWidget(self._status) + set_role(self._status, 'hint') self._details = QPlainTextEdit(self) self._details.setReadOnly(True) self._details.setMaximumHeight(150) - layout.addWidget(self._details) + layout.addWidget(Card().add(self._status).add(self._details)) def menu_actions(self) -> tuple[tuple[str, Callable[[], None]], ...]: """Expose explicit operations through the window's Actions menu.""" diff --git a/je_auto_control/gui/dag_tab.py b/je_auto_control/gui/dag_tab.py index 7b514cce5..86f0ad093 100644 --- a/je_auto_control/gui/dag_tab.py +++ b/je_auto_control/gui/dag_tab.py @@ -7,7 +7,7 @@ from PySide6.QtCore import QObject, Qt, Signal from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QLabel, QSpinBox, + QFileDialog, QLabel, QSpinBox, QPlainTextEdit, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout, QWidget, ) # pylint: disable-next=no-name-in-module # reason: compiled Qt export is exercised by offscreen batch-ID tests @@ -16,6 +16,9 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -142,23 +145,22 @@ def _build_layout(self) -> None: # Load/validate/run commands run from the Actions menu; the tab # keeps only the editor, the parallel input, table, and status. root = QVBoxLayout(self) - controls = QHBoxLayout() - controls.addWidget(QLabel(_t("dag_parallel_label"))) - controls.addWidget(self._max_parallel) + root.setSpacing(12) batch_label, batch_id = QLabel(), QLineEdit() batch_label.setObjectName("dag_batch_label") batch_id.setObjectName("dag_batch_id") - controls.addWidget(batch_label) - controls.addWidget(batch_id) - controls.addStretch() - root.addLayout(controls) - root.addWidget(self._editor, stretch=2) + root.addWidget(Card().add(flow_of( + field_pair(self._tr(QLabel(), "dag_parallel_label"), self._max_parallel), + field_pair(batch_label, batch_id)))) + editor = Card().add(self._editor, stretch=1) + nodes = Card().add(self._table, stretch=1) + root.addWidget(ResponsiveBox(editor, nodes, stretches=(2, 3)), stretch=1) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") root.addWidget(self._status_label) - root.addWidget(self._table, stretch=3) - root.addWidget(self._inspection_output) continuation = QPlainTextEdit("{}") continuation.setObjectName("dag_continuation_request") - root.addWidget(continuation) + root.addWidget(ResponsiveBox(Card().add(self._inspection_output), Card().add(continuation))) self._apply_translations() def dispose(self) -> None: diff --git a/je_auto_control/gui/data_source_tab.py b/je_auto_control/gui/data_source_tab.py index 1a18ba020..8b3fb9f57 100644 --- a/je_auto_control/gui/data_source_tab.py +++ b/je_auto_control/gui/data_source_tab.py @@ -13,6 +13,8 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -49,36 +51,30 @@ def _build_layout(self) -> None: # The load command runs from the Actions menu; the tab keeps the # source form (with its kind-synced browse button) and the table. root = QVBoxLayout(self) - row1 = QHBoxLayout() - row1.addWidget(QLabel(_t("ds_kind"))) - row1.addWidget(self._kind) - row1.addStretch() - root.addLayout(row1) + root.setSpacing(12) + source = Card().add(flow_of(field_pair(self._tr(QLabel(), "ds_kind"), self._kind), + field_pair(self._tr(QLabel(), "ds_limit"), self._limit))) + # The rows of the other kinds hide; they go in as layouts, not + # containers, so a hidden row leaves no gap behind. self._path_row = QHBoxLayout() - self._path_label = QLabel(_t("ds_path")) + self._path_label = self._tr(QLabel(), "ds_path") self._path_row.addWidget(self._path_label) self._path_row.addWidget(self._path, stretch=1) self._browse_btn = self._tr(QPushButton(), "ds_browse") self._browse_btn.clicked.connect(self._on_browse) self._path_row.addWidget(self._browse_btn) - root.addLayout(self._path_row) + source.add(self._path_row) - self._query_label = QLabel(_t("ds_query")) - root.addWidget(self._query_label) - root.addWidget(self._query) + self._query_label = self._tr(QLabel(), "ds_query") + self._inline_label = self._tr(QLabel(), "ds_inline") + for widget in (self._query_label, self._query, self._inline_label, self._inline): + source.add(widget) + root.addWidget(source) - self._inline_label = QLabel(_t("ds_inline")) - root.addWidget(self._inline_label) - root.addWidget(self._inline) - - row2 = QHBoxLayout() - row2.addWidget(QLabel(_t("ds_limit"))) - row2.addWidget(self._limit) - row2.addStretch() - root.addLayout(row2) - - root.addWidget(self._table, stretch=1) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/device_matrix_tab.py b/je_auto_control/gui/device_matrix_tab.py index 7994612e4..9e8229978 100644 --- a/je_auto_control/gui/device_matrix_tab.py +++ b/je_auto_control/gui/device_matrix_tab.py @@ -10,12 +10,15 @@ from PySide6.QtCore import Qt from PySide6.QtWidgets import ( - QAbstractItemView, QHBoxLayout, QLabel, QPlainTextEdit, + QAbstractItemView, QLabel, QPlainTextEdit, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.tab_task_controller import TaskHandle, task_controller from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -68,17 +71,14 @@ def _build_layout(self) -> None: # The run command runs from the Actions menu; the tab keeps only # the device/action editors, the result table, and the summary. root = QVBoxLayout(self) - root.addWidget(QLabel(_t("dm_devices"))) - root.addWidget(self._devices) - root.addWidget(QLabel(_t("dm_actions"))) - root.addWidget(self._actions) - row = QHBoxLayout() - row.addWidget(QLabel(_t("dm_parallel"))) - row.addWidget(self._parallel) - row.addStretch() - root.addLayout(row) - root.addWidget(self._table, stretch=1) - root.addWidget(self._summary) + root.setSpacing(12) + devices = Card("dm_devices").add(self._devices, stretch=1) + actions = Card("dm_actions").add(self._actions, stretch=1) + root.addWidget(ResponsiveBox(devices, actions, stretches=(1, 1))) + self._summary.setWordWrap(True) + set_role(self._summary, "hint") + results = Card().add(flow_of(field_pair(self._tr(QLabel(), "dm_parallel"), self._parallel))) + root.addWidget(results.add(self._table, stretch=1).add(self._summary), stretch=1) def dispose(self) -> None: """Release what the tab holds beyond its widgets: the command still running in the background. diff --git a/je_auto_control/gui/diagnostics_tab.py b/je_auto_control/gui/diagnostics_tab.py index 9c2a89476..829c5a7d7 100644 --- a/je_auto_control/gui/diagnostics_tab.py +++ b/je_auto_control/gui/diagnostics_tab.py @@ -11,6 +11,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.diagnostics_capabilities import CapabilityView from je_auto_control.gui.mcp_discovery_view import MCPDiscoveryView from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsSource, ExecutionPhase @@ -85,11 +86,12 @@ def _build_layout(self) -> None: # The run command runs from the Actions menu; the tab keeps only # the summary label and the results table. root = QVBoxLayout(self) + root.setSpacing(12) root.addWidget(self._capability_view) - root.addWidget(self._summary_label) - root.addWidget(self._progress_label) - root.addWidget(self._table, stretch=1) - root.addWidget(self._mcp_discovery) + set_role(self._progress_label, "hint") + results = Card().add(self._summary_label).add(self._progress_label).add(self._table, stretch=1) + root.addWidget(results, stretch=1) + root.addWidget(Card().add(self._mcp_discovery)) def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" diff --git a/je_auto_control/gui/email_triggers_tab.py b/je_auto_control/gui/email_triggers_tab.py index b478cde19..4b011cb0f 100644 --- a/je_auto_control/gui/email_triggers_tab.py +++ b/je_auto_control/gui/email_triggers_tab.py @@ -3,7 +3,7 @@ from PySide6.QtCore import QTimer, Qt from PySide6.QtWidgets import ( - QAbstractItemView, QCheckBox, QFileDialog, QGroupBox, QHBoxLayout, + QAbstractItemView, QCheckBox, QFileDialog, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -11,6 +11,8 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -96,47 +98,38 @@ def _build_layout(self) -> None: # Actions menu; the tab keeps only the inputs, the table, and the # status line. root = QVBoxLayout(self) + root.setSpacing(12) engine_box = self._tr(QGroupBox(), "eml_engine_group") - engine_layout = QHBoxLayout(engine_box) + engine_layout = QVBoxLayout(engine_box) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") engine_layout.addWidget(self._status_label) - engine_layout.addStretch() root.addWidget(engine_box) add_box = self._tr(QGroupBox(), "eml_add_group") add_layout = QVBoxLayout(add_box) - host_row = QHBoxLayout() - host_row.addWidget(self._tr(QLabel(), "eml_host_label")) - host_row.addWidget(self._host_input) - host_row.addWidget(self._tr(QLabel(), "eml_port_label")) - host_row.addWidget(self._port_input) - host_row.addWidget(self._ssl_check) - add_layout.addLayout(host_row) - creds_row = QHBoxLayout() - creds_row.addWidget(self._tr(QLabel(), "eml_user_label")) - creds_row.addWidget(self._user_input) - creds_row.addWidget(self._tr(QLabel(), "eml_password_label")) - creds_row.addWidget(self._password_input) - add_layout.addLayout(creds_row) - mb_row = QHBoxLayout() - mb_row.addWidget(self._tr(QLabel(), "eml_mailbox_label")) - mb_row.addWidget(self._mailbox_input) - mb_row.addWidget(self._tr(QLabel(), "eml_search_label")) - mb_row.addWidget(self._search_input) - add_layout.addLayout(mb_row) - poll_row = QHBoxLayout() - poll_row.addWidget(self._tr(QLabel(), "eml_poll_label")) - poll_row.addWidget(self._poll_input) - poll_row.addWidget(self._mark_seen_check) - poll_row.addStretch() - add_layout.addLayout(poll_row) - script_row = QHBoxLayout() - script_row.addWidget(self._tr(QLabel(), "eml_script_label")) - script_row.addWidget(self._script_input) - add_layout.addLayout(script_row) + rows = ( + (self._pair("eml_host_label", self._host_input, 280), + self._pair("eml_port_label", self._port_input), self._ssl_check), + (self._pair("eml_user_label", self._user_input, 280), + self._pair("eml_password_label", self._password_input, 280)), + (self._pair("eml_mailbox_label", self._mailbox_input), + self._pair("eml_search_label", self._search_input)), + (self._pair("eml_poll_label", self._poll_input), self._mark_seen_check), + ) + for row in rows: + add_layout.addLayout(flow_of(*row)) + add_layout.addWidget(self._pair("eml_script_label", self._script_input)) root.addWidget(add_box) - root.addWidget(self._table, stretch=1) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + + def _pair(self, label_key: str, field: QWidget, min_width: int = 0) -> QWidget: + """``field`` with its translated label kept beside it, at least ``min_width`` pixels wide.""" + pair = field_pair(self._tr(QLabel(), label_key), field) + pair.setMinimumWidth(min_width) + return pair def menu_actions(self) -> list: """Expose tab commands to the window-level Actions menu.""" diff --git a/je_auto_control/gui/flakiness_tab.py b/je_auto_control/gui/flakiness_tab.py index 9acc7e9bb..e64a2d2a4 100644 --- a/je_auto_control/gui/flakiness_tab.py +++ b/je_auto_control/gui/flakiness_tab.py @@ -7,11 +7,13 @@ from PySide6.QtCore import Qt from PySide6.QtWidgets import ( - QAbstractItemView, QComboBox, QHBoxLayout, QHeaderView, QLabel, + QAbstractItemView, QComboBox, QHeaderView, QLabel, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -67,16 +69,13 @@ def _build_layout(self) -> None: # The refresh command runs from the Actions menu; the tab keeps # only the filter inputs, the table, and the status line. root = QVBoxLayout(self) - controls = QHBoxLayout() - controls.addWidget(QLabel(_t("flaky_limit"))) - controls.addWidget(self._limit) - controls.addWidget(QLabel(_t("flaky_min_runs"))) - controls.addWidget(self._min_runs) - controls.addWidget(QLabel(_t("flaky_group_by"))) - controls.addWidget(self._group_by) - controls.addStretch() - root.addLayout(controls) - root.addWidget(self._table, stretch=1) + root.setSpacing(12) + filters = flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("flaky_limit", self._limit), ("flaky_min_runs", self._min_runs), ("flaky_group_by", self._group_by)))) + root.addWidget(Card().add(filters)) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/flow_editor/tab.py b/je_auto_control/gui/flow_editor/tab.py index 2e18d819b..4bff346a4 100644 --- a/je_auto_control/gui/flow_editor/tab.py +++ b/je_auto_control/gui/flow_editor/tab.py @@ -15,6 +15,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.flow_editor.scene import FlowGraphScene from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -56,12 +57,17 @@ def _build_layout(self) -> None: # Open/save/zoom/fit commands run from the Actions menu; the tab # keeps only the graph view, the inspector, and the status line. root = QVBoxLayout(self) + root.setSpacing(12) splitter = QSplitter(Qt.Orientation.Horizontal) splitter.addWidget(self._view) splitter.addWidget(self._inspector) splitter.setStretchFactor(0, 3) splitter.setStretchFactor(1, 1) - root.addWidget(splitter, stretch=1) + # Start at the same 3:1 split; from the size hints the empty graph got a sliver. + splitter.setSizes([600, 200]) + root.addWidget(Card().add(splitter, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) self._apply_translations() diff --git a/je_auto_control/gui/healing_evaluation_panel.py b/je_auto_control/gui/healing_evaluation_panel.py index 876ac70ac..5fe1f3143 100644 --- a/je_auto_control/gui/healing_evaluation_panel.py +++ b/je_auto_control/gui/healing_evaluation_panel.py @@ -14,6 +14,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.healing_evaluation_worker import HealingEvaluationOutcome, HealingEvaluationWorker from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.exception.exceptions import AutoControlException @@ -86,18 +87,25 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._status.setTextFormat(Qt.TextFormat.PlainText) self._status.setWordWrap(True) self._state, self._error = "idle", "" + self.setProperty("role", "bare") root = QVBoxLayout(self) + root.setSpacing(12) form = QFormLayout() form.addRow(self._tr(QLabel(), "healing_eval_path"), self._path) - root.addLayout(form) - root.addWidget(self._tr(QLabel(), "healing_eval_explanation")) + explanation = self._tr(QLabel(), "healing_eval_explanation") + explanation.setWordWrap(True) + set_role(explanation, "hint") + root.addWidget(Card().add(form).add(explanation)) views = QSplitter(Qt.Orientation.Vertical) views.addWidget(self._summary) cases = QSplitter(Qt.Orientation.Horizontal) - cases.addWidget(self._cases) - cases.addWidget(self._details) + # A user-resizable split: each side may shrink well below its content. + for pane in (self._cases, self._details): + pane.setMinimumWidth(120) + cases.addWidget(pane) views.addWidget(cases) - root.addWidget(views, stretch=1) + root.addWidget(Card().add(views, stretch=1), stretch=1) + set_role(self._status, "hint") root.addWidget(self._status) # pylint: disable-next=no-member # reason: PySide binds the Qt signal at runtime self._path.textChanged.connect(self._path_changed) diff --git a/je_auto_control/gui/hotkeys_tab.py b/je_auto_control/gui/hotkeys_tab.py index 45a77328a..fd27a32ae 100644 --- a/je_auto_control/gui/hotkeys_tab.py +++ b/je_auto_control/gui/hotkeys_tab.py @@ -3,7 +3,7 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QLabel, QLineEdit, QMessageBox, + QFileDialog, QFormLayout, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -11,6 +11,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui._qt_typed import filled_item +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -44,14 +45,14 @@ def _build_layout(self) -> None: # Bind/remove/start/stop commands run from the Actions menu; the # tab keeps only the inputs, the bindings table, and the status. root = QVBoxLayout(self) - form = QHBoxLayout() - form.addWidget(self._tr(QLabel(), "hk_combo_label")) - form.addWidget(self._combo_input) - form.addWidget(self._tr(QLabel(), "hk_script_label")) - form.addWidget(self._script_input, stretch=1) - root.addLayout(form) - - root.addWidget(self._table, stretch=1) + root.setSpacing(12) + form = QFormLayout() + form.addRow(self._tr(QLabel(), "hk_combo_label"), self._combo_input) + form.addRow(self._tr(QLabel(), "hk_script_label"), self._script_input) + root.addWidget(Card().add(form)) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/inspector_tab.py b/je_auto_control/gui/inspector_tab.py index 2a50bb548..c60c93c07 100644 --- a/je_auto_control/gui/inspector_tab.py +++ b/je_auto_control/gui/inspector_tab.py @@ -9,6 +9,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -50,11 +51,14 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: def _build_layout(self) -> None: # Refresh/reset commands run from the Actions menu; the tab keeps - # only the summary, the metrics group, and the samples table. + # only the metrics group, the samples table, and the summary line. root = QVBoxLayout(self) - root.addWidget(self._summary_label) + root.setSpacing(12) root.addWidget(self._build_metrics_group()) - root.addWidget(self._table, stretch=1) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._summary_label.setWordWrap(True) + set_role(self._summary_label, "hint") + root.addWidget(self._summary_label) def dispose(self) -> None: """Release what the tab holds beyond its widgets: its sampling timer. @@ -76,6 +80,7 @@ def _build_metrics_group(self) -> QGroupBox: for key in _METRIC_KEYS: label_widget = self._tr(QLabel(), f"inspector_metric_{key}") value_widget = QLabel("-") + value_widget.setWordWrap(True) self._metric_labels[key] = value_widget form.addRow(label_widget, value_widget) return group diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index c1f523b7f..ecb8a75b6 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -537,7 +537,7 @@ "rd_webrtc_host_id_placeholder": "8-char ID shown on the host", "rd_webrtc_secret_label": "Server secret:", "rd_webrtc_regen_id": "New ID", - "rd_webrtc_publish_via_server": "Publish & wait for viewer", + "rd_webrtc_publish_via_server": "Publish and wait for viewer", "rd_webrtc_connect_via_server": "Connect to host", "rd_webrtc_stun_label": "STUN URL:", "rd_webrtc_turn_label": "TURN URL:", diff --git a/je_auto_control/gui/live_hud_tab.py b/je_auto_control/gui/live_hud_tab.py index 849c0fd96..f33faea67 100644 --- a/je_auto_control/gui/live_hud_tab.py +++ b/je_auto_control/gui/live_hud_tab.py @@ -11,6 +11,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -72,6 +73,7 @@ def _build_layout(self) -> None: # Start/stop/clear commands run from the Actions menu; the tab # keeps only the watcher labels and the log view. root = QVBoxLayout(self) + root.setSpacing(12) status_group = self._tr(QGroupBox(), "hud_watchers_group") status_layout = QVBoxLayout() status_layout.addWidget(self._pos_label) @@ -79,8 +81,10 @@ def _build_layout(self) -> None: status_group.setLayout(status_layout) root.addWidget(status_group) - root.addWidget(self._tr(QLabel(), "hud_recent_log")) - root.addWidget(self._log_view, stretch=1) + log_card = Card() + log_card.add(self._tr(QLabel(), "hud_recent_log")) + log_card.add(self._log_view, stretch=1) + root.addWidget(log_card, stretch=1) def menu_actions(self) -> list: """Expose tab commands to the window-level Actions menu.""" diff --git a/je_auto_control/gui/llm_planner_tab.py b/je_auto_control/gui/llm_planner_tab.py index 0485f7eaa..e75304aa1 100644 --- a/je_auto_control/gui/llm_planner_tab.py +++ b/je_auto_control/gui/llm_planner_tab.py @@ -12,7 +12,7 @@ from PySide6.QtCore import QObject, Signal from PySide6.QtWidgets import ( - QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMessageBox, + QFormLayout, QGroupBox, QLabel, QLineEdit, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) @@ -20,6 +20,8 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask, was_stopped from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -98,13 +100,13 @@ def _build_layout(self) -> None: # Plan/run commands run from the Actions menu; the tab keeps only # the description/model inputs, the plan/result views, and status. root = QVBoxLayout(self) + root.setSpacing(12) desc_group = self._tr(QGroupBox(), "llm_desc_group") desc_layout = QVBoxLayout() desc_layout.addWidget(self._description) - model_row = QHBoxLayout() - model_row.addWidget(self._tr(QLabel(), "llm_model_label")) - model_row.addWidget(self._model, stretch=1) + model_row = QFormLayout() + model_row.addRow(self._tr(QLabel(), "llm_model_label"), self._model) desc_layout.addLayout(model_row) desc_group.setLayout(desc_layout) root.addWidget(desc_group) @@ -113,14 +115,15 @@ def _build_layout(self) -> None: actions_layout = QVBoxLayout() actions_layout.addWidget(self._actions_view) actions_group.setLayout(actions_layout) - root.addWidget(actions_group, stretch=1) result_group = self._tr(QGroupBox(), "llm_result_group") result_layout = QVBoxLayout() result_layout.addWidget(self._result_view) result_group.setLayout(result_layout) - root.addWidget(result_group, stretch=1) + root.addWidget(ResponsiveBox(actions_group, result_group), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def dispose(self) -> None: diff --git a/je_auto_control/gui/mcp_discovery_view.py b/je_auto_control/gui/mcp_discovery_view.py index e5242b0d4..95755e6f2 100644 --- a/je_auto_control/gui/mcp_discovery_view.py +++ b/je_auto_control/gui/mcp_discovery_view.py @@ -8,6 +8,7 @@ QCheckBox, QComboBox, QFormLayout, QLineEdit, QPlainTextEdit, QSpinBox, QVBoxLayout, QWidget, ) +from je_auto_control.gui.adaptive.flow_layout import flow_of from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.mcp_server.discovery import search_mcp_tools, get_mcp_tool_schema @@ -29,15 +30,15 @@ def __init__(self, parent: QWidget | None = None) -> None: self.output = QPlainTextEdit() self.output.setReadOnly(True) self.output.setMaximumBlockCount(2000) + self.setProperty("role", "bare") form = QFormLayout() form.addRow(self.query) form.addRow(self.name) - form.addRow(self.read_only) - form.addRow(self.mode) form.addRow(self.profile) - form.addRow(self.page_size) layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) layout.addLayout(form) + layout.addLayout(flow_of(self.read_only, self.mode, self.page_size)) layout.addWidget(self.output) self.retranslate() diff --git a/je_auto_control/gui/media_checks_tab.py b/je_auto_control/gui/media_checks_tab.py index cc2f04bc1..f87e49606 100644 --- a/je_auto_control/gui/media_checks_tab.py +++ b/je_auto_control/gui/media_checks_tab.py @@ -9,13 +9,15 @@ from typing import Any, Optional from PySide6.QtWidgets import ( - QCheckBox, QDoubleSpinBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, + QCheckBox, QDoubleSpinBox, QFileDialog, QLabel, QLineEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -49,13 +51,13 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._audio_threshold.setDecimals(4) self._audio_threshold.setRange(0.0, 1.0) self._audio_threshold.setValue(0.01) - self._audio_expect = QCheckBox(_t("media_audio_expect")) + self._audio_expect = self._tr(QCheckBox(), "media_audio_expect") self._audio_expect.setChecked(True) self._video_path = QLineEdit() self._video_threshold = QDoubleSpinBox() self._video_threshold.setRange(0.0, 255.0) self._video_threshold.setValue(1.0) - self._video_expect = QCheckBox(_t("media_video_expect")) + self._video_expect = self._tr(QCheckBox(), "media_video_expect") self._video_expect.setChecked(True) self._result = QLabel() self._result.setWordWrap(True) @@ -68,27 +70,18 @@ def _build_layout(self) -> None: # Audio/video check and browse commands run from the Actions menu; # the tab keeps only the inputs and the result label. root = QVBoxLayout(self) - root.addWidget(QLabel(_t("media_audio_label"))) - arow = QHBoxLayout() - arow.addWidget(QLabel(_t("media_audio_duration"))) - arow.addWidget(self._audio_duration) - arow.addWidget(QLabel(_t("media_audio_threshold"))) - arow.addWidget(self._audio_threshold) - arow.addWidget(self._audio_expect) - arow.addStretch() - root.addLayout(arow) - - root.addWidget(QLabel(_t("media_video_label"))) - vrow = QHBoxLayout() - vrow.addWidget(QLabel(_t("media_video_path"))) - vrow.addWidget(self._video_path, stretch=1) - root.addLayout(vrow) - vrow2 = QHBoxLayout() - vrow2.addWidget(QLabel(_t("media_video_threshold"))) - vrow2.addWidget(self._video_threshold) - vrow2.addWidget(self._video_expect) - vrow2.addStretch() - root.addLayout(vrow2) + root.setSpacing(12) + audio = Card("media_audio_label") + audio.add(flow_of(field_pair(self._tr(QLabel(), "media_audio_duration"), self._audio_duration), + field_pair(self._tr(QLabel(), "media_audio_threshold"), self._audio_threshold), + self._audio_expect)) + root.addWidget(audio) + + video = Card("media_video_label") + video.add(field_pair(self._tr(QLabel(), "media_video_path"), self._video_path)) + video.add(flow_of(field_pair(self._tr(QLabel(), "media_video_threshold"), self._video_threshold), + self._video_expect)) + root.addWidget(video) root.addWidget(self._result) root.addStretch() diff --git a/je_auto_control/gui/mobile_tab.py b/je_auto_control/gui/mobile_tab.py index 8c5afd474..a3da46cc6 100644 --- a/je_auto_control/gui/mobile_tab.py +++ b/je_auto_control/gui/mobile_tab.py @@ -22,6 +22,8 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui._qt_typed import filled_item +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -89,17 +91,21 @@ def _build_layout(self) -> None: # Probe / run / fill live in the Actions menu; the tab keeps only the # inputs, the capability table and the result view. root = QVBoxLayout(self) + root.setSpacing(12) + set_role(self._note, "warning") root.addWidget(self._tr(self._note, "mob_untested")) form = QFormLayout() for key, widget in (("mob_platform", self._platform), ("mob_device", self._device), ("mob_adb_path", self._adb_path), ("mob_command", self._command)): form.addRow(self._tr(QLabel(), key), widget) - root.addLayout(form) - root.addWidget(self._tr(QLabel(), "mob_params")) - root.addWidget(self._params) - root.addWidget(self._table, stretch=1) - root.addWidget(self._tr(QLabel(), "mob_result")) - root.addWidget(self._result, stretch=1) + setup = Card().add(form) + setup.add(self._tr(QLabel(), "mob_params")) + setup.add(self._params) + root.addWidget(setup) + result = Card() + result.add(self._tr(QLabel(), "mob_result")) + result.add(self._result, stretch=1) + root.addWidget(ResponsiveBox(Card().add(self._table, stretch=1), result), stretch=1) def dispose(self) -> None: """Release what the tab holds beyond its widgets: the command still running in the background. diff --git a/je_auto_control/gui/ocr_tab.py b/je_auto_control/gui/ocr_tab.py index 8cef017e9..093361def 100644 --- a/je_auto_control/gui/ocr_tab.py +++ b/je_auto_control/gui/ocr_tab.py @@ -10,12 +10,14 @@ from typing import Any, Callable, Optional from PySide6.QtWidgets import ( - QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMessageBox, + QFormLayout, QLabel, QLineEdit, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -72,29 +74,24 @@ def _build_layout(self) -> None: # Pick/dump/find commands run from the Actions menu; the tab keeps # only the region/params/regex inputs, the results view, and status. root = QVBoxLayout(self) - - region_group = self._tr(QGroupBox(), "ocr_region_group") - region_layout = QHBoxLayout() - region_layout.addWidget(self._tr(QLabel(), "ocr_region_label")) - region_layout.addWidget(self._region, stretch=1) - region_group.setLayout(region_layout) - root.addWidget(region_group) - - params_layout = QHBoxLayout() - params_layout.addWidget(self._tr(QLabel(), "ocr_lang_label")) - params_layout.addWidget(self._lang) - params_layout.addWidget(self._tr(QLabel(), "ocr_min_conf_label")) - params_layout.addWidget(self._min_conf) - params_layout.addStretch() - root.addLayout(params_layout) - - regex_layout = QHBoxLayout() - regex_layout.addWidget(self._tr(QLabel(), "ocr_regex_label")) - regex_layout.addWidget(self._regex, stretch=1) - root.addLayout(regex_layout) - - root.addWidget(self._tr(QLabel(), "ocr_results_label")) - root.addWidget(self._result, stretch=1) + root.setSpacing(12) + + region_layout = QFormLayout() + region_layout.addRow(self._tr(QLabel(), "ocr_region_label"), self._region) + root.addWidget(Card("ocr_region_group").add(region_layout)) + + params = Card() + params.add(flow_of(field_pair(self._tr(QLabel(), "ocr_lang_label"), self._lang), + field_pair(self._tr(QLabel(), "ocr_min_conf_label"), self._min_conf))) + params.add(field_pair(self._tr(QLabel(), "ocr_regex_label"), self._regex)) + root.addWidget(params) + + results = Card() + results.add(self._tr(QLabel(), "ocr_results_label")) + results.add(self._result, stretch=1) + root.addWidget(results, stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def dispose(self) -> None: diff --git a/je_auto_control/gui/plugins_tab.py b/je_auto_control/gui/plugins_tab.py index 82baa40a7..418704727 100644 --- a/je_auto_control/gui/plugins_tab.py +++ b/je_auto_control/gui/plugins_tab.py @@ -2,11 +2,12 @@ from typing import Optional from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QLabel, QLineEdit, QListWidget, QMessageBox, + QFileDialog, QFormLayout, QLabel, QLineEdit, QListWidget, QMessageBox, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -36,12 +37,14 @@ def _build_layout(self) -> None: # Browse/load commands run from the Actions menu; the tab keeps # only the directory input, the command list, and the status. root = QVBoxLayout(self) - form = QHBoxLayout() - form.addWidget(self._tr(QLabel(), "pl_dir_label")) - form.addWidget(self._dir_input, stretch=1) - root.addLayout(form) - root.addWidget(self._tr(QLabel(), "pl_registered_label")) - root.addWidget(self._list, stretch=1) + root.setSpacing(12) + form = QFormLayout() + form.addRow(self._tr(QLabel(), "pl_dir_label"), self._dir_input) + root.addWidget(Card().add(form)) + listing = Card().add(self._tr(QLabel(), "pl_registered_label")).add(self._list, stretch=1) + root.addWidget(listing, stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/presence_tab.py b/je_auto_control/gui/presence_tab.py index 02cb159c1..f50708c70 100644 --- a/je_auto_control/gui/presence_tab.py +++ b/je_auto_control/gui/presence_tab.py @@ -16,6 +16,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -77,7 +78,10 @@ def _build_layout(self) -> None: # Refresh/promote/demote/kick commands run from the Actions menu; # the tab keeps only the roster table and the status line. root = QVBoxLayout(self) - root.addWidget(self._table, stretch=1) + root.setSpacing(12) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) header = self._table.horizontalHeader() header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch) diff --git a/je_auto_control/gui/profiler_tab.py b/je_auto_control/gui/profiler_tab.py index 42a746865..ab34c7239 100644 --- a/je_auto_control/gui/profiler_tab.py +++ b/je_auto_control/gui/profiler_tab.py @@ -9,6 +9,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -80,8 +81,10 @@ def _build_layout(self) -> None: # Enable/reset/refresh commands run from the Actions menu; the tab # keeps only the table, the total bar, and the status line. root = QVBoxLayout(self) - root.addWidget(self._table, stretch=1) - root.addWidget(self._totalbar) + root.setSpacing(12) + root.addWidget(Card().add(self._table, stretch=1).add(self._totalbar), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/rbac_users_panel.py b/je_auto_control/gui/rbac_users_panel.py index 4abb208c8..7f79ef0f4 100644 --- a/je_auto_control/gui/rbac_users_panel.py +++ b/je_auto_control/gui/rbac_users_panel.py @@ -14,12 +14,14 @@ from PySide6.QtCore import Qt from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import ( - QAbstractItemView, QCheckBox, QComboBox, QGroupBox, QHBoxLayout, QLabel, + QAbstractItemView, QCheckBox, QComboBox, QFormLayout, QGroupBox, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._qt_typed import filled_item +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -65,25 +67,19 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: def _build_layout(self) -> None: root = QVBoxLayout(self) - path_row = QHBoxLayout() - path_row.addWidget(self._tr(QLabel(), "rest_users_path")) - path_row.addWidget(self._path_input, stretch=1) - root.addLayout(path_row) + path_form = QFormLayout() + path_form.addRow(self._tr(QLabel(), "rest_users_path"), self._path_input) + root.addLayout(path_form) self._tr(self._enable_check, "rest_users_enable") root.addWidget(self._enable_check) - root.addWidget(self._table) - edit_row = QHBoxLayout() - edit_row.addWidget(self._tr(QLabel(), "rest_users_id")) - edit_row.addWidget(self._id_input, stretch=1) - edit_row.addWidget(self._tr(QLabel(), "rest_users_name")) - edit_row.addWidget(self._name_input, stretch=1) - edit_row.addWidget(self._tr(QLabel(), "rest_users_role")) - edit_row.addWidget(self._role_input) - root.addLayout(edit_row) - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "rest_users_new_token")) - token_row.addWidget(self._token_value, stretch=1) - root.addLayout(token_row) + root.addWidget(self._table, stretch=1) + root.addLayout(flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("rest_users_id", self._id_input), ("rest_users_name", self._name_input), + ("rest_users_role", self._role_input))))) + token_form = QFormLayout() + token_form.addRow(self._tr(QLabel(), "rest_users_new_token"), self._token_value) + root.addLayout(token_form) + set_role(self._status_label, "hint") root.addWidget(self._status_label) def retranslate(self) -> None: diff --git a/je_auto_control/gui/recording_editor_tab.py b/je_auto_control/gui/recording_editor_tab.py index 4c5ca05e1..8af5ef30c 100644 --- a/je_auto_control/gui/recording_editor_tab.py +++ b/je_auto_control/gui/recording_editor_tab.py @@ -4,11 +4,14 @@ from PySide6.QtGui import QCloseEvent, QKeySequence, QShortcut from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QInputDialog, QLabel, QLineEdit, QListWidget, + QFileDialog, QFormLayout, QInputDialog, QLabel, QLineEdit, QListWidget, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -69,35 +72,25 @@ def _build_layout(self) -> None: # Load/save/export and every edit command run from the Actions # menu; the tab keeps only inputs, the list, preview, and status. root = QVBoxLayout(self) - top = QHBoxLayout() - top.addWidget(self._tr(QLabel(), "re_file_label")) - top.addWidget(self._path_input, stretch=1) - root.addLayout(top) - - root.addWidget(self._list, stretch=1) - - ops1 = QHBoxLayout() - ops1.addWidget(self._tr(QLabel(), "re_trim_start")) - ops1.addWidget(self._trim_start) - ops1.addWidget(self._tr(QLabel(), "re_trim_end")) - ops1.addWidget(self._trim_end) - ops1.addStretch() - root.addLayout(ops1) - - ops2 = QHBoxLayout() - ops2.addWidget(self._tr(QLabel(), "re_delay_x")) - ops2.addWidget(self._delay_factor) - ops2.addWidget(self._tr(QLabel(), "re_floor_ms")) - ops2.addWidget(self._delay_clamp) - ops2.addWidget(self._tr(QLabel(), "re_scale_x")) - ops2.addWidget(self._scale_x) - ops2.addWidget(self._tr(QLabel(), "re_scale_y")) - ops2.addWidget(self._scale_y) - ops2.addStretch() - root.addLayout(ops2) - - root.addWidget(self._tr(QLabel(), "re_preview")) - root.addWidget(self._preview, stretch=1) + root.setSpacing(12) + file_row = QFormLayout() + file_row.addRow(self._tr(QLabel(), "re_file_label"), self._path_input) + root.addWidget(Card().add(file_row)) + + def pair(key: str, field: QWidget) -> QWidget: + return field_pair(self._tr(QLabel(), key), field) + + edits = Card() + edits.add(flow_of(pair("re_trim_start", self._trim_start), pair("re_trim_end", self._trim_end))) + edits.add(flow_of(pair("re_delay_x", self._delay_factor), pair("re_floor_ms", self._delay_clamp), + pair("re_scale_x", self._scale_x), pair("re_scale_y", self._scale_y))) + root.addWidget(edits) + + preview = Card().add(set_role(self._tr(QLabel(), "re_preview"), "sectionTitle")) + preview.add(self._preview, stretch=1) + root.addWidget(ResponsiveBox(Card().add(self._list, stretch=1), preview, stretches=(2, 3)), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/remote_desktop/_helpers.py b/je_auto_control/gui/remote_desktop/_helpers.py index 07ff3cd2d..4f368ac04 100644 --- a/je_auto_control/gui/remote_desktop/_helpers.py +++ b/je_auto_control/gui/remote_desktop/_helpers.py @@ -6,7 +6,7 @@ from PySide6.QtCore import Qt from PySide6.QtGui import QKeyEvent -from PySide6.QtWidgets import QGroupBox, QLabel, QVBoxLayout, QWidget +from PySide6.QtWidgets import QGroupBox, QHBoxLayout, QLabel, QVBoxLayout, QWidget from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -187,6 +187,7 @@ def __init__(self, title: str = "", self.setCheckable(True) self.setChecked(False) self._body = QWidget(self) + self._body.setProperty("role", "bare") outer = QVBoxLayout(self) outer.setContentsMargins(8, 14, 8, 8) outer.addWidget(self._body) @@ -201,6 +202,26 @@ def set_body_layout(self, layout) -> None: self._body.setLayout(layout) +def _row(field: QWidget, *extras: QWidget) -> QHBoxLayout: + """``field`` taking the width, followed by its buttons at their natural size (one form row).""" + row = QHBoxLayout() + row.addWidget(field, 1) + for extra in extras: + row.addWidget(extra) + return row + + +def _pane(label: QLabel, field: QWidget) -> QWidget: + """A caption over its field, as one part of a side-by-side pair.""" + pane = QWidget() + pane.setProperty("role", "bare") + layout = QVBoxLayout(pane) + layout.setContentsMargins(0, 0, 0, 0) + layout.addWidget(label) + layout.addWidget(field, 1) + return pane + + def displaced_notifier(panel: Any) -> Callable[[str, str], None]: """Return the registry ``on_displaced`` callback for ``panel``. diff --git a/je_auto_control/gui/remote_desktop/advanced_group.py b/je_auto_control/gui/remote_desktop/advanced_group.py index 578c34fd1..e64bceded 100644 --- a/je_auto_control/gui/remote_desktop/advanced_group.py +++ b/je_auto_control/gui/remote_desktop/advanced_group.py @@ -16,7 +16,7 @@ from typing import Protocol, TypeVar from PySide6.QtWidgets import ( - QComboBox, QGridLayout, QGroupBox, QLabel, QLineEdit, QWidget, + QComboBox, QFormLayout, QGroupBox, QLabel, QLineEdit, QWidget, ) from je_auto_control.gui.remote_desktop._helpers import _t @@ -61,33 +61,28 @@ def build_advanced_group(panel: AdvancedGroupHost, *, hardware_codec: HardwareCodecGroupHost | None = None) -> QGroupBox: """Shared 'Advanced' STUN/TURN (+ optional hw codec) group.""" group = panel._tr(QGroupBox(), "rd_webrtc_advanced_group") - grid = QGridLayout() - grid.addWidget(panel._tr(QLabel(), "rd_webrtc_stun_label"), 0, 0) + form = QFormLayout() panel._stun_edit = QLineEdit(DEFAULT_STUN) - grid.addWidget(panel._stun_edit, 0, 1, 1, 3) - grid.addWidget(panel._tr(QLabel(), "rd_webrtc_turn_label"), 1, 0) + form.addRow(panel._tr(QLabel(), "rd_webrtc_stun_label"), panel._stun_edit) panel._turn_edit = panel._tr(QLineEdit(), "rd_webrtc_turn_placeholder") - grid.addWidget(panel._turn_edit, 1, 1, 1, 3) - grid.addWidget(panel._tr(QLabel(), "rd_webrtc_turn_user_label"), 2, 0) + form.addRow(panel._tr(QLabel(), "rd_webrtc_turn_label"), panel._turn_edit) panel._turn_user_edit = QLineEdit() - grid.addWidget(panel._turn_user_edit, 2, 1) - grid.addWidget(panel._tr(QLabel(), "rd_webrtc_turn_cred_label"), 2, 2) + form.addRow(panel._tr(QLabel(), "rd_webrtc_turn_user_label"), panel._turn_user_edit) panel._turn_cred_edit = QLineEdit() panel._turn_cred_edit.setEchoMode(QLineEdit.EchoMode.Password) - grid.addWidget(panel._turn_cred_edit, 2, 3) + form.addRow(panel._tr(QLabel(), "rd_webrtc_turn_cred_label"), panel._turn_cred_edit) if hardware_codec is not None: - _add_hw_codec_row(hardware_codec, grid) - group.setLayout(grid) + _add_hw_codec_row(hardware_codec, form) + group.setLayout(form) return group -def _add_hw_codec_row(panel: HardwareCodecGroupHost, grid: QGridLayout) -> None: +def _add_hw_codec_row(panel: HardwareCodecGroupHost, form: QFormLayout) -> None: """Add the hardware-codec picker, pre-selected to the active codec.""" - grid.addWidget(panel._tr(QLabel(), "rd_webrtc_hw_codec_label"), 3, 0) combo = QComboBox() panel._hw_codec_combo = combo combo.addItem(_t("rd_webrtc_hw_codec_off"), "") - grid.addWidget(combo, 3, 1, 1, 3) + form.addRow(panel._tr(QLabel(), "rd_webrtc_hw_codec_label"), combo) if available_hardware_codecs is None or active_hardware_codec is None: combo.setEnabled(False) return diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 29db49739..12dad599e 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -28,6 +28,8 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._weak_call import WeakCall from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime @@ -194,11 +196,11 @@ def _apply_placeholders(self) -> None: # --- layout ------------------------------------------------------- def _build_layout(self) -> None: - root = QHBoxLayout(self) - root.setContentsMargins(20, 20, 20, 20) - root.setSpacing(20) - root.addWidget(self._build_host_section(), stretch=1) - root.addWidget(self._build_viewer_section(), stretch=1) + root = QVBoxLayout(self) + root.setSpacing(12) + # The two halves sit side by side on a wide window and stack on a narrow one. + root.addWidget(ResponsiveBox(self._build_host_section(), self._build_viewer_section(), + stretches=(1, 1)), stretch=1) def _build_host_section(self) -> QWidget: group = QGroupBox() @@ -279,11 +281,14 @@ def _build_viewer_section(self) -> QWidget: return group def _build_recent_box(self) -> QWidget: - box = QGroupBox() - self._tr(box, "rd_quick_recent", setter="setTitle") + # A heading over the list rather than a box inside the section's box. + box = QWidget() + box.setProperty("role", "bare") layout = QVBoxLayout(box) - layout.setContentsMargins(8, 14, 8, 8) - layout.addWidget(self._recent) + layout.setContentsMargins(0, 6, 0, 0) + layout.setSpacing(6) + layout.addWidget(set_role(self._tr(QLabel(), "rd_quick_recent"), "sectionTitle")) + layout.addWidget(self._recent, stretch=1) return box # --- hosting ------------------------------------------------------ diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index 6cad410ec..cd5cbf963 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -7,13 +7,15 @@ from PySide6.QtCore import QTimer, Signal from PySide6.QtGui import QGuiApplication, QImage from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QFileDialog, QGroupBox, QHBoxLayout, QLabel, + QCheckBox, QComboBox, QFileDialog, QFormLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPushButton, QSpinBox, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui.remote_desktop._helpers import ( _CollapsibleSection, _StatusBadge, _t, @@ -147,114 +149,94 @@ def _apply_placeholders(self) -> None: def _build_layout(self) -> None: root = QVBoxLayout(self) + root.setSpacing(12) warning = QLabel() warning.setWordWrap(True) - warning.setStyleSheet( - "color: #cc7000; padding: 6px; border: 1px solid #cc7000; " - "border-radius: 4px;" - ) + set_role(warning, "warning") self._tr(warning, "rd_host_security_warning") root.addWidget(warning) - # === Connection card — the focal point === + root.addWidget(self._build_card()) + root.addWidget(self._build_basics()) + root.addWidget(self._build_advanced()) + + # === Primary action row === + btn_row = QHBoxLayout() + self._start_btn = self._tr(QPushButton(), "rd_host_start") + self._start_btn.setMinimumHeight(36) + self._start_btn.setStyleSheet("font-weight: bold;") + self._start_btn.clicked.connect(self._start) + self._stop_btn = self._tr(QPushButton(), "rd_host_stop") + self._stop_btn.setMinimumHeight(36) + self._stop_btn.clicked.connect(self._stop) + self._host_op.busy_changed.connect(self._start_btn.setDisabled) + self._host_op.busy_changed.connect(self._stop_btn.setDisabled) + btn_row.addWidget(self._start_btn, stretch=2) + btn_row.addWidget(self._stop_btn, stretch=1) + root.addLayout(btn_row) + + # === Preview === + preview = Card("rd_host_preview_label") + preview.add(self._preview, stretch=1) + root.addWidget(preview, stretch=1) + + def _build_card(self) -> QGroupBox: + """The connection card — the focal point: Host ID, token and the copy buttons.""" card = self._tr(QGroupBox(), "rd_host_card_group") card.setStyleSheet("QGroupBox { font-weight: bold; }") card_layout = QVBoxLayout() - + form = QFormLayout() id_row = QHBoxLayout() - id_row.addWidget(self._tr(QLabel(), "rd_host_id_label")) id_row.addWidget(self._host_id_label, stretch=1) id_row.addWidget(self._badge) - card_layout.addLayout(id_row) - + form.addRow(self._tr(QLabel(), "rd_host_id_label"), id_row) token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "rd_token_label")) token_row.addWidget(self._token, stretch=1) gen_btn = self._tr(QPushButton(), "rd_token_generate") gen_btn.clicked.connect(self._generate_token) token_row.addWidget(gen_btn) - card_layout.addLayout(token_row) + form.addRow(self._tr(QLabel(), "rd_token_label"), token_row) + card_layout.addLayout(form) - copy_row = QHBoxLayout() self._copy_id_btn = self._tr(QPushButton(), "rd_host_id_copy") self._copy_id_btn.clicked.connect(self._copy_host_id) self._copy_share_btn = self._tr(QPushButton(), "rd_host_copy_share") self._copy_share_btn.clicked.connect(self._copy_share_text) - copy_row.addWidget(self._copy_id_btn) - copy_row.addWidget(self._copy_share_btn) - copy_row.addStretch() - card_layout.addLayout(copy_row) - + card_layout.addLayout(flow_of(self._copy_id_btn, self._copy_share_btn)) card.setLayout(card_layout) - root.addWidget(card) + return card - # === Basic connection settings === + def _build_basics(self) -> QGroupBox: + """Basic connection settings: bind address, port and transport, wrapping when narrow.""" basics = self._tr(QGroupBox(), "rd_host_basics_group") basics_layout = QVBoxLayout() - bind_row = QHBoxLayout() - bind_row.addWidget(self._tr(QLabel(), "rd_bind_label")) - bind_row.addWidget(self._bind, stretch=1) - bind_row.addWidget(self._tr(QLabel(), "rd_port_label")) - bind_row.addWidget(self._port) - bind_row.addWidget(self._tr(QLabel(), "rd_transport_label")) - bind_row.addWidget(self._transport) - basics_layout.addLayout(bind_row) + basics_layout.addLayout(flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("rd_bind_label", self._bind), ("rd_port_label", self._port), + ("rd_transport_label", self._transport))))) basics.setLayout(basics_layout) - root.addWidget(basics) + return basics - # === Advanced (collapsible) === + def _build_advanced(self) -> _CollapsibleSection: + """The collapsible TLS / media / audio section.""" advanced = _CollapsibleSection() self._tr(advanced, "rd_advanced_group", setter="setTitle") adv_layout = QVBoxLayout() - - tls_row = QHBoxLayout() - tls_row.addWidget(self._tr(QLabel(), "rd_tls_cert_label")) - tls_row.addWidget(self._tls_cert, stretch=2) - cert_browse = self._tr(QPushButton(), "rd_browse") - cert_browse.clicked.connect(self._browse_cert) - tls_row.addWidget(cert_browse) - adv_layout.addLayout(tls_row) - - key_row = QHBoxLayout() - key_row.addWidget(self._tr(QLabel(), "rd_tls_key_label")) - key_row.addWidget(self._tls_key, stretch=2) - key_browse = self._tr(QPushButton(), "rd_browse") - key_browse.clicked.connect(self._browse_key) - key_row.addWidget(key_browse) - adv_layout.addLayout(key_row) - - media_row = QHBoxLayout() - media_row.addWidget(self._tr(QLabel(), "rd_fps_label")) - media_row.addWidget(self._fps) - media_row.addWidget(self._tr(QLabel(), "rd_quality_label")) - media_row.addWidget(self._quality) - media_row.addStretch() - adv_layout.addLayout(media_row) - + form = QFormLayout() + for label_key, field, slot in (("rd_tls_cert_label", self._tls_cert, self._browse_cert), + ("rd_tls_key_label", self._tls_key, self._browse_key)): + row = QHBoxLayout() + row.addWidget(field, stretch=1) + browse = self._tr(QPushButton(), "rd_browse") + browse.clicked.connect(slot) + row.addWidget(browse) + form.addRow(self._tr(QLabel(), label_key), row) + adv_layout.addLayout(form) + adv_layout.addLayout(flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("rd_fps_label", self._fps), ("rd_quality_label", self._quality))))) adv_layout.addWidget(self._tr(self._enable_audio, "rd_enable_audio")) - advanced.set_body_layout(adv_layout) - root.addWidget(advanced) - - # === Primary action row === - btn_row = QHBoxLayout() - self._start_btn = self._tr(QPushButton(), "rd_host_start") - self._start_btn.setMinimumHeight(36) - self._start_btn.setStyleSheet("font-weight: bold;") - self._start_btn.clicked.connect(self._start) - self._stop_btn = self._tr(QPushButton(), "rd_host_stop") - self._stop_btn.setMinimumHeight(36) - self._stop_btn.clicked.connect(self._stop) - self._host_op.busy_changed.connect(self._start_btn.setDisabled) - self._host_op.busy_changed.connect(self._stop_btn.setDisabled) - btn_row.addWidget(self._start_btn, stretch=2) - btn_row.addWidget(self._stop_btn, stretch=1) - root.addLayout(btn_row) - - # === Preview === - root.addWidget(self._tr(QLabel(), "rd_host_preview_label")) - root.addWidget(self._preview, stretch=1) + return advanced def _generate_token(self) -> None: self._token.setText(secrets.token_urlsafe(24)) diff --git a/je_auto_control/gui/remote_desktop/trusted_group.py b/je_auto_control/gui/remote_desktop/trusted_group.py index d3e7c3b92..bf98900f2 100644 --- a/je_auto_control/gui/remote_desktop/trusted_group.py +++ b/je_auto_control/gui/remote_desktop/trusted_group.py @@ -15,9 +15,11 @@ from typing import Any, Protocol, TypeVar from PySide6.QtWidgets import ( - QGroupBox, QHBoxLayout, QPushButton, QVBoxLayout, QWidget, + QGroupBox, QPushButton, QVBoxLayout, QWidget, ) +from je_auto_control.gui.adaptive.flow_layout import flow_of + from je_auto_control.gui.remote_desktop.webrtc_dialogs import TrustedViewersList @@ -55,7 +57,7 @@ def build_trusted_group(panel: TrustedGroupHost) -> QGroupBox: panel._trusted_list = TrustedViewersList() panel._trusted_list.removed.connect(panel._on_remove_trust) layout.addWidget(panel._trusted_list) - button_row = QHBoxLayout() + buttons = [] for key, slot in ( ("rd_webrtc_remove_trusted", panel._on_remove_trust_button), ("rd_webrtc_clear_trusted", panel._on_clear_trust), @@ -64,8 +66,8 @@ def build_trusted_group(panel: TrustedGroupHost) -> QGroupBox: ): button = panel._tr(QPushButton(), key) button.clicked.connect(slot) - button_row.addWidget(button) - layout.addLayout(button_row) + buttons.append(button) + layout.addLayout(flow_of(*buttons)) group.setLayout(layout) return group diff --git a/je_auto_control/gui/remote_desktop/viewer_panel.py b/je_auto_control/gui/remote_desktop/viewer_panel.py index eead3be56..e1e5250ef 100644 --- a/je_auto_control/gui/remote_desktop/viewer_panel.py +++ b/je_auto_control/gui/remote_desktop/viewer_panel.py @@ -6,12 +6,14 @@ from PySide6.QtCore import Signal from PySide6.QtGui import QGuiApplication, QImage from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QFileDialog, QGroupBox, QHBoxLayout, QInputDialog, + QCheckBox, QComboBox, QFileDialog, QFormLayout, QGroupBox, QHBoxLayout, QInputDialog, QLabel, QLineEdit, QMessageBox, QProgressBar, QPushButton, QSpinBox, QVBoxLayout, QWidget, ) from je_auto_control.gui._slow_op import StopQueue +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._dispose import release_resources @@ -91,7 +93,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._enable_audio.setEnabled(False) self._badge = _StatusBadge() self._status = QLabel() - self._status.setStyleSheet("color: #555; font-size: 9pt;") + set_role(self._status, "hint") # _screen_window is created lazily on connect — the AnyDesk-style # popout. While disconnected we hold ``None`` and the panel # itself stays compact instead of devoting half its height to a @@ -132,8 +134,7 @@ def _apply_placeholders(self) -> None: def _build_layout(self) -> None: root = QVBoxLayout(self) - root.setContentsMargins(12, 12, 12, 12) - root.setSpacing(8) + root.setSpacing(12) root.addWidget(self._build_card()) root.addWidget(self._build_advanced()) @@ -145,6 +146,7 @@ def _build_layout(self) -> None: # surface, status, and transfer progress. root.addWidget(self._progress_label) root.addWidget(self._progress_bar) + self._status.setWordWrap(True) root.addWidget(self._status) root.addStretch(1) @@ -152,27 +154,23 @@ def _build_card(self) -> QGroupBox: card = self._tr(QGroupBox(), "rd_viewer_card_group") card.setStyleSheet("QGroupBox { font-weight: bold; }") card_layout = QVBoxLayout() - card_layout.setSpacing(6) + card_layout.setSpacing(8) + id_form = QFormLayout() id_row = QHBoxLayout() - id_row.addWidget(self._tr(QLabel(), "rd_host_id_label")) id_row.addWidget(self._host_id, stretch=1) id_row.addWidget(self._badge) - card_layout.addLayout(id_row) - - addr_row = QHBoxLayout() - addr_row.addWidget(self._tr(QLabel(), "rd_bind_label")) - addr_row.addWidget(self._host_field, stretch=1) - addr_row.addWidget(self._tr(QLabel(), "rd_port_label")) - addr_row.addWidget(self._port) - addr_row.addWidget(self._tr(QLabel(), "rd_transport_label")) - addr_row.addWidget(self._transport) - card_layout.addLayout(addr_row) - - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "rd_token_label")) - token_row.addWidget(self._token, stretch=1) - card_layout.addLayout(token_row) + id_form.addRow(self._tr(QLabel(), "rd_host_id_label"), id_row) + card_layout.addLayout(id_form) + + # Address, port and transport wrap onto a second line when narrow. + card_layout.addLayout(flow_of(*(field_pair(self._tr(QLabel(), key), field) for key, field in ( + ("rd_bind_label", self._host_field), ("rd_port_label", self._port), + ("rd_transport_label", self._transport))))) + + token_form = QFormLayout() + token_form.addRow(self._tr(QLabel(), "rd_token_label"), self._token) + card_layout.addLayout(token_form) card.setLayout(card_layout) return card @@ -202,15 +200,12 @@ def _build_button_row(self) -> QHBoxLayout: def _build_action_row(self) -> QWidget: action_row_widget = QWidget() - action_row = QHBoxLayout(action_row_widget) - action_row.setContentsMargins(0, 0, 0, 0) + action_row_widget.setProperty("role", "bare") push_clip_btn = self._tr(QPushButton(), "rd_viewer_push_clipboard") push_clip_btn.clicked.connect(self._push_clipboard_to_host) send_file_btn = self._tr(QPushButton(), "rd_viewer_send_file") send_file_btn.clicked.connect(self._on_send_file_clicked) - action_row.addWidget(push_clip_btn) - action_row.addWidget(send_file_btn) - action_row.addStretch() + action_row_widget.setLayout(flow_of(push_clip_btn, send_file_btn)) action_row_widget.setVisible(False) self._action_row = action_row_widget return action_row_widget diff --git a/je_auto_control/gui/remote_desktop/webrtc_dialogs.py b/je_auto_control/gui/remote_desktop/webrtc_dialogs.py index 547b5f0a0..ea847a473 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_dialogs.py +++ b/je_auto_control/gui/remote_desktop/webrtc_dialogs.py @@ -17,6 +17,8 @@ QWidget, ) +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.remote_desktop._helpers import ( _format_short_time, _iso_to_epoch, _t, ) @@ -43,7 +45,9 @@ def __init__(self, viewer_id: Optional[str], self.setMinimumWidth(400) self._result = self.Rejected layout = QVBoxLayout(self) - layout.addWidget(QLabel(_t("rd_webrtc_pending_viewer_prompt"))) + prompt = QLabel(_t("rd_webrtc_pending_viewer_prompt")) + prompt.setWordWrap(True) + layout.addWidget(prompt) if viewer_id: id_label = QLabel(f"viewer_id: {viewer_id[:12]}...{viewer_id[-4:]}") id_label.setTextInteractionFlags( @@ -326,18 +330,15 @@ def __init__(self, audit_log, parent: Optional[QWidget] = None) -> None: self.setWindowTitle(_t("rd_webrtc_audit_title")) self.setMinimumSize(820, 380) layout = QVBoxLayout(self) - filter_row = QHBoxLayout() - filter_row.addWidget(QLabel(_t("rd_webrtc_audit_filter_type"))) self._type_edit = QLineEdit() self._type_edit.setPlaceholderText(_t("rd_webrtc_audit_filter_type_ph")) - filter_row.addWidget(self._type_edit) - filter_row.addWidget(QLabel(_t("rd_webrtc_audit_filter_host"))) self._host_edit = QLineEdit() - filter_row.addWidget(self._host_edit) refresh_btn = QPushButton(_t("rd_webrtc_audit_refresh")) refresh_btn.clicked.connect(self._refresh) - filter_row.addWidget(refresh_btn) - layout.addLayout(filter_row) + layout.addLayout(flow_of( + field_pair(QLabel(_t("rd_webrtc_audit_filter_type")), self._type_edit), + field_pair(QLabel(_t("rd_webrtc_audit_filter_host")), self._host_edit), + refresh_btn)) self._table = QTableWidget(0, 5) self._table.setHorizontalHeaderLabels([ _t("rd_webrtc_audit_col_ts"), @@ -407,7 +408,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self.setMinimumSize(620, 260) self._services: dict = {} layout = QVBoxLayout(self) - layout.addWidget(QLabel(_t("rd_webrtc_lan_help"))) + help_label = QLabel(_t("rd_webrtc_lan_help")) + help_label.setWordWrap(True) + set_role(help_label, "hint") + layout.addWidget(help_label) self._table = QTableWidget(0, 4) self._table.setHorizontalHeaderLabels([ _t("rd_webrtc_lan_col_host"), diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_ui.py b/je_auto_control/gui/remote_desktop/webrtc_host_ui.py index 5925f7b59..052109a5a 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_ui.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_ui.py @@ -10,13 +10,17 @@ from PySide6.QtCore import Qt from PySide6.QtWidgets import ( - QAbstractItemView, QCheckBox, QComboBox, QGridLayout, + QAbstractItemView, QCheckBox, QComboBox, QFormLayout, QGroupBox, QHBoxLayout, QHeaderView, QLabel, QLineEdit, - QPushButton, QSpinBox, QTableWidget, QTextEdit, QVBoxLayout, + QPushButton, QSizePolicy, QSpinBox, QTableWidget, QTextEdit, QVBoxLayout, QWidget, ) +from je_auto_control.gui.adaptive.flow_layout import flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role + from je_auto_control.gui.remote_desktop._helpers import ( - _t, + _pane, _row, _t, ) from je_auto_control.gui.remote_desktop.advanced_group import ( build_advanced_group, @@ -37,13 +41,21 @@ class _HostUiMixin(_HostPanelPart): def _build_ui(self) -> None: layout = QVBoxLayout(self) + layout.setSpacing(12) layout.addWidget(self._build_signaling_group()) layout.addWidget(self._build_config_group()) layout.addWidget(self._build_manual_group()) layout.addWidget(build_advanced_group(self, hardware_codec=self)) layout.addWidget(build_trusted_group(self)) + layout.addWidget(self._build_sessions_card(), stretch=1) + + def _build_sessions_card(self) -> Card: + """Status line, the live sessions table and what can be done to a session.""" + card = Card() self._status_label = QLabel(_t("rd_webrtc_status_idle")) - layout.addWidget(self._status_label) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") + card.add(self._status_label) sessions_row = QHBoxLayout() self._host_quality_dot = QLabel() self._host_quality_dot.setFixedSize(14, 14) @@ -54,7 +66,7 @@ def _build_ui(self) -> None: sessions_row.addWidget(self._host_quality_dot) self._sessions_label = QLabel(_t("rd_webrtc_sessions_count").format(n=0)) sessions_row.addWidget(self._sessions_label, stretch=1) - layout.addLayout(sessions_row) + card.add(sessions_row) self._sessions_table = QTableWidget(0, 5) self._sessions_table.setHorizontalHeaderLabels([ "", # quality dot column @@ -86,46 +98,35 @@ def _build_ui(self) -> None: self._sessions_table.customContextMenuRequested.connect( self._on_sessions_context_menu, ) - layout.addWidget(self._sessions_table) - sessions_btn_row = QHBoxLayout() + card.add(self._sessions_table, stretch=1) self._disconnect_btn = self._tr( QPushButton(), "rd_webrtc_disconnect_selected", ) self._disconnect_btn.clicked.connect(self._on_disconnect_selected) - sessions_btn_row.addWidget(self._disconnect_btn) - sessions_btn_row.addStretch() - layout.addLayout(sessions_btn_row) - push_row = QHBoxLayout() self._push_file_btn = self._tr(QPushButton(), "rd_webrtc_push_file") self._push_file_btn.clicked.connect(self._on_push_file) - push_row.addWidget(self._push_file_btn) audit_btn = self._tr(QPushButton(), "rd_webrtc_view_audit") audit_btn.clicked.connect(self._on_view_audit) - push_row.addWidget(audit_btn) - push_row.addStretch() - layout.addLayout(push_row) + card.add(flow_of(self._disconnect_btn, self._push_file_btn, audit_btn)) + return card def _build_signaling_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_signaling_group") - grid = QGridLayout() - grid.addWidget(self._tr(QLabel(), "rd_webrtc_server_label"), 0, 0) + form = QFormLayout() self._server_edit = QLineEdit(_DEFAULT_SIGNALING_URL) - grid.addWidget(self._server_edit, 0, 1, 1, 3) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_host_id_label"), 1, 0) + form.addRow(self._tr(QLabel(), "rd_webrtc_server_label"), self._server_edit) self._host_id_edit = QLineEdit(generate_host_id()) - grid.addWidget(self._host_id_edit, 1, 1, 1, 2) regen = self._tr(QPushButton(), "rd_webrtc_regen_id") regen.clicked.connect(self._on_regen_id) - grid.addWidget(regen, 1, 3) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_secret_label"), 2, 0) + form.addRow(self._tr(QLabel(), "rd_webrtc_host_id_label"), _row(self._host_id_edit, regen)) self._secret_edit = QLineEdit() self._secret_edit.setEchoMode(QLineEdit.EchoMode.Password) - grid.addWidget(self._secret_edit, 2, 1, 1, 3) + form.addRow(self._tr(QLabel(), "rd_webrtc_secret_label"), self._secret_edit) self._publish_btn = self._tr( QPushButton(), "rd_webrtc_publish_via_server", ) self._publish_btn.clicked.connect(self._on_publish_via_server) - grid.addWidget(self._publish_btn, 3, 0, 1, 4) + form.addRow(self._publish_btn) # Read-only fingerprint label + copy button from je_auto_control.utils.remote_desktop.fingerprint import ( fingerprint_for_display, load_or_create_host_fingerprint, @@ -134,7 +135,6 @@ def _build_signaling_group(self) -> QGroupBox: fp = load_or_create_host_fingerprint() except OSError: fp = "" - grid.addWidget(self._tr(QLabel(), "rd_webrtc_my_fingerprint"), 4, 0) self._fingerprint_label = QLabel( fingerprint_for_display(fp) if fp else "", ) @@ -144,11 +144,14 @@ def _build_signaling_group(self) -> QGroupBox: self._fingerprint_label.setTextInteractionFlags( Qt.TextInteractionFlag.TextSelectableByMouse, ) - grid.addWidget(self._fingerprint_label, 4, 1, 1, 2) + # One unbreakable run of hex: let it clip on a narrow window rather + # than widen the page; the tooltip and the Copy button hold all of it. + self._fingerprint_label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + self._fingerprint_label.setToolTip(self._fingerprint_label.text()) copy_fp_btn = self._tr(QPushButton(), "rd_webrtc_copy_fingerprint") copy_fp_btn.clicked.connect(lambda: self._on_copy_fingerprint(fp)) - grid.addWidget(copy_fp_btn, 4, 3) - group.setLayout(grid) + form.addRow(self._tr(QLabel(), "rd_webrtc_my_fingerprint"), _row(self._fingerprint_label, copy_fp_btn)) + group.setLayout(form) return group def _on_copy_fingerprint(self, fp: str) -> None: @@ -159,65 +162,62 @@ def _on_copy_fingerprint(self, fp: str) -> None: def _build_config_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_config_group") - grid = QGridLayout() - grid.addWidget(self._tr(QLabel(), "rd_token_label"), 0, 0) + form = QFormLayout() self._token_edit = self._tr(QLineEdit(), "rd_token_placeholder") - grid.addWidget(self._token_edit, 0, 1) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_monitor_label"), 1, 0) + form.addRow(self._tr(QLabel(), "rd_token_label"), self._token_edit) self._monitor_combo = QComboBox() self._populate_monitor_combo() self._monitor_combo.currentIndexChanged.connect( self._on_monitor_changed, ) - grid.addWidget(self._monitor_combo, 1, 1) - grid.addWidget(self._tr(QLabel(), "rd_fps_label"), 2, 0) + form.addRow(self._tr(QLabel(), "rd_webrtc_monitor_label"), self._monitor_combo) self._fps_spin = QSpinBox() self._fps_spin.setRange(1, 60) self._fps_spin.setValue(_DEFAULT_FPS) - grid.addWidget(self._fps_spin, 2, 1) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_region_label"), 11, 0) + form.addRow(self._tr(QLabel(), "rd_fps_label"), self._fps_spin) + self._max_bitrate_spin = QSpinBox() + self._max_bitrate_spin.setRange(0, 50000) + self._max_bitrate_spin.setSingleStep(500) + self._max_bitrate_spin.setSuffix(" kbps (0=∞)") + self._max_bitrate_spin.setValue(0) + form.addRow(self._tr(QLabel(), "rd_webrtc_max_bitrate"), self._max_bitrate_spin) self._region_edit = QLineEdit() self._tr(self._region_edit, "rd_webrtc_region_placeholder", "setPlaceholderText") - grid.addWidget(self._region_edit, 11, 1) pick_region_btn = self._tr(QPushButton(), "rd_webrtc_pick_region") pick_region_btn.clicked.connect(self._on_pick_region) - grid.addWidget(pick_region_btn, 11, 2) + form.addRow(self._tr(QLabel(), "rd_webrtc_region_label"), _row(self._region_edit, pick_region_btn)) + self._ip_whitelist_edit = QTextEdit() + self._ip_whitelist_edit.setMaximumHeight(60) + self._tr(self._ip_whitelist_edit, "rd_webrtc_ip_whitelist_ph", + "setPlaceholderText") + form.addRow(self._tr(QLabel(), "rd_webrtc_ip_whitelist"), self._ip_whitelist_edit) + fields = QWidget() + fields.setProperty("role", "bare") + form.setContentsMargins(0, 0, 0, 0) + fields.setLayout(form) + # The fields and the switches sit side by side, and stack when narrow. + layout = QVBoxLayout() + layout.addWidget(ResponsiveBox(fields, self._build_config_switches(), stretches=(3, 2))) + group.setLayout(layout) + return group + + def _build_config_switches(self) -> QWidget: + """The on/off options of the config group, one per line.""" self._cursor_check = self._tr(QCheckBox(), "rd_webrtc_show_cursor") self._cursor_check.setChecked(True) - grid.addWidget(self._cursor_check, 3, 0, 1, 2) self._blank_check = self._tr(QCheckBox(), "rd_webrtc_blank_screen") self._blank_check.setChecked(False) self._blank_check.toggled.connect(self._on_toggle_blanking) - grid.addWidget(self._blank_check, 4, 0, 1, 2) self._readonly_check = self._tr(QCheckBox(), "rd_webrtc_read_only") self._readonly_check.setChecked(False) self._readonly_check.toggled.connect(self._on_toggle_readonly) - grid.addWidget(self._readonly_check, 5, 0, 1, 2) self._adaptive_check = self._tr(QCheckBox(), "rd_webrtc_adaptive") self._adaptive_check.setChecked(True) self._adaptive_check.toggled.connect(self._on_toggle_adaptive) - grid.addWidget(self._adaptive_check, 6, 0, 1, 2) self._mic_recv_check = self._tr(QCheckBox(), "rd_webrtc_recv_mic") self._mic_recv_check.setChecked(False) self._mic_recv_check.toggled.connect(self._on_toggle_mic_receive) - grid.addWidget(self._mic_recv_check, 7, 0, 1, 2) - self._host_voice_check = self._tr(QCheckBox(), "rd_webrtc_host_voice") - self._host_voice_check.setChecked(False) - grid.addWidget(self._host_voice_check, 13, 0, 1, 2) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_max_bitrate"), 10, 0) - self._max_bitrate_spin = QSpinBox() - self._max_bitrate_spin.setRange(0, 50000) - self._max_bitrate_spin.setSingleStep(500) - self._max_bitrate_spin.setSuffix(" kbps (0=∞)") - self._max_bitrate_spin.setValue(0) - grid.addWidget(self._max_bitrate_spin, 10, 1) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_ip_whitelist"), 12, 0) - self._ip_whitelist_edit = QTextEdit() - self._ip_whitelist_edit.setMaximumHeight(60) - self._tr(self._ip_whitelist_edit, "rd_webrtc_ip_whitelist_ph", - "setPlaceholderText") - grid.addWidget(self._ip_whitelist_edit, 12, 1) self._accept_viewer_video_check = self._tr( QCheckBox(), "rd_webrtc_accept_viewer_video", ) @@ -225,7 +225,6 @@ def _build_config_group(self) -> QGroupBox: self._accept_viewer_video_check.toggled.connect( self._on_toggle_accept_viewer_video, ) - grid.addWidget(self._accept_viewer_video_check, 8, 0, 1, 2) self._accept_opus_audio_check = self._tr( QCheckBox(), "rd_webrtc_accept_opus_audio", ) @@ -233,34 +232,40 @@ def _build_config_group(self) -> QGroupBox: self._accept_opus_audio_check.toggled.connect( self._on_toggle_accept_opus_audio, ) - grid.addWidget(self._accept_opus_audio_check, 9, 0, 1, 2) - group.setLayout(grid) - return group + self._host_voice_check = self._tr(QCheckBox(), "rd_webrtc_host_voice") + self._host_voice_check.setChecked(False) + switches = QWidget() + switches.setProperty("role", "bare") + column = QVBoxLayout(switches) + column.setContentsMargins(0, 0, 0, 0) + for check in (self._cursor_check, self._blank_check, self._readonly_check, self._adaptive_check, + self._mic_recv_check, self._accept_viewer_video_check, self._accept_opus_audio_check, + self._host_voice_check): + column.addWidget(check) + column.addStretch(1) + return switches def _build_manual_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_manual_group") layout = QVBoxLayout() self._generate_btn = self._tr(QPushButton(), "rd_webrtc_generate_offer") self._generate_btn.clicked.connect(self._on_generate_offer) - layout.addWidget(self._generate_btn) - layout.addWidget(self._tr(QLabel(), "rd_webrtc_offer_label")) + layout.addLayout(flow_of(self._generate_btn)) self._offer_view = QTextEdit() self._offer_view.setReadOnly(True) self._offer_view.setMinimumHeight(80) - layout.addWidget(self._offer_view) - layout.addWidget(self._tr(QLabel(), "rd_webrtc_answer_input_label")) self._answer_input = QTextEdit() self._answer_input.setMinimumHeight(80) self._tr(self._answer_input, "rd_webrtc_paste_answer", "setPlaceholderText") - layout.addWidget(self._answer_input) - button_row = QHBoxLayout() + # The offer goes out on the left, the answer comes back on the right. + layout.addWidget(ResponsiveBox( + _pane(self._tr(QLabel(), "rd_webrtc_offer_label"), self._offer_view), + _pane(self._tr(QLabel(), "rd_webrtc_answer_input_label"), self._answer_input))) self._apply_btn = self._tr(QPushButton(), "rd_webrtc_apply_answer") self._apply_btn.clicked.connect(self._on_apply_answer) - button_row.addWidget(self._apply_btn) self._stop_btn = self._tr(QPushButton(), "rd_webrtc_stop_host") self._stop_btn.clicked.connect(self._on_stop) - button_row.addWidget(self._stop_btn) - layout.addLayout(button_row) + layout.addLayout(flow_of(self._apply_btn, self._stop_btn)) group.setLayout(layout) return group diff --git a/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py b/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py index edb16dbf6..bc361b1eb 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py +++ b/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py @@ -9,6 +9,7 @@ from typing import Optional +from PySide6.QtCore import Qt from PySide6.QtGui import QColor from PySide6.QtWidgets import ( QAbstractItemView, QDialog, QFileDialog, QFormLayout, QHBoxLayout, @@ -16,6 +17,7 @@ QTableWidgetItem, QVBoxLayout, QWidget, ) +from je_auto_control.gui.adaptive.flow_layout import flow_of from je_auto_control.gui.remote_desktop._helpers import ( _format_last_seen, _short_fp, _t, ) @@ -53,35 +55,26 @@ def __init__(self, known_hosts, parent: Optional[QWidget] = None) -> None: QAbstractItemView.EditTrigger.NoEditTriggers, ) layout.addWidget(self._table) + buttons = [] + for key, slot in ( + ("rd_webrtc_kh_add", self._on_add_manual), + ("rd_webrtc_kh_import", self._on_import), + ("rd_webrtc_kh_export", self._on_export), + ("rd_webrtc_kh_copy_app", self._on_copy_app), + ("rd_webrtc_kh_copy_dtls", self._on_copy_dtls), + ("rd_webrtc_kh_forget", self._on_forget), + ("rd_webrtc_kh_forget_stale", self._on_forget_stale), + ("rd_webrtc_kh_clear_all", self._on_clear_all), + ): + button = QPushButton(_t(key)) + button.clicked.connect(slot) + buttons.append(button) + # Eight actions wrap onto a second line in a narrow dialog; Close stays on the right. button_row = QHBoxLayout() - add_btn = QPushButton(_t("rd_webrtc_kh_add")) - add_btn.clicked.connect(self._on_add_manual) - button_row.addWidget(add_btn) - import_btn = QPushButton(_t("rd_webrtc_kh_import")) - import_btn.clicked.connect(self._on_import) - button_row.addWidget(import_btn) - export_btn = QPushButton(_t("rd_webrtc_kh_export")) - export_btn.clicked.connect(self._on_export) - button_row.addWidget(export_btn) - copy_app_btn = QPushButton(_t("rd_webrtc_kh_copy_app")) - copy_app_btn.clicked.connect(self._on_copy_app) - button_row.addWidget(copy_app_btn) - copy_dtls_btn = QPushButton(_t("rd_webrtc_kh_copy_dtls")) - copy_dtls_btn.clicked.connect(self._on_copy_dtls) - button_row.addWidget(copy_dtls_btn) - forget_btn = QPushButton(_t("rd_webrtc_kh_forget")) - forget_btn.clicked.connect(self._on_forget) - button_row.addWidget(forget_btn) - forget_stale_btn = QPushButton(_t("rd_webrtc_kh_forget_stale")) - forget_stale_btn.clicked.connect(self._on_forget_stale) - button_row.addWidget(forget_stale_btn) - clear_btn = QPushButton(_t("rd_webrtc_kh_clear_all")) - clear_btn.clicked.connect(self._on_clear_all) - button_row.addWidget(clear_btn) - button_row.addStretch() + button_row.addLayout(flow_of(*buttons, spacing=8), stretch=1) close_btn = QPushButton(_t("rd_webrtc_kh_close")) close_btn.clicked.connect(self.accept) - button_row.addWidget(close_btn) + button_row.addWidget(close_btn, alignment=Qt.AlignmentFlag.AlignBottom) layout.addLayout(button_row) self._refresh() diff --git a/je_auto_control/gui/remote_desktop/webrtc_panel.py b/je_auto_control/gui/remote_desktop/webrtc_panel.py index 535536c1b..2d4b6c858 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_panel.py +++ b/je_auto_control/gui/remote_desktop/webrtc_panel.py @@ -148,7 +148,7 @@ def prefill(self, token: Optional[str] = None, """Hand-off entry point used by the Quick Connect screen. Populates the signaling-flow fields so the operator can click - "Publish & wait for viewer" without retyping a token they + "Publish and wait for viewer" without retyping a token they already shared on the Quick Connect tab. """ if token: diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py index c40ba7b26..15e786261 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py @@ -9,13 +9,16 @@ from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QGridLayout, + QCheckBox, QComboBox, QFormLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QPushButton, QSpinBox, QTextEdit, QVBoxLayout, ) +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.remote_desktop._helpers import ( - _CollapsibleSection, _t, + _CollapsibleSection, _pane, _row, _t, ) from je_auto_control.gui.remote_desktop.advanced_group import ( build_advanced_group, @@ -38,8 +41,7 @@ class _ViewerUiMixin(_ViewerPanelPart): def _build_ui(self) -> None: layout = QVBoxLayout(self) - layout.setContentsMargins(12, 12, 12, 12) - layout.setSpacing(8) + layout.setSpacing(12) # Essentials always visible: address book + recommended # signaling-server flow + WebRTC config. layout.addWidget(self._build_address_book_group()) @@ -54,41 +56,51 @@ def _build_ui(self) -> None: layout.addWidget(build_advanced_group(self)) layout.addWidget(self._wrap_collapsed( self._build_remote_files_group(), - "rd_webrtc_files_group", + "rd_webrtc_remote_files_group", )) layout.addWidget(self._wrap_collapsed( self._build_sync_group(), "rd_webrtc_sync_group", )) + layout.addWidget(self._build_session_card()) + # Hidden _FrameDisplay placeholder kept around so the rest of + # the class (pen mode toggle, image setter) doesn't have to + # branch between "popup open" and "popup closed". It also lets + # the panel decode frames before the operator opens the popup. + # When the popup IS open, frames + input round-trip through + # the popup's display instead. + self._frame_display = _FrameDisplay() + self._frame_display.setVisible(False) + layout.addWidget(self._frame_display) + layout.addStretch(1) + self._wire_input_signals() + + def _build_session_card(self) -> Card: + """Status, the in-session actions and the live link statistics.""" + card = Card() self._status_label = QLabel(_t("rd_webrtc_status_idle")) - layout.addWidget(self._status_label) - action_row = QHBoxLayout() + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") + card.add(self._status_label) self._cad_btn = self._tr(QPushButton(), "rd_webrtc_send_cad") self._cad_btn.clicked.connect(self._on_send_cad) - action_row.addWidget(self._cad_btn) self._wol_btn = self._tr(QPushButton(), "rd_webrtc_wake_on_lan") self._wol_btn.clicked.connect(self._on_wake_on_lan) - action_row.addWidget(self._wol_btn) self._mic_btn = self._tr(QPushButton(), "rd_webrtc_send_mic") self._mic_btn.setCheckable(True) self._mic_btn.clicked.connect(self._on_toggle_mic) - action_row.addWidget(self._mic_btn) self._send_file_btn = self._tr(QPushButton(), "rd_webrtc_send_file") self._send_file_btn.clicked.connect(self._on_send_file) - action_row.addWidget(self._send_file_btn) self._record_btn = self._tr(QPushButton(), "rd_webrtc_start_recording") self._record_btn.setCheckable(True) self._record_btn.clicked.connect(self._on_toggle_recording) - action_row.addWidget(self._record_btn) self._pen_btn = self._tr(QPushButton(), "rd_webrtc_pen_off") self._pen_btn.setCheckable(True) self._pen_btn.clicked.connect(self._on_toggle_pen) - action_row.addWidget(self._pen_btn) self._pen_clear_btn = self._tr(QPushButton(), "rd_webrtc_pen_clear") self._pen_clear_btn.clicked.connect(self._on_pen_clear) - action_row.addWidget(self._pen_clear_btn) - action_row.addStretch() - layout.addLayout(action_row) + card.add(flow_of(self._cad_btn, self._wol_btn, self._mic_btn, self._send_file_btn, + self._record_btn, self._pen_btn, self._pen_clear_btn, spacing=8)) stats_row = QHBoxLayout() self._quality_dot = QLabel() self._quality_dot.setFixedSize(14, 14) @@ -101,8 +113,9 @@ def _build_ui(self) -> None: self._stats_label.setStyleSheet( "color: #ccaa55; font-family: 'Consolas', monospace;", ) + self._stats_label.setWordWrap(True) stats_row.addWidget(self._stats_label, stretch=1) - layout.addLayout(stats_row) + card.add(stats_row) spark_row = QHBoxLayout() self._rtt_spark = Sparkline(line_color="#3a9c3a") self._rtt_spark.setToolTip("RTT (ms)") @@ -110,52 +123,34 @@ def _build_ui(self) -> None: self._bitrate_spark = Sparkline(line_color="#c97a00") self._bitrate_spark.setToolTip("kbps") spark_row.addWidget(self._bitrate_spark, stretch=1) - layout.addLayout(spark_row) - # Hidden _FrameDisplay placeholder kept around so the rest of - # the class (pen mode toggle, image setter) doesn't have to - # branch between "popup open" and "popup closed". It also lets - # the panel decode frames before the operator opens the popup. - # When the popup IS open, frames + input round-trip through - # the popup's display instead. - self._frame_display = _FrameDisplay() - self._frame_display.setVisible(False) - layout.addWidget(self._frame_display) - layout.addStretch(1) - self._wire_input_signals() + card.add(spark_row) + return card def _build_sync_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_sync_group") - layout = QGridLayout() - layout.addWidget(self._tr(QLabel(), "rd_webrtc_sync_dir"), 0, 0) + form = QFormLayout() self._sync_dir_edit = QLineEdit() self._tr(self._sync_dir_edit, "rd_webrtc_sync_dir_ph", "setPlaceholderText") - layout.addWidget(self._sync_dir_edit, 0, 1) browse_btn = self._tr(QPushButton(), "rd_webrtc_browse") browse_btn.clicked.connect(self._on_sync_browse) - layout.addWidget(browse_btn, 0, 2) self._sync_btn = self._tr(QPushButton(), "rd_webrtc_sync_start") self._sync_btn.setCheckable(True) self._sync_btn.clicked.connect(self._on_toggle_sync) - layout.addWidget(self._sync_btn, 0, 3) - group.setLayout(layout) + form.addRow(self._tr(QLabel(), "rd_webrtc_sync_dir"), _row(self._sync_dir_edit, browse_btn, self._sync_btn)) + group.setLayout(form) return group def _build_remote_files_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_remote_files_group") layout = QVBoxLayout() - button_row = QHBoxLayout() refresh_btn = self._tr(QPushButton(), "rd_webrtc_browse_refresh") refresh_btn.clicked.connect(self._on_browse_refresh) - button_row.addWidget(refresh_btn) pull_btn = self._tr(QPushButton(), "rd_webrtc_browse_pull") pull_btn.clicked.connect(self._on_browse_pull_button) - button_row.addWidget(pull_btn) delete_btn = self._tr(QPushButton(), "rd_webrtc_browse_delete") delete_btn.clicked.connect(self._on_browse_delete_button) - button_row.addWidget(delete_btn) - button_row.addStretch() - layout.addLayout(button_row) + layout.addLayout(flow_of(refresh_btn, pull_btn, delete_btn, spacing=8)) self._remote_files_table = RemoteFilesTable() self._remote_files_table.pull_requested.connect(self._on_pull_names) self._remote_files_table.delete_requested.connect(self._on_delete_names) @@ -164,7 +159,10 @@ def _build_remote_files_group(self) -> QGroupBox: self._on_copy_name, ) layout.addWidget(self._remote_files_table) - layout.addWidget(self._tr(QLabel(), "rd_webrtc_browse_dnd_hint")) + dnd_hint = self._tr(QLabel(), "rd_webrtc_browse_dnd_hint") + dnd_hint.setWordWrap(True) + set_role(dnd_hint, "hint") + layout.addWidget(dnd_hint) group.setLayout(layout) return group @@ -192,15 +190,14 @@ def _build_address_book_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_address_book_group") layout = QVBoxLayout() # Tag filter row - tag_row = QHBoxLayout() - tag_row.addWidget(self._tr(QLabel(), "rd_webrtc_tag_filter")) self._tag_filter_combo = QComboBox() self._tag_filter_combo.addItem(_t("rd_webrtc_tag_all"), "") self._tag_filter_combo.currentIndexChanged.connect( lambda _i: self._refresh_address_book(), ) - tag_row.addWidget(self._tag_filter_combo, stretch=1) - layout.addLayout(tag_row) + tag_form = QFormLayout() + tag_form.addRow(self._tr(QLabel(), "rd_webrtc_tag_filter"), self._tag_filter_combo) + layout.addLayout(tag_form) self._address_list = AddressBookList() self._address_list.chosen.connect(self._on_address_chosen) self._address_list.deleted.connect(self._on_address_removed) @@ -208,65 +205,52 @@ def _build_address_book_group(self) -> QGroupBox: self._address_list.tags_edit_requested.connect(self._on_address_tags) self._address_list.setMaximumHeight(120) layout.addWidget(self._address_list) - button_row = QHBoxLayout() - connect_btn = self._tr(QPushButton(), "rd_webrtc_connect_selected") - connect_btn.clicked.connect(self._on_connect_selected_address) - button_row.addWidget(connect_btn) - save_btn = self._tr(QPushButton(), "rd_webrtc_save_current") - save_btn.clicked.connect(self._on_save_current_address) - button_row.addWidget(save_btn) - remove_btn = self._tr(QPushButton(), "rd_webrtc_remove_selected") - remove_btn.clicked.connect(self._on_remove_selected_address) - button_row.addWidget(remove_btn) - kh_btn = self._tr(QPushButton(), "rd_webrtc_manage_known_hosts") - kh_btn.clicked.connect(self._on_manage_known_hosts) - button_row.addWidget(kh_btn) - ab_export = self._tr(QPushButton(), "rd_webrtc_ab_export") - ab_export.clicked.connect(self._on_ab_export) - button_row.addWidget(ab_export) - ab_import = self._tr(QPushButton(), "rd_webrtc_ab_import") - ab_import.clicked.connect(self._on_ab_import) - button_row.addWidget(ab_import) - ab_clear = self._tr(QPushButton(), "rd_webrtc_ab_clear") - ab_clear.clicked.connect(self._on_ab_clear) - button_row.addWidget(ab_clear) - layout.addLayout(button_row) + buttons = [] + for key, slot in ( + ("rd_webrtc_connect_selected", self._on_connect_selected_address), + ("rd_webrtc_save_current", self._on_save_current_address), + ("rd_webrtc_remove_selected", self._on_remove_selected_address), + ("rd_webrtc_manage_known_hosts", self._on_manage_known_hosts), + ("rd_webrtc_ab_export", self._on_ab_export), + ("rd_webrtc_ab_import", self._on_ab_import), + ("rd_webrtc_ab_clear", self._on_ab_clear), + ): + button = self._tr(QPushButton(), key) + button.clicked.connect(slot) + buttons.append(button) + layout.addLayout(flow_of(*buttons, spacing=8)) group.setLayout(layout) return group def _build_signaling_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_signaling_group") - grid = QGridLayout() - grid.addWidget(self._tr(QLabel(), "rd_webrtc_server_label"), 0, 0) + form = QFormLayout() self._server_edit = QLineEdit(_DEFAULT_SIGNALING_URL) - grid.addWidget(self._server_edit, 0, 1, 1, 3) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_host_id_label"), 1, 0) + form.addRow(self._tr(QLabel(), "rd_webrtc_server_label"), self._server_edit) self._host_id_edit = self._tr(QLineEdit(), "rd_webrtc_host_id_placeholder") - grid.addWidget(self._host_id_edit, 1, 1, 1, 3) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_secret_label"), 2, 0) + form.addRow(self._tr(QLabel(), "rd_webrtc_host_id_label"), self._host_id_edit) self._secret_edit = QLineEdit() self._secret_edit.setEchoMode(QLineEdit.EchoMode.Password) - grid.addWidget(self._secret_edit, 2, 1, 1, 3) + form.addRow(self._tr(QLabel(), "rd_webrtc_secret_label"), self._secret_edit) self._connect_btn = self._tr(QPushButton(), "rd_webrtc_connect_via_server") self._connect_btn.clicked.connect(self._on_connect_via_server) - grid.addWidget(self._connect_btn, 3, 0, 1, 3) self._lan_browse_btn = self._tr(QPushButton(), "rd_webrtc_lan_browse") self._lan_browse_btn.clicked.connect(self._on_lan_browse) - grid.addWidget(self._lan_browse_btn, 3, 3) - group.setLayout(grid) + form.addRow(_row(self._connect_btn, self._lan_browse_btn)) + group.setLayout(form) return group def _build_config_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_config_group") - grid = QGridLayout() - grid.addWidget(self._tr(QLabel(), "rd_token_label"), 0, 0) + layout = QVBoxLayout() + form = QFormLayout() self._token_edit = self._tr(QLineEdit(), "rd_token_placeholder") - grid.addWidget(self._token_edit, 0, 1) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_bandwidth_label"), 1, 0) + form.addRow(self._tr(QLabel(), "rd_token_label"), self._token_edit) self._bandwidth_combo = QComboBox() for key, info in BANDWIDTH_PRESETS.items(): self._bandwidth_combo.addItem(info["label"], key) - grid.addWidget(self._bandwidth_combo, 1, 1) + form.addRow(self._tr(QLabel(), "rd_webrtc_bandwidth_label"), self._bandwidth_combo) + layout.addLayout(form) self._share_my_screen_check = self._tr( QCheckBox(), "rd_webrtc_share_my_screen", ) @@ -274,7 +258,7 @@ def _build_config_group(self) -> QGroupBox: self._share_my_screen_check.toggled.connect( self._on_toggle_share_my_screen, ) - grid.addWidget(self._share_my_screen_check, 2, 0, 1, 2) + layout.addWidget(self._share_my_screen_check) self._share_opus_mic_check = self._tr( QCheckBox(), "rd_webrtc_share_opus_mic", ) @@ -282,47 +266,43 @@ def _build_config_group(self) -> QGroupBox: self._share_opus_mic_check.toggled.connect( self._on_toggle_share_opus_mic, ) - grid.addWidget(self._share_opus_mic_check, 3, 0, 1, 2) + layout.addWidget(self._share_opus_mic_check) self._auto_reconnect_check = self._tr( QCheckBox(), "rd_webrtc_auto_reconnect", ) self._auto_reconnect_check.setChecked(False) - grid.addWidget(self._auto_reconnect_check, 4, 0, 1, 2) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_reconnect_max"), 5, 0) + layout.addWidget(self._auto_reconnect_check) self._reconnect_max_spin = QSpinBox() self._reconnect_max_spin.setRange(1, 50) self._reconnect_max_spin.setValue(5) - grid.addWidget(self._reconnect_max_spin, 5, 1) - grid.addWidget(self._tr(QLabel(), "rd_webrtc_reconnect_delay"), 6, 0) self._reconnect_delay_spin = QSpinBox() self._reconnect_delay_spin.setRange(1, 60) self._reconnect_delay_spin.setValue(1) self._reconnect_delay_spin.setSuffix(" s") - grid.addWidget(self._reconnect_delay_spin, 6, 1) - group.setLayout(grid) + layout.addLayout(flow_of( + field_pair(self._tr(QLabel(), "rd_webrtc_reconnect_max"), self._reconnect_max_spin), + field_pair(self._tr(QLabel(), "rd_webrtc_reconnect_delay"), self._reconnect_delay_spin))) + group.setLayout(layout) return group def _build_manual_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rd_webrtc_manual_group") layout = QVBoxLayout() - layout.addWidget(self._tr(QLabel(), "rd_webrtc_offer_input_label")) self._offer_input = QTextEdit() self._offer_input.setMinimumHeight(80) self._tr(self._offer_input, "rd_webrtc_paste_offer", "setPlaceholderText") - layout.addWidget(self._offer_input) - button_row = QHBoxLayout() + self._answer_view = QTextEdit() + self._answer_view.setReadOnly(True) + self._answer_view.setMinimumHeight(80) + # The host's offer goes in on the left, this side's answer comes out on the right. + layout.addWidget(ResponsiveBox( + _pane(self._tr(QLabel(), "rd_webrtc_offer_input_label"), self._offer_input), + _pane(self._tr(QLabel(), "rd_webrtc_answer_label"), self._answer_view))) self._answer_btn = self._tr(QPushButton(), "rd_webrtc_create_answer") self._answer_btn.clicked.connect(self._on_create_answer) - button_row.addWidget(self._answer_btn) self._stop_btn = self._tr(QPushButton(), "rd_webrtc_stop_viewer") self._stop_btn.clicked.connect(self._on_stop) - button_row.addWidget(self._stop_btn) - layout.addLayout(button_row) - layout.addWidget(self._tr(QLabel(), "rd_webrtc_answer_label")) - self._answer_view = QTextEdit() - self._answer_view.setReadOnly(True) - self._answer_view.setMinimumHeight(80) - layout.addWidget(self._answer_view) + layout.addLayout(flow_of(self._answer_btn, self._stop_btn)) group.setLayout(layout) return group diff --git a/je_auto_control/gui/rest_api_tab.py b/je_auto_control/gui/rest_api_tab.py index e79c059ed..a37567061 100644 --- a/je_auto_control/gui/rest_api_tab.py +++ b/je_auto_control/gui/rest_api_tab.py @@ -14,13 +14,16 @@ from PySide6.QtCore import Qt, QTimer from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import ( - QCheckBox, QFileDialog, QGroupBox, QHBoxLayout, QLabel, QLineEdit, + QCheckBox, QFileDialog, QFormLayout, QGroupBox, QLabel, QLineEdit, QMessageBox, QSpinBox, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -72,8 +75,8 @@ def _build_layout(self) -> None: # Start/stop/copy/export/import commands run from the Actions # menu; the tab keeps only the config inputs and the status group. root = QVBoxLayout(self) - root.addWidget(self._build_config_group()) - root.addWidget(self._build_status_group()) + root.setSpacing(12) + root.addWidget(ResponsiveBox(self._build_config_group(), self._build_status_group())) root.addWidget(self._users_panel, stretch=1) def menu_actions(self) -> list: @@ -103,19 +106,14 @@ def retranslate(self) -> None: def _build_config_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rest_config_group") - form = QVBoxLayout(group) - addr_row = QHBoxLayout() - addr_row.addWidget(self._tr(QLabel(), "rest_host")) - addr_row.addWidget(self._host_input, stretch=1) - addr_row.addWidget(self._tr(QLabel(), "rest_port")) - addr_row.addWidget(self._port_input) - form.addLayout(addr_row) - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "rest_token")) - token_row.addWidget(self._token_input, stretch=1) - form.addLayout(token_row) + layout = QVBoxLayout(group) + layout.addLayout(flow_of(field_pair(self._tr(QLabel(), "rest_host"), self._host_input), + field_pair(self._tr(QLabel(), "rest_port"), self._port_input))) + form = QFormLayout() + form.addRow(self._tr(QLabel(), "rest_token"), self._token_input) + layout.addLayout(form) self._tr(self._audit_check, "rest_enable_audit") - form.addWidget(self._audit_check) + layout.addWidget(self._audit_check) return group def _on_config_export(self) -> None: @@ -173,16 +171,14 @@ def _on_config_import(self) -> None: def _build_status_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "rest_status_group") - form = QVBoxLayout(group) - url_row = QHBoxLayout() - url_row.addWidget(self._tr(QLabel(), "rest_url")) - url_row.addWidget(self._url_value, stretch=1) - form.addLayout(url_row) - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "rest_active_token")) - token_row.addWidget(self._token_value, stretch=1) - form.addLayout(token_row) - form.addWidget(self._status_label) + layout = QVBoxLayout(group) + form = QFormLayout() + form.addRow(self._tr(QLabel(), "rest_url"), self._url_value) + form.addRow(self._tr(QLabel(), "rest_active_token"), self._token_value) + layout.addLayout(form) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") + layout.addWidget(self._status_label) return group def _on_start(self) -> None: diff --git a/je_auto_control/gui/run_history_tab.py b/je_auto_control/gui/run_history_tab.py index 5fd5cfbdb..42b439dda 100644 --- a/je_auto_control/gui/run_history_tab.py +++ b/je_auto_control/gui/run_history_tab.py @@ -6,12 +6,15 @@ from PySide6.QtCore import QTimer, Qt, QUrl from PySide6.QtGui import QCloseEvent, QDesktopServices, QPixmap from PySide6.QtWidgets import ( - QAbstractItemView, QComboBox, QFrame, QHBoxLayout, QHeaderView, QLabel, + QAbstractItemView, QComboBox, QFrame, QHeaderView, QLabel, QMessageBox, QSplitter, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -147,36 +150,30 @@ def _build_layout(self) -> None: # Refresh/clear/open-artifact commands run from the Actions menu; # the tab keeps only the filter, timeline, table, and preview. root = QVBoxLayout(self) - top = QHBoxLayout() - top.addWidget(self._tr(QLabel(), "rh_filter_label")) - top.addWidget(self._filter) - top.addStretch() - root.addLayout(top) - - timeline_label = self._tr(QLabel(), "rh_timeline_heading") - root.addWidget(timeline_label) - root.addWidget(self._timeline) - - splitter = QSplitter(Qt.Orientation.Horizontal) - splitter.addWidget(self._table) - preview = QWidget() - preview_layout = QVBoxLayout(preview) - preview_layout.setContentsMargins(0, 0, 0, 0) - preview_layout.addWidget(self._tr(QLabel(), "rh_preview_heading")) - preview_layout.addWidget(self._thumb_label, stretch=1) - preview_layout.addWidget(self._thumb_caption) - splitter.addWidget(preview) - splitter.setStretchFactor(0, 3) - splitter.setStretchFactor(1, 1) + root.setSpacing(12) + root.addWidget(Card().add(flow_of(field_pair(self._tr(QLabel(), "rh_filter_label"), self._filter)))) + + timeline_label = set_role(self._tr(QLabel(), "rh_timeline_heading"), "sectionTitle") + root.addWidget(Card().add(timeline_label).add(self._timeline)) + + preview = Card().add(set_role(self._tr(QLabel(), "rh_preview_heading"), "sectionTitle")) + preview.add(self._thumb_label, stretch=1).add(self._thumb_caption) + # Stacked under a narrow window the table would otherwise shrink to its header. + self._table.setMinimumHeight(200) + runs = ResponsiveBox(Card().add(self._table, stretch=1), preview, stretches=(3, 1)) + # The journal browser is shared with Self-Healing; tag it so it shows the card behind it. + self._journal.setProperty("role", "bare") sections = QSplitter(Qt.Orientation.Vertical) - sections.addWidget(splitter) - sections.addWidget(self._journal) + sections.addWidget(runs) + sections.addWidget(Card().add(self._journal, stretch=1)) sections.setStretchFactor(0, 1) sections.setStretchFactor(1, 1) root.addWidget(sections, stretch=1) self._table.cellDoubleClicked.connect(self._on_cell_double_clicked) self._table.itemSelectionChanged.connect(self._on_selection_changed) + self._count_label.setWordWrap(True) + set_role(self._count_label, "hint") root.addWidget(self._count_label) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/scheduler_tab.py b/je_auto_control/gui/scheduler_tab.py index 4e60ded70..c7031febd 100644 --- a/je_auto_control/gui/scheduler_tab.py +++ b/je_auto_control/gui/scheduler_tab.py @@ -3,7 +3,7 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QCheckBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, QMessageBox, + QCheckBox, QFileDialog, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -11,6 +11,8 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui._qt_typed import filled_item +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -90,15 +92,14 @@ def _build_layout(self) -> None: # Browse/add/remove/start/stop commands run from the Actions menu; # the tab keeps only the inputs, the jobs table, and the status. root = QVBoxLayout(self) - form = QHBoxLayout() - form.addWidget(self._tr(QLabel(), "sch_script_label")) - form.addWidget(self._path_input, stretch=1) - form.addWidget(self._tr(QLabel(), "sch_interval_label")) - form.addWidget(self._interval_input) - form.addWidget(self._repeat_check) - root.addLayout(form) - - root.addWidget(self._table, stretch=1) + root.setSpacing(12) + inputs = Card().add(field_pair(self._tr(QLabel(), "sch_script_label"), self._path_input)) + inputs.add(flow_of(field_pair(self._tr(QLabel(), "sch_interval_label"), self._interval_input), + self._repeat_check)) + root.addWidget(inputs) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/script_builder/builder_tab.py b/je_auto_control/gui/script_builder/builder_tab.py index fc8a19f58..00c44fd9d 100644 --- a/je_auto_control/gui/script_builder/builder_tab.py +++ b/je_auto_control/gui/script_builder/builder_tab.py @@ -20,11 +20,13 @@ from PySide6.QtCore import Qt from PySide6.QtGui import QAction, QCloseEvent from PySide6.QtWidgets import ( - QFileDialog, QHBoxLayout, QMenu, QMessageBox, QPushButton, QSplitter, + QFileDialog, QMenu, QMessageBox, QPushButton, QSplitter, QTextEdit, QToolButton, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources +from je_auto_control.gui.adaptive.flow_layout import FlowLayout, flow_of +from je_auto_control.gui.adaptive.surfaces import Card from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.manual_run_controls import ManualRunControls, _requested_manual_run from je_auto_control.gui._tab_task import TabTask, was_stopped @@ -63,6 +65,15 @@ def _run_actions(actions: list, collector: OneTimeCollector, return execute_action(actions, result_callback=collector.note) +def _button_group(buttons: Sequence[QWidget]) -> QWidget: + """A bare container whose buttons wrap onto further lines when the row is too narrow.""" + group = QWidget() + group.setProperty("role", "bare") + flow = flow_of(*buttons, spacing=8) + group.setLayout(flow) + return group + + class ScriptBuilderTab(TranslatableMixin, QWidget): """Visual editor for composing AC_* scripts.""" @@ -111,19 +122,21 @@ def retranslate(self) -> None: self._form.retranslate() def _build_layout(self) -> None: + # The step list and the step form keep their user-resizable splitter; + # each side may shrink small, so the page fits a compact window. root = QVBoxLayout(self) - root.addLayout(self._build_toolbar()) - root.addWidget(self._capture) + root.setSpacing(12) + root.addWidget(Card().add(self._build_toolbar()).add(self._capture)) splitter = QSplitter(Qt.Orientation.Horizontal) splitter.addWidget(self._tree) splitter.addWidget(self._form) splitter.setSizes([320, 480]) - root.addWidget(splitter, stretch=1) - root.addWidget(self._result) + root.addWidget(Card().add(splitter, stretch=1), stretch=1) + root.addWidget(Card().add(self._result)) - def _build_toolbar(self) -> QHBoxLayout: - bar = QHBoxLayout() - bar.addWidget(self._add_button()) + def _build_toolbar(self) -> FlowLayout: + """Two wrapping button groups: editing the steps, and the file and run commands.""" + edit_buttons: List[QWidget] = [self._add_button()] for key, handler in ( ("sb_delete", self._on_delete), ("sb_up", lambda: self._tree.move_selected(-1)), @@ -131,8 +144,8 @@ def _build_toolbar(self) -> QHBoxLayout: ): btn = self._tr(QPushButton(), key) btn.clicked.connect(handler) - bar.addWidget(btn) - bar.addStretch() + edit_buttons.append(btn) + run_buttons: List[QWidget] = [] for key, handler in ( ("sb_load_json", self._on_load), ("sb_save_json", self._on_save), @@ -141,12 +154,12 @@ def _build_toolbar(self) -> QHBoxLayout: ): btn = self._tr(QPushButton(), key) btn.clicked.connect(handler) - bar.addWidget(btn) + run_buttons.append(btn) self._tr(self._reveal_btn, "sb_one_time_show") self._reveal_btn.setEnabled(False) self._reveal_btn.clicked.connect(self._on_reveal) - bar.addWidget(self._reveal_btn) - return bar + run_buttons.append(self._reveal_btn) + return flow_of(_button_group(edit_buttons), _button_group(run_buttons), spacing=16) def _add_button(self) -> QToolButton: button = QToolButton() diff --git a/je_auto_control/gui/script_builder/step_form_view.py b/je_auto_control/gui/script_builder/step_form_view.py index 3eca0b2d2..c2ebf7e0e 100644 --- a/je_auto_control/gui/script_builder/step_form_view.py +++ b/je_auto_control/gui/script_builder/step_form_view.py @@ -48,8 +48,11 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: # one at a time — so without this each setText() commits a half-filled # form, overwriting params from fields that have not been set yet. self._populating = False + # Sits on the Script Builder's card: paint nothing of its own. + self.setProperty("role", "bare") self._layout = QFormLayout(self) self._title = _plain_label(_t("sb_no_step_selected")) + self._title.setWordWrap(True) self._layout.addRow(self._title) def retranslate(self) -> None: @@ -136,6 +139,7 @@ def _build_enum(self, spec: FieldSpec) -> QWidget: def _build_file(self, spec: FieldSpec) -> QWidget: container = QWidget() + container.setProperty("role", "bare") row = QHBoxLayout(container) row.setContentsMargins(0, 0, 0, 0) line = QLineEdit() diff --git a/je_auto_control/gui/secrets_tab.py b/je_auto_control/gui/secrets_tab.py index d80d430cf..9e58c8146 100644 --- a/je_auto_control/gui/secrets_tab.py +++ b/je_auto_control/gui/secrets_tab.py @@ -2,12 +2,13 @@ from typing import Optional from PySide6.QtWidgets import ( - QAbstractItemView, QGroupBox, QHBoxLayout, QInputDialog, QLabel, + QAbstractItemView, QFormLayout, QGroupBox, QInputDialog, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -43,11 +44,11 @@ def _build_layout(self) -> None: # run from the Actions menu; the tab keeps only passphrase input, # the entry list, and the status line. root = QVBoxLayout(self) + root.setSpacing(12) unlock_box = self._tr(QGroupBox(), "secret_unlock_group") - unlock_layout = QHBoxLayout(unlock_box) - unlock_layout.addWidget(self._tr(QLabel(), "secret_passphrase_label")) + unlock_layout = QFormLayout(unlock_box) self._passphrase.setPlaceholderText(_t("secret_passphrase_placeholder")) - unlock_layout.addWidget(self._passphrase) + unlock_layout.addRow(self._tr(QLabel(), "secret_passphrase_label"), self._passphrase) root.addWidget(unlock_box) manage_box = self._tr(QGroupBox(), "secret_manage_group") @@ -55,6 +56,8 @@ def _build_layout(self) -> None: manage_layout.addWidget(self._list) root.addWidget(manage_box, stretch=1) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") root.addWidget(self._status_label) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/self_healing_tab.py b/je_auto_control/gui/self_healing_tab.py index 93b0fd08f..57b316500 100644 --- a/je_auto_control/gui/self_healing_tab.py +++ b/je_auto_control/gui/self_healing_tab.py @@ -15,6 +15,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.healing_evaluation_panel import HealingEvaluationPanel from je_auto_control.gui.journal_browser import JournalBrowser from je_auto_control.gui.template_candidate_panel import TemplateCandidatePanel @@ -88,13 +89,18 @@ def _build_layout(self) -> None: # Browse/locate/click/refresh/clear commands run from the Actions # menu; the tab keeps only the inputs, the log table, and the status. root = QVBoxLayout(self) + root.setSpacing(12) runtime = QWidget() + runtime.setProperty("role", "bare") runtime_layout = QVBoxLayout(runtime) + runtime_layout.setSpacing(12) runtime_layout.addWidget(self._build_form_group()) views = QSplitter(Qt.Orientation.Vertical) views.addWidget(self._table) views.addWidget(self._details) - runtime_layout.addWidget(views, stretch=1) + runtime_layout.addWidget(Card().add(views, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") runtime_layout.addWidget(self._status) self._views = QTabWidget() self._evaluation = HealingEvaluationPanel(self) diff --git a/je_auto_control/gui/test_suite_tab.py b/je_auto_control/gui/test_suite_tab.py index d59560857..9aaf05896 100644 --- a/je_auto_control/gui/test_suite_tab.py +++ b/je_auto_control/gui/test_suite_tab.py @@ -18,6 +18,8 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask, was_stopped +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -73,12 +75,13 @@ def _build_layout(self) -> None: # Load/run/export and quarantine commands run from the Actions # menu; the tab keeps only the spec editor, tables, and summary. root = QVBoxLayout(self) - root.addWidget(QLabel(_t("suite_spec_label"))) - root.addWidget(self._spec, stretch=1) - root.addWidget(self._table, stretch=2) - root.addWidget(self._summary) - root.addWidget(QLabel(_t("suite_q_label"))) - root.addWidget(self._quarantine) + root.setSpacing(12) + root.addWidget(Card("suite_spec_label").add(self._spec, stretch=1), stretch=1) + self._summary.setWordWrap(True) + set_role(self._summary, "hint") + results = Card().add(self._table, stretch=1).add(self._summary) + quarantine = Card("suite_q_label").add(self._quarantine, stretch=1) + root.addWidget(ResponsiveBox(results, quarantine, stretches=(2, 1)), stretch=2) def dispose(self) -> None: """Release what the tab holds beyond its widgets: the command still running in the background. diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index c53ab0f07..f3ee7c1b4 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -134,13 +134,14 @@ def type_scale_rules(point_size: int) -> str: border-bottom: 1px solid {border}; padding: {half}px {spacing}px; }} QTableCornerButton::section {{ background-color: {surface_raised}; border: 0; }} -QGroupBox {{ border: 1px solid {border}; border-radius: {radius_large}px; margin-top: 1.7em; - padding: {half}px {half}px {half}px {half}px; background-color: {surface}; font-weight: 600; }} -QGroupBox::title {{ subcontrol-origin: margin; subcontrol-position: top left; left: {small}px; top: 0; +QGroupBox {{ border: 1px solid {border}; border-radius: {radius_large}px; margin-top: 0; + padding: 2.3em {spacing}px {spacing}px {spacing}px; background-color: {surface}; font-weight: 600; }} +QGroupBox::title {{ subcontrol-origin: padding; subcontrol-position: top left; left: {wide}px; top: {spacing}px; padding: 0; color: {text}; background: transparent; }} QGroupBox QLabel, QGroupBox QCheckBox, QGroupBox QRadioButton, QGroupBox QPushButton, QGroupBox QLineEdit, QGroupBox QComboBox, QGroupBox QAbstractItemView {{ font-weight: normal; }} QFrame[role="card"] {{ background-color: {surface}; border: 1px solid {border}; border-radius: {radius_large}px; }} +QWidget[role="bare"] {{ background: transparent; }} QLabel[role="pageTitle"] {{ font-weight: 600; color: {text}; }} QLabel[role="pageSubtitle"], QLabel[role="hint"] {{ color: {text_muted}; }} QLabel[role="sectionTitle"] {{ font-weight: 600; color: {text}; }} diff --git a/je_auto_control/gui/trace_replay_tab.py b/je_auto_control/gui/trace_replay_tab.py index b4d3fcbe6..203496b73 100644 --- a/je_auto_control/gui/trace_replay_tab.py +++ b/je_auto_control/gui/trace_replay_tab.py @@ -13,10 +13,12 @@ from PySide6.QtGui import QPixmap from PySide6.QtWidgets import ( QFileDialog, QLabel, QMessageBox, QSlider, - QSplitter, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, + QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -62,13 +64,13 @@ def _build_layout(self) -> None: # Open/first/prev/next/last commands run from the Actions menu; # the tab keeps only the slider, frame, table, and status. root = QVBoxLayout(self) - root.addWidget(self._slider) - splitter = QSplitter(Qt.Orientation.Horizontal) - splitter.addWidget(self._frame_label) - splitter.addWidget(self._actions_table) - splitter.setStretchFactor(0, 3) - splitter.setStretchFactor(1, 1) - root.addWidget(splitter, stretch=1) + root.setSpacing(12) + root.addWidget(Card().add(self._slider)) + frame = Card().add(self._frame_label, stretch=1) + actions = Card().add(self._actions_table, stretch=1) + root.addWidget(ResponsiveBox(frame, actions, stretches=(3, 2)), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) self._apply_translations() diff --git a/je_auto_control/gui/triggers_tab.py b/je_auto_control/gui/triggers_tab.py index 2954f7253..8247417cc 100644 --- a/je_auto_control/gui/triggers_tab.py +++ b/je_auto_control/gui/triggers_tab.py @@ -3,7 +3,7 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, + QCheckBox, QComboBox, QFileDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QStackedWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -11,6 +11,8 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -145,17 +147,36 @@ def _build_layout(self) -> None: # Browse/add/remove/combine/start/stop commands run from the Actions # menu; the tab keeps only the inputs, the table, and the status. root = QVBoxLayout(self) - form_top = QHBoxLayout() - form_top.addWidget(self._tr(QLabel(), "tr_script_label")) - form_top.addWidget(self._script_input, stretch=1) - form_top.addWidget(self._repeat_check) - form_top.addWidget(self._tr(QLabel(), "tr_type_label")) - form_top.addWidget(self._type_combo) - root.addLayout(form_top) - root.addWidget(self._stack) - root.addWidget(self._table, stretch=1) + root.setSpacing(12) + self._stack.setProperty("role", "bare") + options = flow_of(self._repeat_check, + field_pair(self._tr(QLabel(), "tr_type_label"), self._type_combo)) + inputs = Card().add(self._field_row("tr_script_label", self._script_input)) + root.addWidget(inputs.add(options).add(self._stack)) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) + def _field_row(self, label_key: str, field: QWidget, + button: Optional[QWidget] = None) -> QWidget: + """A label, a field taking the rest of the line, and an optional button after it.""" + row = field_pair(self._tr(QLabel(), label_key), field) + layout = row.layout() + if button is not None and layout is not None: + layout.addWidget(button) + return row + + def _add_page(self, *rows: QWidget) -> None: + """Stack one trigger type's inputs, one row under another, as a page of the type stack.""" + page = QWidget() + page.setProperty("role", "bare") + layout = QVBoxLayout(page) + layout.setContentsMargins(0, 0, 0, 0) + for row in rows: + layout.addWidget(row) + self._stack.addWidget(page) + def menu_actions(self) -> list: """Expose tab commands to the window-level Actions menu.""" return [ @@ -170,57 +191,42 @@ def menu_actions(self) -> list: ] def _build_image_form(self) -> dict: - widget = QWidget() - layout = QHBoxLayout(widget) path_input = QLineEdit() threshold_input = QLineEdit("0.8") browse = self._tr(QPushButton(), "browse") browse.clicked.connect(lambda: self._browse_image(path_input)) - layout.addWidget(self._tr(QLabel(), "tr_image_label")) - layout.addWidget(path_input, stretch=1) - layout.addWidget(browse) - layout.addWidget(self._tr(QLabel(), "tr_threshold_label")) - layout.addWidget(threshold_input) - self._stack.addWidget(widget) + threshold = QWidget() + threshold.setProperty("role", "bare") + threshold.setLayout(flow_of(field_pair(self._tr(QLabel(), "tr_threshold_label"), threshold_input))) + self._add_page(self._field_row("tr_image_label", path_input, browse), threshold) return {"path": path_input, "threshold": threshold_input} def _build_window_form(self) -> dict: - widget = QWidget() - layout = QHBoxLayout(widget) title_input = QLineEdit() - layout.addWidget(self._tr(QLabel(), "tr_title_contains_label")) - layout.addWidget(title_input, stretch=1) - self._stack.addWidget(widget) + self._add_page(self._field_row("tr_title_contains_label", title_input)) return {"title": title_input} def _build_pixel_form(self) -> dict: - widget = QWidget() - layout = QHBoxLayout(widget) x_input = QLineEdit("0") y_input = QLineEdit("0") r_input = QLineEdit("0") g_input = QLineEdit("0") b_input = QLineEdit("0") tol_input = QLineEdit("8") - for label, field in (("X:", x_input), ("Y:", y_input), - ("R:", r_input), ("G:", g_input), ("B:", b_input), - ("\u00b1:", tol_input)): - layout.addWidget(QLabel(label)) - layout.addWidget(field) - self._stack.addWidget(widget) + channels = QWidget() + channels.setProperty("role", "bare") + channels.setLayout(flow_of(*(field_pair(QLabel(label), field) for label, field in ( + ("X:", x_input), ("Y:", y_input), ("R:", r_input), ("G:", g_input), + ("B:", b_input), ("\u00b1:", tol_input))))) + self._add_page(channels) return {"x": x_input, "y": y_input, "r": r_input, "g": g_input, "b": b_input, "tol": tol_input} def _build_file_form(self) -> dict: - widget = QWidget() - layout = QHBoxLayout(widget) path_input = QLineEdit() browse = self._tr(QPushButton(), "browse") browse.clicked.connect(lambda: self._browse_watch(path_input)) - layout.addWidget(self._tr(QLabel(), "tr_watch_label")) - layout.addWidget(path_input, stretch=1) - layout.addWidget(browse) - self._stack.addWidget(widget) + self._add_page(self._field_row("tr_watch_label", path_input, browse)) return {"path": path_input} def _browse_script(self) -> None: @@ -283,12 +289,8 @@ def _build_trigger(self, script: str): ) def _build_cron_form(self) -> dict: - widget = QWidget() - layout = QHBoxLayout(widget) cron_input = QLineEdit("* * * * *") - layout.addWidget(self._tr(QLabel(), "tr_cron_label")) - layout.addWidget(cron_input, stretch=1) - self._stack.addWidget(widget) + self._add_page(self._field_row("tr_cron_label", cron_input)) return {"cron": cron_input} def _build_pixel_trigger(self, common: _TriggerOptions): diff --git a/je_auto_control/gui/usb_browser_tab.py b/je_auto_control/gui/usb_browser_tab.py index 399ada297..8c8943d4f 100644 --- a/je_auto_control/gui/usb_browser_tab.py +++ b/je_auto_control/gui/usb_browser_tab.py @@ -24,13 +24,14 @@ from PySide6.QtCore import QObject, Signal from PySide6.QtWidgets import ( - QGroupBox, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QMessageBox, + QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import CallWorker as _CallWorker, WorkerHandle, start_worker +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -157,11 +158,14 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: def _build_layout(self) -> None: # Fetch/open commands run from the Actions menu; the tab keeps - # only the target inputs, the status line, and the device table. + # only the target inputs, the device table, and the status line. root = QVBoxLayout(self) + root.setSpacing(12) root.addWidget(self._build_target_group()) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") root.addWidget(self._status_label) - root.addWidget(self._table, stretch=1) def dispose(self) -> None: """Release what the tab holds beyond its widgets: the device listing or open still out, whose answer is dropped. @@ -180,15 +184,9 @@ def menu_actions(self) -> list: def _build_target_group(self) -> QGroupBox: group = self._tr(QGroupBox(), "usb_browser_target_group") - form = QVBoxLayout(group) - url_row = QHBoxLayout() - url_row.addWidget(self._tr(QLabel(), "usb_browser_url")) - url_row.addWidget(self._url_input, stretch=1) - form.addLayout(url_row) - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "usb_browser_token")) - token_row.addWidget(self._token_input, stretch=1) - form.addLayout(token_row) + form = QFormLayout(group) + form.addRow(self._tr(QLabel(), "usb_browser_url"), self._url_input) + form.addRow(self._tr(QLabel(), "usb_browser_token"), self._token_input) return group def _apply_table_headers(self) -> None: diff --git a/je_auto_control/gui/usb_devices_tab.py b/je_auto_control/gui/usb_devices_tab.py index 45259bc05..1c4d9a8a8 100644 --- a/je_auto_control/gui/usb_devices_tab.py +++ b/je_auto_control/gui/usb_devices_tab.py @@ -3,13 +3,15 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QCheckBox, QHBoxLayout, QHeaderView, QLabel, QTableWidget, + QCheckBox, QHeaderView, QLabel, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -54,18 +56,18 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: def _build_layout(self) -> None: # The refresh command runs from the Actions menu; the tab keeps - # only the backend labels, the auto-refresh toggle, and the table. + # only the backend labels, the auto-refresh toggle, the table and the status lines. root = QVBoxLayout(self) - header = QHBoxLayout() - header.addWidget(self._tr(QLabel(), "usb_backend_label")) - header.addWidget(self._backend_label) - header.addStretch(1) + root.setSpacing(12) self._tr(self._auto_check, "usb_auto_refresh") - header.addWidget(self._auto_check) - root.addLayout(header) - root.addWidget(self._error_label) - root.addWidget(self._events_label) - root.addWidget(self._table, stretch=1) + root.addWidget(Card().add(flow_of( + field_pair(self._tr(QLabel(), "usb_backend_label"), self._backend_label), self._auto_check))) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + # Status lines under the table, like the other pages: empty most of the time. + for label, role in ((self._error_label, "danger"), (self._events_label, "hint")): + label.setWordWrap(True) + set_role(label, role) + root.addWidget(label) def dispose(self) -> None: """Release what the tab holds beyond its widgets: its hotplug timer and its share of the USB watcher. diff --git a/je_auto_control/gui/usb_passthrough_panel.py b/je_auto_control/gui/usb_passthrough_panel.py index 1a8520a2c..e9c553b5c 100644 --- a/je_auto_control/gui/usb_passthrough_panel.py +++ b/je_auto_control/gui/usb_passthrough_panel.py @@ -23,7 +23,7 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QCheckBox, QComboBox, QFileDialog, QGroupBox, QHBoxLayout, QHeaderView, + QCheckBox, QComboBox, QFileDialog, QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -32,6 +32,8 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui._worker_thread import CallWorker as _CallWorker, WorkerHandle, start_worker +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -127,11 +129,9 @@ def _default_loopback(self) -> UsbLoopback: def _build_layout(self) -> None: # Share/ACL/use/remote-fetch commands run from the Actions menu; # the panel keeps only the badge, tables, inputs, and status. - root = QHBoxLayout(self) - root.setContentsMargins(16, 16, 16, 16) - root.setSpacing(16) - root.addWidget(self._build_host_section(), stretch=1) - root.addWidget(self._build_viewer_section(), stretch=1) + root = QVBoxLayout(self) + root.setSpacing(12) + root.addWidget(ResponsiveBox(self._build_host_section(), self._build_viewer_section()), stretch=1) def menu_actions(self) -> list: """Expose tab commands to the window-level Actions menu.""" @@ -156,11 +156,8 @@ def _build_host_section(self) -> QWidget: layout.addWidget(self._host_badge) layout.addWidget(self._tr(QLabel(), "usb_share_local_devices")) layout.addWidget(self._local_table, stretch=1) - acl_row = QHBoxLayout() self._tr(self._auto_check, "usb_share_auto_refresh") - acl_row.addWidget(self._auto_check) - acl_row.addStretch(1) - layout.addLayout(acl_row) + layout.addWidget(self._auto_check) return group def _build_viewer_section(self) -> QWidget: @@ -171,11 +168,12 @@ def _build_viewer_section(self) -> QWidget: intro = self._tr(QLabel(), "usb_share_intro") intro.setWordWrap(True) layout.addWidget(intro) - source_row = QHBoxLayout() - source_row.addWidget(self._tr(QLabel(), "usb_share_source_label")) - source_row.addWidget(self._source_combo, stretch=1) - layout.addLayout(source_row) + source_form = QFormLayout() + source_form.addRow(self._tr(QLabel(), "usb_share_source_label"), self._source_combo) + layout.addLayout(source_form) layout.addWidget(self._shared_table, stretch=1) + self._viewer_status.setWordWrap(True) + set_role(self._viewer_status, "hint") layout.addWidget(self._viewer_status) layout.addWidget(self._build_remote_box()) return group @@ -183,15 +181,9 @@ def _build_viewer_section(self) -> QWidget: def _build_remote_box(self) -> QWidget: box = QGroupBox() self._tr(box, "usb_share_remote_group", setter="setTitle") - layout = QVBoxLayout(box) - url_row = QHBoxLayout() - url_row.addWidget(self._tr(QLabel(), "usb_share_remote_url")) - url_row.addWidget(self._remote_url, stretch=1) - layout.addLayout(url_row) - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "usb_share_remote_token")) - token_row.addWidget(self._remote_token, stretch=1) - layout.addLayout(token_row) + layout = QFormLayout(box) + layout.addRow(self._tr(QLabel(), "usb_share_remote_url"), self._remote_url) + layout.addRow(self._tr(QLabel(), "usb_share_remote_token"), self._remote_token) return box def _apply_local_headers(self) -> None: diff --git a/je_auto_control/gui/variables_tab.py b/je_auto_control/gui/variables_tab.py index adf19d1dc..046f40f5f 100644 --- a/je_auto_control/gui/variables_tab.py +++ b/je_auto_control/gui/variables_tab.py @@ -9,12 +9,13 @@ from typing import Optional from PySide6.QtWidgets import ( - QGroupBox, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QMessageBox, + QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -63,29 +64,29 @@ def _build_layout(self) -> None: # Refresh/clear/set/seed commands run from the Actions menu; the # tab keeps only the table, the inputs, and the status line. root = QVBoxLayout(self) + root.setSpacing(12) view_group = self._tr(QGroupBox(), "vars_current_group") view_layout = QVBoxLayout() self._update_table_headers() view_layout.addWidget(self._table) view_group.setLayout(view_layout) - root.addWidget(view_group) + root.addWidget(view_group, stretch=2) set_group = self._tr(QGroupBox(), "vars_set_group") - set_layout = QHBoxLayout() - set_layout.addWidget(self._tr(QLabel(), "vars_name_label")) - set_layout.addWidget(self._set_name, stretch=1) - set_layout.addWidget(self._tr(QLabel(), "vars_value_label")) - set_layout.addWidget(self._set_value, stretch=2) - set_group.setLayout(set_layout) + set_layout = QFormLayout(set_group) + set_layout.addRow(self._tr(QLabel(), "vars_name_label"), self._set_name) + set_layout.addRow(self._tr(QLabel(), "vars_value_label"), self._set_value) root.addWidget(set_group) seed_group = self._tr(QGroupBox(), "vars_seed_group") seed_layout = QVBoxLayout() seed_layout.addWidget(self._seed_text) seed_group.setLayout(seed_layout) - root.addWidget(seed_group) + root.addWidget(seed_group, stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/vlm_tab.py b/je_auto_control/gui/vlm_tab.py index 9248b4b65..42bf5e461 100644 --- a/je_auto_control/gui/vlm_tab.py +++ b/je_auto_control/gui/vlm_tab.py @@ -2,12 +2,13 @@ from typing import Optional from PySide6.QtWidgets import ( - QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget, + QFormLayout, QLabel, QLineEdit, QVBoxLayout, QWidget, ) from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -46,14 +47,14 @@ def _build_layout(self) -> None: # Locate/click commands run from the Actions menu; the tab keeps # only the description/model inputs and the result labels. root = QVBoxLayout(self) - desc_row = QHBoxLayout() - desc_row.addWidget(self._tr(QLabel(), "vlm_desc_label")) - desc_row.addWidget(self._description, stretch=1) - root.addLayout(desc_row) - model_row = QHBoxLayout() - model_row.addWidget(self._tr(QLabel(), "vlm_model_label")) - model_row.addWidget(self._model, stretch=1) - root.addLayout(model_row) + root.setSpacing(12) + form = QFormLayout() + form.addRow(self._tr(QLabel(), "vlm_desc_label"), self._description) + form.addRow(self._tr(QLabel(), "vlm_model_label"), self._model) + root.addWidget(Card().add(form)) + self._last_result.setWordWrap(True) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._last_result) root.addWidget(self._status) root.addStretch() diff --git a/je_auto_control/gui/webhooks_tab.py b/je_auto_control/gui/webhooks_tab.py index 1454973e8..e19b8bf62 100644 --- a/je_auto_control/gui/webhooks_tab.py +++ b/je_auto_control/gui/webhooks_tab.py @@ -3,7 +3,7 @@ from PySide6.QtCore import QTimer, Qt from PySide6.QtWidgets import ( - QAbstractItemView, QCheckBox, QFileDialog, QGroupBox, QHBoxLayout, + QAbstractItemView, QCheckBox, QFileDialog, QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QSpinBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) @@ -11,6 +11,8 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -86,41 +88,32 @@ def _build_layout(self) -> None: # Start/stop/browse/register/remove commands run from the Actions # menu; the tab keeps only the inputs, the table, and the status. root = QVBoxLayout(self) + root.setSpacing(12) server_box = self._tr(QGroupBox(), "wh_server_group") - server_layout = QHBoxLayout(server_box) - server_layout.addWidget(self._tr(QLabel(), "wh_host_label")) - server_layout.addWidget(self._host_input) - server_layout.addWidget(self._tr(QLabel(), "wh_port_label")) - server_layout.addWidget(self._port_input) - server_layout.addStretch() + server_layout = QVBoxLayout(server_box) + server_layout.addLayout(flow_of( + field_pair(self._tr(QLabel(), "wh_host_label"), self._host_input), + field_pair(self._tr(QLabel(), "wh_port_label"), self._port_input), + )) + self._status_label.setWordWrap(True) + set_role(self._status_label, "hint") + server_layout.addWidget(self._status_label) root.addWidget(server_box) - root.addWidget(self._status_label) add_box = self._tr(QGroupBox(), "wh_add_group") - add_layout = QVBoxLayout(add_box) - path_row = QHBoxLayout() - path_row.addWidget(self._tr(QLabel(), "wh_path_label")) - path_row.addWidget(self._path_input) - add_layout.addLayout(path_row) - script_row = QHBoxLayout() - script_row.addWidget(self._tr(QLabel(), "wh_script_label")) - script_row.addWidget(self._script_input) - add_layout.addLayout(script_row) - method_row = QHBoxLayout() - method_row.addWidget(self._tr(QLabel(), "wh_methods_label")) - for method, check in self._method_checks.items(): - method_row.addWidget(check) - method_row.addStretch() - add_layout.addLayout(method_row) - token_row = QHBoxLayout() - token_row.addWidget(self._tr(QLabel(), "wh_token_label")) - self._token_input.setPlaceholderText(_t("wh_token_placeholder")) - token_row.addWidget(self._token_input) - add_layout.addLayout(token_row) + add_layout = QFormLayout(add_box) + add_layout.addRow(self._tr(QLabel(), "wh_path_label"), self._path_input) + add_layout.addRow(self._tr(QLabel(), "wh_script_label"), self._script_input) + methods = QWidget() + methods.setProperty("role", "bare") + methods.setLayout(flow_of(*self._method_checks.values())) + add_layout.addRow(self._tr(QLabel(), "wh_methods_label"), methods) + self._tr(self._token_input, "wh_token_placeholder") + add_layout.addRow(self._tr(QLabel(), "wh_token_label"), self._token_input) root.addWidget(add_box) - root.addWidget(self._table, stretch=1) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) def menu_actions(self) -> list: """Expose tab commands to the window-level Actions menu.""" diff --git a/je_auto_control/gui/webrunner_tab.py b/je_auto_control/gui/webrunner_tab.py index 656f36303..a8eff07b7 100644 --- a/je_auto_control/gui/webrunner_tab.py +++ b/je_auto_control/gui/webrunner_tab.py @@ -12,7 +12,7 @@ from PySide6.QtCore import Qt from PySide6.QtWidgets import ( - QComboBox, QFileDialog, QFormLayout, QGroupBox, QHBoxLayout, QLabel, + QComboBox, QFileDialog, QFormLayout, QGroupBox, QLabel, QLineEdit, QListWidget, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) @@ -20,6 +20,8 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -69,15 +71,14 @@ def _build_layout(self) -> None: # Browse/open/quit/screenshot/run/refresh commands run from the # Actions menu; the tab keeps only the inputs, list, and output. root = QVBoxLayout(self) + root.setSpacing(12) + self._available_label.setWordWrap(True) + set_role(self._available_label, "hint") root.addWidget(self._available_label) - root.addWidget(self._build_convenience_group()) - root.addWidget(self._build_freeform_group()) - commands_row = QHBoxLayout() - commands_row.addWidget(QLabel(_t("web_commands_label")), stretch=0) - commands_row.addWidget(self._commands_list, stretch=1) - root.addLayout(commands_row, stretch=1) - root.addWidget(QLabel(_t("web_output_label"))) - root.addWidget(self._output, stretch=2) + root.addWidget(ResponsiveBox(self._build_convenience_group(), self._build_freeform_group())) + commands = Card().add(self._tr(QLabel(), "web_commands_label")).add(self._commands_list, stretch=1) + output = Card().add(self._tr(QLabel(), "web_output_label")).add(self._output, stretch=1) + root.addWidget(ResponsiveBox(commands, output, stretches=(1, 2)), stretch=1) def dispose(self) -> None: """Release what the tab holds beyond its widgets: the command still running in the background. @@ -99,22 +100,20 @@ def menu_actions(self) -> list: ] def _build_convenience_group(self) -> QGroupBox: - group = QGroupBox(_t("web_convenience_title")) + group = self._tr(QGroupBox(), "web_convenience_title") form = QFormLayout(group) - form.addRow(QLabel(_t("web_url_label")), self._url_input) - form.addRow(QLabel(_t("web_browser_label")), self._browser_input) - form.addRow(QLabel(_t("web_screenshot_label")), self._screenshot_input) + form.addRow(self._tr(QLabel(), "web_url_label"), self._url_input) + form.addRow(self._tr(QLabel(), "web_browser_label"), self._browser_input) + form.addRow(self._tr(QLabel(), "web_screenshot_label"), self._screenshot_input) return group def _build_freeform_group(self) -> QGroupBox: - group = QGroupBox(_t("web_freeform_title")) + group = self._tr(QGroupBox(), "web_freeform_title") form = QFormLayout(group) - self._action_input.setPlaceholderText(_t("web_action_placeholder")) - self._params_input.setPlaceholderText( - _t("web_params_placeholder"), - ) - form.addRow(QLabel(_t("web_action_label")), self._action_input) - form.addRow(QLabel(_t("web_params_label")), self._params_input) + self._tr(self._action_input, "web_action_placeholder") + self._tr(self._params_input, "web_params_placeholder", "setPlaceholderText") + form.addRow(self._tr(QLabel(), "web_action_label"), self._action_input) + form.addRow(self._tr(QLabel(), "web_params_label"), self._params_input) return group # --- availability --------------------------------------------- diff --git a/je_auto_control/gui/window_tab.py b/je_auto_control/gui/window_tab.py index b9082edf1..787404954 100644 --- a/je_auto_control/gui/window_tab.py +++ b/je_auto_control/gui/window_tab.py @@ -3,11 +3,12 @@ from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( - QHBoxLayout, QLabel, QLineEdit, QMessageBox, QTableWidget, + QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -61,10 +62,11 @@ def _build_layout(self) -> None: # Refresh/focus/close commands run from the Actions menu; the tab # keeps only the filter input, the window table, and the status. root = QVBoxLayout(self) - top = QHBoxLayout() - top.addWidget(self._filter, stretch=1) - root.addLayout(top) - root.addWidget(self._table, stretch=1) + root.setSpacing(12) + root.addWidget(Card().add(self._filter)) + root.addWidget(Card().add(self._table, stretch=1), stretch=1) + self._status.setWordWrap(True) + set_role(self._status, "hint") root.addWidget(self._status) def menu_actions(self) -> list: diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index 4f49c986e..f5fdf21d3 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -2,7 +2,7 @@ import weakref from typing import Any, Callable, List, Optional -from PySide6.QtCore import QPointF, Qt, QObject, QMetaObject, Signal, Slot +from PySide6.QtCore import QEvent, QPointF, QSize, Qt, QObject, QMetaObject, Signal, Slot from PySide6.QtGui import QPaintEvent, QPainter, QPen from PySide6.QtWidgets import QAbstractButton, QScrollArea, QTabBar, QTabWidget, QWidget, QSplitter, QVBoxLayout @@ -45,6 +45,47 @@ def paintEvent(self, _event: QPaintEvent) -> None: # noqa: N802 # reason: Qt o painter.end() +class PageScrollArea(QScrollArea): + """Give a page the whole viewport, and scroll only when the page cannot shrink that far. + + ``QScrollArea.setWidgetResizable(True)`` sizes a page whose layout reports + height-for-width (any word-wrapped label does) from every item's + *preferred* height, so a page with a table or text box scrolled in windows + it fitted. Here the page gets the viewport's size, or its minimum size + where that is larger, and its layout shares the rest out as usual. + """ + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setWidgetResizable(False) + self.setFrameShape(QScrollArea.Shape.NoFrame) + self.viewport().installEventFilter(self) + + def setWidget(self, widget: QWidget) -> None: # noqa: N802 # reason: Qt override + """Hold ``widget`` and size it to the viewport.""" + super().setWidget(widget) + widget.installEventFilter(self) + self.fit_page() + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 # reason: Qt override + """Re-fit the page when the viewport is resized or the page's layout changes.""" + if event.type() in (QEvent.Type.Resize, QEvent.Type.LayoutRequest) \ + and (watched is self.viewport() or watched is self.widget()): + self.fit_page() + return False + + def fit_page(self) -> None: + """Size the page to the viewport, never below the page's minimum.""" + page = self.widget() + if page is None: + return + view = self.viewport().size() + minimum = page.minimumSizeHint().expandedTo(page.minimumSize()) + target = QSize(max(view.width(), minimum.width()), max(view.height(), minimum.height())) + if page.size() != target: + page.resize(target) + + class ScrollableTabs(QTabWidget): """Wrap pages in scroll areas while returning original pages to callers. @@ -87,9 +128,7 @@ def addTab(self, widget: QWidget, *args: Any) -> int: # noqa: N802 # reason: Q def insertTab(self, index: int, widget: QWidget, *args: Any) -> int: # noqa: N802 # reason: Qt overloads """Insert a scrollable page and a vector close button.""" - container = QScrollArea(self) - container.setWidgetResizable(True) - container.setFrameShape(QScrollArea.Shape.NoFrame) + container = PageScrollArea(self) container.setWidget(widget) result = super().insertTab(index, container, *args) self._install_close_button(result, widget) diff --git a/pyproject.toml b/pyproject.toml index dc5023c1b..a3bda176d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -471,6 +471,9 @@ module = [ "je_auto_control.utils.accessibility.backends.windows_automation", "je_auto_control.utils.accessibility.backends.windows_events", "je_auto_control.utils.remote_desktop.input_send_queue", + "je_auto_control.gui.adaptive", + "je_auto_control.gui.adaptive.*", + "je_auto_control.gui.adaptive_window", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/unit_test/headless/test_gui_adaptive.py b/test/unit_test/headless/test_gui_adaptive.py index b72854d12..c8b1f139c 100644 --- a/test/unit_test/headless/test_gui_adaptive.py +++ b/test/unit_test/headless/test_gui_adaptive.py @@ -87,6 +87,57 @@ def test_a_flow_row_wraps_instead_of_widening(qapp): host.deleteLater() +def test_a_page_with_a_flow_row_scrolls_only_below_its_minimum_height(qapp): + from PySide6.QtWidgets import QPlainTextEdit, QScrollArea, QVBoxLayout, QWidget + from je_auto_control.gui.adaptive.flow_layout import FlowLayout + page = QWidget() + layout = QVBoxLayout(page) + flow = FlowLayout(spacing=10) + for index in range(3): + flow.addWidget(_button(f"b{index}", 100)) + layout.addLayout(flow) + editor = QPlainTextEdit() + editor.setMinimumHeight(60) + layout.addWidget(editor, 1) + area = QScrollArea() + area.setWidgetResizable(True) + area.setWidget(page) + area.resize(420, 200) # below the page's preferred height, above its minimum + area.show() + for _ in range(4): + qapp.processEvents() + assert page.sizeHint().height() > 200 + assert area.verticalScrollBar().maximum() == 0, "a page that fits its minimum must not scroll" + one_row = page.minimumSizeHint().height() + area.resize(150, 400) # 100 px buttons in ~130 px: one per row + for _ in range(4): + qapp.processEvents() + assert page.minimumSizeHint().height() >= one_row + 2 * 30, "the wrapped rows raise the minimum height" + assert all(flow.itemAt(i).geometry().bottom() < editor.geometry().top() for i in range(3)), \ + "wrapped rows never overlap what comes after them" + area.deleteLater() + + +def test_a_flow_line_gives_spare_width_to_fields_and_centres_short_items(qapp): + from PySide6.QtWidgets import QCheckBox, QLineEdit, QPlainTextEdit, QWidget + from je_auto_control.gui.adaptive.flow_layout import FlowLayout + host = QWidget() + flow = FlowLayout(host, spacing=10) + button, field, check = _button("fixed", 80), QLineEdit(), QCheckBox("Auto") + tall = QPlainTextEdit() + tall.setFixedSize(100, 80) + for widget in (button, field, check, tall): + flow.addWidget(widget) + host.resize(700, 120) + flow.setGeometry(host.rect()) + used = sum(w.width() for w in (button, field, check, tall)) + 3 * 10 + assert button.width() == 80, "a fixed item keeps its width" + assert field.width() > field.sizeHint().width(), "the line edit takes the spare width" + assert used == 700, used + assert abs(check.geometry().center().y() - tall.geometry().center().y()) <= 1, "short items are centred on the line" + host.deleteLater() + + def test_a_hidden_item_takes_no_room_in_a_flow(qapp): from PySide6.QtWidgets import QWidget from je_auto_control.gui.adaptive.flow_layout import FlowLayout diff --git a/test/unit_test/headless/test_gui_adaptive_window.py b/test/unit_test/headless/test_gui_adaptive_window.py index 06d81c1c9..5646522ed 100644 --- a/test/unit_test/headless/test_gui_adaptive_window.py +++ b/test/unit_test/headless/test_gui_adaptive_window.py @@ -195,3 +195,34 @@ def test_the_glyphs_draw_on_transparent_ground(qapp): assert image.pixelColor(0, 0).alpha() == 0 assert any(image.pixelColor(x, y).red() > 200 and image.pixelColor(x, y).alpha() > 200 for x in range(40) for y in range(40)), name + + +def test_a_page_with_wrapped_text_scrolls_only_below_its_minimum(qapp): + from PySide6.QtWidgets import QLabel, QPlainTextEdit, QVBoxLayout, QWidget + from je_auto_control.gui.workspace import ScrollableTabs + page = QWidget() + layout = QVBoxLayout(page) + note = QLabel("A note long enough to wrap onto a second line in a narrow window, as status lines do.") + note.setWordWrap(True) + layout.addWidget(note) + editor = QPlainTextEdit() + editor.setMinimumHeight(60) + layout.addWidget(editor, 1) + tabs = ScrollableTabs() + tabs.addTab(page, "Page") + scroll = tabs.scroll_area(0) + tabs.resize(420, 200) # shorter than the page's preferred height, taller than its minimum + tabs.show() + for _ in range(4): + qapp.processEvents() + try: + assert page.sizeHint().height() > scroll.viewport().height() + assert scroll.verticalScrollBar().maximum() == 0, "a page that fits its minimum must not scroll" + assert page.size() == scroll.viewport().size(), "the page fills the viewport" + tabs.resize(420, 90) # now below the page's minimum + for _ in range(4): + qapp.processEvents() + assert scroll.verticalScrollBar().maximum() > 0 + assert page.height() >= page.minimumSizeHint().height() + finally: + tabs.deleteLater() diff --git a/test/unit_test/headless/test_gui_page_widths.py b/test/unit_test/headless/test_gui_page_widths.py index 2c4011b6c..0d6a83f4c 100644 --- a/test/unit_test/headless/test_gui_page_widths.py +++ b/test/unit_test/headless/test_gui_page_widths.py @@ -23,13 +23,9 @@ #: The most a page may need, in average characters of the label font (about 460 px in 10 pt Segoe UI): #: a compact window's width less the navigation rail and a scroll bar. BUDGET = 72 -#: Pages still over the budget, with the most each may need until it is reworked. -WIDE_PAGES = { - "script_builder": 134, - "flakiness": 92, - "audit_log": 83, - "usb_share": 81, -} +#: Pages still over the budget, with the most each may need until it is reworked. Empty since the +#: 2026-11-14 rework; a page that needs an entry again needs a reason in Progress.md. +WIDE_PAGES: dict = {} _PROBE = r""" import json, os, sys From 386d9cf73f0bfee64ad29bf5110cbb54b47ff489 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 05:38:39 +0800 Subject: [PATCH 069/161] Theme the application palette so check boxes ignore the Windows accent Reviewing the redesign on the real desktop (Windows 11, 150 %) showed checked boxes in the system accent colour instead of the theme's. A widget styled by a style sheet starts from the application palette, not its window's, and on Windows that palette carries the user's accent. apply_theme now also sets the application palette for a top-level window. --- CHANGELOG.md | 4 ++++ Progress.md | 2 +- architecture_explore.md | 8 ++++---- docs/updates/2026-11-b.md | 8 ++++++++ docs/updates/README.md | 1 + je_auto_control/gui/theme.py | 10 +++++++++- test/unit_test/headless/test_gui_adaptive.py | 17 +++++++++++++++++ 7 files changed, 44 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9b87ec1b..64f83edf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- GUI: applying a theme to a top-level window also sets the application palette. Widgets a + style sheet styles start from the application palette, which on Windows carries the system + accent colour, so checked boxes were drawn in the user's accent instead of the theme's. + - GUI: every tab's layout is rebuilt on cards, wrapping rows and side-by-side panes that stack when narrow; widget objects, attributes, signals, Actions-menu entries and translation keys are unchanged. Each page's scroll area no longer uses `setWidgetResizable(True)` diff --git a/Progress.md b/Progress.md index f5477bfa2..4dab115a5 100644 --- a/Progress.md +++ b/Progress.md @@ -535,7 +535,7 @@ F 還缺: - **F2 其餘**:Diagnostics 以外面板的執行詳情,以及各面板的空白/錯誤/permission states 尚未全面交付。 - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - - 所有截圖都是 offscreen 平台加 Windows 字型,尚未在真實螢幕、混合 DPI 與 Linux/macOS 字型上目視審閱。 + - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - 重排時看到、但屬邏輯或字串而未改的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; Remote Desktop 的走勢圖背景(黑)、統計文字(`#ccaa55`)與大號 ID(`#2070d0`)寫死顏色,淺色主題下不協調; 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複;Diagnostics 閒置時空的進度列仍佔一行; diff --git a/architecture_explore.md b/architecture_explore.md index 3a844c1ba..5729ad85a 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,536 | -| 程式碼總行數 | 235,230 | +| 程式碼總行數 | 235,238 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1299,7 +1299,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 234 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 242 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | @@ -1542,7 +1542,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 159 | 42,033 | +| `gui/` | 159 | 42,041 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,7 +1563,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,524** | **234,485** | +| **總計** | **1,524** | **234,493** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 0bfa6e176..61db38ac1 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -310,3 +310,11 @@ - **Tests:** batches reported 140 + 216 + 160 + 171 + 293 + 170 + 1,463 tab tests passing (Remote Desktop's count equals its baseline). `test_gui_adaptive.py` +2 (a flow row inside a scroll area does not scroll above its minimum and never overlaps what follows; spare width and centring), `test_gui_adaptive_window.py` +1 (a page with wrapped text scrolls only below its minimum). - **Files:** 70 modules under `gui/`, `gui/adaptive/{flow_layout,responsive}.py`, `gui/theme.py`, `gui/workspace.py`, `english.py`, the three tests, both `v224_features_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** review on a real screen and other fonts; the pre-existing defects listed in `Progress.md` › F2 GUI 重製. + +## U-20261114-05 · 2026-11-14 · GUI reviewed on the real Windows desktop at 150 %; check boxes took the system accent · #done #gui #windows + +- **What:** the redesigned window shown on this machine's desktop (Windows 11, one 1920×1080 screen at 150 %, i.e. 1280×720 logical) at 1,360, 1,000 and 640 px wide on Auto Click, Triggers and REST API, captured from the screen (`QScreen.grabWindow`) as well as from the widget. No input was sent. Text, cards, headers and wrapped rows render crisply at 1.5×; the compact rail and the wrapped REST API form behave as offscreen. +- **Found and fixed:** checked boxes were purple, the Windows system accent, not the theme's blue. A widget styled by a style sheet starts from the application palette rather than its window's, and Qt fills that palette's highlight from the system accent. `apply_theme` now also sets the application palette when given a top-level window (an embedded widget leaves it alone). After the change the check box samples `#5b9dff`, the dark theme's accent. Offscreen renders could not show this: the offscreen platform has no system accent. +- **Tests:** `test_gui_adaptive.py` +1 (a top-level theme sets the application highlight; an embedded one does not). Adaptive, navigation and layout tests: 47 passed. +- **Files:** `gui/theme.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** mixed DPI, a second monitor, and Linux / macOS fonts (`Progress.md` › F2 GUI 重製). diff --git a/docs/updates/README.md b/docs/updates/README.md index e0c109bf1..e48e9e8f7 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-05 | 2026-11-14 | GUI reviewed on the real Windows desktop at 150 %; check boxes took the system accent | #done #gui #windows | [2026-11-b](2026-11-b.md) | | U-20261114-04 | 2026-11-14 | GUI redesign, stage 2: every tab rebuilt on the adaptive layout | #migration #gui | [2026-11-b](2026-11-b.md) | | U-20261114-03 | 2026-11-14 | PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit | #decision #ci #gui | [2026-11-b](2026-11-b.md) | | U-20261114-02 | 2026-11-14 | GUI redesign, stage 1: adaptive building blocks, page headers, cards, window breakpoints and the width gate | #migration #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index f3ee7c1b4..7918d6825 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -217,7 +217,15 @@ def apply_theme(window: Any, tokens: ThemeTokens, point_size: Optional[int] = No close_rules = close_button_rules(tokens) if close_rules: sheet = f"{sheet}\n{close_rules}" - window.setPalette(_palette(tokens)) + palette = _palette(tokens) + window.setPalette(palette) + # A widget a style sheet styles starts from the *application* palette, not + # its window's: on Windows that palette carries the system accent colour, + # so check boxes were drawn in the user's accent instead of the theme's. + from PySide6.QtWidgets import QApplication + app = QApplication.instance() + if isinstance(app, QApplication) and window.isWindow(): + app.setPalette(palette) window.setStyleSheet(sheet if point_size is None else f"{sheet}\n{font_rule(point_size)}\n{type_scale_rules(point_size)}") return sheet diff --git a/test/unit_test/headless/test_gui_adaptive.py b/test/unit_test/headless/test_gui_adaptive.py index c8b1f139c..cf6aeda9c 100644 --- a/test/unit_test/headless/test_gui_adaptive.py +++ b/test/unit_test/headless/test_gui_adaptive.py @@ -299,3 +299,20 @@ def test_the_type_scale_grows_titles_with_the_text_size(): assert 'QLabel[role="pageTitle"] { font-size: 18pt; }' in rules assert 'QLabel[role="hint"], QLabel[role="pageSubtitle"] { font-size: 11pt; }' in rules assert "font-size: 8pt" in type_scale_rules(6), "hints never drop below 8 pt" + + +def test_applying_a_theme_sets_the_application_palette_so_styled_widgets_follow_it(qapp): + from PySide6.QtGui import QPalette + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.theme import DARK, LIGHT, apply_theme + previous = qapp.palette() + window, child = QWidget(), None + try: + apply_theme(window, DARK) + assert qapp.palette().color(QPalette.ColorRole.Highlight).name() == DARK.accent + child = QWidget(window) + apply_theme(child, LIGHT) # an embedded widget leaves the application alone + assert qapp.palette().color(QPalette.ColorRole.Highlight).name() == DARK.accent + finally: + qapp.setPalette(previous) + window.deleteLater() From 2f0b252d2b58261938effa32b78aee44c9cdc027 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 05:43:47 +0800 Subject: [PATCH 070/161] Take Remote Desktop's colours from the theme; fix two untranslated strings Remote Desktop's host IDs, stats line, sparklines and missing-extras note used fixed colours that clashed with the light theme (the #555 note was unreadable on the dark one); they now use label roles and the palette. Diagnostics no longer holds an empty progress row while idle, and the Assertions kind list and Email Triggers password placeholder follow a language switch. --- CHANGELOG.md | 6 +++++ Progress.md | 11 +++++---- architecture_explore.md | 24 +++++++++---------- docs/updates/2026-11-b.md | 9 +++++++ docs/updates/README.md | 1 + je_auto_control/gui/assertions_tab.py | 6 +++++ je_auto_control/gui/diagnostics_tab.py | 1 + je_auto_control/gui/email_triggers_tab.py | 2 +- .../gui/remote_desktop/connection_screen.py | 3 ++- .../gui/remote_desktop/host_panel.py | 3 ++- .../gui/remote_desktop/sparkline.py | 9 +++---- je_auto_control/gui/remote_desktop/tab.py | 3 ++- .../gui/remote_desktop/webrtc_viewer_ui.py | 5 ++-- je_auto_control/gui/theme.py | 1 + 14 files changed, 56 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64f83edf0..e590df344 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI: Remote Desktop's host-ID labels, stats line, sparklines and missing-extras message take + their colours from the theme instead of fixed values (the sparkline's `background` now + defaults to the palette's base colour; pass a colour to keep a fixed one). A new `accent` + label role carries the theme's accent. Diagnostics hides its progress line while idle, and the + Assertions kind list and the Email Triggers password placeholder follow a language switch. + - GUI: applying a theme to a top-level window also sets the application palette. Widgets a style sheet styles start from the application palette, which on Windows carries the system accent colour, so checked boxes were drawn in the user's accent instead of the theme's. diff --git a/Progress.md b/Progress.md index 4dab115a5..3fdbc311b 100644 --- a/Progress.md +++ b/Progress.md @@ -536,11 +536,12 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - - 重排時看到、但屬邏輯或字串而未改的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; - Remote Desktop 的走勢圖背景(黑)、統計文字(`#ccaa55`)與大號 ID(`#2070d0`)寫死顏色,淺色主題下不協調; - 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複;Diagnostics 閒置時空的進度列仍佔一行; - Assertions 的種類下拉選單項目與 Email Triggers 的密碼提示字在 `__init__` 設定,切換語言不會更新; - 下拉選單的箭頭貼齊右緣(`theme.py`);Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 + - 重排時看到、尚未處理的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; + Remote Desktop 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複; + 下拉選單的箭頭貼齊右緣(`theme.py`);Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線; + Assertions 的種類選項在繁中目錄沒有翻譯(`assert_kind_*`,退回英文)。 + - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` + (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/architecture_explore.md b/architecture_explore.md index 5729ad85a..b2d6f171a 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,536 | -| 程式碼總行數 | 235,238 | +| 程式碼總行數 | 235,249 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1299,7 +1299,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 242 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 243 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | @@ -1370,7 +1370,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | webhooks | `webhooks_tab.py` | 222 | 將 HTTP 請求綁到 action 腳本。 | | email_triggers | `email_triggers_tab.py` | 250 | 將 IMAP 信箱綁到 action 腳本。 | | test_suite | `test_suite_tab.py` | 200 | 執行 QA 套件規格並管理易碎隔離區。 | -| assertions | `assertions_tab.py` | 148 | 執行單一畫面狀態斷言並顯示通過/失敗。 | +| assertions | `assertions_tab.py` | 154 | 執行單一畫面狀態斷言並顯示通過/失敗。 | | data_source | `data_source_tab.py` | 132 | 預覽無頭資料層載入的資料列。 | | flakiness | `flakiness_tab.py` | 115 | 依執行歷史排序間歇失敗的腳本。 | | a11y_audit | `a11y_audit_tab.py` | 138 | 從即時樹找出無障礙/i18n 缺陷。 | @@ -1385,7 +1385,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 371 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,335 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,338 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 326 | 管理多個遠端 AutoControl REST 端點。 | @@ -1394,7 +1394,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | usb_devices | `usb_devices_tab.py` | 170 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 288 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 770 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | -| diagnostics | `diagnostics_tab.py` | 234 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | +| diagnostics | `diagnostics_tab.py` | 235 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1403,7 +1403,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,335 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,338 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1418,18 +1418,18 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `webrtc_dialogs.py` | 524 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | -| `connection_screen.py` | 672 | Quick Connect —— AnyDesk 風格單畫面入口。 | +| `connection_screen.py` | 673 | Quick Connect —— AnyDesk 風格單畫面入口。 | | `viewer_panel.py` | 594 | 「控制另一台機器」子分頁。 | | `webrtc_known_hosts.py` | 339 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | -| `host_panel.py` | 419 | 「分享這台機器」子分頁。 | +| `host_panel.py` | 420 | 「分享這台機器」子分頁。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | | `webrtc_workers.py` | 237 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | -| `tab.py` | 179 | 外層容器分頁。 | +| `tab.py` | 180 | 外層容器分頁。 | | `_helpers.py` | 294 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | | `remote_screen_window.py` | 140 | 檢視端的彈出視窗。 | | `tray_icon.py` | 106 | WebRTC 主機的系統匣圖示。 | | `annotation_overlay.py` | 174 | 主機端標註的透明最上層覆蓋。 | -| `sparkline.py` | 77 | WebRTC 統計面板的迷你走勢圖。 | +| `sparkline.py` | 78 | WebRTC 統計面板的迷你走勢圖。 | | `blanking_overlay.py` | 71 | 遠端連線期間的隱私遮蔽全螢幕覆蓋。 | | `viewer_screen_window.py` | 46 | 顯示連入檢視端分享畫面的彈出視窗。 | @@ -1542,7 +1542,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 159 | 42,041 | +| `gui/` | 159 | 42,052 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,7 +1563,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,524** | **234,493** | +| **總計** | **1,524** | **234,504** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 61db38ac1..a86a04e93 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -318,3 +318,12 @@ - **Tests:** `test_gui_adaptive.py` +1 (a top-level theme sets the application highlight; an embedded one does not). Adaptive, navigation and layout tests: 47 passed. - **Files:** `gui/theme.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** mixed DPI, a second monitor, and Linux / macOS fonts (`Progress.md` › F2 GUI 重製). + +## U-20261114-06 · 2026-11-14 · GUI polish: theme colours in Remote Desktop, idle progress line, two strings that ignored a language switch · #done #gui + +- **What:** four of the defects the tab rework listed (U-20261114-04). Remote Desktop's large host-ID labels (fixed `#2070d0`) use a new `accent` label role, its stats line (fixed `#ccaa55`) and missing-extras message (fixed `#555`, unreadable on dark) use `hint`, and its sparklines paint the palette's base colour and muted text unless given a colour. Diagnostics hides its progress label when it has no text (it held an empty row while idle). The Assertions kind entries are re-read in place on a language switch (`setItemText`, so the selection is kept) and the Email Triggers password placeholder is registered through `_tr`. +- **Checked:** after a switch to Traditional Chinese the kind selection stays at its index and the placeholder changes; the kind entries stay English there because `traditional_chinese.py` has no `assert_kind_*` keys (left in `Progress.md`). +- **Seen while checking:** building Email Triggers alone and leaving through `os._exit` sometimes prints `pure virtual method 'QLayout.itemAt'` from the Python `FlowLayout` (HEAD 2 of 3 runs, after the change 0 of 3); no crash. Recorded in `Progress.md`. +- **Tests:** affected Remote Desktop tests 259 passed, Diagnostics 37, Assertions and Email Triggers 79. +- **Files:** `gui/remote_desktop/{sparkline,connection_screen,host_panel,webrtc_viewer_ui,tab}.py`, `gui/diagnostics_tab.py`, `gui/assertions_tab.py`, `gui/email_triggers_tab.py`, `gui/theme.py`, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the remaining defects in `Progress.md` › F2 GUI 重製. diff --git a/docs/updates/README.md b/docs/updates/README.md index e48e9e8f7..d266a0bcf 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-06 | 2026-11-14 | GUI polish: theme colours in Remote Desktop, idle progress line, two strings that ignored a language switch | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-05 | 2026-11-14 | GUI reviewed on the real Windows desktop at 150 %; check boxes took the system accent | #done #gui #windows | [2026-11-b](2026-11-b.md) | | U-20261114-04 | 2026-11-14 | GUI redesign, stage 2: every tab rebuilt on the adaptive layout | #migration #gui | [2026-11-b](2026-11-b.md) | | U-20261114-03 | 2026-11-14 | PySide6 back to 6.11.2: 6.12.0 crashes every CI platform at exit | #decision #ci #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/assertions_tab.py b/je_auto_control/gui/assertions_tab.py index d3f4c29ff..0b4386a17 100644 --- a/je_auto_control/gui/assertions_tab.py +++ b/je_auto_control/gui/assertions_tab.py @@ -94,6 +94,12 @@ def menu_actions(self) -> list: ("assert_run", self._on_run), ] + def retranslate(self) -> None: + """Re-read every registered label, then the kind list's entries in place (the selection stays).""" + TranslatableMixin.retranslate(self) + for index, kind in enumerate(_KINDS): + self._kind.setItemText(index, _t(f"assert_kind_{kind}")) + def _current_kind(self) -> str: return _KINDS[self._kind.currentIndex()] diff --git a/je_auto_control/gui/diagnostics_tab.py b/je_auto_control/gui/diagnostics_tab.py index 829c5a7d7..86cc5a27d 100644 --- a/je_auto_control/gui/diagnostics_tab.py +++ b/je_auto_control/gui/diagnostics_tab.py @@ -191,6 +191,7 @@ def _render_summary(self) -> None: if self._active_task is not None and self._view.total: progress = _t('diag_progress').format(completed=self._view.completed, total=self._view.total) self._progress_label.setText(progress) + self._progress_label.setVisible(bool(progress)) # an empty line took a row while idle phase: ExecutionPhase if self._view.kind == 'result': phase = 'succeeded' if report is not None and report.ok else 'error' diff --git a/je_auto_control/gui/email_triggers_tab.py b/je_auto_control/gui/email_triggers_tab.py index 4b011cb0f..487b47f35 100644 --- a/je_auto_control/gui/email_triggers_tab.py +++ b/je_auto_control/gui/email_triggers_tab.py @@ -45,7 +45,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._user_input.setPlaceholderText("user@example.com") self._password_input = QLineEdit() self._password_input.setEchoMode(QLineEdit.EchoMode.Password) - self._password_input.setPlaceholderText(_t("eml_password_placeholder")) + self._tr(self._password_input, "eml_password_placeholder", "setPlaceholderText") self._mailbox_input = QLineEdit("INBOX") self._search_input = QLineEdit("UNSEEN") self._poll_input = QSpinBox() diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 12dad599e..8b44d36da 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -63,7 +63,7 @@ _HOST_ID_CSS = ( "font-family: 'Consolas', 'Menlo', 'Courier New', monospace; " - "font-size: 40pt; font-weight: bold; color: #2070d0; " + "font-size: 40pt; font-weight: bold; " "letter-spacing: 4px;" ) _BIG_INPUT_CSS = ( @@ -120,6 +120,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._displaced.connect(self._on_displaced) self._host_id_label = QLabel("---") self._host_id_label.setStyleSheet(_HOST_ID_CSS) + set_role(self._host_id_label, "accent") self._host_id_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self._host_badge = _StatusBadge() self._viewer_badge = _StatusBadge() diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index cd5cbf963..d7bab5442 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -81,9 +81,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._host_id_label = QLabel("---") self._host_id_label.setStyleSheet( "font-family: 'Consolas', 'Menlo', 'Courier New', monospace; " - "font-size: 26pt; font-weight: bold; color: #2070d0; " + "font-size: 26pt; font-weight: bold; " "letter-spacing: 2px;" ) + set_role(self._host_id_label, "accent") self._badge = _StatusBadge() self._token = QLineEdit() self._bind = QLineEdit("127.0.0.1") diff --git a/je_auto_control/gui/remote_desktop/sparkline.py b/je_auto_control/gui/remote_desktop/sparkline.py index a573dec30..c7067d891 100644 --- a/je_auto_control/gui/remote_desktop/sparkline.py +++ b/je_auto_control/gui/remote_desktop/sparkline.py @@ -19,12 +19,13 @@ class Sparkline(QWidget): def __init__(self, *, capacity: int = 60, line_color: str = "#3a9c3a", - background: str = "#161616", + background: Optional[str] = None, parent: Optional[QWidget] = None) -> None: + """``background`` defaults to the palette's base colour, so the chart follows the theme.""" super().__init__(parent) self._values: "deque[float]" = deque(maxlen=capacity) self._line_color = QColor(line_color) - self._bg_color = QColor(background) + self._bg_color: Optional[QColor] = QColor(background) if background else None self.setMinimumHeight(28) self.setMinimumWidth(120) self.setSizePolicy(QSizePolicy.Policy.Expanding, @@ -42,7 +43,7 @@ def clear(self) -> None: def paintEvent(self, _event) -> None: # noqa: N802 Qt override painter = QPainter(self) try: - painter.fillRect(self.rect(), self._bg_color) + painter.fillRect(self.rect(), self._bg_color or self.palette().base().color()) if len(self._values) < 2: return w = self.width() @@ -64,7 +65,7 @@ def paintEvent(self, _event) -> None: # noqa: N802 Qt override painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.drawPolyline(poly) # Latest value text in the corner - painter.setPen(QColor("#888")) + painter.setPen(self.palette().placeholderText().color()) painter.drawText( self.rect().adjusted(2, 2, -2, -2), Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignRight, diff --git a/je_auto_control/gui/remote_desktop/tab.py b/je_auto_control/gui/remote_desktop/tab.py index 4c5843250..7dc4297cf 100644 --- a/je_auto_control/gui/remote_desktop/tab.py +++ b/je_auto_control/gui/remote_desktop/tab.py @@ -16,6 +16,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.remote_desktop._helpers import _t from je_auto_control.gui.remote_desktop.connection_screen import ( QuickConnectScreen, @@ -52,7 +53,7 @@ def _build_webrtc_placeholder() -> QWidget: message = QLabel(_t("rd_webrtc_missing_extras")) message.setWordWrap(True) message.setAlignment(Qt.AlignmentFlag.AlignCenter) - message.setStyleSheet("font-size: 11pt; color: #555;") + set_role(message, "hint") layout.addWidget(message) layout.addStretch(1) return widget diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py index 15e786261..85b6b3a50 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py @@ -110,9 +110,8 @@ def _build_session_card(self) -> Card: self._quality_dot.setToolTip(_t("rd_webrtc_quality_unknown")) stats_row.addWidget(self._quality_dot) self._stats_label = QLabel(_t("rd_webrtc_stats_idle")) - self._stats_label.setStyleSheet( - "color: #ccaa55; font-family: 'Consolas', monospace;", - ) + self._stats_label.setStyleSheet("font-family: 'Consolas', monospace;") + set_role(self._stats_label, "hint") self._stats_label.setWordWrap(True) stats_row.addWidget(self._stats_label, stretch=1) card.add(stats_row) diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index 7918d6825..1e62d2ae8 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -149,6 +149,7 @@ def type_scale_rules(point_size: int) -> str: QLabel[role="danger"] {{ color: {danger}; }} QLabel[role="success"] {{ color: {success}; }} QLabel[role="warning"] {{ color: {warning}; }} +QLabel[role="accent"] {{ color: {accent}; }} QPushButton[role="primary"] {{ background-color: {accent}; color: {accent_text}; border-color: {accent}; }} QPushButton[role="primary"]:hover {{ background-color: {accent_hover}; }} From d80313dd1d51c50fc5c9c6f72a0a39835ee7ff61 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 06:44:35 +0800 Subject: [PATCH 071/161] Translate the strings seven testing tabs shipped in English only Test Suites, A11y Audit, Device Matrix, Media Checks, Assertions, Data Sources and Flaky Tests had 95 keys missing from all three bundled catalogues. A missing key falls back to English, so those tabs showed English inside a translated window without anything failing. A parity test now fails on a missing key or a translation that changes a format field. --- Progress.md | 3 +- architecture_explore.md | 8 +- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + .../gui/language_wrapper/japanese.py | 100 ++++++++++++++++++ .../language_wrapper/simplified_chinese.py | 100 ++++++++++++++++++ .../language_wrapper/traditional_chinese.py | 100 ++++++++++++++++++ .../test_language_catalogue_parity.py | 39 +++++++ 8 files changed, 353 insertions(+), 6 deletions(-) create mode 100644 test/unit_test/headless/test_language_catalogue_parity.py diff --git a/Progress.md b/Progress.md index 3fdbc311b..0ca5b1a07 100644 --- a/Progress.md +++ b/Progress.md @@ -538,8 +538,7 @@ F 還缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - 重排時看到、尚未處理的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; Remote Desktop 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複; - 下拉選單的箭頭貼齊右緣(`theme.py`);Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線; - Assertions 的種類選項在繁中目錄沒有翻譯(`assert_kind_*`,退回英文)。 + 下拉選單的箭頭貼齊右緣(`theme.py`);Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, diff --git a/architecture_explore.md b/architecture_explore.md index b2d6f171a..271544c39 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,536 | -| 程式碼總行數 | 235,249 | +| 程式碼總行數 | 235,549 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1335,7 +1335,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,195 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,495 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1542,7 +1542,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 159 | 42,052 | +| `gui/` | 159 | 42,352 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,7 +1563,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,524** | **234,504** | +| **總計** | **1,524** | **234,804** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index a86a04e93..ab1fa2619 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -327,3 +327,11 @@ - **Tests:** affected Remote Desktop tests 259 passed, Diagnostics 37, Assertions and Email Triggers 79. - **Files:** `gui/remote_desktop/{sparkline,connection_screen,host_panel,webrtc_viewer_ui,tab}.py`, `gui/diagnostics_tab.py`, `gui/assertions_tab.py`, `gui/email_triggers_tab.py`, `gui/theme.py`, `CHANGELOG.md`, `Progress.md`. - **Open items:** the remaining defects in `Progress.md` › F2 GUI 重製. + +## U-20261114-07 · 2026-11-14 · Translate the 95 strings seven testing tabs shipped in English only · #done #gui #i18n + +- **What:** Test Suites, A11y Audit, Device Matrix, Media Checks, Assertions, Data Sources and Flaky Tests (their tab names, labels, column headers and result lines) had no entries in the Traditional Chinese, Simplified Chinese or Japanese catalogues. A missing key falls back to English, so nothing failed: those tabs showed English inside a translated window. The 95 keys are now in all three catalogues, appended as one block each. U-20261114-06 had noted only the `assert_kind_*` part. +- **Guard:** `test_language_catalogue_parity.py` fails when an English key is missing from a bundled catalogue, and when a translation drops or renames a `{field}` the English text formats (every existing entry already matched). +- **Tests:** the new test, 6 passed. +- **Files:** `gui/language_wrapper/{traditional_chinese,simplified_chinese,japanese}.py`, the test, `Progress.md`. +- **Open items:** none for translations; the other F2 defects stay in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index d266a0bcf..80cddd884 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-07 | 2026-11-14 | Translate the 95 strings seven testing tabs shipped in English only | #done #gui #i18n | [2026-11-b](2026-11-b.md) | | U-20261114-06 | 2026-11-14 | GUI polish: theme colours in Remote Desktop, idle progress line, two strings that ignored a language switch | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-05 | 2026-11-14 | GUI reviewed on the real Windows desktop at 150 %; check boxes took the system accent | #done #gui #windows | [2026-11-b](2026-11-b.md) | | U-20261114-04 | 2026-11-14 | GUI redesign, stage 2: every tab rebuilt on the adaptive layout | #migration #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index cb7a5ca3a..d96c39bfd 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -2026,3 +2026,103 @@ 'tab_diagnostics_subtitle': 'このマシンで何を自動化できるか、機能が使えない理由は何かを確認します。', 'tab_config_sync_subtitle': 'ワークスペースの設定とスクリプトを他のマシンと同期します。', 'tab_report_subtitle': '記録したテスト結果から HTML、JSON、XML のレポートを作成します。'}) + +# Testing tabs (Test Suites, A11y Audit, Device Matrix, Media Checks, Assertions, +# Data Sources, Flaky Tests): these strings had shipped in English only. +japanese_word_dict.update({ + 'tab_assertions': 'アサーション', + 'tab_data_source': 'データソース', + 'tab_flakiness': '不安定なテスト', + 'tab_test_suite': 'テストスイート', + 'suite_spec_label': 'スイート定義(JSON)', + 'suite_load_file': 'ファイルを読み込む…', + 'suite_run': 'スイートを実行', + 'suite_junit': 'JUnit XML を書き出す…', + 'suite_allure': 'Allure ディレクトリを書き出す…', + 'suite_col_case': 'ケース', + 'suite_col_status': '状態', + 'suite_col_time': '時間', + 'suite_col_message': 'メッセージ', + 'suite_summary': '成功 {passed}、失敗 {failed}、エラー {errored}、スキップ {skipped}', + 'suite_error': '実行に失敗しました:{error}', + 'suite_q_label': '隔離', + 'suite_q_auto': '不安定なケースを自動隔離', + 'suite_q_clear': '隔離をクリア', + 'suite_q_remove': '選択を解除', + 'tab_a11y_audit': 'アクセシビリティ監査', + 'tab_device_matrix': 'デバイスマトリクス', + 'tab_media_checks': 'メディアチェック', + 'audit_app': 'アプリ名(空欄 = すべて)', + 'audit_run': '監査を実行', + 'audit_col_kind': '種類', + 'audit_col_severity': '重大度', + 'audit_col_target': '対象', + 'audit_col_message': 'メッセージ', + 'audit_summary': 'エラー {errors} 件、警告 {warnings} 件', + 'audit_contrast_label': 'コントラスト確認(前景/背景 RGB)', + 'audit_contrast_run': 'コントラストを確認', + 'dm_devices': 'デバイス(JSON リスト)', + 'dm_actions': 'アクションリスト(JSON)', + 'dm_parallel': '最大並列数', + 'dm_run': 'マトリクスを実行', + 'dm_col_device': 'デバイス', + 'dm_col_platform': 'プラットフォーム', + 'dm_col_result': '結果', + 'dm_col_time': '時間', + 'dm_col_error': 'エラー', + 'dm_summary': '{total} 台中 成功 {passed}、失敗 {failed}', + 'dm_error': '実行に失敗しました:{error}', + 'media_audio_label': '音声アクティビティ確認', + 'media_audio_duration': '長さ(秒)', + 'media_audio_threshold': 'RMS しきい値', + 'media_audio_expect': '音があることを期待', + 'media_audio_run': '録音して確認', + 'media_video_label': '動画の動き確認', + 'media_video_path': '動画ファイル', + 'media_video_browse': '参照…', + 'media_video_threshold': '動きのしきい値', + 'media_video_expect': '動きがあることを期待', + 'media_video_run': '動画を確認', + 'media_result': '結果', + 'assert_kind': 'アサーション', + 'assert_kind_text': '画面上のテキスト(OCR)', + 'assert_kind_image': '画面上の画像', + 'assert_kind_pixel': 'ピクセルの色', + 'assert_kind_window': 'ウィンドウが存在', + 'assert_kind_vlm': '画面が説明と一致(VLM)', + 'assert_target': '対象', + 'assert_target_text_hint': '検索するテキスト/正規表現', + 'assert_target_image_hint': 'テンプレート画像のパス', + 'assert_target_window_hint': 'ウィンドウタイトルに含む', + 'assert_pixel_xy': 'x, y', + 'assert_pixel_rgb': 'r, g, b', + 'assert_expect_present': '出現/一致/存在を期待', + 'assert_regex': 'テキストを正規表現として扱う', + 'assert_run': 'アサーションを実行', + 'assert_passed': '成功', + 'assert_failed': '失敗', + 'ds_kind': 'ソースの種類', + 'ds_path': 'ファイルパス', + 'ds_browse': '参照…', + 'ds_query': 'SQL クエリ(SELECT のみ)', + 'ds_inline': 'インライン JSON 行', + 'ds_limit': '行数の上限(0 = すべて)', + 'ds_load': '行を読み込む', + 'ds_row_count': '{n} 行を読み込みました', + 'ds_error': '読み込みに失敗しました:{error}', + 'flaky_refresh': '更新', + 'flaky_limit': '走査する実行数', + 'flaky_min_runs': '最小実行数', + 'flaky_group_by': 'グループ化', + 'flaky_col_key': 'スクリプト/ソース', + 'flaky_col_runs': '実行数', + 'flaky_col_ok': '成功', + 'flaky_col_error': '失敗', + 'flaky_col_flips': '反転', + 'flaky_col_flip_rate': '反転率', + 'flaky_col_pass_rate': '成功率', + 'flaky_col_last': '最新', + 'flaky_col_flaky': '不安定?', + 'flaky_summary': '{total} グループ中 {flaky} 件が不安定', + 'flaky_summary_empty': '実行履歴はまだありません', +}) diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 30284cecd..5b14a7f20 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1968,3 +1968,103 @@ 'tab_diagnostics_subtitle': '检查本机能自动化哪些功能,以及某项功能为何无法使用。', 'tab_config_sync_subtitle': '与其他电脑同步工作区设置与脚本。', 'tab_report_subtitle': '将记录的测试结果生成为 HTML、JSON 或 XML 报告。'}) + +# Testing tabs (Test Suites, A11y Audit, Device Matrix, Media Checks, Assertions, +# Data Sources, Flaky Tests): these strings had shipped in English only. +simplified_chinese_word_dict.update({ + 'tab_assertions': '断言', + 'tab_data_source': '数据源', + 'tab_flakiness': '不稳定测试', + 'tab_test_suite': '测试套件', + 'suite_spec_label': '套件规格(JSON)', + 'suite_load_file': '加载文件…', + 'suite_run': '运行套件', + 'suite_junit': '写出 JUnit XML…', + 'suite_allure': '写出 Allure 目录…', + 'suite_col_case': '用例', + 'suite_col_status': '状态', + 'suite_col_time': '时间', + 'suite_col_message': '消息', + 'suite_summary': '{passed} 通过、{failed} 失败、{errored} 错误、{skipped} 跳过', + 'suite_error': '运行失败:{error}', + 'suite_q_label': '隔离', + 'suite_q_auto': '自动隔离不稳定用例', + 'suite_q_clear': '清除隔离', + 'suite_q_remove': '解除所选', + 'tab_a11y_audit': '无障碍审计', + 'tab_device_matrix': '设备矩阵', + 'tab_media_checks': '媒体检查', + 'audit_app': '应用名称(留空 = 全部)', + 'audit_run': '运行审计', + 'audit_col_kind': '类型', + 'audit_col_severity': '严重程度', + 'audit_col_target': '目标', + 'audit_col_message': '消息', + 'audit_summary': '{errors} 个错误、{warnings} 个警告', + 'audit_contrast_label': '对比度检查(前景/背景 RGB)', + 'audit_contrast_run': '检查对比度', + 'dm_devices': '设备(JSON 列表)', + 'dm_actions': '动作列表(JSON)', + 'dm_parallel': '最大并行数', + 'dm_run': '运行矩阵', + 'dm_col_device': '设备', + 'dm_col_platform': '平台', + 'dm_col_result': '结果', + 'dm_col_time': '时间', + 'dm_col_error': '错误', + 'dm_summary': '共 {total} 台:{passed} 通过、{failed} 失败', + 'dm_error': '运行失败:{error}', + 'media_audio_label': '音频活动检查', + 'media_audio_duration': '时长(秒)', + 'media_audio_threshold': 'RMS 阈值', + 'media_audio_expect': '预期有声音', + 'media_audio_run': '录音并检查', + 'media_video_label': '视频动态检查', + 'media_video_path': '视频文件', + 'media_video_browse': '浏览…', + 'media_video_threshold': '动态阈值', + 'media_video_expect': '预期有动态', + 'media_video_run': '检查视频', + 'media_result': '结果', + 'assert_kind': '断言', + 'assert_kind_text': '屏幕上的文字(OCR)', + 'assert_kind_image': '屏幕上的图片', + 'assert_kind_pixel': '像素颜色', + 'assert_kind_window': '窗口存在', + 'assert_kind_vlm': '屏幕符合描述(VLM)', + 'assert_target': '目标', + 'assert_target_text_hint': '要查找的文字/正则表达式', + 'assert_target_image_hint': '模板图片路径', + 'assert_target_window_hint': '窗口标题包含', + 'assert_pixel_xy': 'x, y', + 'assert_pixel_rgb': 'r, g, b', + 'assert_expect_present': '预期出现/匹配/存在', + 'assert_regex': '将文字视为正则表达式', + 'assert_run': '运行断言', + 'assert_passed': '通过', + 'assert_failed': '失败', + 'ds_kind': '来源类型', + 'ds_path': '文件路径', + 'ds_browse': '浏览…', + 'ds_query': 'SQL 查询(仅限 SELECT)', + 'ds_inline': '内联 JSON 行', + 'ds_limit': '行数上限(0 = 全部)', + 'ds_load': '加载行', + 'ds_row_count': '已加载 {n} 行', + 'ds_error': '加载失败:{error}', + 'flaky_refresh': '刷新', + 'flaky_limit': '扫描的运行次数', + 'flaky_min_runs': '最少运行次数', + 'flaky_group_by': '分组依据', + 'flaky_col_key': '脚本/来源', + 'flaky_col_runs': '运行次数', + 'flaky_col_ok': '通过', + 'flaky_col_error': '失败', + 'flaky_col_flips': '翻转', + 'flaky_col_flip_rate': '翻转率', + 'flaky_col_pass_rate': '通过率', + 'flaky_col_last': '最近', + 'flaky_col_flaky': '不稳定?', + 'flaky_summary': '{total} 组中有 {flaky} 组不稳定', + 'flaky_summary_empty': '暂无运行记录', +}) diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index db0957b06..a2da38645 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1976,3 +1976,103 @@ 'tab_diagnostics_subtitle': '檢查本機能自動化哪些功能,以及某項功能為何無法使用。', 'tab_config_sync_subtitle': '與其他電腦同步工作區設定與腳本。', 'tab_report_subtitle': '將記錄的測試結果產生為 HTML、JSON 或 XML 報告。'}) + +# Testing tabs (Test Suites, A11y Audit, Device Matrix, Media Checks, Assertions, +# Data Sources, Flaky Tests): these strings had shipped in English only. +traditional_chinese_word_dict.update({ + 'tab_assertions': '斷言', + 'tab_data_source': '資料來源', + 'tab_flakiness': '不穩定測試', + 'tab_test_suite': '測試套件', + 'suite_spec_label': '套件規格(JSON)', + 'suite_load_file': '載入檔案…', + 'suite_run': '執行套件', + 'suite_junit': '寫出 JUnit XML…', + 'suite_allure': '寫出 Allure 目錄…', + 'suite_col_case': '案例', + 'suite_col_status': '狀態', + 'suite_col_time': '時間', + 'suite_col_message': '訊息', + 'suite_summary': '{passed} 通過、{failed} 失敗、{errored} 錯誤、{skipped} 略過', + 'suite_error': '執行失敗:{error}', + 'suite_q_label': '隔離', + 'suite_q_auto': '自動隔離不穩定案例', + 'suite_q_clear': '清除隔離', + 'suite_q_remove': '解除所選', + 'tab_a11y_audit': '無障礙稽核', + 'tab_device_matrix': '裝置矩陣', + 'tab_media_checks': '媒體檢查', + 'audit_app': '應用程式名稱(空白 = 全部)', + 'audit_run': '執行稽核', + 'audit_col_kind': '種類', + 'audit_col_severity': '嚴重程度', + 'audit_col_target': '目標', + 'audit_col_message': '訊息', + 'audit_summary': '{errors} 個錯誤、{warnings} 個警告', + 'audit_contrast_label': '對比檢查(前景/背景 RGB)', + 'audit_contrast_run': '檢查對比', + 'dm_devices': '裝置(JSON 清單)', + 'dm_actions': '動作清單(JSON)', + 'dm_parallel': '最大平行數', + 'dm_run': '執行矩陣', + 'dm_col_device': '裝置', + 'dm_col_platform': '平台', + 'dm_col_result': '結果', + 'dm_col_time': '時間', + 'dm_col_error': '錯誤', + 'dm_summary': '共 {total} 台:{passed} 通過、{failed} 失敗', + 'dm_error': '執行失敗:{error}', + 'media_audio_label': '音訊活動檢查', + 'media_audio_duration': '時長(秒)', + 'media_audio_threshold': 'RMS 門檻', + 'media_audio_expect': '預期有聲音', + 'media_audio_run': '錄音並檢查', + 'media_video_label': '影片動態檢查', + 'media_video_path': '影片檔案', + 'media_video_browse': '瀏覽…', + 'media_video_threshold': '動態門檻', + 'media_video_expect': '預期有動態', + 'media_video_run': '檢查影片', + 'media_result': '結果', + 'assert_kind': '斷言', + 'assert_kind_text': '畫面上的文字(OCR)', + 'assert_kind_image': '畫面上的圖片', + 'assert_kind_pixel': '像素顏色', + 'assert_kind_window': '視窗存在', + 'assert_kind_vlm': '畫面符合描述(VLM)', + 'assert_target': '目標', + 'assert_target_text_hint': '要尋找的文字/正規表示式', + 'assert_target_image_hint': '範本圖片路徑', + 'assert_target_window_hint': '視窗標題包含', + 'assert_pixel_xy': 'x, y', + 'assert_pixel_rgb': 'r, g, b', + 'assert_expect_present': '預期出現/相符/存在', + 'assert_regex': '將文字視為正規表示式', + 'assert_run': '執行斷言', + 'assert_passed': '通過', + 'assert_failed': '失敗', + 'ds_kind': '來源種類', + 'ds_path': '檔案路徑', + 'ds_browse': '瀏覽…', + 'ds_query': 'SQL 查詢(僅限 SELECT)', + 'ds_inline': '內嵌 JSON 資料列', + 'ds_limit': '列數上限(0 = 全部)', + 'ds_load': '載入資料列', + 'ds_row_count': '已載入 {n} 列', + 'ds_error': '載入失敗:{error}', + 'flaky_refresh': '重新整理', + 'flaky_limit': '掃描的執行次數', + 'flaky_min_runs': '最少執行次數', + 'flaky_group_by': '分組依據', + 'flaky_col_key': '腳本/來源', + 'flaky_col_runs': '執行次數', + 'flaky_col_ok': '通過', + 'flaky_col_error': '失敗', + 'flaky_col_flips': '翻轉', + 'flaky_col_flip_rate': '翻轉率', + 'flaky_col_pass_rate': '通過率', + 'flaky_col_last': '最近', + 'flaky_col_flaky': '不穩定?', + 'flaky_summary': '{total} 組中有 {flaky} 組不穩定', + 'flaky_summary_empty': '尚無執行紀錄', +}) diff --git a/test/unit_test/headless/test_language_catalogue_parity.py b/test/unit_test/headless/test_language_catalogue_parity.py new file mode 100644 index 000000000..0477ce12a --- /dev/null +++ b/test/unit_test/headless/test_language_catalogue_parity.py @@ -0,0 +1,39 @@ +"""Every English GUI string has a translation in each bundled language. + +A key missing from a catalogue does not fail at run time: the lookup falls +back to English, so a tab silently shows English text inside a translated +window. Seven testing tabs shipped that way (95 strings in all three +catalogues) before this check existed. +""" +import re + +import pytest + +from je_auto_control.gui.language_wrapper.english import english_word_dict +from je_auto_control.gui.language_wrapper.japanese import japanese_word_dict +from je_auto_control.gui.language_wrapper.simplified_chinese import simplified_chinese_word_dict +from je_auto_control.gui.language_wrapper.traditional_chinese import traditional_chinese_word_dict + +CATALOGUES = { + "Traditional_Chinese": traditional_chinese_word_dict, + "Simplified_Chinese": simplified_chinese_word_dict, + "Japanese": japanese_word_dict, +} +_FIELD = re.compile(r"{(\w*)}") + + +@pytest.mark.parametrize("name", sorted(CATALOGUES)) +def test_catalogue_translates_every_english_key(name): + missing = sorted(set(english_word_dict) - set(CATALOGUES[name])) + assert not missing, f"{name} lacks {len(missing)} keys: {missing[:20]}" + + +@pytest.mark.parametrize("name", sorted(CATALOGUES)) +def test_translations_keep_the_format_fields(name): + catalogue = CATALOGUES[name] + wrong = [ + key for key, text in english_word_dict.items() + if isinstance(text, str) and isinstance(catalogue.get(key), str) + and set(_FIELD.findall(text)) != set(_FIELD.findall(catalogue[key])) + ] + assert not wrong, f"{name} changes the format fields of: {wrong[:20]}" From e86fac76cbf3a5415b8c6fa54c2e0e0ac746f719 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 06:54:49 +0800 Subject: [PATCH 072/161] Draw drop-down and spin box arrows in theme colours, inset from the border Fusion's drop-down box sat flush against the rounded right border and spin buttons were empty boxes. Placing those sub-controls in the style sheet stops Qt from drawing the style's arrow, and a sheet can only show one from a file, so the chevrons are painted with the rail's glyphs and cached per colour; without a writable cache no rules are emitted and the native arrows stay. A spin box's editor ignores left padding, so its digits get a text margin from the proxy style instead. --- CHANGELOG.md | 5 ++ Progress.md | 2 +- architecture_explore.md | 15 ++-- docs/updates/2026-11-b.md | 9 +++ docs/updates/README.md | 1 + je_auto_control/gui/_arrow_icons.py | 76 +++++++++++++++++++ je_auto_control/gui/adaptive/glyphs.py | 16 +++- je_auto_control/gui/adaptive/style.py | 17 ++++- je_auto_control/gui/theme.py | 7 +- pyproject.toml | 1 + .../headless/test_gui_arrow_icons.py | 76 +++++++++++++++++++ 11 files changed, 211 insertions(+), 14 deletions(-) create mode 100644 je_auto_control/gui/_arrow_icons.py create mode 100644 test/unit_test/headless/test_gui_arrow_icons.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e590df344..e6866c9ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI: drop-down lists and spin boxes draw theme-coloured chevrons, inset from the rounded + border, and spin boxes inset their digits like every other field. The chevrons are drawn + once per theme colour into `~/.je_auto_control/gui_cache/`, next to the tab close cross; + when that folder cannot be written the controls keep the style's own arrows. + - GUI: Remote Desktop's host-ID labels, stats line, sparklines and missing-extras message take their colours from the theme instead of fixed values (the sparkline's `background` now defaults to the palette's base colour; pass a colour to keep a fixed one). A new `accent` diff --git a/Progress.md b/Progress.md index 0ca5b1a07..09c2cd7b2 100644 --- a/Progress.md +++ b/Progress.md @@ -538,7 +538,7 @@ F 還缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - 重排時看到、尚未處理的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; Remote Desktop 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複; - 下拉選單的箭頭貼齊右緣(`theme.py`);Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 + Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, diff --git a/architecture_explore.md b/architecture_explore.md index 271544c39..a830a1d04 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,536 | -| 程式碼總行數 | 235,549 | +| Python 模組總數(含周邊子專案) | 1,537 | +| 程式碼總行數 | 235,653 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1299,15 +1299,16 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 243 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 242 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | | `adaptive/responsive.py` | 120 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行),工作區放入每頁時跑一次。 | | `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | -| `adaptive/style.py` | 102 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | -| `adaptive/glyphs.py` | 52 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | +| `adaptive/style.py` | 117 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | +| `adaptive/glyphs.py` | 66 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | | `adaptive/overlay.py` | 102 | A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed. `OverlayDrawer`:Escape 或點擊遮罩關閉。 | +| `_arrow_icons.py` | 76 | Chevrons for drop-down lists and spin boxes, drawn in code and handed to the style sheet. 以導覽列的線條圖示畫出、依主題色快取成檔案;寫不進快取時不放置子控制項,保留樣式原生箭頭。 | | `adaptive_window.py` | 179 | Rearrange the main window's navigation and details panes as the window's width class changes. `AdaptiveWindowLayout`:expanded 兩側停靠;medium 詳情改抽屜;compact 導覽改圖示欄+抽屜。「想要停靠導覽」與寬度是否允許分開記錄,窄視窗不會改寫使用者偏好。 | | `workspace.py` | 567 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | | `workspace_details.py` | 97 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | @@ -1542,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 159 | 42,352 | +| `gui/` | 160 | 42,456 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,524** | **234,804** | +| **總計** | **1,525** | **234,908** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index ab1fa2619..ca721aabe 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -335,3 +335,12 @@ - **Tests:** the new test, 6 passed. - **Files:** `gui/language_wrapper/{traditional_chinese,simplified_chinese,japanese}.py`, the test, `Progress.md`. - **Open items:** none for translations; the other F2 defects stay in `Progress.md`. + +## U-20261114-08 · 2026-11-14 · Drop-down and spin box arrows drawn in theme colours, inset from the border · #done #gui + +- **What:** one of the defects the tab rework listed (U-20261114-04). Fusion drew a combo box's arrow in its own drop-down box flush against the rounded right border, and a spin box's buttons as empty boxes. The theme now places the drop-down and both spin buttons with a half-spacing inset and shows chevrons drawn with the navigation rail's glyph painter (`adaptive/glyphs.py` gains `chevron_down` / `chevron_up`) in the muted text colour, dimmed to the border colour when disabled or at the end of the range; spin buttons get the hover fill. +- **Why images:** once a style sheet places `QComboBox::drop-down` or a spin button, Qt no longer draws the style's arrow there, and a style sheet can draw one only from a file. `gui/_arrow_icons.py` paints them at 1x/2x/3x into `~/.je_auto_control/gui_cache/` (as the tab close cross already is); if that cannot be written it returns no rules at all, so the controls keep the style's arrows rather than losing them. +- **Also fixed:** a spin box's digits sat on its left border. Qt places a spin box's inner editor from the border box whatever the padding (the same in plain Fusion with a one-rule sheet), so `AdaptiveStyle.polish` gives the editor a 9 px text margin (the theme's 8 px padding plus the border). A spin box at its own size hint still fits `-99999` and `9999.99 ms`. +- **Tests:** `test_gui_arrow_icons.py` (5: cache at three scales in one colour and reused, the rules and their six image references, no rules without a writable cache, the theme carries them, the spin inset); adaptive, window and page-width tests 43 passed; strict typing tier and the extras contract pass. +- **Files:** `gui/_arrow_icons.py` (new), `gui/adaptive/{glyphs,style}.py`, `gui/theme.py`, the test, `pyproject.toml` (strict tier), `architecture_explore.md`, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the remaining defects in `Progress.md` › F2 GUI 重製. diff --git a/docs/updates/README.md b/docs/updates/README.md index 80cddd884..69559c0fa 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-08 | 2026-11-14 | Drop-down and spin box arrows drawn in theme colours, inset from the border | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-07 | 2026-11-14 | Translate the 95 strings seven testing tabs shipped in English only | #done #gui #i18n | [2026-11-b](2026-11-b.md) | | U-20261114-06 | 2026-11-14 | GUI polish: theme colours in Remote Desktop, idle progress line, two strings that ignored a language switch | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-05 | 2026-11-14 | GUI reviewed on the real Windows desktop at 150 %; check boxes took the system accent | #done #gui #windows | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_arrow_icons.py b/je_auto_control/gui/_arrow_icons.py new file mode 100644 index 000000000..0bf9a4f2a --- /dev/null +++ b/je_auto_control/gui/_arrow_icons.py @@ -0,0 +1,76 @@ +"""Chevrons for drop-down lists and spin boxes, drawn in code and handed to the style sheet. + +Once a style sheet places ``QComboBox::drop-down`` or a spin box's buttons, Qt +stops drawing the style's arrow in them, and a style sheet can show an arrow +only from an image file. Fusion's own drop-down box, left unstyled, sat flush +against the rounded right border. So the chevrons are painted with the +navigation rail's glyphs in the theme's colours and cached as files beside the +tab close cross (:mod:`je_auto_control.gui._tab_close_icon`). +""" +from pathlib import Path +from typing import Any, Dict, Optional + +from je_auto_control.gui._tab_close_icon import cache_directory +from je_auto_control.utils.logging.logging_instance import autocontrol_logger + +_SIDE = 12 +_SCALES = (1, 2, 3) + + +def arrow_file(name: str, colour: str, directory: Optional[Path] = None) -> Optional[Path]: + """Path of glyph ``name`` (``chevron_down`` / ``chevron_up``) in ``colour``, drawn if not cached yet. + + Written at 1x, 2x and 3x (``name@2x.png``), which Qt picks by screen + scale. ``None`` when the cache cannot be written. + """ + from je_auto_control.gui.adaptive.glyphs import glyph_pixmap + folder = directory if directory is not None else cache_directory() + base = folder / f"{name}_{colour.lstrip('#').lower()}_{_SIDE}.png" + try: + folder.mkdir(parents=True, exist_ok=True) + for scale in _SCALES: + target = base if scale == 1 else base.with_name(f"{base.stem}@{scale}x.png") + if not target.is_file() and not glyph_pixmap(name, colour, _SIDE, scale).save(str(target), "PNG"): + raise OSError(f"could not write {target}") + except OSError as error: + autocontrol_logger.warning("arrow icon not cached: %r", error) + return None + return base + + +def _files(tokens: Any, directory: Optional[Path]) -> Optional[Dict[str, str]]: + wanted = { + "down": ("chevron_down", tokens.text_muted), "up": ("chevron_up", tokens.text_muted), + "down_off": ("chevron_down", tokens.border), "up_off": ("chevron_up", tokens.border), + } + files = {key: arrow_file(name, colour, directory) for key, (name, colour) in wanted.items()} + if any(path is None for path in files.values()): + return None + return {key: path.as_posix() for key, path in files.items() if path is not None} + + +def arrow_rules(tokens: Any, directory: Optional[Path] = None) -> str: + """Style sheet rules that place the drop-down and spin buttons and draw their chevrons. + + An empty string when the cache cannot be written: the controls then keep + the style's own arrows rather than losing them. + """ + files = _files(tokens, directory) + if files is None: + return "" + button = 2 * tokens.spacing + small = max(tokens.radius - 2, 2) + return f"""QComboBox::drop-down {{ subcontrol-origin: padding; subcontrol-position: center right; width: {button}px; + margin-right: {tokens.spacing // 2}px; + border: none; }} +QComboBox::down-arrow {{ image: url("{files['down']}"); width: {_SIDE}px; height: {_SIDE}px; }} +QComboBox::down-arrow:disabled {{ image: url("{files['down_off']}"); }} +QAbstractSpinBox::up-button, QAbstractSpinBox::down-button {{ subcontrol-origin: border; width: {button}px; + border: none; border-radius: {small}px; margin-right: {tokens.spacing // 2}px; }} +QAbstractSpinBox::up-button {{ subcontrol-position: top right; margin-top: 2px; }} +QAbstractSpinBox::down-button {{ subcontrol-position: bottom right; margin-bottom: 2px; }} +QAbstractSpinBox::up-button:hover, QAbstractSpinBox::down-button:hover {{ background-color: {tokens.hover}; }} +QAbstractSpinBox::up-arrow {{ image: url("{files['up']}"); width: {_SIDE - 2}px; height: {_SIDE - 2}px; }} +QAbstractSpinBox::down-arrow {{ image: url("{files['down']}"); width: {_SIDE - 2}px; height: {_SIDE - 2}px; }} +QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off {{ image: url("{files['up_off']}"); }} +QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off {{ image: url("{files['down_off']}"); }}""" diff --git a/je_auto_control/gui/adaptive/glyphs.py b/je_auto_control/gui/adaptive/glyphs.py index eaafd2e5a..e6e2308de 100644 --- a/je_auto_control/gui/adaptive/glyphs.py +++ b/je_auto_control/gui/adaptive/glyphs.py @@ -22,7 +22,20 @@ def _details(painter: QPainter, side: float) -> None: painter.drawLine(QPointF(side * 0.58, side * 0.22), QPointF(side * 0.58, side * 0.78)) -GLYPHS: Dict[str, _Painter] = {"menu": _menu, "search": _search, "details": _details} +def _chevron_down(painter: QPainter, side: float) -> None: + painter.drawPolyline([QPointF(side * 0.25, side * 0.38), QPointF(side * 0.5, side * 0.63), + QPointF(side * 0.75, side * 0.38)]) + + +def _chevron_up(painter: QPainter, side: float) -> None: + painter.drawPolyline([QPointF(side * 0.25, side * 0.62), QPointF(side * 0.5, side * 0.37), + QPointF(side * 0.75, side * 0.62)]) + + +GLYPHS: Dict[str, _Painter] = { + "menu": _menu, "search": _search, "details": _details, + "chevron_down": _chevron_down, "chevron_up": _chevron_up, +} def glyph_pixmap(name: str, colour: str, side: int = 20, scale: float = 1.0) -> QPixmap: @@ -33,6 +46,7 @@ def glyph_pixmap(name: str, colour: str, side: int = 20, scale: float = 1.0) -> pixmap.fill(Qt.GlobalColor.transparent) pen = QPen(QColor(colour), max(1.5, side / 12)) pen.setCapStyle(Qt.PenCapStyle.RoundCap) + pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) painter = QPainter(pixmap) try: painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) diff --git a/je_auto_control/gui/adaptive/style.py b/je_auto_control/gui/adaptive/style.py index 057baa312..c6bde9147 100644 --- a/je_auto_control/gui/adaptive/style.py +++ b/je_auto_control/gui/adaptive/style.py @@ -10,8 +10,10 @@ from PySide6.QtCore import QPointF, QRectF, Qt from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen -from PySide6.QtWidgets import QProxyStyle, QStyle, QStyleOption, QWidget +from PySide6.QtWidgets import QAbstractSpinBox, QLineEdit, QProxyStyle, QStyle, QStyleOption, QWidget +# The theme pads fields by 8 px inside a 1 px border; a spin box editor starts under the border. +SPIN_TEXT_INSET = 9 _INDICATORS = (QStyle.PrimitiveElement.PE_IndicatorCheckBox, QStyle.PrimitiveElement.PE_IndicatorRadioButton) @@ -93,6 +95,19 @@ def drawPrimitive(self, element: QStyle.PrimitiveElement, option: QStyleOption, return super().drawPrimitive(element, option, painter, widget) + def polish(self, target: Any) -> None: + """Inset a spin box's text as the theme pads every other field. + + A style sheet's padding moves the text of a line edit or combo box, but + a spin box places its inner editor over the left border regardless, so + its digits touched the frame. + """ + super().polish(target) + if isinstance(target, QAbstractSpinBox): + editor = target.findChild(QLineEdit) + if editor is not None: + editor.setTextMargins(SPIN_TEXT_INSET, 0, 0, 0) + def pixelMetric(self, metric: QStyle.PixelMetric, option: Any = None, # noqa: N802 # reason: Qt override widget: Optional[QWidget] = None) -> int: """Slightly larger indicators than Fusion's 13 px, easier to hit and to see.""" diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index 1e62d2ae8..3bebfcf44 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -213,11 +213,10 @@ def apply_theme(window: Any, tokens: ThemeTokens, point_size: Optional[int] = No ``point_size`` appends :func:`font_rule`, so the size is set on top of the theme instead of replacing it. """ + from je_auto_control.gui._arrow_icons import arrow_rules from je_auto_control.gui._tab_close_icon import close_button_rules - sheet = build_stylesheet(tokens) - close_rules = close_button_rules(tokens) - if close_rules: - sheet = f"{sheet}\n{close_rules}" + sheet = "\n".join(part for part in (build_stylesheet(tokens), close_button_rules(tokens), arrow_rules(tokens)) + if part) palette = _palette(tokens) window.setPalette(palette) # A widget a style sheet styles starts from the *application* palette, not diff --git a/pyproject.toml b/pyproject.toml index a3bda176d..205ad597e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -474,6 +474,7 @@ module = [ "je_auto_control.gui.adaptive", "je_auto_control.gui.adaptive.*", "je_auto_control.gui.adaptive_window", + "je_auto_control.gui._arrow_icons", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/unit_test/headless/test_gui_arrow_icons.py b/test/unit_test/headless/test_gui_arrow_icons.py new file mode 100644 index 000000000..1bc25a829 --- /dev/null +++ b/test/unit_test/headless/test_gui_arrow_icons.py @@ -0,0 +1,76 @@ +"""Drop-down and spin box chevrons drawn for the style sheet, and the spin box text inset.""" +import os + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + + +@pytest.fixture(scope="module") +def qapp(): + widgets = pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + return widgets.QApplication.instance() or widgets.QApplication([]) + + +def test_a_chevron_is_drawn_once_at_three_scales_in_the_given_colour(qapp, tmp_path): + from PySide6.QtGui import QImage + from je_auto_control.gui._arrow_icons import arrow_file + path = arrow_file("chevron_down", "#9AA1AE", tmp_path) + assert path is not None and path.is_file() + assert sorted(p.name for p in tmp_path.iterdir()) == [ + path.name, f"{path.stem}@2x.png", f"{path.stem}@3x.png"] + image = QImage(str(path.with_name(f"{path.stem}@3x.png"))) + inked = {image.pixelColor(x, y).name() for x in range(image.width()) for y in range(image.height()) + if image.pixelColor(x, y).alpha() == 255} + assert inked == {"#9aa1ae"}, "the stroke is the theme colour, nothing else" + stamp = path.stat().st_mtime_ns + assert arrow_file("chevron_down", "#9aa1ae", tmp_path) == path and path.stat().st_mtime_ns == stamp + + +def test_rules_place_both_controls_and_point_at_the_drawn_files(qapp, tmp_path): + from je_auto_control.gui._arrow_icons import arrow_rules + from je_auto_control.gui.theme import DARK + rules = arrow_rules(DARK, tmp_path) + for selector in ("QComboBox::drop-down", "QComboBox::down-arrow", "QAbstractSpinBox::up-button", + "QAbstractSpinBox::up-arrow", "QAbstractSpinBox::down-arrow:disabled"): + assert selector in rules + assert rules.count(tmp_path.as_posix()) == 6, "combo: arrow and dimmed; spin: up, down and both dimmed" + + +def test_without_a_writable_cache_the_controls_keep_the_style_arrows(qapp, tmp_path): + from je_auto_control.gui._arrow_icons import arrow_rules + from je_auto_control.gui.theme import DARK + blocker = tmp_path / "file" + blocker.write_text("not a directory", encoding="utf-8") + assert arrow_rules(DARK, blocker / "cache") == "", "placing the drop-down without an image would hide its arrow" + + +def test_the_theme_carries_the_arrow_rules(qapp): + from PySide6.QtWidgets import QWidget + from je_auto_control.gui.theme import LIGHT, apply_theme + window = QWidget() + try: + assert "QComboBox::down-arrow" in apply_theme(window, LIGHT) + finally: + window.deleteLater() + + +def test_a_themed_spin_box_insets_its_text_like_other_fields(qapp): + from PySide6.QtWidgets import QLineEdit, QSpinBox, QVBoxLayout, QWidget + from je_auto_control.gui.adaptive.style import SPIN_TEXT_INSET, AdaptiveStyle + from je_auto_control.gui.theme import DARK, apply_theme + previous = qapp.style().name() + style = AdaptiveStyle() + qapp.setStyle(style) + window = QWidget() + try: + spin = QSpinBox() + QVBoxLayout(window).addWidget(spin) + apply_theme(window, DARK) + window.show() + qapp.processEvents() + assert spin.findChild(QLineEdit).textMargins().left() == SPIN_TEXT_INSET + finally: + window.hide() + window.deleteLater() + qapp.setStyle(previous) From aa155b973b18d9a1800144d71ddf2bc6f213da52 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 07:06:17 +0800 Subject: [PATCH 073/161] Let tables fill their width and keep filling it after a refresh Columns sized to their contents stopped short of the table's edge, leaving a strip with no header; half the GUI's tables never stretched a column. The page fit pass stretches every table's last column, and since sizing columns by hand holds that column until the next resize, the five refresh paths now re-apply the stretch through fit_columns. --- Progress.md | 3 +- architecture_explore.md | 10 ++-- docs/updates/2026-11-b.md | 8 +++ docs/updates/README.md | 1 + je_auto_control/gui/adaptive/responsive.py | 59 +++++++++++++------ je_auto_control/gui/config_sync_tab.py | 4 +- je_auto_control/gui/dag_tab.py | 4 +- .../gui/healing_evaluation_panel.py | 3 +- je_auto_control/gui/self_healing_tab.py | 6 +- je_auto_control/gui/trace_replay_tab.py | 4 +- test/unit_test/headless/test_gui_adaptive.py | 36 +++++++++++ 11 files changed, 103 insertions(+), 35 deletions(-) diff --git a/Progress.md b/Progress.md index 09c2cd7b2..aaa158c74 100644 --- a/Progress.md +++ b/Progress.md @@ -536,8 +536,7 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - - 重排時看到、尚未處理的:Self-Healing 執行表在空表時 `resizeColumnsToContents()` 把欄名擠扁; - Remote Desktop 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複; + - 重排時看到、尚未處理的:Remote Desktop 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複; Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 diff --git a/architecture_explore.md b/architecture_explore.md index a830a1d04..04bba7ff3 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,653 | +| 程式碼總行數 | 235,677 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1303,7 +1303,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | -| `adaptive/responsive.py` | 120 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行),工作區放入每頁時跑一次。 | +| `adaptive/responsive.py` | 145 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行、表格最後一欄延展填滿),工作區放入每頁時跑一次;`fit_columns` 依內容定欄寬後重新延展最後一欄。 | | `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | | `adaptive/style.py` | 117 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | | `adaptive/glyphs.py` | 66 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | @@ -1358,7 +1358,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | | vlm | `vlm_tab.py` | 126 | 用文字描述 UI 元素,交由模型定位。 | -| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 955 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | +| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 954 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,456 | +| `gui/` | 160 | 42,480 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,525** | **234,908** | +| **總計** | **1,525** | **234,932** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index ca721aabe..b97a57f8a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -344,3 +344,11 @@ - **Tests:** `test_gui_arrow_icons.py` (5: cache at three scales in one colour and reused, the rules and their six image references, no rules without a writable cache, the theme carries them, the spin inset); adaptive, window and page-width tests 43 passed; strict typing tier and the extras contract pass. - **Files:** `gui/_arrow_icons.py` (new), `gui/adaptive/{glyphs,style}.py`, `gui/theme.py`, the test, `pyproject.toml` (strict tier), `architecture_explore.md`, `CHANGELOG.md`, `Progress.md`. - **Open items:** the remaining defects in `Progress.md` › F2 GUI 重製. + +## U-20261114-09 · 2026-11-14 · Tables fill their width: a stretched last column, re-applied after a refresh · #done #gui + +- **What:** the Self-Healing defect U-20261114-04 listed as squashed headers. Rendered, the headers were not squashed: the columns, sized to their contents, stopped at about two thirds of the table and left a strip with no header above it. 19 of the 38 GUI modules that build a table never stretched a column. The page fit pass (`fit_to_width`) now gives every horizontal table header a stretched last column; its per-widget branches moved into `_fit_widget` to stay under the complexity limit. +- **Refresh:** sizing a column by hand holds a stretched last column at that width until the table is next resized, so a refresh still left the strip. `adaptive.responsive.fit_columns(table, capped=(), cap=240)` sizes columns to their contents, caps the named ones and asks the header to re-apply the stretch; the five callers of `resizeColumnsToContents` (Self-Healing and its evaluation panel, DAG, Trace Replay, Config Sync) use it. Self-Healing's empty table now spans its full 904 px; before, 609. +- **Tests:** `test_gui_adaptive.py` +2 (the fit pass stretches a table's last column but not its rows; `fit_columns` refills after sizing and after capping; the second fails with the re-apply removed). Self-Healing, healing evaluation, DAG, Trace Replay, Config Sync, adaptive, page-width, typing, complexity and file-length tests: 846 passed, 27 skipped. +- **Files:** `gui/adaptive/responsive.py`, `gui/{self_healing_tab,healing_evaluation_panel,dag_tab,trace_replay_tab,config_sync_tab}.py`, the test, `architecture_explore.md`, `Progress.md`. +- **Open items:** tables built after the page's fit pass (panels created on first use) keep Qt's default; the remaining F2 defects stay in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 69559c0fa..7573433a9 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-09 | 2026-11-14 | Tables fill their width: a stretched last column, re-applied after a refresh | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-08 | 2026-11-14 | Drop-down and spin box arrows drawn in theme colours, inset from the border | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-07 | 2026-11-14 | Translate the 95 strings seven testing tabs shipped in English only | #done #gui #i18n | [2026-11-b](2026-11-b.md) | | U-20261114-06 | 2026-11-14 | GUI polish: theme colours in Remote Desktop, idle progress line, two strings that ignored a language switch | #done #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/adaptive/responsive.py b/je_auto_control/gui/adaptive/responsive.py index 89ea97862..0aa50e3d1 100644 --- a/je_auto_control/gui/adaptive/responsive.py +++ b/je_auto_control/gui/adaptive/responsive.py @@ -1,9 +1,12 @@ """Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide.""" -from typing import Callable, Optional, Tuple +from typing import Callable, Iterable, Optional, Tuple -from PySide6.QtCore import QCoreApplication, QEvent, QObject, QSize +from PySide6.QtCore import QCoreApplication, QEvent, QObject, QSize, Qt from PySide6.QtGui import QResizeEvent -from PySide6.QtWidgets import QBoxLayout, QComboBox, QFormLayout, QLabel, QLayout, QSizePolicy, QTabWidget, QWidget +from PySide6.QtWidgets import ( + QBoxLayout, QComboBox, QFormLayout, QHeaderView, QLabel, QLayout, QSizePolicy, QTableView, QTabWidget, + QWidget, +) #: Below this many logical pixels a :class:`ResponsiveBox` stacks its parts. DEFAULT_STACK_BELOW = 720 @@ -82,29 +85,51 @@ def fit_to_width(root: QWidget) -> int: """Let every control under ``root`` shrink with the window; return how many were adjusted. Combo boxes stop sizing themselves to their longest entry, form layouts - move a label above its field when both do not fit, long labels wrap and - nested tab widgets scroll their tab bar. Run once, after the page is - built; a control already fitted is left alone, so calling it again is cheap. + move a label above its field when both do not fit, long labels wrap, + nested tab widgets scroll their tab bar and a table's last column takes + the width its columns leave over. Run once, after the page is built; a + control already fitted is left alone, so calling it again is cheap. """ adjusted = 0 - widgets = [root, *root.findChildren(QWidget)] - for widget in widgets: + for widget in (root, *root.findChildren(QWidget)): if widget.property(_FITTED): continue widget.setProperty(_FITTED, True) _fit_layout(widget.layout()) - if isinstance(widget, QComboBox): - _fit_combo(widget) - elif isinstance(widget, QLabel) and not widget.wordWrap() and len(widget.text()) > 40: - widget.setWordWrap(True) - elif isinstance(widget, QTabWidget): - widget.setUsesScrollButtons(True) - else: - continue - adjusted += 1 + adjusted += _fit_widget(widget) return adjusted +def _fit_widget(widget: QWidget) -> bool: + if isinstance(widget, QComboBox): + _fit_combo(widget) + elif isinstance(widget, QLabel) and not widget.wordWrap() and len(widget.text()) > 40: + widget.setWordWrap(True) + elif isinstance(widget, QTabWidget): + widget.setUsesScrollButtons(True) + elif (isinstance(widget, QHeaderView) and widget.orientation() == Qt.Orientation.Horizontal + and not widget.stretchLastSection()): + # Columns sized to their contents stopped short of the table's right + # edge, leaving a strip with no header above it. + widget.setStretchLastSection(True) + else: + return False + return True + + +def fit_columns(table: QTableView, capped: Iterable[int] = (), cap: int = 240) -> None: + """Size ``table``'s columns to their contents, hold the ``capped`` ones to ``cap`` pixels, then refill the width. + + Sizing a column by hand keeps a stretched last column at its new width + until the table is next resized, so a refreshed table stopped short of its + right edge. The header re-applies the stretch here instead. + """ + table.resizeColumnsToContents() + for column in capped: + table.setColumnWidth(column, min(table.columnWidth(column), cap)) + table.horizontalHeader().resizeSections() + + class WidthWatcher(QObject): """Call ``callback(width)`` whenever ``target`` is resized.""" diff --git a/je_auto_control/gui/config_sync_tab.py b/je_auto_control/gui/config_sync_tab.py index 57b38d095..86c92fc45 100644 --- a/je_auto_control/gui/config_sync_tab.py +++ b/je_auto_control/gui/config_sync_tab.py @@ -12,7 +12,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.responsive import ResponsiveBox, fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui._worker_thread import WorkerHandle, start_worker from je_auto_control.gui.config_sync_worker import ConfigSyncWorker, SyncUIOutcome, SyncUIRequest @@ -378,7 +378,7 @@ def _show_heads(self, heads: dict[str, dict[str, object]]) -> None: entry['is_deleted'], json.dumps(entry['value'], ensure_ascii=False)) for column, value in enumerate(values): self._heads.setItem(row, column, QTableWidgetItem(str(value)[:1000])) - self._heads.resizeColumnsToContents() + fit_columns(self._heads) if heads: self._heads.selectRow(0) diff --git a/je_auto_control/gui/dag_tab.py b/je_auto_control/gui/dag_tab.py index 86f0ad093..0e72bd8dd 100644 --- a/je_auto_control/gui/dag_tab.py +++ b/je_auto_control/gui/dag_tab.py @@ -17,7 +17,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import WorkerHandle, start_worker from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of -from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.responsive import ResponsiveBox, fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -365,7 +365,7 @@ def _render_rows(self, rows: list[tuple]) -> None: item = QTableWidgetItem(str(text)) item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled) self._table.setItem(row, col, item) - self._table.resizeColumnsToContents() + fit_columns(self._table) __all__ = ["DagTab"] diff --git a/je_auto_control/gui/healing_evaluation_panel.py b/je_auto_control/gui/healing_evaluation_panel.py index 5fe1f3143..6c540d1b3 100644 --- a/je_auto_control/gui/healing_evaluation_panel.py +++ b/je_auto_control/gui/healing_evaluation_panel.py @@ -14,6 +14,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui.adaptive.responsive import fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.healing_evaluation_worker import HealingEvaluationOutcome, HealingEvaluationWorker from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper @@ -44,7 +45,7 @@ def _populate(table: QTableWidget, rows: list[list[str]]) -> None: for index, row in enumerate(rows): for column, value in enumerate(row): table.setItem(index, column, QTableWidgetItem(value)) - table.resizeColumnsToContents() + fit_columns(table) def _ratio(ratio: EvaluationRatio) -> str: diff --git a/je_auto_control/gui/self_healing_tab.py b/je_auto_control/gui/self_healing_tab.py index 57b316500..317abc4cf 100644 --- a/je_auto_control/gui/self_healing_tab.py +++ b/je_auto_control/gui/self_healing_tab.py @@ -15,6 +15,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui.adaptive.responsive import fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.healing_evaluation_panel import HealingEvaluationPanel from je_auto_control.gui.journal_browser import JournalBrowser @@ -251,10 +252,7 @@ def refresh_log(self) -> None: item = QTableWidgetItem(str(text)) item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled) self._table.setItem(row, col, item) - self._table.resizeColumnsToContents() - for name in ("template_path", "description"): - column = _COLUMNS.index(name) - self._table.setColumnWidth(column, min(self._table.columnWidth(column), 240)) + fit_columns(self._table, capped=(_COLUMNS.index("template_path"), _COLUMNS.index("description"))) self._show_event() def _show_event(self) -> None: diff --git a/je_auto_control/gui/trace_replay_tab.py b/je_auto_control/gui/trace_replay_tab.py index 203496b73..04f2e8608 100644 --- a/je_auto_control/gui/trace_replay_tab.py +++ b/je_auto_control/gui/trace_replay_tab.py @@ -17,7 +17,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.responsive import ResponsiveBox, fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -188,7 +188,7 @@ def _render_actions(self, state: ReplayState) -> None: item = QTableWidgetItem(text) item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled) self._actions_table.setItem(row, col, item) - self._actions_table.resizeColumnsToContents() + fit_columns(self._actions_table) __all__ = ["TraceReplayTab"] diff --git a/test/unit_test/headless/test_gui_adaptive.py b/test/unit_test/headless/test_gui_adaptive.py index cf6aeda9c..ed0517dc5 100644 --- a/test/unit_test/headless/test_gui_adaptive.py +++ b/test/unit_test/headless/test_gui_adaptive.py @@ -316,3 +316,39 @@ def test_applying_a_theme_sets_the_application_palette_so_styled_widgets_follow_ finally: qapp.setPalette(previous) window.deleteLater() + + +def test_the_fit_pass_stretches_a_tables_last_column(qapp): + from PySide6.QtWidgets import QTableWidget, QTreeWidget, QVBoxLayout, QWidget + from je_auto_control.gui.adaptive.responsive import fit_to_width + page = QWidget() + table, tree = QTableWidget(0, 3), QTreeWidget() + layout = QVBoxLayout(page) + layout.addWidget(table) + layout.addWidget(tree) + table.verticalHeader().setStretchLastSection(False) + fit_to_width(page) + assert table.horizontalHeader().stretchLastSection() + assert not table.verticalHeader().stretchLastSection(), "rows keep their height" + page.deleteLater() + + +def test_fit_columns_caps_the_named_columns_then_refills_the_table(qapp): + from PySide6.QtWidgets import QTableWidget, QTableWidgetItem + from je_auto_control.gui.adaptive.responsive import fit_columns + table = QTableWidget(1, 3) + table.horizontalHeader().setStretchLastSection(True) + table.resize(900, 200) + table.show() + qapp.processEvents() + for column, text in enumerate(("a", "bb", "tail")): + table.setItem(0, column, QTableWidgetItem(text)) + header = table.horizontalHeader() + fit_columns(table) # sizing the last column by hand would otherwise hold it until the next resize + assert header.length() == table.viewport().width(), "the last column takes the width the others leave" + table.setItem(0, 1, QTableWidgetItem("x" * 120)) + fit_columns(table, capped=(1,), cap=150) + assert table.columnWidth(1) == 150 + assert header.length() == table.viewport().width() + table.hide() + table.deleteLater() From 4d26d2423349c40c9adee578e18ac51310828af3 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 07:12:48 +0800 Subject: [PATCH 074/161] Shrink collapsed Remote Desktop sections to their title; show wrapped groups' title once A collapsed section kept its layout margins and bottom padding, and the style sheet's minimum hint counts the title twice, so it drew an empty strip under the title. The WebRTC viewer also wrapped titled groups in sections with the same title key, so the title showed twice; the section now adopts the group without its title or frame, and a language switch no longer restores it. --- Progress.md | 3 +- architecture_explore.md | 14 ++-- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + .../gui/remote_desktop/_helpers.py | 46 +++++++++-- .../gui/remote_desktop/webrtc_viewer_ui.py | 16 ++-- je_auto_control/gui/theme.py | 1 + .../headless/test_rd_collapsible_section.py | 82 +++++++++++++++++++ 8 files changed, 146 insertions(+), 25 deletions(-) create mode 100644 test/unit_test/headless/test_rd_collapsible_section.py diff --git a/Progress.md b/Progress.md index aaa158c74..491c394da 100644 --- a/Progress.md +++ b/Progress.md @@ -536,8 +536,7 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - - 重排時看到、尚未處理的:Remote Desktop 收合中的區段仍畫出一條空卡片、展開後區段與內層群組標題重複; - Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 + - 重排時看到、尚未處理的:Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, diff --git a/architecture_explore.md b/architecture_explore.md index 04bba7ff3..f60ac3de0 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,677 | +| 程式碼總行數 | 235,708 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1299,7 +1299,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 242 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 243 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | @@ -1386,7 +1386,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 371 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,338 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,368 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 326 | 管理多個遠端 AutoControl REST 端點。 | @@ -1404,7 +1404,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,338 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,368 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1426,7 +1426,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | | `webrtc_workers.py` | 237 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | | `tab.py` | 180 | 外層容器分頁。 | -| `_helpers.py` | 294 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | +| `_helpers.py` | 326 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | | `remote_screen_window.py` | 140 | 檢視端的彈出視窗。 | | `tray_icon.py` | 106 | WebRTC 主機的系統匣圖示。 | | `annotation_overlay.py` | 174 | 主機端標註的透明最上層覆蓋。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,480 | +| `gui/` | 160 | 42,511 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,525** | **234,932** | +| **總計** | **1,525** | **234,963** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index b97a57f8a..794b58e14 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -352,3 +352,11 @@ - **Tests:** `test_gui_adaptive.py` +2 (the fit pass stretches a table's last column but not its rows; `fit_columns` refills after sizing and after capping; the second fails with the re-apply removed). Self-Healing, healing evaluation, DAG, Trace Replay, Config Sync, adaptive, page-width, typing, complexity and file-length tests: 846 passed, 27 skipped. - **Files:** `gui/adaptive/responsive.py`, `gui/{self_healing_tab,healing_evaluation_panel,dag_tab,trace_replay_tab,config_sync_tab}.py`, the test, `architecture_explore.md`, `Progress.md`. - **Open items:** tables built after the page's fit pass (panels created on first use) keep Qt's default; the remaining F2 defects stay in `Progress.md`. + +## U-20261114-10 · 2026-11-14 · Remote Desktop's collapsed sections shrink to their title; wrapped groups show one title · #done #gui #remote-desktop + +- **What:** two defects U-20261114-04 listed. A collapsed `_CollapsibleSection` was a 69 px card with an empty strip under its title: its layout margins (8, 14, 8, 8) and the box's bottom padding stayed with the body hidden, and the style sheet's minimum size hint adds the title's height to a top padding that already holds the title. Collapsed, the section now drops its layout margins, gets a `collapsed` property the theme uses to remove the bottom padding, and reports only its padding as minimum height: 39 px, a bar with the title centred. Expanded, the body sits 4 px under the title instead of 14 px and is no longer indented 8 px past other group boxes. +- **Double title:** the WebRTC viewer wraps its manual-signalling, remote-files and folder-sync group boxes in sections titled with the same keys, so the title showed twice and the inner group kept its title padding. `_CollapsibleSection.adopt` takes the inner group without its title, frame or padding, and `_wrap_collapsed` drops the inner group's translation entry so a language switch does not restore the title. +- **Tests:** `test_rd_collapsible_section.py` (3: closed height equals the title padding and grows when opened, an adopted group loses title and frame, a retranslate leaves it untitled). Remote Desktop, WebRTC, adaptive, page-width and dispose tests: 1,817 passed, 11 skipped. +- **Files:** `gui/remote_desktop/{_helpers,webrtc_viewer_ui}.py`, `gui/theme.py`, the test, `Progress.md`. +- **Open items:** Trace Replay's divider, in `Progress.md` › F2 GUI 重製. diff --git a/docs/updates/README.md b/docs/updates/README.md index 7573433a9..584fb960d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-10 | 2026-11-14 | Remote Desktop's collapsed sections shrink to their title; wrapped groups show one title | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-09 | 2026-11-14 | Tables fill their width: a stretched last column, re-applied after a refresh | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-08 | 2026-11-14 | Drop-down and spin box arrows drawn in theme colours, inset from the border | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-07 | 2026-11-14 | Translate the 95 strings seven testing tabs shipped in English only | #done #gui #i18n | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/_helpers.py b/je_auto_control/gui/remote_desktop/_helpers.py index 4f368ac04..aa9dd52e5 100644 --- a/je_auto_control/gui/remote_desktop/_helpers.py +++ b/je_auto_control/gui/remote_desktop/_helpers.py @@ -4,7 +4,7 @@ import weakref from typing import Any, Callable, Optional -from PySide6.QtCore import Qt +from PySide6.QtCore import QSize, Qt from PySide6.QtGui import QKeyEvent from PySide6.QtWidgets import QGroupBox, QHBoxLayout, QLabel, QVBoxLayout, QWidget @@ -179,7 +179,11 @@ def set_state(self, state: str, text: str) -> None: class _CollapsibleSection(QGroupBox): - """``QGroupBox`` with a checkable header that hides/shows its body.""" + """``QGroupBox`` with a checkable header that hides/shows its body. + + Collapsed, it shrinks to its title: the layout margins and the box's + bottom padding go too, or the card kept an empty strip under the title. + """ def __init__(self, title: str = "", parent: Optional[QWidget] = None) -> None: @@ -188,11 +192,10 @@ def __init__(self, title: str = "", self.setChecked(False) self._body = QWidget(self) self._body.setProperty("role", "bare") - outer = QVBoxLayout(self) - outer.setContentsMargins(8, 14, 8, 8) - outer.addWidget(self._body) - self._body.setVisible(False) - self.toggled.connect(self._body.setVisible) + self._outer = QVBoxLayout(self) + self._outer.addWidget(self._body) + self.toggled.connect(self._show_body) + self._show_body(False) @property def body(self) -> QWidget: @@ -201,6 +204,35 @@ def body(self) -> QWidget: def set_body_layout(self, layout) -> None: self._body.setLayout(layout) + def adopt(self, inner: QGroupBox) -> None: + """Make ``inner`` the body, without its own frame and title: the section already shows both.""" + inner.setTitle("") + inner.setStyleSheet( + "QGroupBox { border: none; margin: 0px; padding: 0px; background: transparent; }") + body = QVBoxLayout() + body.setContentsMargins(0, 0, 0, 0) + body.addWidget(inner) + self.set_body_layout(body) + + def minimumSizeHint(self) -> QSize: # noqa: N802 # reason: Qt override + """Collapsed, only the padding that holds the title. + + The style sheet's hint adds the title's height on top of a top padding + that already contains the title, which alone left a strip below it. + """ + hint = super().minimumSizeHint() + if not self.isChecked(): + margins = self.contentsMargins() + hint.setHeight(margins.top() + margins.bottom()) + return hint + + def _show_body(self, shown: bool) -> None: + self._body.setVisible(shown) + self._outer.setContentsMargins(0, 4 if shown else 0, 0, 0) + self.setProperty("collapsed", not shown) + self.style().unpolish(self) + self.style().polish(self) + def _row(field: QWidget, *extras: QWidget) -> QHBoxLayout: """``field`` taking the width, followed by its buttons at their natural size (one form row).""" diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py index 85b6b3a50..701a57c6c 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_ui.py @@ -169,20 +169,18 @@ def _wrap_collapsed(self, inner: QGroupBox, title_key: str) -> _CollapsibleSection: """Wrap an existing groupbox in a collapsed-by-default container. - The inner group keeps its own translated title, so we just pass - it through the wrapper's body. Heavy / rarely-used groups + The section shows the title and the frame, so the inner group + loses both (see ``_CollapsibleSection.adopt``). Heavy / rarely-used groups (manual SDP, remote files, sync) hide their bodies by default so the panel doesn't scroll past the fold on a normal display. """ section = _CollapsibleSection() - # Translate the wrapper title; the inner groupbox already has - # its own header so we strip its frame to avoid double chrome. + # The section carries the title; the inner group gives up its own + # (the same key, so it showed twice) and must not get it back on a + # language switch. self._tr(section, title_key, setter="setTitle") - inner.setStyleSheet("QGroupBox { border: none; margin-top: 0px; }") - body = QVBoxLayout() - body.setContentsMargins(0, 0, 0, 0) - body.addWidget(inner) - section.set_body_layout(body) + self._tr_registry = [entry for entry in self._tr_registry if entry[0] is not inner] + section.adopt(inner) return section def _build_address_book_group(self) -> QGroupBox: diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index 3bebfcf44..3c0201f15 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -136,6 +136,7 @@ def type_scale_rules(point_size: int) -> str: QGroupBox {{ border: 1px solid {border}; border-radius: {radius_large}px; margin-top: 0; padding: 2.3em {spacing}px {spacing}px {spacing}px; background-color: {surface}; font-weight: 600; }} +QGroupBox[collapsed="true"] {{ padding-bottom: 0; }} QGroupBox::title {{ subcontrol-origin: padding; subcontrol-position: top left; left: {wide}px; top: {spacing}px; padding: 0; color: {text}; background: transparent; }} QGroupBox QLabel, QGroupBox QCheckBox, QGroupBox QRadioButton, QGroupBox QPushButton, diff --git a/test/unit_test/headless/test_rd_collapsible_section.py b/test/unit_test/headless/test_rd_collapsible_section.py new file mode 100644 index 000000000..39e94690d --- /dev/null +++ b/test/unit_test/headless/test_rd_collapsible_section.py @@ -0,0 +1,82 @@ +"""Remote Desktop's collapsible sections: a bare title bar when closed, one title when a group is wrapped.""" +import os + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + + +@pytest.fixture(scope="module") +def qapp(): + widgets = pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + return widgets.QApplication.instance() or widgets.QApplication([]) + + +def _themed(qapp, *sections): + from PySide6.QtWidgets import QVBoxLayout, QWidget + from je_auto_control.gui.theme import DARK, apply_theme + window = QWidget() + layout = QVBoxLayout(window) + for section in sections: + layout.addWidget(section) + layout.addStretch(1) + apply_theme(window, DARK) + window.resize(400, 400) + window.show() + qapp.processEvents() + return window + + +def test_a_closed_section_is_only_as_tall_as_its_title_padding(qapp): + from PySide6.QtWidgets import QCheckBox, QVBoxLayout + from je_auto_control.gui.remote_desktop._helpers import _CollapsibleSection + section = _CollapsibleSection("Advanced") + body = QVBoxLayout() + body.addWidget(QCheckBox("Enable audio")) + section.set_body_layout(body) + window = _themed(qapp, section) + try: + margins = section.contentsMargins() + assert section.height() == margins.top() + margins.bottom(), "no strip under the title" + assert section.property("collapsed") is True + section.setChecked(True) + qapp.processEvents() + assert section.body.isVisible() and section.property("collapsed") is False + assert section.height() > margins.top() + margins.bottom() + section.body.sizeHint().height() - 1 + finally: + window.hide() + window.deleteLater() + + +def test_an_adopted_group_gives_up_its_title_and_frame(qapp): + from PySide6.QtWidgets import QGroupBox, QLabel, QVBoxLayout + from je_auto_control.gui.remote_desktop._helpers import _CollapsibleSection + section = _CollapsibleSection("Folder sync") + inner = QGroupBox("Folder sync") + QVBoxLayout(inner).addWidget(QLabel("Local folder")) + section.adopt(inner) + window = _themed(qapp, section) + try: + assert inner.title() == "" + assert inner.parent() is section.body + assert "border: none" in inner.styleSheet() + finally: + window.hide() + window.deleteLater() + + +def test_a_language_switch_does_not_give_the_wrapped_group_its_title_back(qapp): + pytest.importorskip("aiortc", exc_type=ImportError) + from PySide6.QtWidgets import QGroupBox, QWidget + from je_auto_control.gui._i18n_helpers import TranslatableMixin + from je_auto_control.gui.remote_desktop.webrtc_viewer_ui import _ViewerUiMixin + + class Host(TranslatableMixin, QWidget): + _wrap_collapsed = _ViewerUiMixin._wrap_collapsed + + host = Host() + inner = host._tr(QGroupBox(), "rd_webrtc_sync_group") + section = host._wrap_collapsed(inner, "rd_webrtc_sync_group") + host.retranslate() + assert inner.title() == "" and section.title() != "" + host.deleteLater() From b51479ca9ba420a491d31b99c40454e247373908 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 07:17:51 +0800 Subject: [PATCH 075/161] Give Trace Replay and Run History their draggable divider back The tab rework replaced their splitters with a stacking box, since a splitter asks for the sum of its parts' minimum widths, and the user lost the divider. ResponsiveSplitter stacks like the box and keeps the divider in both arrangements; its handle is drawn as the cards' gap instead of a seam. --- Progress.md | 1 - architecture_explore.md | 10 ++-- .../doc/new_features/v224_features_doc.rst | 9 +++- .../Zh/doc/new_features/v224_features_doc.rst | 7 ++- docs/updates/2026-11-b.md | 9 ++++ docs/updates/README.md | 1 + je_auto_control/gui/adaptive/responsive.py | 46 ++++++++++++++++++- je_auto_control/gui/run_history_tab.py | 4 +- je_auto_control/gui/theme.py | 4 ++ je_auto_control/gui/trace_replay_tab.py | 4 +- test/unit_test/headless/test_gui_adaptive.py | 23 ++++++++++ 11 files changed, 105 insertions(+), 13 deletions(-) diff --git a/Progress.md b/Progress.md index 491c394da..7885121f7 100644 --- a/Progress.md +++ b/Progress.md @@ -536,7 +536,6 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - - 重排時看到、尚未處理的:Trace Replay 的畫面/動作改為 `ResponsiveBox` 後不能再拖曳分隔線。 - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, diff --git a/architecture_explore.md b/architecture_explore.md index f60ac3de0..df9c3b507 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,708 | +| 程式碼總行數 | 235,756 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1299,11 +1299,11 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 243 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 247 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | -| `adaptive/responsive.py` | 145 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行、表格最後一欄延展填滿),工作區放入每頁時跑一次;`fit_columns` 依內容定欄寬後重新延展最後一欄。 | +| `adaptive/responsive.py` | 189 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`ResponsiveSplitter`(同上但分隔線可拖曳)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行、表格最後一欄延展填滿),工作區放入每頁時跑一次;`fit_columns` 依內容定欄寬後重新延展最後一欄。 | | `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | | `adaptive/style.py` | 117 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | | `adaptive/glyphs.py` | 66 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,511 | +| `gui/` | 160 | 42,559 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,525** | **234,963** | +| **總計** | **1,525** | **235,011** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v224_features_doc.rst b/docs/source/Eng/doc/new_features/v224_features_doc.rst index 9bacb1b59..46911079a 100644 --- a/docs/source/Eng/doc/new_features/v224_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v224_features_doc.rst @@ -59,7 +59,8 @@ What every page gets * **Controls that shrink.** When a page is first shown it goes through a fit pass: drop-down lists stop sizing themselves to their longest entry (Mobile needed 1,464 px for one command label), form labels move above their field - when both do not fit, and long notes wrap. + when both do not fit, long notes wrap, and a table's last column takes the + width its other columns leave. Building blocks --------------- @@ -77,6 +78,12 @@ They live in ``je_auto_control.gui.adaptive``: ``responsive.ResponsiveBox`` Two or more parts side by side when there is room, stacked below a width you choose. +``responsive.ResponsiveSplitter`` + The same, with a divider the user can drag in either arrangement (Trace + Replay, Run History). +``responsive.fit_columns`` + Sizes a table's columns to their contents, caps the ones you name, then + lets the last column fill the table again. ``responsive.fit_to_width`` The fit pass described above. The workspace runs it on every page it shows; a control already fitted is left alone. diff --git a/docs/source/Zh/doc/new_features/v224_features_doc.rst b/docs/source/Zh/doc/new_features/v224_features_doc.rst index 9f2567915..ccbf48aa6 100644 --- a/docs/source/Zh/doc/new_features/v224_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v224_features_doc.rst @@ -49,7 +49,8 @@ GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一 * **看得見的核取方塊與選項按鈕。** Fusion 以視窗色的深淺描邊,深色主題下幾乎看不見; 現在改由程式依調色盤繪製(強調色填色、勾號、外圈與圓點),隨主題變化,不需要圖檔。 * **會縮小的控制項。** 分頁第一次顯示時會經過一次調整:下拉選單不再以最長項目決定寬度 - (Mobile 曾因一個指令名稱需要 1,464 px)、表單放不下時標籤移到欄位上方、長說明自動換行。 + (Mobile 曾因一個指令名稱需要 1,464 px)、表單放不下時標籤移到欄位上方、長說明自動換行, + 表格最後一欄延展填滿其餘欄位留下的寬度。 元件 ---- @@ -64,6 +65,10 @@ GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一 放不下時換到下一行、而不撐寬頁面的列;最小寬度等於最寬的單一項目。 ``responsive.ResponsiveBox`` 空間足夠時並排、低於指定寬度時上下堆疊。 +``responsive.ResponsiveSplitter`` + 同上,且兩種排列下都有可拖曳的分隔線(Trace Replay、Run History)。 +``responsive.fit_columns`` + 依內容定欄寬、限制指定欄的寬度,再讓最後一欄重新填滿表格。 ``responsive.fit_to_width`` 上述的調整。工作區顯示每個分頁時都會執行;已調整過的控制項不會重複處理。 ``surfaces`` diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 794b58e14..8fe809f1c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -360,3 +360,12 @@ - **Tests:** `test_rd_collapsible_section.py` (3: closed height equals the title padding and grows when opened, an adopted group loses title and frame, a retranslate leaves it untitled). Remote Desktop, WebRTC, adaptive, page-width and dispose tests: 1,817 passed, 11 skipped. - **Files:** `gui/remote_desktop/{_helpers,webrtc_viewer_ui}.py`, `gui/theme.py`, the test, `Progress.md`. - **Open items:** Trace Replay's divider, in `Progress.md` › F2 GUI 重製. + +## U-20261114-11 · 2026-11-14 · Trace Replay and Run History get their draggable divider back · #done #gui + +- **What:** the last layout defect U-20261114-04 listed. The tab rework swapped two horizontal `QSplitter`s (Trace Replay's frame and actions, Run History's runs and preview) for `ResponsiveBox`, because a splitter asks for the sum of its parts' minimum widths and the box can stack; the user lost the divider. `adaptive.responsive.ResponsiveSplitter` is a `QSplitter` that does what the box does (side by side from `stack_below`, stacked under it, minimum width of its widest part, stretches per part) and keeps the divider in both arrangements; children do not collapse. Both tabs use it. +- **Look:** the theme drew every splitter handle as a 1 px border line, which between two cards reads as a seam with no gap. Splitters with the `cards` role (this one) get a transparent 12 px handle, the gap the box had, filled with the hover colour under the pointer. +- **Checked:** Trace Replay at 1,000 px is side by side and its divider moves; at 600 px it stacks and the divider still moves; the tab's minimum width is unchanged at 372 px. +- **Tests:** `test_gui_adaptive.py` +1 (minimum width is the widest part, the divider drags, a resize stacks it). Adaptive, page-width, Trace Replay, Run History, workspace and theme tests: 240 passed, 17 skipped. The v224 feature pages (English and Chinese) list `ResponsiveSplitter` and `fit_columns` (U-20261114-09) and the table stretch in the fit pass. +- **Files:** `gui/adaptive/responsive.py`, `gui/{trace_replay_tab,run_history_tab}.py`, `gui/theme.py`, the test, both `v224_features_doc.rst`, `architecture_explore.md`, `Progress.md`. +- **Open items:** mixed DPI, a second monitor and Linux / macOS fonts, and the `FlowLayout` teardown message (`Progress.md` › F2 GUI 重製). diff --git a/docs/updates/README.md b/docs/updates/README.md index 584fb960d..7d92ac10a 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-11 | 2026-11-14 | Trace Replay and Run History get their draggable divider back | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-10 | 2026-11-14 | Remote Desktop's collapsed sections shrink to their title; wrapped groups show one title | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-09 | 2026-11-14 | Tables fill their width: a stretched last column, re-applied after a refresh | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-08 | 2026-11-14 | Drop-down and spin box arrows drawn in theme colours, inset from the border | #done #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/adaptive/responsive.py b/je_auto_control/gui/adaptive/responsive.py index 0aa50e3d1..51d25fd2e 100644 --- a/je_auto_control/gui/adaptive/responsive.py +++ b/je_auto_control/gui/adaptive/responsive.py @@ -4,7 +4,7 @@ from PySide6.QtCore import QCoreApplication, QEvent, QObject, QSize, Qt from PySide6.QtGui import QResizeEvent from PySide6.QtWidgets import ( - QBoxLayout, QComboBox, QFormLayout, QHeaderView, QLabel, QLayout, QSizePolicy, QTableView, QTabWidget, + QBoxLayout, QComboBox, QFormLayout, QHeaderView, QLabel, QLayout, QSizePolicy, QSplitter, QTableView, QTabWidget, QWidget, ) @@ -60,6 +60,50 @@ def arrange(self, width: int) -> None: self._layout.setDirection(direction) +class ResponsiveSplitter(QSplitter): + """A :class:`ResponsiveBox` whose divider can be dragged. + + Side by side when there is room, one above the other when there is not; in + both, the user moves the divider. A plain ``QSplitter`` asks for the sum of + its parts' minimum widths even where stacking would fit, which is why pages + had swapped theirs for a box and lost the divider. + """ + + def __init__(self, *parts: QWidget, stack_below: int = DEFAULT_STACK_BELOW, + stretches: Tuple[int, ...] = (), parent: Optional[QWidget] = None) -> None: + super().__init__(Qt.Orientation.Horizontal, parent) + self.stack_below = stack_below + self.setChildrenCollapsible(False) + # The theme draws this role's handle as a card gap that lights up on hover. + self.setProperty("role", "cards") + for index, part in enumerate(parts): + self.addWidget(part) + self.setStretchFactor(index, stretches[index] if index < len(stretches) else 1) + + @property + def stacked(self) -> bool: + """Whether the parts are currently one above the other.""" + return self.orientation() == Qt.Orientation.Vertical + + def minimumSizeHint(self) -> QSize: # noqa: N802 # reason: Qt override + """Never ask for more width than the widest part needs on its own.""" + hint = super().minimumSizeHint() + parts = (self.widget(index) for index in range(self.count())) + hint.setWidth(max((part.minimumSizeHint().width() for part in parts if part is not None), default=0)) + return hint + + def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 # reason: Qt override + """Switch between side by side and stacked as the width crosses ``stack_below``.""" + self.arrange(event.size().width()) + super().resizeEvent(event) + + def arrange(self, width: int) -> None: + """Lay the parts out for ``width`` pixels.""" + orientation = Qt.Orientation.Vertical if width < self.stack_below else Qt.Orientation.Horizontal + if self.orientation() != orientation: + self.setOrientation(orientation) + + def _fit_combo(combo: QComboBox) -> None: combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) combo.setMinimumContentsLength(COMBO_MINIMUM_CHARACTERS) diff --git a/je_auto_control/gui/run_history_tab.py b/je_auto_control/gui/run_history_tab.py index 42b439dda..48e414c2b 100644 --- a/je_auto_control/gui/run_history_tab.py +++ b/je_auto_control/gui/run_history_tab.py @@ -13,7 +13,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of -from je_auto_control.gui.adaptive.responsive import ResponsiveBox +from je_auto_control.gui.adaptive.responsive import ResponsiveSplitter from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -160,7 +160,7 @@ def _build_layout(self) -> None: preview.add(self._thumb_label, stretch=1).add(self._thumb_caption) # Stacked under a narrow window the table would otherwise shrink to its header. self._table.setMinimumHeight(200) - runs = ResponsiveBox(Card().add(self._table, stretch=1), preview, stretches=(3, 1)) + runs = ResponsiveSplitter(Card().add(self._table, stretch=1), preview, stretches=(3, 1)) # The journal browser is shared with Self-Healing; tag it so it shows the card behind it. self._journal.setProperty("role", "bare") sections = QSplitter(Qt.Orientation.Vertical) diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index 3c0201f15..655449a10 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -164,6 +164,10 @@ def type_scale_rules(point_size: int) -> str: QSplitter::handle {{ background-color: {border}; }} QSplitter::handle:horizontal {{ width: 1px; }} QSplitter::handle:vertical {{ height: 1px; }} +QSplitter[role="cards"]::handle {{ background-color: transparent; border-radius: {small}px; }} +QSplitter[role="cards"]::handle:horizontal {{ width: 12px; }} +QSplitter[role="cards"]::handle:vertical {{ height: 12px; }} +QSplitter[role="cards"]::handle:hover {{ background-color: {hover}; }} QProgressBar {{ background-color: {surface_raised}; border: 0; border-radius: {small}px; text-align: center; }} QProgressBar::chunk {{ background-color: {accent}; border-radius: {small}px; }} QStatusBar {{ background-color: {window}; border-top: 1px solid {border}; color: {text_muted}; }} diff --git a/je_auto_control/gui/trace_replay_tab.py b/je_auto_control/gui/trace_replay_tab.py index 04f2e8608..1ee1f8659 100644 --- a/je_auto_control/gui/trace_replay_tab.py +++ b/je_auto_control/gui/trace_replay_tab.py @@ -17,7 +17,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui.adaptive.responsive import ResponsiveBox, fit_columns +from je_auto_control.gui.adaptive.responsive import ResponsiveSplitter, fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -68,7 +68,7 @@ def _build_layout(self) -> None: root.addWidget(Card().add(self._slider)) frame = Card().add(self._frame_label, stretch=1) actions = Card().add(self._actions_table, stretch=1) - root.addWidget(ResponsiveBox(frame, actions, stretches=(3, 2)), stretch=1) + root.addWidget(ResponsiveSplitter(frame, actions, stretches=(3, 2)), stretch=1) self._status.setWordWrap(True) set_role(self._status, "hint") root.addWidget(self._status) diff --git a/test/unit_test/headless/test_gui_adaptive.py b/test/unit_test/headless/test_gui_adaptive.py index ed0517dc5..523ce3f74 100644 --- a/test/unit_test/headless/test_gui_adaptive.py +++ b/test/unit_test/headless/test_gui_adaptive.py @@ -187,6 +187,29 @@ def test_a_responsive_box_stacks_below_its_threshold(qapp): box.deleteLater() +def test_a_responsive_splitter_stacks_like_a_box_and_keeps_its_divider(qapp): + from PySide6.QtWidgets import QLabel + from je_auto_control.gui.adaptive.responsive import ResponsiveSplitter + left, right = QLabel("frame"), QLabel("actions") + left.setMinimumWidth(300) + right.setMinimumWidth(200) + splitter = ResponsiveSplitter(left, right, stack_below=600, stretches=(3, 2)) + assert splitter.minimumSizeHint().width() == 300, "never more than the widest part" + assert not splitter.childrenCollapsible() + splitter.resize(900, 300) + splitter.show() + qapp.processEvents() + assert not splitter.stacked + before = splitter.sizes() + splitter.moveSplitter(before[0] - 100, 1) + assert splitter.sizes()[0] == before[0] - 100, "the user can still drag the divider" + splitter.resize(500, 600) + qapp.processEvents() + assert splitter.stacked + splitter.hide() + splitter.deleteLater() + + def test_the_fit_pass_stops_a_long_combo_from_widening_its_page(qapp): from PySide6.QtWidgets import QComboBox, QFormLayout, QLabel, QVBoxLayout, QWidget from je_auto_control.gui.adaptive.responsive import fit_to_width From 8f5699ccb4faeda3dc060f1553d8ce5621cac6b2 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 09:35:35 +0800 Subject: [PATCH 076/161] Require merging and removing git worktrees when work is done --- CLAUDE.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index f1770f99f..076a43b4c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -222,3 +222,9 @@ Workspace rule shared by every repository under `D:\Codes` (full text: `D:\Codes - Platform backends are named `{platform}_{function}.py` (e.g. `win32_ctype_mouse_control.py`). - Virtual key mappings live in `core/utils/*_vk.py` per platform. - Two PyPI packages, both published by CI: a push to `main` releases `je_auto_control` (the `publish` job of `stable.yml`), and a push to `dev` that passes the headless suite and changes what the package ships releases `je_auto_control_dev` (the `publish-dev` job of `dev.yml`, `scripts/dev_release.py`). Never bump a patch version by hand: `scripts/stable_release.py` releases one patch above the version `pyproject.toml` declares whenever that version already has a `v*` tag. A minor or major release is the one exception — set the new version in `pyproject.toml` in the pull request that ships it, and the job releases that untagged version as written (`test/unit_test/headless/test_stable_release.py`). The version in `dev.toml` is only a floor. `dev.toml` must declare what `pyproject.toml` declares, so a change to dependencies, extras, scripts, entry points or `[tool.setuptools]` goes into both files (`test/unit_test/headless/test_dev_toml_parity.py` fails otherwise). Both publish jobs hold the PyPI token, so they install only the hash-locked `.github/requirements/publish.txt` and build with `python -m build --no-isolation`: a new tool, or a higher floor in `build-system.requires`, needs the lock regenerated with the command at the top of `.github/requirements/publish.in` (`test/unit_test/headless/test_publish_tooling_lock.py` fails otherwise). + +## Git worktrees: merge and remove + +- Every git worktree created for a task must be finished off: merge its branch back into the branch it was started from, then remove the worktree (`git worktree remove `) and delete its branch (`git branch -d `). +- Do not leave worktrees behind when the work is done; check `git worktree list` before ending the task. +- If a worktree cannot be merged yet, say so explicitly instead of leaving it behind silently. From 2837798b7c77ae24b97b470e7992c005c25e93ed Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 10:13:02 +0800 Subject: [PATCH 077/161] End whole-window probes without Windows DLL teardown os._exit still runs every DLL's process-detach on Windows, so Qt's static teardown raced the helper threads tabs start and faulted the page-width probe after its report was written. The same teardown printed the FlowLayout pure-virtual message, so that F2 item is closed. --- Progress.md | 2 -- docs/updates/2026-11-b.md | 8 ++++++++ docs/updates/README.md | 1 + test/unit_test/headless/test_actions_menu_gui.py | 8 ++++++++ test/unit_test/headless/test_gui_lazy_registry.py | 8 ++++++++ test/unit_test/headless/test_gui_page_widths.py | 8 ++++++++ test/unit_test/headless/test_gui_workspace_navigation.py | 8 ++++++++ test/unit_test/headless/test_r3_gui_thread_marshal.py | 8 ++++++++ 8 files changed, 49 insertions(+), 2 deletions(-) diff --git a/Progress.md b/Progress.md index 7885121f7..01d3671e7 100644 --- a/Progress.md +++ b/Progress.md @@ -536,8 +536,6 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - - Python 實作的 `FlowLayout` 在行程以 `os._exit` 結束時偶發印出 `pure virtual method 'QLayout.itemAt'` - (Email Triggers 分頁單獨建立時 HEAD 三次兩次、改後三次零次;未崩潰):結束時 Qt 呼叫到正在拆除的 Python 覆寫。來源未查。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 8fe809f1c..33cc7c105 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -369,3 +369,11 @@ - **Tests:** `test_gui_adaptive.py` +1 (minimum width is the widest part, the divider drags, a resize stacks it). Adaptive, page-width, Trace Replay, Run History, workspace and theme tests: 240 passed, 17 skipped. The v224 feature pages (English and Chinese) list `ResponsiveSplitter` and `fit_columns` (U-20261114-09) and the table stretch in the fit pass. - **Files:** `gui/adaptive/responsive.py`, `gui/{trace_replay_tab,run_history_tab}.py`, `gui/theme.py`, the test, both `v224_features_doc.rst`, `architecture_explore.md`, `Progress.md`. - **Open items:** mixed DPI, a second monitor and Linux / macOS fonts, and the `FlowLayout` teardown message (`Progress.md` › F2 GUI 重製). + +## U-20261114-12 · 2026-11-14 · Whole-window probes end without Windows DLL teardown · #done #gui #test + +- **What:** CI's `pytest-headless (windows-2022, 3.11)` on b51479ca failed the three page-width tests at setup: the probe's child interpreter exited with 0xC0000005 on its last line, `os._exit(0)`, after its report was on stdout, while a tab's USB-enumeration worker was still in `subprocess.run`. On Windows `os._exit` still runs every DLL's process-detach, so Qt's static teardown runs while the helper threads tabs start at construction are alive. The five whole-window probes (`test_actions_menu_gui`, `test_gui_lazy_registry`, `test_gui_workspace_navigation`, `test_r3_gui_thread_marshal`, `test_gui_page_widths`) now end with `TerminateProcess` on Windows, which ends the process without detach; `os._exit` stays the exit elsewhere. +- **Same cause:** the `pure virtual method 'QLayout.itemAt'` message `Progress.md` listed under F2 for `FlowLayout`. Building the Email Triggers tab alone and exiting ten times each way: `os._exit` printed it 15 times, `TerminateProcess` and a normal interpreter exit never did. The layout is not at fault and the application's own exit does not print it, so the item is closed. +- **Tests:** the five probe files: 96 passed. +- **Files:** the five tests, `Progress.md`. +- **Open items:** mixed DPI, a second monitor and Linux / macOS fonts (`Progress.md` › F2 GUI 重製). diff --git a/docs/updates/README.md b/docs/updates/README.md index 7d92ac10a..f584b98ff 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-12 | 2026-11-14 | Whole-window probes end without Windows DLL teardown | #done #gui #test | [2026-11-b](2026-11-b.md) | | U-20261114-11 | 2026-11-14 | Trace Replay and Run History get their draggable divider back | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-10 | 2026-11-14 | Remote Desktop's collapsed sections shrink to their title; wrapped groups show one title | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-09 | 2026-11-14 | Tables fill their width: a stretched last column, re-applied after a refresh | #done #gui | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/test_actions_menu_gui.py b/test/unit_test/headless/test_actions_menu_gui.py index 78fb11b27..d9c4e63a0 100644 --- a/test/unit_test/headless/test_actions_menu_gui.py +++ b/test/unit_test/headless/test_actions_menu_gui.py @@ -95,6 +95,14 @@ def entry_actions(entry): # Skip Qt/native-thread teardown entirely: some tabs start helper threads # at construction and interpreter shutdown can abort. The report is # already on stdout, so a hard exit is the safe end for this probe. +if sys.platform == "win32": + # os._exit still runs every DLL's detach on Windows, where Qt's teardown + # races the helper threads tabs start and can fault (0xC0000005) after the + # report is written. TerminateProcess ends the process without it. + import ctypes + kernel32 = ctypes.windll.kernel32 + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.TerminateProcess(ctypes.c_void_p(kernel32.GetCurrentProcess()), 0) os._exit(0) """ diff --git a/test/unit_test/headless/test_gui_lazy_registry.py b/test/unit_test/headless/test_gui_lazy_registry.py index 6c81f9949..cca3af11f 100644 --- a/test/unit_test/headless/test_gui_lazy_registry.py +++ b/test/unit_test/headless/test_gui_lazy_registry.py @@ -134,6 +134,14 @@ def test_a_lazy_factory_imports_at_call_time(): and widget.current_tab_key() == "remote_desktop") sys.stdout.write(json.dumps(report)) sys.stdout.flush() +if sys.platform == "win32": + # os._exit still runs every DLL's detach on Windows, where Qt's teardown + # races the helper threads tabs start and can fault (0xC0000005) after the + # report is written. TerminateProcess ends the process without it. + import ctypes + kernel32 = ctypes.windll.kernel32 + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.TerminateProcess(ctypes.c_void_p(kernel32.GetCurrentProcess()), 0) os._exit(0) """ diff --git a/test/unit_test/headless/test_gui_page_widths.py b/test/unit_test/headless/test_gui_page_widths.py index 0d6a83f4c..5e8b51dc4 100644 --- a/test/unit_test/headless/test_gui_page_widths.py +++ b/test/unit_test/headless/test_gui_page_widths.py @@ -52,6 +52,14 @@ widths[spec.key] = page.minimumSizeHint().width() / unit if workspace.current_tab_key() == spec.key else -1 sys.stdout.write(json.dumps({"unit": unit, "widths": widths})) sys.stdout.flush() +if sys.platform == "win32": + # os._exit still runs every DLL's detach on Windows, where Qt's teardown + # races the helper threads tabs start and can fault (0xC0000005) after the + # report is written. TerminateProcess ends the process without it. + import ctypes + kernel32 = ctypes.windll.kernel32 + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.TerminateProcess(ctypes.c_void_p(kernel32.GetCurrentProcess()), 0) os._exit(0) """ diff --git a/test/unit_test/headless/test_gui_workspace_navigation.py b/test/unit_test/headless/test_gui_workspace_navigation.py index cdfa27b86..9960f4b91 100644 --- a/test/unit_test/headless/test_gui_workspace_navigation.py +++ b/test/unit_test/headless/test_gui_workspace_navigation.py @@ -190,6 +190,14 @@ def test_a_search_survives_the_list_being_refreshed(panel): or window._adaptive.panel.search.isVisible(), window._sidebar_action.isChecked()] sys.stdout.write(json.dumps(report)) sys.stdout.flush() +if sys.platform == "win32": + # os._exit still runs every DLL's detach on Windows, where Qt's teardown + # races the helper threads tabs start and can fault (0xC0000005) after the + # report is written. TerminateProcess ends the process without it. + import ctypes + kernel32 = ctypes.windll.kernel32 + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.TerminateProcess(ctypes.c_void_p(kernel32.GetCurrentProcess()), 0) os._exit(0) """ diff --git a/test/unit_test/headless/test_r3_gui_thread_marshal.py b/test/unit_test/headless/test_r3_gui_thread_marshal.py index 93c51e4a0..88cbacbfa 100644 --- a/test/unit_test/headless/test_r3_gui_thread_marshal.py +++ b/test/unit_test/headless/test_r3_gui_thread_marshal.py @@ -213,6 +213,14 @@ def check_thumbnail_reaped(): sys.stdout.flush() # Skip Qt/native-thread teardown entirely -- that teardown is the whole # reason this runs out of process. The report is already on stdout. +if sys.platform == "win32": + # os._exit still runs every DLL's detach on Windows, where Qt's teardown + # races the helper threads tabs start and can fault (0xC0000005) after the + # report is written. TerminateProcess ends the process without it. + import ctypes + kernel32 = ctypes.windll.kernel32 + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.TerminateProcess(ctypes.c_void_p(kernel32.GetCurrentProcess()), 0) os._exit(0) """ From d422deb3c7d47ccec656a80902ff60f1c1f8c3e7 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 11:28:30 +0800 Subject: [PATCH 078/161] Give AI Locator and LLM Planner requests a Stop and a deadline Both handed the model round trip to a bare worker, so a request could not be stopped or time out, and an AI Locator click whose answer arrived after the tab closed still moved the mouse. They now run as TabTask work, and the VLM API checks the bound cancellation scope before the request and before it clicks. --- CHANGELOG.md | 8 + Progress.md | 4 + architecture_explore.md | 18 +- .../Eng/doc/new_features/new_features_doc.rst | 15 +- .../Zh/doc/new_features/new_features_doc.rst | 12 +- docs/updates/2026-11-b.md | 9 + docs/updates/README.md | 1 + .../gui/language_wrapper/english.py | 1 + .../gui/language_wrapper/japanese.py | 1 + .../language_wrapper/simplified_chinese.py | 1 + .../language_wrapper/traditional_chinese.py | 1 + je_auto_control/gui/llm_planner_tab.py | 77 ++++---- je_auto_control/gui/vlm_tab.py | 58 ++++-- je_auto_control/utils/vision/vlm_api.py | 6 + .../headless/test_gui_model_task_deadlines.py | 166 ++++++++++++++++++ .../headless/test_gui_panel_dispose.py | 7 +- .../headless/test_gui_worker_owner_death.py | 7 +- .../headless/test_vlm_cancellation.py | 74 ++++++++ 18 files changed, 385 insertions(+), 81 deletions(-) create mode 100644 test/unit_test/headless/test_gui_model_task_deadlines.py create mode 100644 test/unit_test/headless/test_vlm_cancellation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e6866c9ee..82e00f4ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- `locate_by_description` and `click_by_description` observe a bound cancellation scope: + cancelled before the model request, they raise `concurrent.futures.CancelledError` without + sending it, and `click_by_description` checks again before it moves the mouse, so an answer + that arrives after a stop or a deadline no longer clicks. Calls outside a scope are unchanged. + GUI: the AI Locator tab and the LLM Planner's Plan step run as cancellable tasks with a + **Stop run** action and a deadline (120 s and 200 s); `LLMPlannerTab._plan_thread` and + `VLMTab._vlm_thread` are gone (`_plans` and `_task` are their `TabTask`s). + - GUI: drop-down lists and spin boxes draw theme-coloured chevrons, inset from the rounded border, and spin boxes inset their digits like every other field. The chevrons are drawn once per theme colour into `~/.je_auto_control/gui_cache/`, next to the tab close cross; diff --git a/Progress.md b/Progress.md index 01d3671e7..7e286dc4d 100644 --- a/Progress.md +++ b/Progress.md @@ -538,6 +538,10 @@ F 還缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 + AI Locator 與 LLM Planner 的 Plan 已遷移(U-20261114-13);仍直接使用 `start_worker`、沒有 Stop/期限的面板: + `admin_console_tab`、`computer_use_tab`、`config_sync_tab`、`dag_tab`、`email_triggers_tab`、 + `healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`、 + `usb_browser_tab`、`usb_devices_tab`、`usb_passthrough_panel`。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index df9c3b507..9be62d7c8 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,756 | +| 程式碼總行數 | 235,783 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -516,7 +516,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,945 行。 +> 14 個套件、約 52,951 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -533,7 +533,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/mcp_server/` | 22,228 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | -| `utils/vision/` | 660 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | +| `utils/vision/` | 666 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | ### 5.4.10 遠端桌面與 USB @@ -1336,7 +1336,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,495 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,499 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1357,12 +1357,12 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | recording_editor | `recording_editor_tab.py` | 255 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | -| vlm | `vlm_tab.py` | 126 | 用文字描述 UI 元素,交由模型定位。 | +| vlm | `vlm_tab.py` | 150 | 用文字描述 UI 元素,交由模型定位。 | | self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 954 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | -| llm_planner | `llm_planner_tab.py` | 203 | 自然語言描述 → 預覽 → 執行。 | +| llm_planner | `llm_planner_tab.py` | 196 | 自然語言描述 → 預覽 → 執行。 | | computer_use | `computer_use_tab.py` | 185 | 從 GUI 啟動 Anthropic 閉環 agent。 | | agent_tasks | `agent_tasks_tab.py` | 618 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | | scheduler | `scheduler_tab.py` | 174 | 註冊間隔式 action JSON 執行。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,559 | +| `gui/` | 160 | 42,580 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,8 +1563,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,153 | -| **總計** | **1,525** | **235,011** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,159 | +| **總計** | **1,525** | **235,038** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/new_features_doc.rst b/docs/source/Eng/doc/new_features/new_features_doc.rst index a36d51bd2..e12335cbf 100644 --- a/docs/source/Eng/doc/new_features/new_features_doc.rst +++ b/docs/source/Eng/doc/new_features/new_features_doc.rst @@ -327,8 +327,14 @@ Environment variables (keys are never logged or persisted): - ``AUTOCONTROL_VLM_BACKEND=anthropic|openai`` - ``AUTOCONTROL_VLM_MODEL=`` +Inside a cancellation scope (a GUI task, or any caller that binds one) both +calls check for cancellation before the model request and ``click_by_description`` +checks again before it moves the mouse, so an answer that arrives after a +stop or a deadline raises ``CancelledError`` instead of clicking. + Action-JSON commands: ``AC_vlm_locate``, ``AC_vlm_click``. GUI: -**AI Locator** tab. +**AI Locator** tab: one request at a time, off the GUI thread, with a **Stop +run** action and a two-minute deadline (*Took too long and was stopped.*). Run history + error-snapshot artifacts @@ -682,9 +688,10 @@ Backend selection mirrors ``vision.backends``: Action-JSON commands: ``AC_llm_plan``, ``AC_llm_run``. -GUI: **LLM Planner** tab. Description box, ``QThread``-backed *Plan* -button, action-list preview, and a *Run plan* button — long calls run -off the GUI thread so the UI stays responsive. +GUI: **LLM Planner** tab. Description box, *Plan* button, action-list +preview, and a *Run plan* button. Planning and running happen off the GUI +thread; a plan has a deadline of 200 seconds, and **Stop run** ends the run +or, when none is going, drops the plan still being asked for. Remote desktop (host + viewer) diff --git a/docs/source/Zh/doc/new_features/new_features_doc.rst b/docs/source/Zh/doc/new_features/new_features_doc.rst index 1df7ac8b9..e9176677c 100644 --- a/docs/source/Zh/doc/new_features/new_features_doc.rst +++ b/docs/source/Zh/doc/new_features/new_features_doc.rst @@ -302,8 +302,13 @@ VLM(AI)元件定位 - ``AUTOCONTROL_VLM_BACKEND=anthropic|openai`` - ``AUTOCONTROL_VLM_MODEL=`` +在取消範圍內(GUI 背景工作,或任何綁定範圍的呼叫端)兩者都會在送出模型請求前檢查取消, +``click_by_description`` 在移動滑鼠前會再檢查一次:停止或逾時之後才回來的答案會拋出 +``CancelledError``,不會點擊。 + Action-JSON 指令:``AC_vlm_locate``、``AC_vlm_click``。GUI: -**AI Locator** 分頁。 +**AI Locator** 分頁:一次一個請求、在 GUI 執行緒之外執行,有 **停止執行** 動作與兩分鐘期限 +(「執行逾時,已停止。」)。 執行歷史 + 錯誤截圖附件 @@ -622,8 +627,9 @@ LLM 動作規劃器 Action-JSON 指令:``AC_llm_plan``、``AC_llm_run``。 -GUI:**LLM Planner** 分頁。描述輸入框、``QThread`` 背景執行的 *Plan* -按鈕、預覽指令清單、以及 *Run plan* 按鈕 — 長時間呼叫不會卡 UI。 +GUI:**LLM Planner** 分頁。描述輸入框、*Plan* 按鈕、預覽指令清單、以及 *Run plan* 按鈕。 +規劃與執行都在 GUI 執行緒之外;規劃有 200 秒期限,**停止執行** 會停止執行中的腳本, +沒有腳本在跑時則丟棄仍在等待的規劃。 遠端桌面(Host + Viewer) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 33cc7c105..7d0e66a00 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -377,3 +377,12 @@ - **Tests:** the five probe files: 96 passed. - **Files:** the five tests, `Progress.md`. - **Open items:** mixed DPI, a second monitor and Linux / macOS fonts (`Progress.md` › F2 GUI 重製). + +## U-20261114-13 · 2026-11-14 · AI Locator and LLM Planner requests get Stop, a deadline and no late click · #done #gui #vision + +- **What:** part of F3 (shared task controller for the remaining panels). The AI Locator tab and the LLM Planner's Plan step handed the model round trip to a bare `start_worker`: no Stop, no deadline, and an AI Locator Click whose answer came back after the tab was closed still moved the mouse and clicked. Both now run as `TabTask` work: one request at a time (a second one says *Already running*), **Stop run** in the Actions menu (the Planner's stops a script run first, else drops the plan still out), and a deadline (120 s for a locate or click, 200 s for a plan; each leaves room for the backend's request timeout and its SDK's two retries) that reports *Took too long and was stopped.* (`task_timed_out`, in all four catalogues). The Planner shows every plan error now, not only the five types the old worker caught. +- **Backend:** `locate_by_description` checks the bound cancellation scope before the model request, and `click_by_description` again before it moves the mouse, so a late answer raises `CancelledError` instead of clicking. Calls outside a scope (scripts, `AC_vlm_click`) are unchanged. The HTTP request itself still runs to its end. +- **Tests:** `test_vlm_cancellation.py` (4, no Qt) and `test_gui_model_task_deadlines.py` (7: stopped click, timed-out click, finished click, busy refusal, stopped plan, timed-out plan with no dialog, failed plan); the stopped and timed-out click tests fail without the backend checks. The dispose and owner-death tests follow the new attributes. +- **Docs:** both `new_features_doc.rst` (VLM and LLM planner sections), `CHANGELOG.md`. +- **Files:** `utils/vision/vlm_api.py`, `gui/{vlm_tab,llm_planner_tab}.py`, the four catalogues, the tests, the docs, `Progress.md`. +- **Open items:** twelve panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index f584b98ff..7768905c5 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-13 | 2026-11-14 | AI Locator and LLM Planner requests get Stop, a deadline and no late click | #done #gui #vision | [2026-11-b](2026-11-b.md) | | U-20261114-12 | 2026-11-14 | Whole-window probes end without Windows DLL teardown | #done #gui #test | [2026-11-b](2026-11-b.md) | | U-20261114-11 | 2026-11-14 | Trace Replay and Run History get their draggable divider back | #done #gui | [2026-11-b](2026-11-b.md) | | U-20261114-10 | 2026-11-14 | Remote Desktop's collapsed sections shrink to their title; wrapped groups show one title | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index ecb8a75b6..a44383c56 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -1485,6 +1485,7 @@ "task_stopping": "Stopping...", "task_stopped": "Stopped.", "task_stop": "Stop run", + "task_timed_out": "Took too long and was stopped.", "stop_playback": "Stop playback", "record_playing": "Playing back...", "rd_file_sending": "Sending {name}...", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index d96c39bfd..ae4619501 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -1381,6 +1381,7 @@ "task_stopping": "停止中...", "task_stopped": "停止しました。", "task_stop": "実行を停止", + "task_timed_out": "時間がかかりすぎたため停止しました。", "stop_playback": "再生を停止", "record_playing": "再生中...", "rd_file_sending": "{name} を送信中...", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 5b14a7f20..d8cb52257 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1345,6 +1345,7 @@ "task_stopping": "正在停止...", "task_stopped": "已停止。", "task_stop": "停止执行", + "task_timed_out": "执行超时,已停止。", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在发送 {name}...", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index a2da38645..5118bd37a 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1353,6 +1353,7 @@ "task_stopping": "正在停止...", "task_stopped": "已停止。", "task_stop": "停止執行", + "task_timed_out": "執行逾時,已停止。", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在傳送 {name}...", diff --git a/je_auto_control/gui/llm_planner_tab.py b/je_auto_control/gui/llm_planner_tab.py index e75304aa1..a8192cde6 100644 --- a/je_auto_control/gui/llm_planner_tab.py +++ b/je_auto_control/gui/llm_planner_tab.py @@ -2,15 +2,16 @@ The tab calls the headless ``plan_actions`` helper, shows the resulting JSON action list for review, and lets the user execute it through the -shared global executor. Planning and running both happen off the GUI thread; -a run is a stoppable executor run, one at a time. +shared global executor. Planning and running both happen off the GUI thread +as :class:`~je_auto_control.gui._tab_task.TabTask` work, one of each at a time: +a run is a stoppable executor run, and a plan has a deadline and is dropped +when stopped. The Actions menu's Stop ends whichever is going. """ import copy import functools import json from typing import List, Optional -from PySide6.QtCore import QObject, Signal from PySide6.QtWidgets import ( QFormLayout, QGroupBox, QLabel, QLineEdit, QMessageBox, QTextEdit, QVBoxLayout, QWidget, @@ -19,15 +20,15 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask, was_stopped -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker from je_auto_control.gui.adaptive.responsive import ResponsiveBox from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) +from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.utils.executor.action_executor import execute_action, executor from je_auto_control.utils.llm.backends.base import LLMNotAvailableError -from je_auto_control.utils.llm.planner import LLMPlanError, plan_actions +from je_auto_control.utils.llm.planner import plan_actions def _t(key: str) -> str: @@ -39,32 +40,23 @@ def _run_plan(actions: list) -> object: return execute_action(actions) -class _PlanWorker(QObject): - """Runs ``plan_actions`` off the GUI thread and emits the result.""" +#: How long one plan may take. The backend gives a request 60 s and its SDK +#: retries a failed one twice, so this leaves room for all three tries. +PLAN_DEADLINE_S = 200.0 - finished = Signal(list) - failed = Signal(str) - def __init__(self, description: str, model: Optional[str], - known_commands: List[str]) -> None: - super().__init__() - self._description = description - self._model = model - self._known = list(known_commands) +def _plan(description: str, model: Optional[str], known_commands: List[str]) -> list: + """Worker thread: ask the model for a plan.""" + return plan_actions(description, known_commands=known_commands, model=model) - def run(self) -> None: - try: - actions = plan_actions( - self._description, - known_commands=self._known, - model=self._model, - ) - except LLMNotAvailableError as error: - self.failed.emit(str(error)) - except (LLMPlanError, ValueError, OSError, RuntimeError) as error: - self.failed.emit(f"{type(error).__name__}: {error}") - else: - self.finished.emit(actions) + +def _plan_error_text(error: object) -> str: + """What the status line says about a plan that failed.""" + if isinstance(error, TaskTimeout): + return _t("task_timed_out") + if isinstance(error, LLMNotAvailableError): + return str(error) + return f"{type(error).__name__}: {error}" class LLMPlannerTab(TranslatableMixin, QWidget): @@ -81,7 +73,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._result_view.setReadOnly(True) self._status = QLabel() self._planned_actions: Optional[list] = None - self._plan_thread: Optional[WorkerHandle] = None + self._plans = TabTask(self) + self._plans.result.connect(self._on_plan_finished) + self._plans.error.connect(self._on_plan_failed) self._runs = TabTask(self) self._runs.result.connect(self._show_run_result) self._runs.error.connect(self._show_run_error) @@ -129,8 +123,8 @@ def _build_layout(self) -> None: def dispose(self) -> None: """Release what the tab holds beyond its widgets: the command still running in the background. - A script run is stopped; other work cannot be interrupted, so it runs to its end and its - result is dropped. Called by ``close_tab(key, release=True)``; safe to call twice. + A script run is stopped; a plan still out is cancelled: the request runs to its end and + its answer is dropped. Called by ``close_tab(key, release=True)``; safe to call twice. """ release_resources(self) @@ -147,16 +141,14 @@ def _on_plan(self) -> None: if not description: self._status.setText(_t("llm_desc_required")) return - if self._plan_thread is not None and self._plan_thread.isRunning(): - return model = self._model.text().strip() or None + work = functools.partial(_plan, description, model, sorted(executor.known_commands())) + if not self._plans.start(work, timeout_s=PLAN_DEADLINE_S): + self._status.setText(_t("task_busy")) + return self._status.setText(_t("llm_planning")) self._actions_view.clear() self._planned_actions = None - worker = _PlanWorker(description, model, sorted(executor.known_commands())) - self._plan_thread = start_worker( - self, worker, on_done=self._on_plan_finished, - on_fail=self._on_plan_failed, on_thread_done=self._on_thread_done) def _on_plan_finished(self, actions: list) -> None: self._planned_actions = actions @@ -167,14 +159,13 @@ def _on_plan_finished(self, actions: list) -> None: _t("llm_plan_count").replace("{n}", str(len(actions))) ) - def _on_plan_failed(self, message: str) -> None: + def _on_plan_failed(self, error: object) -> None: self._planned_actions = None - QMessageBox.warning(self, _t("llm_plan_btn"), message) + message = _plan_error_text(error) + if not isinstance(error, TaskTimeout): + QMessageBox.warning(self, _t("llm_plan_btn"), message) self._status.setText(message) - def _on_thread_done(self) -> None: - self._plan_thread = None - def _on_run(self) -> None: if not self._planned_actions: self._status.setText(_t("llm_no_plan")) @@ -188,6 +179,8 @@ def _on_run(self) -> None: def _on_stop(self) -> None: if self._runs.stop(): self._status.setText(_t("task_stopping")) + elif self._plans.stop(): + self._status.setText(_t("task_stopped")) def _show_run_result(self, record: object) -> None: self._result_view.setText( diff --git a/je_auto_control/gui/vlm_tab.py b/je_auto_control/gui/vlm_tab.py index 42bf5e461..4d7f387ae 100644 --- a/je_auto_control/gui/vlm_tab.py +++ b/je_auto_control/gui/vlm_tab.py @@ -1,4 +1,11 @@ -"""VLM tab: describe a UI element in words and have a model find it.""" +"""VLM tab: describe a UI element in words and have a model find it. + +The model round trip runs as a :class:`~je_auto_control.gui._tab_task.TabTask`: +one request at a time, a Stop in the Actions menu, and a deadline. A stopped or +timed-out Click never clicks: :func:`click_by_description` checks the task's +cancellation once the model has answered, before it moves the mouse. +""" +import functools from typing import Optional from PySide6.QtWidgets import ( @@ -7,15 +14,20 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) +from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.utils.vision.vlm_api import ( click_by_description, locate_by_description, ) +#: How long one locate or click may take. Each backend gives a request 30 s and +#: its SDK retries a failed one twice, so this leaves room for all three tries. +REQUEST_DEADLINE_S = 120.0 + def _t(key: str) -> str: return language_wrapper.translate(key, key) @@ -31,7 +43,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._model = QLineEdit() self._status = QLabel() self._last_result = QLabel() - self._vlm_thread: Optional[WorkerHandle] = None + self._task = TabTask(self) # one model request at a time, off the GUI thread + self._task.result.connect(self._show_outcome) + self._task.error.connect(self._show_task_error) self._apply_placeholders() self._build_layout() @@ -60,9 +74,10 @@ def _build_layout(self) -> None: root.addStretch() def dispose(self) -> None: - """Release what the tab holds beyond its widgets: the model request still out, whose answer is dropped. + """Release what the tab holds beyond its widgets: the model request still out. - The request itself cannot be interrupted and runs to its end. Called by + The request is cancelled: its answer is dropped and a Click does not + click. The HTTP call itself runs to its end. Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. """ release_resources(self) @@ -72,6 +87,7 @@ def menu_actions(self) -> list: return [ ("vlm_locate", self._on_locate), ("vlm_click", self._on_click), + ("task_stop", self._on_stop), ] def _collect_inputs(self): @@ -82,25 +98,35 @@ def _collect_inputs(self): model = self._model.text().strip() or None return description, model - def _run_off_gui_thread(self, call, on_done) -> None: + def _run_off_gui_thread(self, call, tag: str) -> None: """The VLM round trip (network, seconds) froze the window on the GUI thread.""" - if self._vlm_thread is not None: + if not self._task.start(call, tag=tag, timeout_s=REQUEST_DEADLINE_S): + self._status.setText(_t("task_busy")) return - self._vlm_thread = start_worker(self, CallWorker(call), on_done=on_done, - on_fail=self._show_error, on_thread_done=self._on_vlm_done) + self._status.setText(_t("task_running")) + + def _on_stop(self) -> None: + if self._task.stop(): + self._status.setText(_t("task_stopped")) - def _on_vlm_done(self) -> None: - self._vlm_thread = None + def _show_outcome(self, value: object) -> None: + if self._task.tag == "click": + self._show_clicked(value) + else: + self._show_located(value) - def _show_error(self, message: str) -> None: - self._status.setText(f"{_t('vlm_error')}: {message}") + def _show_task_error(self, error: object) -> None: + if isinstance(error, TaskTimeout): + self._status.setText(_t("task_timed_out")) + return + self._status.setText(f"{_t('vlm_error')}: {error}") def _on_locate(self) -> None: inputs = self._collect_inputs() if inputs is None: return description, model = inputs - self._run_off_gui_thread(lambda: locate_by_description(description, model=model), self._show_located) + self._run_off_gui_thread(functools.partial(locate_by_description, description, model=model), "locate") def _show_located(self, coords) -> None: if coords is None: @@ -118,9 +144,7 @@ def _on_click(self) -> None: if inputs is None: return description, model = inputs - self._run_off_gui_thread( - lambda: click_by_description(description, model=model), - self._show_clicked) + self._run_off_gui_thread(functools.partial(click_by_description, description, model=model), "click") def _show_clicked(self, ok) -> None: self._status.setText(_t("vlm_ok") if ok else _t("vlm_not_found")) diff --git a/je_auto_control/utils/vision/vlm_api.py b/je_auto_control/utils/vision/vlm_api.py index 28283a5ea..2ae9721ef 100644 --- a/je_auto_control/utils/vision/vlm_api.py +++ b/je_auto_control/utils/vision/vlm_api.py @@ -9,6 +9,7 @@ from hashlib import sha256 from typing import List, Optional, Tuple +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.vision.backends import get_backend from je_auto_control.utils.cv2_utils.locator_frame import ( LocatorFrame, LocatorFrameOwner, current_locator_frame, provided_locator_frame, @@ -49,6 +50,8 @@ def locate_by_description(description: str, image_bytes = frame.png else: image_bytes, frame = capture_with_geometry(_capture_screenshot_bytes, screen_region) + # A task stopped while the screen was captured does not pay for a model request. + cancellation_checkpoint() coords = bound.locate(image_bytes, description, model=model) if coords is None: return None @@ -107,6 +110,9 @@ def click_by_description(description: str, if coords is None: return False cx, cy = coords + # The model can answer after the task was stopped or timed out; that + # answer must not still move the mouse and click. + cancellation_checkpoint() # pylint: disable-next=import-outside-toplevel # reason: native input initializes only for an explicit click from je_auto_control.wrapper.auto_control_mouse import ( click_mouse, set_mouse_position, diff --git a/test/unit_test/headless/test_gui_model_task_deadlines.py b/test/unit_test/headless/test_gui_model_task_deadlines.py new file mode 100644 index 000000000..4c2220894 --- /dev/null +++ b/test/unit_test/headless/test_gui_model_task_deadlines.py @@ -0,0 +1,166 @@ +"""The VLM tab and the LLM Planner's plan step: Stop, a deadline, and no late effect. + +Both used to hand the model round trip to a bare worker: no Stop, no deadline, +and a VLM Click whose answer came back after the tab was closed still clicked. +They now run as :class:`~je_auto_control.gui._tab_task.TabTask` work. +""" +import functools +import os +import sys +import threading +import types + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtWidgets import QApplication, QMessageBox # noqa: E402 + +from je_auto_control.gui import llm_planner_tab, vlm_tab # noqa: E402 +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 +from je_auto_control.utils.vision import vlm_api # noqa: E402 +from je_auto_control.utils.vision.backends.base import VLMBackend # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) + + +def _t(key): + return language_wrapper.translate(key, key) + + +class _SlowBackend(VLMBackend): + """Answers ``(10, 20)`` once ``release`` is set.""" + + name = "slow" + available = True + + def __init__(self): + self.release = threading.Event() + self.asked = threading.Event() + self.answered = threading.Event() + + def locate(self, image_bytes, description, model=None, image_mime="image/png"): + self.asked.set() + self.release.wait(30.0) + self.answered.set() + return (10, 20) + + +@pytest.fixture +def slow_click(monkeypatch): + """The real ``click_by_description`` against a slow model and a recording mouse.""" + backend = _SlowBackend() + moves = [] + mouse = types.ModuleType("je_auto_control.wrapper.auto_control_mouse") + mouse.set_mouse_position = lambda x, y: moves.append(("move", x, y)) + mouse.click_mouse = lambda button, x, y: moves.append(("click", x, y)) + monkeypatch.setitem(sys.modules, "je_auto_control.wrapper.auto_control_mouse", mouse) + monkeypatch.setattr(vlm_api, "_capture_screenshot_bytes", lambda screen_region=None: b"fake-png-bytes") + monkeypatch.setattr(vlm_tab, "click_by_description", + functools.partial(vlm_api.click_by_description, backend=backend)) + tab = vlm_tab.VLMTab() + tab._description.setText("the OK button") + yield tab, backend, moves + backend.release.set() + tab.deleteLater() + + +def _menu(tab, key): + return dict(tab.menu_actions())[key] + + +def test_a_stopped_vlm_click_does_not_click_when_the_model_answers(slow_click): + tab, backend, moves = slow_click + _menu(tab, "vlm_click")() + assert backend.asked.wait(10.0) + _menu(tab, "task_stop")() + assert tab._status.text() == _t("task_stopped") + assert not tab._task.running # free for the next request at once + backend.release.set() + assert backend.answered.wait(10.0) + # The model answered after the Stop; give the worker the chance to click. + assert pump_until(lambda: moves != [], timeout=0.5) is False + assert moves == [] + + +def test_a_vlm_click_past_its_deadline_reports_it_and_does_not_click(slow_click, monkeypatch): + tab, backend, moves = slow_click + monkeypatch.setattr(vlm_tab, "REQUEST_DEADLINE_S", 0.05) + _menu(tab, "vlm_click")() + assert pump_until(lambda: tab._status.text() == _t("task_timed_out")) + backend.release.set() + assert backend.answered.wait(10.0) + assert pump_until(lambda: moves != [], timeout=0.5) is False + assert tab._status.text() == _t("task_timed_out") + + +def test_a_vlm_click_that_finishes_clicks(slow_click): + tab, backend, moves = slow_click + backend.release.set() + _menu(tab, "vlm_click")() + assert pump_until(lambda: tab._status.text() == _t("vlm_ok")) + assert moves == [("move", 10, 20), ("click", 10, 20)] + + +def test_a_second_vlm_request_while_one_is_out_is_refused(slow_click): + tab, backend, _moves = slow_click + _menu(tab, "vlm_click")() + _menu(tab, "vlm_locate")() + assert tab._status.text() == _t("task_busy") + + +@pytest.fixture +def slow_plan(monkeypatch): + release = threading.Event() + + def plan(description, known_commands=None, model=None): + release.wait(30.0) + return [["AC_x", {}]] + + monkeypatch.setattr(llm_planner_tab, "plan_actions", plan) + warnings = [] + monkeypatch.setattr(QMessageBox, "warning", lambda *args: warnings.append(args)) + tab = llm_planner_tab.LLMPlannerTab() + tab._description.setPlainText("open the editor") + yield tab, release, warnings + release.set() + tab.deleteLater() + + +def test_stop_drops_a_plan_still_out(slow_plan): + tab, release, _warnings = slow_plan + _menu(tab, "llm_plan_btn")() + assert tab._plans.running + _menu(tab, "task_stop")() + assert tab._status.text() == _t("task_stopped") + release.set() + assert pump_until(lambda: tab._actions_view.toPlainText() != "", timeout=0.5) is False + assert tab._planned_actions is None + + +def test_a_plan_past_its_deadline_says_so_without_a_dialog(slow_plan, monkeypatch): + tab, _release, warnings = slow_plan + monkeypatch.setattr(llm_planner_tab, "PLAN_DEADLINE_S", 0.05) + _menu(tab, "llm_plan_btn")() + assert pump_until(lambda: tab._status.text() == _t("task_timed_out")) + assert warnings == [] + assert tab._planned_actions is None + + +def test_a_plan_that_fails_shows_its_error(monkeypatch): + def plan(description, known_commands=None, model=None): + raise ValueError("no plan") + + monkeypatch.setattr(llm_planner_tab, "plan_actions", plan) + warnings = [] + monkeypatch.setattr(QMessageBox, "warning", lambda *args: warnings.append(args)) + tab = llm_planner_tab.LLMPlannerTab() + try: + tab._description.setPlainText("open the editor") + _menu(tab, "llm_plan_btn")() + assert pump_until(lambda: tab._status.text() == "ValueError: no plan") + assert len(warnings) == 1 + finally: + tab.deleteLater() diff --git a/test/unit_test/headless/test_gui_panel_dispose.py b/test/unit_test/headless/test_gui_panel_dispose.py index d8d700945..c60603264 100644 --- a/test/unit_test/headless/test_gui_panel_dispose.py +++ b/test/unit_test/headless/test_gui_panel_dispose.py @@ -310,12 +310,13 @@ def locate(_description, model=None): tab = vlm_tab.VLMTab() tab._description.setText("the button") tab._on_locate() - assert tab._vlm_thread is not None + assert tab._task.running + status = tab._status.text() tab.dispose() release.set() - assert pump_until(lambda: tab._vlm_thread is None) + assert pump_until(lambda: not tab._task.running) assert tab._last_result.text() == "" - assert tab._status.text() == "" + assert tab._status.text() == status def test_a_released_usb_browser_tab_drops_the_open_still_out(monkeypatch): diff --git a/test/unit_test/headless/test_gui_worker_owner_death.py b/test/unit_test/headless/test_gui_worker_owner_death.py index f4737dab1..dc29e613e 100644 --- a/test/unit_test/headless/test_gui_worker_owner_death.py +++ b/test/unit_test/headless/test_gui_worker_owner_death.py @@ -119,8 +119,9 @@ def failing_run(definition, max_parallel, stop_event=None): tab = mod.LLMPlannerTab() tab._description.setPlainText("do it") # noqa: SLF001 tab._on_plan() # noqa: SLF001 - guard = "_plan_thread" - assert getattr(tab, guard) is not None - assert _pump_until(app, lambda: getattr(tab, guard) is None), "the guard never cleared" + guard = "task" + holder = tab._plans if which == "llm_planner" else tab # noqa: SLF001 + assert getattr(holder, guard) is not None + assert _pump_until(app, lambda: getattr(holder, guard) is None), "the guard never cleared" assert seen tab.deleteLater() diff --git a/test/unit_test/headless/test_vlm_cancellation.py b/test/unit_test/headless/test_vlm_cancellation.py new file mode 100644 index 000000000..d11858b60 --- /dev/null +++ b/test/unit_test/headless/test_vlm_cancellation.py @@ -0,0 +1,74 @@ +"""A VLM locate or click bound to a cancelled task stops before it costs a request or moves the mouse. + +The GUI runs these calls as cancellable tasks (Stop, a deadline, a closed tab). +The HTTP request itself cannot be interrupted, so the answer can arrive after +the task was cancelled; :func:`click_by_description` must not click on it. +""" +import sys +import types +from concurrent.futures import CancelledError +from typing import Optional, Tuple + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.vision import vlm_api +from je_auto_control.utils.vision.backends.base import VLMBackend + + +class _Backend(VLMBackend): + name = "fake" + available = True + + def __init__(self, coords: Optional[Tuple[int, int]], token: Optional[CancellationToken] = None) -> None: + self._coords = coords + self._token = token + self.calls = 0 + + def locate(self, image_bytes: bytes, description: str, model: Optional[str] = None, + image_mime: str = "image/png") -> Optional[Tuple[int, int]]: + self.calls += 1 + if self._token is not None: + self._token.cancel() # Stop pressed while the model was thinking + return self._coords + + +@pytest.fixture +def mouse(monkeypatch): + """Stand in for the native mouse module ``click_by_description`` imports on a click.""" + moves = [] + fake = types.ModuleType("je_auto_control.wrapper.auto_control_mouse") + fake.set_mouse_position = lambda x, y: moves.append(("move", x, y)) + fake.click_mouse = lambda button, x, y: moves.append(("click", x, y)) + monkeypatch.setitem(sys.modules, "je_auto_control.wrapper.auto_control_mouse", fake) + monkeypatch.setattr(vlm_api, "_capture_screenshot_bytes", lambda screen_region=None: b"fake-png-bytes") + return moves + + +def test_a_click_whose_task_was_cancelled_during_the_request_does_not_click(mouse): + token = CancellationToken(task_id=1) + backend = _Backend((10, 20), token) + with cancellation_scope(token), pytest.raises(CancelledError): + vlm_api.click_by_description("the OK button", backend=backend) + assert backend.calls == 1 + assert mouse == [] + + +def test_a_task_cancelled_before_the_request_does_not_send_it(mouse): + token = CancellationToken(task_id=2) + token.cancel() + backend = _Backend((10, 20)) + with cancellation_scope(token), pytest.raises(CancelledError): + vlm_api.locate_by_description("the OK button", backend=backend) + assert backend.calls == 0 + + +def test_without_a_task_the_click_still_lands(mouse): + assert vlm_api.click_by_description("the OK button", backend=_Backend((10, 20))) is True + assert mouse == [("move", 10, 20), ("click", 10, 20)] + + +def test_a_live_task_clicks(mouse): + with cancellation_scope(CancellationToken(task_id=3)): + assert vlm_api.click_by_description("the OK button", backend=_Backend((10, 20))) is True + assert mouse == [("move", 10, 20), ("click", 10, 20)] From fe3f4cf1377030c4f5f0b9b47746ada78ae49e4e Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 11:35:21 +0800 Subject: [PATCH 079/161] End the USB enumeration tool when its tab closes The enumeration ran PowerShell, lsusb or system_profiler under a 10 s subprocess.run on a bare worker, so a closed tab left both running; CI's page-width probe faulted at exit with that worker still waiting. It now starts the tool through the cancellable capture helper, and the two USB listings run as cancellable tasks. --- CHANGELOG.md | 7 ++ Progress.md | 9 +- architecture_explore.md | 18 +-- .../operations_layer/operations_layer_doc.rst | 7 +- .../operations_layer/operations_layer_doc.rst | 5 +- docs/updates/2026-11-b.md | 9 ++ docs/updates/README.md | 1 + je_auto_control/gui/usb_devices_tab.py | 31 +++--- je_auto_control/gui/usb_passthrough_panel.py | 18 +-- je_auto_control/utils/usb/usb_devices.py | 33 ++++-- .../headless/test_usb_enumeration_cancel.py | 104 ++++++++++++++++++ .../headless/test_usb_windows_encoding.py | 10 +- 12 files changed, 199 insertions(+), 53 deletions(-) create mode 100644 test/unit_test/headless/test_usb_enumeration_cancel.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 82e00f4ac..7dc703fac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- `list_usb_devices` starts its command-line tool (PowerShell `Get-PnpDevice`, `lsusb`, + `system_profiler`) through `run_capture_helper`: inside a cancellation scope, cancelling ends + the tool's process and raises `CancelledError` instead of waiting out the 10 s timeout. Its + output is decoded with `errors="replace"`. Failures and timeouts are still `result.error`. + GUI: the USB Devices tab and the USB passthrough panel list devices as cancellable tasks, + so closing them ends a listing still running (`_list_thread` is gone; `_listing` is the task). + - `locate_by_description` and `click_by_description` observe a bound cancellation scope: cancelled before the model request, they raise `concurrent.futures.CancelledError` without sending it, and `click_by_description` checks again before it moves the mouse, so an answer diff --git a/Progress.md b/Progress.md index 7e286dc4d..b46d89ce2 100644 --- a/Progress.md +++ b/Progress.md @@ -538,10 +538,11 @@ F 還缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - AI Locator 與 LLM Planner 的 Plan 已遷移(U-20261114-13);仍直接使用 `start_worker`、沒有 Stop/期限的面板: - `admin_console_tab`、`computer_use_tab`、`config_sync_tab`、`dag_tab`、`email_triggers_tab`、 - `healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`、 - `usb_browser_tab`、`usb_devices_tab`、`usb_passthrough_panel`。 + AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)已遷移; + 仍直接使用 `start_worker` 的面板:`admin_console_tab`、`computer_use_tab`(已有自己的 stop event)、 + `config_sync_tab`、`dag_tab`、`email_triggers_tab`、`healing_evaluation_panel`、`journal_browser`、 + `journal_candidate_panel`、`template_candidate_panel`、`usb_browser_tab`,以及 `usb_passthrough_panel` + 列舉以外的 loopback/遠端操作。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 9be62d7c8..c62417ddf 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,783 | +| 程式碼總行數 | 235,797 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,7 +537,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,005 行。 +> 6 個套件、約 32,014 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -545,7 +545,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | | `utils/remote_desktop/` | 16,736 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | -| `utils/usb/` | 5,060 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | +| `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | > **2026-10-09 第三輪新增的模組**(各自的子套件列在 §5.4 的原表格裡,這裡只列檔名與職責): @@ -883,7 +883,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `permissions.py` / `clipboard_sync.py` / `wake_on_lan.py` / `session_actions.py` / `auth.py` | 64 / 137 / 56 / 40 / 28 | 逐 session 權限、剪貼簿同步、WOL、SAS 注入與螢幕遮蔽、HMAC 挑戰回應。 | | `ws_host.py` / `ws_viewer.py` / `jpeg_recorder.py` | 40 / 29 / 146 | WebSocket 傳輸變體與 TCP 路徑錄影。 | -#### `utils/usb/`(5,060 行)與 `utils/usbip/`(1,008 行) +#### `utils/usb/`(5,069 行)與 `utils/usbip/`(1,008 行) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -899,7 +899,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `usb/passthrough/descriptor.py` | 134 | USB 標準裝置描述元解析。 | | `usb/passthrough/key_provider.py` | 125 | ACL 的可插拔 HMAC 金鑰來源。 | | `usb/passthrough/commands.py` | 150 | 無頭直通指令(單一真實來源)。 | -| `usb/usb_devices.py` | 299 | 跨平台 USB 裝置列舉。 | +| `usb/usb_devices.py` | 308 | 跨平台 USB 裝置列舉。 | | `usb/usb_watcher.py` | 308 | 輪詢式 USB 熱插拔監看。 | | `usbip/protocol.py` | 342 | USB/IP 線路格式封裝/解析。 | | `usbip/server.py` | 295 | USB/IP 主機端 TCP 伺服器。 | @@ -1392,7 +1392,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | admin_console | `admin_console_tab.py` | 326 | 管理多個遠端 AutoControl REST 端點。 | | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | -| usb_devices | `usb_devices_tab.py` | 170 | 唯讀列舉 + 熱插拔監看控制。 | +| usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 288 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 770 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | | diagnostics | `diagnostics_tab.py` | 235 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | @@ -1543,11 +1543,11 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,580 | +| `gui/` | 160 | 42,585 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | -| `utils/usb/` | 20 | 5,060 | +| `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | | `utils/accessibility/` | 16 | 3,374 | | `wrapper/` | 25 | 6,044 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,159 | -| **總計** | **1,525** | **235,038** | +| **總計** | **1,525** | **235,052** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 4c9694cc1..47c3da2d0 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -543,6 +543,10 @@ Backends: - macOS: ``system_profiler -json SPUSBDataType`` (recursive walk) - Linux: ``/sys/bus/usb/devices`` (sysfs read) +A command-line tool gets 10 seconds (``SUBPROCESS_TIMEOUT_S``); a failure or +timeout comes back as ``result.error``. Called inside a cancellation scope, +cancelling ends the tool's process and raises ``CancelledError``. + Headless:: from je_auto_control.utils.usb import list_usb_devices @@ -561,7 +565,8 @@ Executor command:: AC_list_usb_devices GUI: *USB Devices* tab — backend label, devices table (VID/PID/ -manufacturer/product/serial/location), refresh button. +manufacturer/product/serial/location), refresh button. The listing runs off +the GUI thread; closing the tab ends a listing still running. Phase 2 (actual USB passthrough) ships in stages — see :doc:`usb_passthrough_design` for the protocol + backend ABCs and diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index 9c8481896..a76a3efc0 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -485,6 +485,9 @@ pyusb 不存在則退回平台特定指令。 - macOS:``system_profiler -json SPUSBDataType``\ (遞迴走訪) - Linux:``/sys/bus/usb/devices``\ (讀取 sysfs) +命令列工具有 10 秒期限(``SUBPROCESS_TIMEOUT_S``),失敗或逾時會放在 ``result.error``。 +在取消範圍內呼叫時,取消會結束該工具的行程並拋出 ``CancelledError``。 + Headless:: from je_auto_control.utils.usb import list_usb_devices @@ -503,7 +506,7 @@ Executor 指令:: AC_list_usb_devices GUI:*USB Devices* 分頁 — 後端標籤、裝置表格(VID/PID/廠商/產品/ -序號/位置)、重新整理按鈕。 +序號/位置)、重新整理按鈕。列舉在 GUI 執行緒之外執行;關閉分頁會結束仍在執行的列舉。 Phase 2(真正的 USB passthrough)分階段發布 — 協定與 backend ABC 見 :doc:`usb_passthrough_design`\ ,端到端使用方式見 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 7d0e66a00..c41c47c82 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -386,3 +386,12 @@ - **Docs:** both `new_features_doc.rst` (VLM and LLM planner sections), `CHANGELOG.md`. - **Files:** `utils/vision/vlm_api.py`, `gui/{vlm_tab,llm_planner_tab}.py`, the four catalogues, the tests, the docs, `Progress.md`. - **Open items:** twelve panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-14 · 2026-11-14 · Closing a USB tab ends the enumeration tool it started · #done #gui #usb + +- **What:** part of F3 (cancellation that reaches the backend). `list_usb_devices` ran PowerShell `Get-PnpDevice` (about 5 s here), `lsusb` or `system_profiler` through `subprocess.run` with a 10 s timeout, and the USB Devices tab and the USB passthrough panel ran it on a bare worker. Closing either left the tool and the worker running; CI's page-width probe on b51479ca faulted at exit with exactly that worker still in `subprocess.run` (U-20261114-12). The enumeration now starts its tool through `utils.cancellable_process.run_capture_helper`, which ends the tool's process when the bound cancellation scope is cancelled and raises `CancelledError`; both GUI listings run as `TabTask` work, whose cancellation on dispose binds that scope. Output is decoded the same way (UTF-8 from the PowerShell query, else the locale's encoding) with `errors="replace"`; failures, a missing tool and a timeout are still `result.error`. +- **Checked:** this machine still lists its 3 devices through PowerShell. +- **Tests:** `test_usb_enumeration_cancel.py` (6: decoded output, exit code and stderr, missing tool, timeout, a cancelled scope ends a 30 s tool within 5 s, closing the USB Devices tab does the same); the last two fail on the old code, where the tool ran to its timeout. `test_usb_windows_encoding.py` now hooks `Popen` in `cancellable_process` instead of `usb_devices.subprocess.run` and keeps all its checks (Unicode under both UTF-8 modes, stderr on a failure, hidden console). USB, dispose and GUI tests: 958 passed, 5 skipped. +- **Docs:** both `operations_layer_doc.rst` (USB enumeration: the tool's deadline, cancellation, the tab), `CHANGELOG.md`. +- **Files:** `utils/usb/usb_devices.py`, `gui/{usb_devices_tab,usb_passthrough_panel}.py`, the two tests, the docs, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 7768905c5..65e2366f8 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-14 | 2026-11-14 | Closing a USB tab ends the enumeration tool it started | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-13 | 2026-11-14 | AI Locator and LLM Planner requests get Stop, a deadline and no late click | #done #gui #vision | [2026-11-b](2026-11-b.md) | | U-20261114-12 | 2026-11-14 | Whole-window probes end without Windows DLL teardown | #done #gui #test | [2026-11-b](2026-11-b.md) | | U-20261114-11 | 2026-11-14 | Trace Replay and Run History get their draggable divider back | #done #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/usb_devices_tab.py b/je_auto_control/gui/usb_devices_tab.py index 1c4d9a8a8..e3e9dec2f 100644 --- a/je_auto_control/gui/usb_devices_tab.py +++ b/je_auto_control/gui/usb_devices_tab.py @@ -1,4 +1,9 @@ -"""USB devices tab: read-only enumeration + hotplug watcher controls.""" +"""USB devices tab: read-only enumeration + hotplug watcher controls. + +The enumeration runs as a :class:`~je_auto_control.gui._tab_task.TabTask`: +closing the tab cancels it, which ends the enumeration tool's process +(PowerShell, ``lsusb``, ``system_profiler``) instead of leaving it to time out. +""" from typing import Optional from PySide6.QtCore import QTimer @@ -9,7 +14,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( @@ -47,7 +52,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._last_seen_seq = 0 # Enumerated off the GUI thread, first when the tab is shown: the # PowerShell query took ~5 s and ran at start-up for a hidden tab. - self._list_thread: Optional[WorkerHandle] = None + self._listing = TabTask(self) + self._listing.result.connect(self._apply_devices) + self._listing.error.connect(self._show_list_error) self._listed = False self._hold = _WatcherHold() self.destroyed.connect(self._hold.release) @@ -70,7 +77,8 @@ def _build_layout(self) -> None: root.addWidget(label) def dispose(self) -> None: - """Release what the tab holds beyond its widgets: its hotplug timer and its share of the USB watcher. + """Release what the tab holds beyond its widgets: its hotplug timer, its share of the USB watcher + and an enumeration still running, whose tool process is ended. Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. """ @@ -104,15 +112,12 @@ def _apply_table_headers(self) -> None: ]) def _refresh(self) -> None: - if self._list_thread is not None: - return # one enumeration at a time; a tick during one is skipped - self._listed = True - self._list_thread = start_worker( - self, CallWorker(list_usb_devices), on_done=self._apply_devices, - on_fail=self._error_label.setText, on_thread_done=self._on_list_done) - - def _on_list_done(self) -> None: - self._list_thread = None + # One enumeration at a time; a tick during one is skipped. + if self._listing.start(list_usb_devices): + self._listed = True + + def _show_list_error(self, error: object) -> None: + self._error_label.setText(str(error)) def _apply_devices(self, result) -> None: self._backend_label.setText(result.backend) diff --git a/je_auto_control/gui/usb_passthrough_panel.py b/je_auto_control/gui/usb_passthrough_panel.py index e9c553b5c..2bc3c9090 100644 --- a/je_auto_control/gui/usb_passthrough_panel.py +++ b/je_auto_control/gui/usb_passthrough_panel.py @@ -31,6 +31,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui._worker_thread import CallWorker as _CallWorker, WorkerHandle, start_worker from je_auto_control.gui.adaptive.responsive import ResponsiveBox from je_auto_control.gui.adaptive.surfaces import set_role @@ -112,7 +113,10 @@ def __init__(self, parent: Optional[QWidget] = None, *, self._apply_local_headers() self._apply_shared_headers() # Listed off the GUI thread when first shown (see UsbDevicesTab). - self._list_thread: Optional[WorkerHandle] = None + # Local enumeration; closing the panel ends the enumeration tool's process. + self._listing = TabTask(self) + self._listing.result.connect(self._show_local_devices) + self._listing.error.connect(self._show_list_error) self._listed = False self._refresh_host_badge() @@ -274,15 +278,11 @@ def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override self._refresh_local_devices() def _refresh_local_devices(self) -> None: - if self._list_thread is not None: - return - self._listed = True - self._list_thread = start_worker( - self, _CallWorker(list_usb_devices), on_done=self._show_local_devices, - on_fail=self._viewer_status.setText, on_thread_done=self._on_list_done) + if self._listing.start(list_usb_devices): + self._listed = True - def _on_list_done(self) -> None: - self._list_thread = None + def _show_list_error(self, error: object) -> None: + self._viewer_status.setText(str(error)) def _show_local_devices(self, result) -> None: devices = result.devices diff --git a/je_auto_control/utils/usb/usb_devices.py b/je_auto_control/utils/usb/usb_devices.py index 9aeda3fb0..74ae0b2c1 100644 --- a/je_auto_control/utils/usb/usb_devices.py +++ b/je_auto_control/utils/usb/usb_devices.py @@ -14,6 +14,7 @@ from __future__ import annotations import json +import locale import platform import re import subprocess # nosec B404 # reason: needed for platform-specific enumeration tools @@ -21,6 +22,7 @@ from pathlib import Path from typing import Any, Dict, List, Optional +from je_auto_control.utils.cancellable_process import run_capture_helper from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -208,25 +210,32 @@ def _linux_node_to_device(node: Path) -> Optional[UsbDevice]: def _run_capture(cmd: List[str], backend: str) -> Any: + """Run one enumeration tool; return its decoded stdout, or a result carrying the failure. + + Runs through :func:`run_capture_helper`, so a caller inside a cancellation + scope (a GUI tab that was closed, a task that was stopped) ends the tool's + process instead of waiting out its timeout; the ``CancelledError`` propagates. + """ try: - completed = subprocess.run( # nosec B603 B607 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit.dangerous-subprocess-use-audit # reason: argv list (never shell=True); cmd is built from project-controlled allowlists in _enumerate_via_lsusb / _enumerate_via_system_profiler — no user input flows in - cmd, capture_output=True, text=True, - encoding="utf-8" if backend == "windows" else None, - creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), - timeout=SUBPROCESS_TIMEOUT_S, check=False, - ) - except (OSError, subprocess.TimeoutExpired) as error: + completed = run_capture_helper(cmd, SUBPROCESS_TIMEOUT_S) + except subprocess.CalledProcessError as error: return UsbEnumerationResult( backend=backend, devices=[], - error=f"{cmd[0]}: {error}", + error=f"{cmd[0]} exit {error.returncode}: " + f"{_decode(error.stderr, backend).strip()[:200]}", ) - if completed.returncode != 0: + except (OSError, subprocess.TimeoutExpired) as error: return UsbEnumerationResult( backend=backend, devices=[], - error=f"{cmd[0]} exit {completed.returncode}: " - f"{completed.stderr.strip()[:200]}", + error=f"{cmd[0]}: {error}", ) - return completed.stdout + return _decode(completed.stdout, backend) + + +def _decode(data: Optional[bytes], backend: str) -> str: + """The tools' bytes as text: UTF-8 from the PowerShell query (it sets that), else the locale's.""" + encoding = "utf-8" if backend == "windows" else locale.getpreferredencoding(False) + return (data or b"").decode(encoding, errors="replace") def _read_sys_file(path: Path) -> Optional[str]: diff --git a/test/unit_test/headless/test_usb_enumeration_cancel.py b/test/unit_test/headless/test_usb_enumeration_cancel.py new file mode 100644 index 000000000..f2ef17a7d --- /dev/null +++ b/test/unit_test/headless/test_usb_enumeration_cancel.py @@ -0,0 +1,104 @@ +"""Closing a USB tab mid-enumeration ends the enumeration tool's process. + +The enumeration (PowerShell ``Get-PnpDevice``, ``lsusb``, ``system_profiler``) +took up to its 10 s timeout, and a tab closed meanwhile left it running on a +bare worker: CI's page-width probe faulted at exit with that worker still in +``subprocess.run``. It now runs through the cancellable capture helper, and +the tabs run it as a cancellable task. +""" +import subprocess +import sys +import threading +import time +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.usb import usb_devices + +_SLOW_TOOL = [sys.executable, "-c", "import time; time.sleep(30)"] + + +def _tool(code: str) -> list: + return [sys.executable, "-c", code] + + +def test_the_tool_output_is_decoded(): + assert usb_devices._run_capture(_tool("print('ok')"), "linux").strip() == "ok" + + +def test_a_failing_tool_reports_its_exit_code_and_stderr(): + result = usb_devices._run_capture(_tool("import sys; sys.stderr.write('no bus'); sys.exit(3)"), "linux") + assert result.devices == [] + assert "exit 3: no bus" in result.error + + +def test_a_missing_tool_is_a_result_not_an_exception(): + result = usb_devices._run_capture(["je-no-such-usb-tool"], "linux") + assert result.devices == [] and result.error.startswith("je-no-such-usb-tool: ") + + +def test_a_tool_past_its_timeout_is_a_result(monkeypatch): + monkeypatch.setattr(usb_devices, "SUBPROCESS_TIMEOUT_S", 0.2) + result = usb_devices._run_capture(_SLOW_TOOL, "linux") + assert result.devices == [] and "timed out" in result.error + + +def test_cancelling_the_scope_ends_the_tool_process(): + token = CancellationToken(task_id=1) + outcome = [] + + def enumerate_in_scope(): + with cancellation_scope(token): + try: + usb_devices._run_capture(_SLOW_TOOL, "linux") + except CancelledError: + outcome.append(time.monotonic()) + + worker = threading.Thread(target=enumerate_in_scope) + worker.start() + time.sleep(0.3) + cancelled_at = time.monotonic() + token.cancel() + worker.join(10.0) + assert outcome, "the enumeration did not end with CancelledError" + assert outcome[0] - cancelled_at < 5.0 + + +def test_closing_the_usb_devices_tab_ends_the_enumeration(monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + import os + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + from je_auto_control.gui import usb_devices_tab + from headless._qt_settle import pump_until + + started, ended = threading.Event(), [] + real_popen = subprocess.Popen + + def popen(*args, **kwargs): + started.set() + return real_popen(*args, **kwargs) + + def slow_enumeration(): + try: + return usb_devices._run_capture(_SLOW_TOOL, "linux") + finally: + ended.append(time.monotonic()) + + monkeypatch.setattr(subprocess, "Popen", popen) + monkeypatch.setattr(usb_devices_tab, "list_usb_devices", slow_enumeration) + tab = usb_devices_tab.UsbDevicesTab() + try: + tab._refresh() + assert started.wait(10.0) + assert tab._listing.running + closed_at = time.monotonic() + tab.dispose() + assert pump_until(lambda: bool(ended), timeout=10.0) + assert ended[0] - closed_at < 5.0 + assert tab._error_label.text() == "" + finally: + tab.deleteLater() diff --git a/test/unit_test/headless/test_usb_windows_encoding.py b/test/unit_test/headless/test_usb_windows_encoding.py index 83d3ad168..2dbfb3c34 100644 --- a/test/unit_test/headless/test_usb_windows_encoding.py +++ b/test/unit_test/headless/test_usb_windows_encoding.py @@ -15,6 +15,7 @@ import json, subprocess, sys, threading from pathlib import Path import je_auto_control +from je_auto_control.utils import cancellable_process from je_auto_control.utils.usb import usb_devices assert Path(je_auto_control.__file__).resolve().is_relative_to(Path(sys.argv[3])) @@ -23,11 +24,11 @@ query = ("Get-PnpDevice -PresentOnly -Class USB" " | Select-Object FriendlyName, InstanceId, Manufacturer, Status" " | ConvertTo-Json -Compress") -real_run = subprocess.run +real_popen = subprocess.Popen errors, observed_flags = [], [] threading.excepthook = lambda args: errors.append(type(args.exc_value).__name__) -def synthetic_query(argv, **options): +def synthetic_query(argv, *args, **options): assert argv[:4] == ['powershell', '-NoProfile', '-NonInteractive', '-Command'] assert argv[-1].endswith(query) payload = json.dumps(expected, ensure_ascii=False).replace("'", "''") @@ -41,9 +42,10 @@ def synthetic_query(argv, **options): observed_flags.append(flags) # The RED control must also stay hidden even before the library supplies the required flag. options['creationflags'] = flags | subprocess.CREATE_NO_WINDOW - return real_run(command, **options) + return real_popen(command, *args, **options) -usb_devices.subprocess.run = synthetic_query +# The enumeration starts its tool through the cancellable capture helper. +cancellable_process.subprocess.Popen = synthetic_query result = usb_devices._enumerate_windows() assert errors == [], ('background stream decoding failed', errors) if exit_code: From 3eadb9ce6f9835ee6ef3572b3d6c1f3348d05210 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 11:38:59 +0800 Subject: [PATCH 080/161] Let Stop and closing the tab cancel an email Poll Now With several mailboxes at 30 s per IMAP step, a manual poll on a bare worker could not be ended. It now runs as a cancellable task, and the pass checks its scope between triggers, never inside one, so no message is marked seen without its script having fired. --- CHANGELOG.md | 6 ++ Progress.md | 5 +- architecture_explore.md | 14 +-- .../Eng/doc/new_features/new_features_doc.rst | 7 +- .../Zh/doc/new_features/new_features_doc.rst | 5 +- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/email_triggers_tab.py | 34 ++++---- .../utils/triggers/email_trigger.py | 9 +- .../headless/test_email_poll_cancel.py | 85 +++++++++++++++++++ 10 files changed, 147 insertions(+), 27 deletions(-) create mode 100644 test/unit_test/headless/test_email_poll_cancel.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dc703fac..c91ed85d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- `EmailTriggerWatcher.poll_once` observes a bound cancellation scope between triggers: cancelled, + it raises `CancelledError` before the next trigger's server; a trigger already being read + finishes. Unscoped calls (`AC_email_trigger_poll_once`, the watcher's own loop) are unchanged. + GUI: the Email Triggers tab's Poll Now runs as a cancellable task, which Stop and closing the + tab cancel (`_poll_thread` is gone; `_polls` is the task). + - `list_usb_devices` starts its command-line tool (PowerShell `Get-PnpDevice`, `lsusb`, `system_profiler`) through `run_capture_helper`: inside a cancellation scope, cancelling ends the tool's process and raises `CancelledError` instead of waiting out the 10 s timeout. Its diff --git a/Progress.md b/Progress.md index b46d89ce2..cc5003aa2 100644 --- a/Progress.md +++ b/Progress.md @@ -538,9 +538,10 @@ F 還缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)已遷移; + AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 + Email Triggers 的 Poll Now(U-20261114-15)已遷移; 仍直接使用 `start_worker` 的面板:`admin_console_tab`、`computer_use_tab`(已有自己的 stop event)、 - `config_sync_tab`、`dag_tab`、`email_triggers_tab`、`healing_evaluation_panel`、`journal_browser`、 + `config_sync_tab`、`dag_tab`、`healing_evaluation_panel`、`journal_browser`、 `journal_candidate_panel`、`template_candidate_panel`、`usb_browser_tab`,以及 `usb_passthrough_panel` 列舉以外的 loopback/遠端操作。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/architecture_explore.md b/architecture_explore.md index c62417ddf..477602ba8 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,797 | +| 程式碼總行數 | 235,808 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -346,7 +346,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.3 排程、觸發與背景監看 -> 11 個套件、約 4,391 行。 +> 11 個套件、約 4,398 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -357,7 +357,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/recurrence/` | 470 | RFC 5545 重複規則解析與發生時間展開 | | `utils/scheduler/` | 503 | 間隔式與 cron 式的 action JSON 排程器 | | `utils/session_guard/` | 62 | 驅動輸入前先偵測工作階段是否已鎖定/非互動 | -| `utils/triggers/` | 1,401 | 事件驅動觸發引擎:影像/視窗/像素/檔案/webhook/IMAP 郵件 | +| `utils/triggers/` | 1,408 | 事件驅動觸發引擎:影像/視窗/像素/檔案/webhook/IMAP 郵件 | | `utils/voice/` | 99 | 語音指令路由:把辨識到的語句對應到 `AC_*` action list | | `utils/watchdog/` | 232 | 背景彈窗/中斷看門狗;每條規則涵蓋 matcher/action 與錯誤日誌的秘密遮罩 | | `utils/watcher/` | 90 | 無頭輪詢原語:滑鼠位置、像素顏色、log tail | @@ -1369,7 +1369,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | hotkeys | `hotkeys_tab.py` | 166 | 將全域熱鍵綁到 action 檔。 | | triggers | `triggers_tab.py` | 384 | 影像/視窗/像素/檔案事件監看。 | | webhooks | `webhooks_tab.py` | 222 | 將 HTTP 請求綁到 action 腳本。 | -| email_triggers | `email_triggers_tab.py` | 250 | 將 IMAP 信箱綁到 action 腳本。 | +| email_triggers | `email_triggers_tab.py` | 254 | 將 IMAP 信箱綁到 action 腳本。 | | test_suite | `test_suite_tab.py` | 200 | 執行 QA 套件規格並管理易碎隔離區。 | | assertions | `assertions_tab.py` | 154 | 執行單一畫面狀態斷言並顯示通過/失敗。 | | data_source | `data_source_tab.py` | 132 | 預覽無頭資料層載入的資料列。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,585 | +| `gui/` | 160 | 42,589 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1556,7 +1556,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | | `linux_wayland/` | 24 | 4,437 | -| `utils/triggers/` | 4 | 1,401 | +| `utils/triggers/` | 4 | 1,408 | | `utils/ocr/` | 10 | 1,382 | | `utils/usbip/` | 5 | 1,008 | | `utils/assertion/` | 3 | 888 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,159 | -| **總計** | **1,525** | **235,052** | +| **總計** | **1,525** | **235,063** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/new_features_doc.rst b/docs/source/Eng/doc/new_features/new_features_doc.rst index e12335cbf..b5bce86ca 100644 --- a/docs/source/Eng/doc/new_features/new_features_doc.rst +++ b/docs/source/Eng/doc/new_features/new_features_doc.rst @@ -1659,8 +1659,13 @@ flags messages ``\\Seen`` so the same mail isn't replayed across restarts. TLS is pinned at 1.2 minimum. Combine ``AC_email_trigger_add`` with ``${secrets.NAME}`` so passwords never appear in the JSON. +``poll_once`` called inside a cancellation scope stops before the next +trigger's server when cancelled (``CancelledError``); a trigger already being +read finishes, so no message is marked seen without its script firing. + GUI: **Email Triggers** tab — register IMAP triggers, start/stop the -watcher, run a manual poll, inspect last error and fire counter. +watcher, run a manual poll, inspect last error and fire counter. **Stop** +(or closing the tab) also cancels a manual poll still running. Structured action journals (experimental) ================================================ diff --git a/docs/source/Zh/doc/new_features/new_features_doc.rst b/docs/source/Zh/doc/new_features/new_features_doc.rst index e9176677c..5a16151f5 100644 --- a/docs/source/Zh/doc/new_features/new_features_doc.rst +++ b/docs/source/Zh/doc/new_features/new_features_doc.rst @@ -1529,8 +1529,11 @@ Watcher 在 process 記憶體中追蹤已觸發的 UID,可選擇把訊息標為 ``AC_email_trigger_add`` 跟 ``${secrets.NAME}`` 搭配使用, 密碼就不會出現在 JSON 裡。 +在取消範圍內呼叫 ``poll_once`` 時,取消會讓它在下一個觸發的伺服器之前停止(``CancelledError``); +正在讀取的觸發會完成,因此不會有訊息被標為已讀卻沒有執行腳本。 + GUI: **Email Triggers** 分頁 — 註冊 IMAP 觸發、啟動 / 停止 watcher、 -手動觸發一次輪詢、檢視最近錯誤與觸發次數。 +手動觸發一次輪詢、檢視最近錯誤與觸發次數。\ **Stop**\ (或關閉分頁)也會取消仍在執行的手動輪詢。 結構化動作日誌(實驗性) ================================ diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c41c47c82..c7ac84de7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -395,3 +395,11 @@ - **Docs:** both `operations_layer_doc.rst` (USB enumeration: the tool's deadline, cancellation, the tab), `CHANGELOG.md`. - **Files:** `utils/usb/usb_devices.py`, `gui/{usb_devices_tab,usb_passthrough_panel}.py`, the two tests, the docs, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-15 · 2026-11-14 · Stop and closing the tab cancel an email Poll Now between mailboxes · #done #gui #triggers + +- **What:** part of F3. The Email Triggers tab's Poll Now ran `default_email_trigger_watcher.poll_once` on a bare worker; with several mailboxes, each IMAP step allowed 30 s, neither Stop nor closing the tab could end it. Poll Now is now a `TabTask`: the tab's Stop cancels it (before stopping the watcher, as before) and so does disposing the tab, and a stopped poll shows no *Fired n* box. `poll_once` checks the bound cancellation scope before each trigger, never inside one: a trigger already being read finishes, so a message is not flagged `\Seen` without its script having fired. The watcher's own loop and `AC_email_trigger_poll_once` run unscoped and are unchanged. +- **Tests:** `test_email_poll_cancel.py` (3: a poll cancelled during the first mailbox does not open the second, an unscoped poll reads both, the tab's Stop cancels a Poll Now in flight); the first and the last fail without the checkpoint. Email trigger, offload, slow-stop and dispose tests: 67 passed. +- **Docs:** both `new_features_doc.rst` (email triggers), `CHANGELOG.md`. +- **Files:** `utils/triggers/email_trigger.py`, `gui/email_triggers_tab.py`, the test, the docs, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 65e2366f8..9575e8533 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-15 | 2026-11-14 | Stop and closing the tab cancel an email Poll Now between mailboxes | #done #gui #triggers | [2026-11-b](2026-11-b.md) | | U-20261114-14 | 2026-11-14 | Closing a USB tab ends the enumeration tool it started | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-13 | 2026-11-14 | AI Locator and LLM Planner requests get Stop, a deadline and no late click | #done #gui #vision | [2026-11-b](2026-11-b.md) | | U-20261114-12 | 2026-11-14 | Whole-window probes end without Windows DLL teardown | #done #gui #test | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/email_triggers_tab.py b/je_auto_control/gui/email_triggers_tab.py index 487b47f35..53cf05fe0 100644 --- a/je_auto_control/gui/email_triggers_tab.py +++ b/je_auto_control/gui/email_triggers_tab.py @@ -1,4 +1,10 @@ -"""Email Triggers tab: bind IMAP mailboxes to action scripts.""" +"""Email Triggers tab: bind IMAP mailboxes to action scripts. + +Poll Now runs as a :class:`~je_auto_control.gui._tab_task.TabTask`. Stop (or +closing the tab) cancels it: the pass ends before the next trigger's server, +and a trigger already being polled finishes, so no message is marked seen +without its script having fired. +""" from typing import Optional from PySide6.QtCore import QTimer, Qt @@ -13,7 +19,7 @@ from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.surfaces import Card, set_role -from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -35,7 +41,9 @@ class EmailTriggersTab(TranslatableMixin, QWidget): def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() - self._poll_thread: Optional[WorkerHandle] = None + self._polls = TabTask(self) # Poll Now, off the GUI thread; one at a time + self._polls.result.connect(self._on_polled) + self._polls.error.connect(self._on_poll_failed) self._host_input = QLineEdit() self._host_input.setPlaceholderText("imap.example.com") self._port_input = QSpinBox() @@ -75,7 +83,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._refresh() def dispose(self) -> None: - """Release what the tab holds beyond its widgets: its refresh timer (the watcher itself keeps running). + """Release what the tab holds beyond its widgets: its refresh timer and a Poll Now still running. + + The poll stops before the next trigger; the watcher itself keeps running. Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. """ @@ -151,6 +161,8 @@ def _on_start(self) -> None: def _on_stop(self) -> None: # stop() joins the poll thread for up to 5 s (an IMAP round in # flight), which used to hold the GUI thread; a second Stop is ignored. + # A Poll Now in flight stops before its next trigger. + self._polls.stop() if self._watcher_op.run(default_email_trigger_watcher.stop, on_done=self._on_watcher_stopped, on_error=self._on_watcher_stopped): self._refresh() @@ -161,12 +173,7 @@ def _on_watcher_stopped(self, _outcome: object = None) -> None: def _on_poll_now(self) -> None: # Off the GUI thread: an IMAP server that never greets froze the # window for the full 30 s socket timeout. - if self._poll_thread is not None: - return - self._poll_thread = start_worker( - self, CallWorker(default_email_trigger_watcher.poll_once), - on_done=self._on_polled, on_fail=self._on_poll_failed, - on_thread_done=self._on_poll_thread_done) + self._polls.start(default_email_trigger_watcher.poll_once) # False while one runs def _on_polled(self, fired: int) -> None: # Per-trigger errors too: a timeout was reported as "Fired 0". @@ -177,11 +184,8 @@ def _on_polled(self, fired: int) -> None: QMessageBox.information(self, _t("eml_poll_now"), "\n".join([text, *errors])) self._refresh() - def _on_poll_failed(self, message: str) -> None: - QMessageBox.warning(self, _t("eml_poll_now"), message) - - def _on_poll_thread_done(self) -> None: - self._poll_thread = None + def _on_poll_failed(self, error: object) -> None: + QMessageBox.warning(self, _t("eml_poll_now"), str(error)) def _on_browse(self) -> None: path, _ = QFileDialog.getOpenFileName( diff --git a/je_auto_control/utils/triggers/email_trigger.py b/je_auto_control/utils/triggers/email_trigger.py index 1e62d4868..ec5016678 100644 --- a/je_auto_control/utils/triggers/email_trigger.py +++ b/je_auto_control/utils/triggers/email_trigger.py @@ -25,6 +25,7 @@ from email.header import decode_header, make_header from typing import Any, Callable, Dict, Iterable, List, Optional +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.json.json_file import read_executable_action_json from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.run_history.context import HistoryBinding, bound_history @@ -334,7 +335,12 @@ def stop(self, timeout: float = 5.0) -> None: self._thread = None def poll_once(self) -> int: - """Run exactly one polling pass; return total messages fired.""" + """Run exactly one polling pass; return total messages fired. + + Inside a cancellation scope a cancelled pass stops before the next + trigger's server, raising ``CancelledError``; a trigger already being + polled finishes, so no message is marked seen without being fired. + """ return self._poll_pass() def _run(self, stop: threading.Event) -> None: @@ -366,6 +372,7 @@ def _poll_pass(self) -> int: fired = 0 for trigger in self.list_triggers(): if trigger.enabled: + cancellation_checkpoint() fired += self._poll_one(trigger) return fired diff --git a/test/unit_test/headless/test_email_poll_cancel.py b/test/unit_test/headless/test_email_poll_cancel.py new file mode 100644 index 000000000..7fc752ef2 --- /dev/null +++ b/test/unit_test/headless/test_email_poll_cancel.py @@ -0,0 +1,85 @@ +"""A cancelled email poll stops before the next trigger's server; the tab's Stop cancels a Poll Now. + +Poll Now ran on a bare worker: with several mailboxes, each allowed 30 s per +IMAP step, Stop and closing the tab could not end it. The pass now checks its +cancellation scope between triggers -- never inside one, so a message is not +marked seen without its script having fired. +""" +import os +import threading +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.triggers import email_trigger as et + +_FAKE_PW = "p" # never sent anywhere: _poll_one is replaced below + + +@pytest.fixture +def watcher(tmp_path): + script = tmp_path / "s.json" + script.write_text('[["AC_screen_size"]]', encoding="utf-8") + w = et.EmailTriggerWatcher(executor=lambda actions, variables: None) + for host in ("imap.one.example", "imap.two.example"): + w.add(host=host, username="u", password=_FAKE_PW, script_path=str(script)) + yield w + w.stop() + + +def test_a_poll_cancelled_during_one_trigger_does_not_reach_the_next(watcher, monkeypatch): + token = CancellationToken(task_id=1) + polled = [] + + def poll_one(trigger): + polled.append(trigger.host) + token.cancel() # Stop pressed while this mailbox was being read + return 1 + + monkeypatch.setattr(watcher, "_poll_one", poll_one) + with cancellation_scope(token), pytest.raises(CancelledError): + watcher.poll_once() + assert polled == ["imap.one.example"] + + +def test_an_unscoped_poll_reads_every_trigger(watcher, monkeypatch): + polled = [] + monkeypatch.setattr(watcher, "_poll_one", lambda trigger: polled.append(trigger.host) or 1) + assert watcher.poll_once() == 2 + assert polled == ["imap.one.example", "imap.two.example"] + + +def test_the_tabs_stop_cancels_a_poll_now_in_flight(watcher, monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + from je_auto_control.gui import email_triggers_tab + from headless._qt_settle import pump_until + + entered, release, polled, shown = threading.Event(), threading.Event(), [], [] + + def poll_one(trigger): + polled.append(trigger.host) + entered.set() + release.wait(10.0) + return 1 + + monkeypatch.setattr(watcher, "_poll_one", poll_one) + monkeypatch.setattr(email_triggers_tab, "default_email_trigger_watcher", watcher) + for name in ("information", "warning"): + monkeypatch.setattr(email_triggers_tab.QMessageBox, name, lambda *args: shown.append(args[-1])) + tab = email_triggers_tab.EmailTriggersTab() + try: + tab._on_poll_now() + assert entered.wait(10.0) + tab._on_stop() + assert not tab._polls.running + release.set() + assert pump_until(lambda: not tab._watcher_op.busy) # the watcher Stop went through too + assert pump_until(lambda: bool(shown), timeout=0.5) is False # no "Fired n" for a stopped poll + assert polled == ["imap.one.example"] + finally: + release.set() + tab.deleteLater() From cb4a1dcb4a0311e19fb8bfd278fba5c93cde2be0 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 11:39:51 +0800 Subject: [PATCH 081/161] Split the F3 panel list by what each still lacks Most panels left on a bare worker already cancel on their own; only two have no Stop, and the admin broadcast needs a decision on what a partial stop reports. --- Progress.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Progress.md b/Progress.md index cc5003aa2..20130ac21 100644 --- a/Progress.md +++ b/Progress.md @@ -539,11 +539,12 @@ F 還缺: - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 - Email Triggers 的 Poll Now(U-20261114-15)已遷移; - 仍直接使用 `start_worker` 的面板:`admin_console_tab`、`computer_use_tab`(已有自己的 stop event)、 - `config_sync_tab`、`dag_tab`、`healing_evaluation_panel`、`journal_browser`、 - `journal_candidate_panel`、`template_candidate_panel`、`usb_browser_tab`,以及 `usb_passthrough_panel` - 列舉以外的 loopback/遠端操作。 + Email Triggers 的 Poll Now(U-20261114-15)已遷移。仍直接使用 `start_worker` 的面板分兩類: + - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`computer_use_tab`、`config_sync_tab`、 + `dag_tab`、`healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 + - 沒有 Stop/期限:`usb_browser_tab`(遠端裝置清單與本機 descriptor)、`usb_passthrough_panel` 列舉以外的 + loopback/遠端操作,以及 `admin_console_tab`。Admin Console 的 broadcast 以 thread pool 平行送往各主機, + 取消範圍不會進入 pool 執行緒;中途停止時要回報哪些主機已執行、哪些未送出,需先決定這個語意(`DECIDE`)。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 From bdcde92cd92a68a104e4a597c1f57845df59f8dc Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 12:01:40 +0800 Subject: [PATCH 082/161] Let an admin broadcast stop and say which hosts it reached A broadcast runs actions on many machines and could not be stopped. Now a stop skips the hosts not sent to yet, a host already sent to finishes, and every row says in sent whether the actions went there, so the operator knows where they ran. --- CHANGELOG.md | 7 + Progress.md | 6 +- architecture_explore.md | 16 +-- .../operations_layer/operations_layer_doc.rst | 12 +- .../operations_layer/operations_layer_doc.rst | 8 +- docs/updates/2026-11-b.md | 9 ++ docs/updates/README.md | 1 + je_auto_control/gui/admin_console_tab.py | 60 +++++++-- .../gui/language_wrapper/english.py | 4 + .../gui/language_wrapper/japanese.py | 4 + .../language_wrapper/simplified_chinese.py | 4 + .../language_wrapper/traditional_chinese.py | 4 + je_auto_control/utils/admin/admin_client.py | 37 +++++- .../headless/test_admin_broadcast_stop.py | 122 ++++++++++++++++++ .../headless/test_admin_console_audit.py | 2 +- 15 files changed, 265 insertions(+), 31 deletions(-) create mode 100644 test/unit_test/headless/test_admin_broadcast_stop.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c91ed85d4..585ddc210 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- `AdminConsoleClient.broadcast_execute` rows carry `sent`: whether the actions went to that + host. It takes `stop_event` and observes the caller's cancellation scope: once stopped, hosts + not sent to yet are skipped with `sent: false` and `error` `NOT_SENT_STOPPED` (exported from + `utils.admin.admin_client`), and a host already being sent to finishes. Unknown labels are + `sent: false`; code that compared whole rows sees the new key. GUI: the Admin Console tab has + **Stop broadcast** and a line summarising how many hosts were sent to. + - `EmailTriggerWatcher.poll_once` observes a bound cancellation scope between triggers: cancelled, it raises `CancelledError` before the next trigger's server; a trigger already being read finishes. Unscoped calls (`AC_email_trigger_poll_once`, the watcher's own loop) are unchanged. diff --git a/Progress.md b/Progress.md index 20130ac21..16662d141 100644 --- a/Progress.md +++ b/Progress.md @@ -539,12 +539,12 @@ F 還缺: - **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 - Email Triggers 的 Poll Now(U-20261114-15)已遷移。仍直接使用 `start_worker` 的面板分兩類: + Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: + 停止時逐台回報已執行或未送出)已遷移。仍直接使用 `start_worker` 的面板分兩類: - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`computer_use_tab`、`config_sync_tab`、 `dag_tab`、`healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - 沒有 Stop/期限:`usb_browser_tab`(遠端裝置清單與本機 descriptor)、`usb_passthrough_panel` 列舉以外的 - loopback/遠端操作,以及 `admin_console_tab`。Admin Console 的 broadcast 以 thread pool 平行送往各主機, - 取消範圍不會進入 pool 執行緒;中途停止時要回報哪些主機已執行、哪些未送出,需先決定這個語意(`DECIDE`)。 + loopback/遠端操作,以及 `admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 477602ba8..619d3ac67 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,808 | +| 程式碼總行數 | 235,887 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,11 +537,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,014 行。 +> 6 個套件、約 32,043 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `utils/admin/` | 423 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | +| `utils/admin/` | 452 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | | `utils/remote_desktop/` | 16,736 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | @@ -1336,7 +1336,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,499 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,515 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1389,7 +1389,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | remote_desktop | `remote_desktop/`(40 檔) | 8,368 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | -| admin_console | `admin_console_tab.py` | 326 | 管理多個遠端 AutoControl REST 端點。 | +| admin_console | `admin_console_tab.py` | 360 | 管理多個遠端 AutoControl REST 端點。 | | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | | usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,589 | +| `gui/` | 160 | 42,639 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,8 +1563,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,159 | -| **總計** | **1,525** | **235,063** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,188 | +| **總計** | **1,525** | **235,142** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 47c3da2d0..a52fcef06 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -433,6 +433,14 @@ action and report ``ok: false`` with the error; otherwise ``ok`` only means the host answered, and action failures are recorded inside ``result``. The DAG runner's remote nodes and the Admin Console tab both pass it. +Every row also says in ``sent`` whether the actions went to that host. Hosts +are sent to ``max_parallel`` at a time; pass ``stop_event`` (a +``threading.Event``), or call inside a cancellation scope, to stop a +broadcast: once it is set, a host not sent to yet is skipped with +``sent: false`` and ``error`` ``NOT_SENT_STOPPED``, and a host already being +sent to finishes and reports its result. An unknown label is ``sent: false`` as +well. + Persistence: hosts are saved to ``~/.je_auto_control/admin_hosts.json`` (mode 0600 on POSIX). Reload happens automatically on construction. @@ -446,7 +454,9 @@ Executor commands:: AC_admin_poll, AC_admin_broadcast_execute GUI: *Admin Console* tab — register host form, hosts table with -health/latency/jobs columns, broadcast textarea. +health/latency/jobs columns, broadcast textarea. **Stop broadcast** skips the +hosts not sent to yet; the results still list every host, and the line under +them reads *Sent to n of m hosts; k not sent.* Audit log hash chain diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index a76a3efc0..e0fd1e388 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -382,6 +382,11 @@ Headless:: ``ok: false`` 附上錯誤回報;否則 ``ok`` 只代表主機有回應,動作失敗記在 ``result`` 裡。DAG runner 的遠端節點與 Admin Console 分頁都會傳這個參數。 +每一列也以 ``sent`` 標明動作是否送到該主機。主機一次送 ``max_parallel`` 台;傳入 +``stop_event``\ (``threading.Event``)或在取消範圍內呼叫即可停止廣播:設定後尚未送出的主機 +會略過,該列為 ``sent: false``、``error`` 為 ``NOT_SENT_STOPPED``;已在傳送中的主機會執行完並回報結果。 +未知的標籤同樣是 ``sent: false``。 + 持久化:主機儲存在 ``~/.je_auto_control/admin_hosts.json``\ (POSIX 上 模式 0600)。建構時自動 reload。 @@ -394,7 +399,8 @@ Executor 指令:: AC_admin_poll, AC_admin_broadcast_execute GUI:*Admin Console* 分頁 — 註冊主機表單、含健康/延遲/任務數欄位的 -主機表、廣播文字框。 +主機表、廣播文字框。\ **停止廣播**\ 會略過尚未送出的主機;結果仍列出每台主機, +下方一行顯示「已送往 n/m 台主機;k 台未送出。」 稽核紀錄雜湊鏈 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c7ac84de7..2cf53dcc9 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -403,3 +403,12 @@ - **Docs:** both `new_features_doc.rst` (email triggers), `CHANGELOG.md`. - **Files:** `utils/triggers/email_trigger.py`, `gui/email_triggers_tab.py`, the test, the docs, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-16 · 2026-11-14 · A stopped admin broadcast reports per host whether it was sent · #done #gui #admin + +- **What:** the F3 decision left open after U-20261114-15: the maintainer chose (2026-11-14) that a broadcast stopped partway reports, host by host, whether the actions ran or were not sent. `AdminConsoleClient.broadcast_execute` sends to `max_parallel` hosts at a time from a thread pool, where the caller's cancellation scope does not reach; it now reads the scope's token in the caller's thread and takes a `stop_event`, and checks both before each host's POST. A host not sent to yet gets `{"sent": false, "ok": false, "error": NOT_SENT_STOPPED}`; a host already being sent to finishes and its row (`sent: true`) carries its result or error, since an HTTP request already out cannot be recalled. Every row now has `sent`, unknown labels included (`false`). `AC_admin_broadcast_execute` and the DAG runner's remote nodes read only `ok`, `error` and `result` and are unchanged. +- **GUI:** the Admin Console tab's broadcast is a `TabTask` with **Stop broadcast** in the Actions menu. Stop sets the event rather than cancelling the task, so the rows of every host still arrive and the line under them reads *Sent to n of m hosts; k not sent.* (four new keys in all four catalogues); closing the tab cancels the task, which skips the same hosts and drops the rows. A second broadcast while one runs says *Already running*. +- **Tests:** `test_admin_broadcast_stop.py` (6: a finished broadcast is sent everywhere, a stop during the first host skips the other two with the documented rows, a stop before the start sends nothing, a cancelled scope stops it the same way, a failed host was still sent to and an unknown label was not, the tab's Stop shows alpha sent and beta and gamma not). `test_admin_console_audit.py`'s unknown-label row gains `sent`. Admin, DAG, REST, worker, dispose and Actions-menu tests: 854 passed. +- **Docs:** both `operations_layer_doc.rst` (multi-host admin console), `CHANGELOG.md`. +- **Files:** `utils/admin/admin_client.py`, `gui/admin_console_tab.py`, the four catalogues, the tests, the docs, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 9575e8533..29b4cd0bf 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-16 | 2026-11-14 | A stopped admin broadcast reports per host whether it was sent | #done #gui #admin | [2026-11-b](2026-11-b.md) | | U-20261114-15 | 2026-11-14 | Stop and closing the tab cancel an email Poll Now between mailboxes | #done #gui #triggers | [2026-11-b](2026-11-b.md) | | U-20261114-14 | 2026-11-14 | Closing a USB tab ends the enumeration tool it started | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-13 | 2026-11-14 | AI Locator and LLM Planner requests get Stop, a deadline and no late click | #done #gui #vision | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/admin_console_tab.py b/je_auto_control/gui/admin_console_tab.py index 81bd45d26..47a7f4474 100644 --- a/je_auto_control/gui/admin_console_tab.py +++ b/je_auto_control/gui/admin_console_tab.py @@ -1,5 +1,13 @@ -"""Admin console tab: manage many remote AutoControl REST endpoints.""" +"""Admin console tab: manage many remote AutoControl REST endpoints. + +A broadcast runs as a :class:`~je_auto_control.gui._tab_task.TabTask`. Its +Stop skips the hosts not sent to yet and still shows every host's row, with +``sent`` saying whether the actions went there; closing the tab does the same +skipping and drops the rows. +""" +import functools import json +import threading from typing import Dict, List, Optional from PySide6.QtCore import QObject, QSize, QTimer, Qt, Signal @@ -12,10 +20,11 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import CallWorker, WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui._worker_thread import WorkerHandle, start_worker from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.responsive import ResponsiveBox -from je_auto_control.gui.adaptive.surfaces import Card +from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -91,7 +100,13 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._broadcast_output = QTextEdit() self._broadcast_output.setReadOnly(True) self._poll_thread: Optional[WorkerHandle] = None - self._broadcast_thread: Optional[WorkerHandle] = None + self._broadcast_status = QLabel() + self._broadcast_status.setWordWrap(True) + set_role(self._broadcast_status, "hint") + self._broadcasts = TabTask(self) # one broadcast at a time + self._broadcasts.result.connect(self._show_broadcast) + self._broadcasts.error.connect(self._show_broadcast_error) + self._broadcast_stop: Optional[threading.Event] = None # Phase 6.5: live-thumbnail grid + auto-poll timer. self._thumbnails = QListWidget() self._thumbnails.setViewMode(QListWidget.ViewMode.IconMode) @@ -129,7 +144,9 @@ def _build_layout(self) -> None: root.addWidget(ResponsiveBox(hosts, self._build_broadcast_group(), stretches=(3, 2)), stretch=1) def dispose(self) -> None: - """Release what the tab holds beyond its widgets: its thumbnail timer and the polls still out. + """Release what the tab holds beyond its widgets: its thumbnail timer, the polls still out and a broadcast. + + A broadcast skips the hosts it has not sent to yet; one already being sent to finishes. Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. """ @@ -143,6 +160,7 @@ def menu_actions(self) -> list: ("admin_refresh", self._on_refresh), ("admin_thumb_refresh_now", self._refresh_thumbnails), ("admin_broadcast_run", self._on_broadcast), + ("admin_broadcast_stop", self._on_broadcast_stop), ] def _build_thumbnails_group(self) -> QGroupBox: @@ -171,6 +189,7 @@ def _build_broadcast_group(self) -> QGroupBox: form.addWidget(self._actions_input) form.addWidget(self._tr(QLabel(), "admin_results_label")) form.addWidget(self._broadcast_output, stretch=1) + form.addWidget(self._broadcast_status) return group def _on_add(self) -> None: @@ -214,20 +233,35 @@ def _on_broadcast(self) -> None: return # Each host stops at its first failing action and its row says so. # Off the GUI thread: every host is an HTTP round trip. - if self._broadcast_thread is not None: + stop = threading.Event() + work = functools.partial(self._client.broadcast_execute, actions=actions, + raise_on_error=True, stop_event=stop) + if not self._broadcasts.start(work): + self._broadcast_status.setText(_t("task_busy")) + return + self._broadcast_stop = stop + self._broadcast_status.setText(_t("admin_broadcast_running")) + + def _on_broadcast_stop(self) -> None: + """Skip the hosts not sent to yet; the rows of every host still arrive.""" + if self._broadcast_stop is None or not self._broadcasts.running: return - self._broadcast_thread = start_worker( - self, CallWorker(lambda: self._client.broadcast_execute(actions=actions, raise_on_error=True)), - on_done=self._show_broadcast, on_fail=self._broadcast_output.setPlainText, - on_thread_done=self._on_broadcast_thread_done) + self._broadcast_stop.set() + self._broadcast_status.setText(_t("admin_broadcast_stopping")) def _show_broadcast(self, results) -> None: + self._broadcast_stop = None self._broadcast_output.setPlainText( json.dumps(results, indent=2, ensure_ascii=False, default=str), ) - - def _on_broadcast_thread_done(self) -> None: - self._broadcast_thread = None + sent = sum(1 for row in results if row.get("sent")) + self._broadcast_status.setText(_t("admin_broadcast_summary").format( + sent=sent, total=len(results), skipped=len(results) - sent)) + + def _show_broadcast_error(self, error: object) -> None: + self._broadcast_stop = None + self._broadcast_output.setPlainText(str(error)) + self._broadcast_status.setText("") def _apply_poll_result(self, statuses: list) -> None: self._refresh_table(statuses=statuses) diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index a44383c56..d9cdc844e 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -432,6 +432,10 @@ "admin_broadcast_group": "Broadcast", "admin_actions_label": "Actions JSON (sent to every host):", "admin_broadcast_run": "Run on all hosts", + "admin_broadcast_stop": "Stop broadcast", + "admin_broadcast_running": "Sending to the hosts...", + "admin_broadcast_stopping": "Stopping: hosts not sent to yet are skipped; hosts already sent to finish.", + "admin_broadcast_summary": "Sent to {sent} of {total} hosts; {skipped} not sent.", "admin_results_label": "Per-host results:", "admin_col_label": "Label", "admin_col_url": "URL", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index ae4619501..eee9a654c 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -326,6 +326,10 @@ "admin_broadcast_group": "ブロードキャスト", "admin_actions_label": "アクション JSON (全ホストへ送信):", "admin_broadcast_run": "全ホストで実行", + "admin_broadcast_stop": "ブロードキャストを停止", + "admin_broadcast_running": "各ホストへ送信中...", + "admin_broadcast_stopping": "停止中: まだ送信していないホストはスキップし、送信済みのホストは最後まで実行します。", + "admin_broadcast_summary": "{total} 台中 {sent} 台に送信、{skipped} 台は未送信。", "admin_results_label": "ホスト別結果:", "admin_col_label": "ラベル", "admin_col_url": "URL", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index d8cb52257..3da7b163a 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -297,6 +297,10 @@ "admin_broadcast_group": "广播", "admin_actions_label": "动作 JSON (发送给所有主机):", "admin_broadcast_run": "对所有主机执行", + "admin_broadcast_stop": "停止广播", + "admin_broadcast_running": "正在发送到各主机...", + "admin_broadcast_stopping": "正在停止:尚未发送的主机会跳过,已发送的主机会执行完。", + "admin_broadcast_summary": "已发送到 {sent}/{total} 台主机;{skipped} 台未发送。", "admin_results_label": "各主机结果:", "admin_col_label": "标签", "admin_col_url": "URL", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index 5118bd37a..7d6f47cac 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -304,6 +304,10 @@ "admin_broadcast_group": "廣播", "admin_actions_label": "動作 JSON (送至所有主機):", "admin_broadcast_run": "對所有主機執行", + "admin_broadcast_stop": "停止廣播", + "admin_broadcast_running": "正在送往各主機...", + "admin_broadcast_stopping": "正在停止:尚未送出的主機會略過,已送出的主機會執行完。", + "admin_broadcast_summary": "已送往 {sent}/{total} 台主機;{skipped} 台未送出。", "admin_results_label": "各主機結果:", "admin_col_label": "標籤", "admin_col_url": "URL", diff --git a/je_auto_control/utils/admin/admin_client.py b/je_auto_control/utils/admin/admin_client.py index 4350f3934..3488cc8ca 100644 --- a/je_auto_control/utils/admin/admin_client.py +++ b/je_auto_control/utils/admin/admin_client.py @@ -19,8 +19,9 @@ from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, dataclass, field from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional +from je_auto_control.utils.exception.cancellation import CancellationToken, current_cancellation_token from je_auto_control.utils.json_store.json_store import load_json_or_quarantine, quarantine_file from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -31,6 +32,16 @@ #: Largest response body read from a host (a screenshot is the big one). _MAX_RESPONSE_BYTES = 16 * 1024 * 1024 _READ_CHUNK_BYTES = 65536 +#: The ``error`` of a broadcast row for a host that was skipped because the broadcast was stopped. +NOT_SENT_STOPPED = "not sent: the broadcast was stopped" + + +def _stop_requested(stop_event: Optional[threading.Event], + token: Optional[CancellationToken]) -> Callable[[], bool]: + """Whether a broadcast should skip the hosts it has not sent to yet.""" + def stopped() -> bool: + return (stop_event is not None and stop_event.is_set()) or (token is not None and token.is_cancelled) + return stopped class _RefuseRedirects(urllib.request.HTTPRedirectHandler): @@ -166,6 +177,7 @@ def grab(host: AdminHost) -> tuple: def broadcast_execute(self, actions: List[Any], *, labels: Optional[List[str]] = None, raise_on_error: bool = False, + stop_event: Optional[threading.Event] = None, ) -> List[Dict[str, Any]]: """Run ``actions`` on every host (or ``labels``); one row per host. @@ -173,20 +185,37 @@ def broadcast_execute(self, actions: List[Any], and that host's row is ``ok: false`` with the error. Otherwise ``ok`` only means the host answered, and action failures sit inside ``result``. A host too old to know the flag ignores it. + + Every row says in ``sent`` whether the actions went to that host. + Hosts are sent to in parallel, ``max_parallel`` at a time; once + ``stop_event`` is set, or the caller's cancellation scope is + cancelled, a host not yet sent to is skipped (``sent: false``, + ``error`` :data:`NOT_SENT_STOPPED`) and a host already being sent to + finishes and reports its result. An unknown label is ``sent: false`` too. """ targets = self._resolve_targets(labels) # A label that names no host is a failure to report, not a host to # skip: a typo used to make the broadcast look complete. known = {host.label for host in targets} - missing = [{"label": label, "ok": False, "error": "unknown host"} + missing = [{"label": label, "ok": False, "sent": False, "error": "unknown host"} for label in (labels or []) if label not in known] if not targets: return missing + # Read in the caller's thread: the pool's threads do not see its scope. + stopped = _stop_requested(stop_event, current_cancellation_token()) with ThreadPoolExecutor(max_workers=self._max_parallel) as pool: return list(pool.map( - lambda host: self._execute_one(host, actions, raise_on_error), targets, + lambda host: self._execute_unless_stopped(host, actions, raise_on_error, stopped), targets, )) + missing + def _execute_unless_stopped(self, host: AdminHost, actions: List[Any], raise_on_error: bool, + stopped: Callable[[], bool]) -> Dict[str, Any]: + if stopped(): + return {"label": host.label, "ok": False, "sent": False, "error": NOT_SENT_STOPPED} + row = self._execute_one(host, actions, raise_on_error) + row["sent"] = True + return row + def _resolve_targets(self, labels: Optional[List[str]]) -> List[AdminHost]: # None is "every host"; an empty list is no host -- it ran a # broadcast on every host when a caller's filter matched nothing. @@ -412,6 +441,6 @@ def default_admin_console() -> AdminConsoleClient: __all__ = [ - "AdminConsoleClient", "AdminHost", "HostStatus", + "AdminConsoleClient", "AdminHost", "HostStatus", "NOT_SENT_STOPPED", "default_admin_console", "default_admin_hosts_path", "current_admin_hosts_path", ] diff --git a/test/unit_test/headless/test_admin_broadcast_stop.py b/test/unit_test/headless/test_admin_broadcast_stop.py new file mode 100644 index 000000000..1e4494b4a --- /dev/null +++ b/test/unit_test/headless/test_admin_broadcast_stop.py @@ -0,0 +1,122 @@ +"""A stopped admin broadcast reports, host by host, whether the actions were sent. + +A broadcast runs actions on many machines. Stopping it used to be impossible; +now hosts not sent to yet are skipped and every host still gets a row whose +``sent`` says which happened, so the operator knows where the actions ran. +""" +import os +import threading + +import pytest + +from je_auto_control.utils.admin.admin_client import NOT_SENT_STOPPED, AdminConsoleClient +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope + +_HOSTS = ("alpha", "beta", "gamma") + + +@pytest.fixture +def console(tmp_path): + # One host at a time, so "not reached yet" is well defined. + client = AdminConsoleClient(persist_path=tmp_path / "hosts.json", max_parallel=1) + for label in _HOSTS: + client.add_host(label, f"http://{label}.example", "tok") # NOSONAR python:S5332 # reason: no network, _http_post is faked + return client + + +def _fake_post(console, monkeypatch, on_post=None): + posted = [] + + def post(host, path, body): + posted.append(host.label) + if on_post is not None: + on_post(host) + return {"result": {"host": host.label}} + + monkeypatch.setattr(console, "_http_post", post) + return posted + + +def test_every_row_of_a_finished_broadcast_was_sent(console, monkeypatch): + posted = _fake_post(console, monkeypatch) + rows = console.broadcast_execute([["AC_x"]]) + assert [(row["label"], row["ok"], row["sent"]) for row in rows] == [(label, True, True) for label in _HOSTS] + assert posted == list(_HOSTS) + + +def test_a_stop_during_the_first_host_skips_the_rest_and_says_so(console, monkeypatch): + stop = threading.Event() + posted = _fake_post(console, monkeypatch, on_post=lambda host: stop.set()) + rows = console.broadcast_execute([["AC_x"]], stop_event=stop) + assert posted == ["alpha"] + assert rows[0] == {"label": "alpha", "ok": True, "sent": True, "result": {"result": {"host": "alpha"}}} + assert rows[1:] == [{"label": label, "ok": False, "sent": False, "error": NOT_SENT_STOPPED} + for label in ("beta", "gamma")] + + +def test_a_broadcast_stopped_before_it_starts_sends_nothing(console, monkeypatch): + stop = threading.Event() + stop.set() + posted = _fake_post(console, monkeypatch) + rows = console.broadcast_execute([["AC_x"]], stop_event=stop) + assert posted == [] + assert all(row["sent"] is False and row["error"] == NOT_SENT_STOPPED for row in rows) + + +def test_a_cancelled_scope_stops_the_broadcast_the_same_way(console, monkeypatch): + token = CancellationToken(task_id=1) + posted = _fake_post(console, monkeypatch, on_post=lambda host: token.cancel()) + with cancellation_scope(token): + rows = console.broadcast_execute([["AC_x"]]) + assert posted == ["alpha"] + assert [row["sent"] for row in rows] == [True, False, False] + + +def test_a_host_that_failed_was_still_sent_to(console, monkeypatch): + monkeypatch.setattr(console, "_http_post", lambda host, path, body: {"ok": False, "error": "boom"}) + rows = console.broadcast_execute([["AC_x"]], labels=["alpha", "typo"]) + assert rows == [ + {"label": "alpha", "ok": False, "sent": True, "error": "boom", "result": {"ok": False, "error": "boom"}}, + {"label": "typo", "ok": False, "sent": False, "error": "unknown host"}, + ] + + +def test_the_tabs_stop_shows_which_hosts_were_sent_to(console, monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + import json + from je_auto_control.gui import admin_console_tab + from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper + from headless._qt_settle import pump_until + + entered, release = threading.Event(), threading.Event() + + def hold(host): + entered.set() + release.wait(10.0) + + posted = _fake_post(console, monkeypatch, on_post=hold) + monkeypatch.setattr(admin_console_tab, "default_admin_console", lambda: console) + monkeypatch.setattr(console, "fetch_thumbnails", lambda *a, **k: {}) + tab = admin_console_tab.AdminConsoleTab() + try: + tab._thumb_timer.stop() + tab._actions_input.setPlainText('[["AC_x"]]') + actions = dict(tab.menu_actions()) + actions["admin_broadcast_run"]() + assert entered.wait(10.0) + actions["admin_broadcast_stop"]() + assert tab._broadcast_status.text() == language_wrapper.translate( + "admin_broadcast_stopping", "admin_broadcast_stopping") + release.set() + assert pump_until(lambda: tab._broadcast_output.toPlainText() != "") + rows = json.loads(tab._broadcast_output.toPlainText()) + assert [(row["label"], row["sent"]) for row in rows] == [("alpha", True), ("beta", False), ("gamma", False)] + assert posted == ["alpha"] + assert tab._broadcast_status.text() == language_wrapper.translate( + "admin_broadcast_summary", "admin_broadcast_summary").format(sent=1, total=3, skipped=2) + finally: + release.set() + tab.deleteLater() diff --git a/test/unit_test/headless/test_admin_console_audit.py b/test/unit_test/headless/test_admin_console_audit.py index cda68efa5..1d1853736 100644 --- a/test/unit_test/headless/test_admin_console_audit.py +++ b/test/unit_test/headless/test_admin_console_audit.py @@ -91,7 +91,7 @@ def log_message(self, *_args): def test_an_unknown_label_is_reported(console): rows = console.broadcast_execute([["AC_screen_size"]], labels=["typo-host"]) - assert rows == [{"label": "typo-host", "ok": False, "error": "unknown host"}] + assert rows == [{"label": "typo-host", "ok": False, "sent": False, "error": "unknown host"}] def test_a_whitespace_label_is_refused(console): From d21237eb0ac4018c40eac2b394a4b9d6a127f8ea Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 13:18:08 +0800 Subject: [PATCH 083/161] Give the USB Browser's Fetch and Open a Stop and a deadline Both ran on bare workers: a host that accepted the connection and then said nothing held Fetch with no way out, and a second request was silently ignored. They now share one TabTask with a 30 s deadline and Stop run in the Actions menu; a late answer is dropped. --- CHANGELOG.md | 5 + Progress.md | 5 +- architecture_explore.md | 8 +- .../usb_passthrough_operator_guide.rst | 5 +- .../usb_passthrough_operator_guide.rst | 4 +- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/usb_browser_tab.py | 99 +++++++++---------- .../headless/test_gui_panel_dispose.py | 4 +- .../headless/test_usb_browser_stop.py | 98 ++++++++++++++++++ 10 files changed, 171 insertions(+), 66 deletions(-) create mode 100644 test/unit_test/headless/test_usb_browser_stop.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 585ddc210..717f41a7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI: the USB Browser tab's Fetch and Open run as one cancellable task with a 30 s deadline + (`REQUEST_DEADLINE_S`) and **Stop run** in the Actions menu; a stopped, timed-out or abandoned + request's answer is dropped, and a second request while one runs says *Already running* + instead of being ignored. `_fetch_thread` and `_open_thread` are gone; `_requests` is the task. + - `AdminConsoleClient.broadcast_execute` rows carry `sent`: whether the actions went to that host. It takes `stop_event` and observes the caller's cancellation scope: once stopped, hosts not sent to yet are skipped with `sent: false` and `error` `NOT_SENT_STOPPED` (exported from diff --git a/Progress.md b/Progress.md index 16662d141..42577b874 100644 --- a/Progress.md +++ b/Progress.md @@ -540,11 +540,10 @@ F 還缺: 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: - 停止時逐台回報已執行或未送出)已遷移。仍直接使用 `start_worker` 的面板分兩類: + 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)已遷移。仍直接使用 `start_worker` 的面板分兩類: - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`computer_use_tab`、`config_sync_tab`、 `dag_tab`、`healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - - 沒有 Stop/期限:`usb_browser_tab`(遠端裝置清單與本機 descriptor)、`usb_passthrough_panel` 列舉以外的 - loopback/遠端操作,以及 `admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 + - 沒有 Stop/期限:`usb_passthrough_panel` 列舉以外的 loopback/遠端操作,以及 `admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 619d3ac67..55c35cb00 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,887 | +| 程式碼總行數 | 235,876 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1393,7 +1393,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | | usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | -| usb_browser | `usb_browser_tab.py` | 288 | 檢視端 USB 裝置瀏覽器。 | +| usb_browser | `usb_browser_tab.py` | 277 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 770 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | | diagnostics | `diagnostics_tab.py` | 235 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,639 | +| `gui/` | 160 | 42,628 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,188 | -| **總計** | **1,525** | **235,142** | +| **總計** | **1,525** | **235,131** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst b/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst index 05adddd80..67e06786e 100644 --- a/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst +++ b/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst @@ -376,7 +376,10 @@ What is *not* shipped yet right, list the shared devices over the in-process channel and *Open* one (a descriptor read proves the full stack). The *USB Browser* tab's *Open* button now also works against a **localhost** target via the - same loopback path. Sharing lasts as long as the panel: when the window + same loopback path. Its *Fetch* and *Open* run one at a time, with + **Stop run** in the Actions menu and a 30 s deadline; the answer to a + stopped or timed-out request, or one left by a closed tab, is dropped. + Sharing lasts as long as the panel: when the window holding it is destroyed, its loopback and hotplug watcher close and the feature flag it turned on goes back off. - Cross-machine is fully wired: the WebRTC host creates a ``usb`` diff --git a/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst b/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst index 7604b94ab..16ca1d5fd 100644 --- a/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst +++ b/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst @@ -340,7 +340,9 @@ JSON action 範例:: - *USB 分享* 分頁是簡易的 AnyDesk 風介面:左側啟用分享並對本機裝置 做 ACL 允許/封鎖;右側經 in-process channel 列出分享裝置並 *開啟* 其中一個(讀描述元即證明整條堆疊運作)。*USB Browser* 分頁的 *Open* - 按鈕現在對 **localhost** 目標也會走同一條 loopback 路徑。分享只跟著面板存在: + 按鈕現在對 **localhost** 目標也會走同一條 loopback 路徑。它的 *Fetch* 與 *Open* + 一次只跑一個,Actions 選單有\ **停止執行**\ ,期限 30 秒;已停止、逾時或分頁已關閉的請求, + 回應會被丟棄。分享只跟著面板存在: 容納它的視窗被銷毀時,它的 loopback 與熱插拔監看會關閉,它開啟的功能旗標也會關回去。 - 跨機器已完整串接:WebRTC host 建立 ``usb`` DataChannel,viewer 以 ``viewer.usb_client()`` 暴露 ``UsbChannelClient``\ (含 ``list_devices`` diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 2cf53dcc9..fba50bf5c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -412,3 +412,11 @@ - **Docs:** both `operations_layer_doc.rst` (multi-host admin console), `CHANGELOG.md`. - **Files:** `utils/admin/admin_client.py`, `gui/admin_console_tab.py`, the four catalogues, the tests, the docs, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-17 · 2026-11-14 · The USB Browser's Fetch and Open get a Stop and a deadline · #done #gui #usb + +- **What:** the next `Progress.md` › F3 panel with no Stop. The USB Browser tab ran *Fetch devices* (`fetch_remote_devices`, a 5 s HTTP limit) and the localhost *Open selected* (`open_local_descriptor` over the loopback transport) on two bare workers: no Stop, no deadline, and a second request while one was out was silently ignored. Both now run as one `TabTask` (`_requests`, tagged `fetch` / `open`) with `REQUEST_DEADLINE_S = 30.0` and **Stop run** in the Actions menu. Stop, the deadline and closing the tab free the tab at once and drop the late answer (the request itself cannot be interrupted); a second request says *Already running*; a timeout says so instead of showing a fetch error. The work is handed plain values (`functools.partial` over the URL, token, VID, PID and serial), so it holds no widget. `_FetchWorker` is gone; every failure, not only `ValueError` / `OSError`, now reaches the status line. +- **Tests:** `test_usb_browser_stop.py` (5: Stop drops a fetch still out, a fetch past its deadline says so, a second request is refused visibly, a finished fetch fills the table, a failed fetch shows its error; the first three fail on the old tab). `test_gui_panel_dispose.py`'s USB Browser case now checks the task is free after `dispose()` and the late open leaves the status untouched. USB, dispose, worker-thread and owner-death tests: 77 passed. +- **Docs:** both `usb_passthrough_operator_guide.rst`, `CHANGELOG.md`. +- **Files:** `gui/usb_browser_tab.py`, the tests, the docs, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 29b4cd0bf..662b5ffa2 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-17 | 2026-11-14 | The USB Browser's Fetch and Open get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-16 | 2026-11-14 | A stopped admin broadcast reports per host whether it was sent | #done #gui #admin | [2026-11-b](2026-11-b.md) | | U-20261114-15 | 2026-11-14 | Stop and closing the tab cancel an email Poll Now between mailboxes | #done #gui #triggers | [2026-11-b](2026-11-b.md) | | U-20261114-14 | 2026-11-14 | Closing a USB tab ends the enumeration tool it started | #done #gui #usb | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/usb_browser_tab.py b/je_auto_control/gui/usb_browser_tab.py index 8c8943d4f..16b1e616e 100644 --- a/je_auto_control/gui/usb_browser_tab.py +++ b/je_auto_control/gui/usb_browser_tab.py @@ -13,6 +13,10 @@ integration. The browse + enumerate path works against any reachable REST server today; for the simple share/use flow see the *USB Sharing* panel. + +Both requests run as a :class:`~je_auto_control.gui._tab_task.TabTask`: one +at a time, a Stop in the Actions menu and a deadline. A request stopped, timed +out or left by a closed tab has its answer dropped. """ from __future__ import annotations @@ -22,7 +26,6 @@ from email.message import Message from typing import Any, Dict, List, Optional -from PySide6.QtCore import QObject, Signal from PySide6.QtWidgets import ( QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, @@ -30,8 +33,9 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import CallWorker as _CallWorker, WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.surfaces import Card, set_role +from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) @@ -48,6 +52,8 @@ def _t(key: str) -> str: _DESC_REQUEST = 0x06 _DESC_VALUE = 0x0100 _DESC_LENGTH = 18 +#: How long a fetch or a local open may take before the tab gives up on it. +REQUEST_DEADLINE_S = 30.0 def _is_loopback_target(base_url: str) -> bool: @@ -112,28 +118,10 @@ def fetch_remote_devices(*, base_url: str, return devices -class _FetchWorker(QObject): - """Background fetch — keeps the Qt thread responsive.""" - - finished = Signal(list) - failed = Signal(str) - - def __init__(self, *, base_url: str, token: str) -> None: - super().__init__() - self._base_url = base_url - self._token = token - - def run(self) -> None: - try: - devices = fetch_remote_devices( - base_url=self._base_url, token=self._token, - ) - # Not redundant: TimeoutError is not an OSError on Python 3.10. - # URLError already is one, so it was dropped. - except (ValueError, OSError, TimeoutError) as error: # NOSONAR - self.failed.emit(str(error)) - return - self.finished.emit(devices) +def _open_local(vendor_id: str, product_id: str, serial: Optional[str]) -> tuple: + """Open the device locally; return ``(vendor_id, product_id, descriptor)`` for the status line.""" + return vendor_id, product_id, open_local_descriptor( + vendor_id=vendor_id, product_id=product_id, serial=serial) class UsbBrowserTab(TranslatableMixin, QWidget): @@ -151,8 +139,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._table.horizontalHeader().setSectionResizeMode( QHeaderView.ResizeMode.ResizeToContents, ) - self._fetch_thread: Optional[WorkerHandle] = None - self._open_thread: Optional[WorkerHandle] = None + self._requests = TabTask(self) + self._requests.result.connect(self._show_outcome) + self._requests.error.connect(self._apply_failure) self._build_layout() self._apply_table_headers() @@ -168,9 +157,9 @@ def _build_layout(self) -> None: root.addWidget(self._status_label) def dispose(self) -> None: - """Release what the tab holds beyond its widgets: the device listing or open still out, whose answer is dropped. + """Release what the tab holds beyond its widgets: cancel the listing or open still out. - The request itself cannot be interrupted and runs to its end. Called by + The request itself cannot be interrupted and runs to its end; its answer is dropped. Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. """ release_resources(self) @@ -180,6 +169,7 @@ def menu_actions(self) -> list: return [ ("usb_browser_fetch", self._on_fetch), ("usb_browser_open", self._on_open_selected), + ("task_stop", self._on_stop), ] def _build_target_group(self) -> QGroupBox: @@ -199,19 +189,26 @@ def _apply_table_headers(self) -> None: ]) def _on_fetch(self) -> None: - if self._fetch_thread is not None: - return - self._status_label.setText(_t("usb_browser_fetching")) - self._fetch_thread = start_worker( - self, _FetchWorker( - base_url=self._url_input.text().strip(), - token=self._token_input.text().strip(), - ), - on_done=self._apply_devices, on_fail=self._apply_failure, - on_thread_done=self._on_fetch_done) - - def _on_fetch_done(self) -> None: - self._fetch_thread = None + work = functools.partial(fetch_remote_devices, base_url=self._url_input.text().strip(), + token=self._token_input.text().strip()) + if self._start(work, "fetch"): + self._status_label.setText(_t("usb_browser_fetching")) + + def _start(self, work, tag: str) -> bool: + if self._requests.start(work, tag=tag, timeout_s=REQUEST_DEADLINE_S): + return True + self._status_label.setText(_t("task_busy")) + return False + + def _on_stop(self) -> None: + if self._requests.stop(): + self._status_label.setText(_t("task_stopped")) + + def _show_outcome(self, value: Any) -> None: + if self._requests.tag == "open": + self._on_local_opened(*value) + else: + self._apply_devices(value) def _apply_devices(self, devices: list) -> None: self._status_label.setText( @@ -229,9 +226,12 @@ def _apply_devices(self, devices: list) -> None: for col_index, text in enumerate(cells): self._table.setItem(row_index, col_index, QTableWidgetItem(text)) - def _apply_failure(self, message: str) -> None: + def _apply_failure(self, error: object) -> None: + if isinstance(error, TaskTimeout): + self._status_label.setText(_t("task_timed_out")) + return self._status_label.setText( - _t("usb_browser_fetch_failed").format(error=message), + _t("usb_browser_fetch_failed").format(error=error), ) def _on_open_selected(self) -> None: @@ -250,8 +250,6 @@ def _on_open_selected(self) -> None: _t("usb_browser_open_unwired"), ) return - if self._open_thread is not None: - return row = rows[0] vid = self._row_text(row, 0) pid = self._row_text(row, 1) @@ -260,16 +258,7 @@ def _on_open_selected(self) -> None: def _start_local_open(self, vid: str, pid: str, serial: Optional[str]) -> None: - # on_done runs on the GUI thread (start_worker relays it) and is held weakly. - self._open_thread = start_worker( - self, _CallWorker(lambda: open_local_descriptor( - vendor_id=vid, product_id=pid, serial=serial, - )), - on_done=functools.partial(self._on_local_opened, vid, pid), - on_fail=self._apply_failure, on_thread_done=self._on_open_done) - - def _on_open_done(self) -> None: - self._open_thread = None + self._start(functools.partial(_open_local, vid, pid, serial), "open") def _on_local_opened(self, vid: str, pid: str, descriptor: bytes) -> None: from je_auto_control.utils.usb.passthrough import describe_descriptor diff --git a/test/unit_test/headless/test_gui_panel_dispose.py b/test/unit_test/headless/test_gui_panel_dispose.py index c60603264..dd332fc9b 100644 --- a/test/unit_test/headless/test_gui_panel_dispose.py +++ b/test/unit_test/headless/test_gui_panel_dispose.py @@ -331,9 +331,9 @@ def open_local(**_kwargs): tab._start_local_open("1234", "5678", None) before = tab._status_label.text() tab.dispose() + assert not tab._requests.running release.set() - assert pump_until(lambda: tab._open_thread is None) - assert tab._status_label.text() == before + assert pump_until(lambda: tab._status_label.text() != before, timeout=0.5) is False # --- the helper -------------------------------------------------------------------------------------------------- diff --git a/test/unit_test/headless/test_usb_browser_stop.py b/test/unit_test/headless/test_usb_browser_stop.py new file mode 100644 index 000000000..3fd708dd2 --- /dev/null +++ b/test/unit_test/headless/test_usb_browser_stop.py @@ -0,0 +1,98 @@ +"""The USB Browser's fetch and local open: a Stop, a deadline, and no late answer. + +Both ran on bare workers with no Stop: a host that accepted the connection and +then said nothing held the tab's Fetch for the whole HTTP timeout, and a second +Fetch was silently ignored. They now run as one +:class:`~je_auto_control.gui._tab_task.TabTask`. +""" +import os +import threading + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtWidgets import QApplication # noqa: E402 + +from je_auto_control.gui import usb_browser_tab # noqa: E402 +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) +_DEVICE = {"vendor_id": "046d", "product_id": "c52b", "product": "Receiver"} + + +def _t(key): + return language_wrapper.translate(key, key) + + +@pytest.fixture +def slow_fetch(monkeypatch): + release, asked = threading.Event(), threading.Event() + + def fetch(*, base_url, token, timeout_s=5.0): + asked.set() + release.wait(30.0) + return [_DEVICE] + + monkeypatch.setattr(usb_browser_tab, "fetch_remote_devices", fetch) + tab = usb_browser_tab.UsbBrowserTab() + yield tab, release, asked + release.set() + tab.deleteLater() + + +def _menu(tab, key): + return dict(tab.menu_actions())[key] + + +def test_stop_drops_a_fetch_still_out(slow_fetch): + tab, release, asked = slow_fetch + _menu(tab, "usb_browser_fetch")() + assert asked.wait(10.0) + _menu(tab, "task_stop")() + assert tab._status_label.text() == _t("task_stopped") + assert not tab._requests.running # a new Fetch can start at once + release.set() + assert pump_until(lambda: tab._table.rowCount() != 0, timeout=0.5) is False + assert tab._status_label.text() == _t("task_stopped") + + +def test_a_fetch_past_its_deadline_says_so(slow_fetch, monkeypatch): + tab, _release, _asked = slow_fetch + monkeypatch.setattr(usb_browser_tab, "REQUEST_DEADLINE_S", 0.05) + _menu(tab, "usb_browser_fetch")() + assert pump_until(lambda: tab._status_label.text() == _t("task_timed_out")) + assert tab._table.rowCount() == 0 + + +def test_a_second_request_while_one_is_out_is_refused_visibly(slow_fetch): + tab, _release, asked = slow_fetch + _menu(tab, "usb_browser_fetch")() + assert asked.wait(10.0) + tab._start_local_open("046d", "c52b", None) + assert tab._status_label.text() == _t("task_busy") + + +def test_a_finished_fetch_fills_the_table(slow_fetch): + tab, release, _asked = slow_fetch + release.set() + _menu(tab, "usb_browser_fetch")() + assert pump_until(lambda: tab._table.rowCount() == 1) + assert tab._table.item(0, 3).text() == "Receiver" + assert tab._status_label.text() == _t("usb_browser_fetched").format(count=1) + + +def test_a_failed_fetch_shows_its_error(monkeypatch): + def fetch(**_kwargs): + raise ValueError("base_url is required") + + monkeypatch.setattr(usb_browser_tab, "fetch_remote_devices", fetch) + tab = usb_browser_tab.UsbBrowserTab() + try: + _menu(tab, "usb_browser_fetch")() + assert pump_until(lambda: tab._status_label.text() == _t("usb_browser_fetch_failed").format( + error="base_url is required")) + finally: + tab.deleteLater() From 125bacd66aa976266acbdf8296a4996560cebeaa Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 13:27:28 +0800 Subject: [PATCH 084/161] Give the USB passthrough panel's use requests a Stop and a deadline List shared, Open and the remote fetch shared one bare worker: a WebRTC peer that stopped answering held the panel, and a second request was silently ignored. They now run as one TabTask with a 30 s deadline and Stop run in the Actions menu; a late answer is dropped. --- CHANGELOG.md | 6 + Progress.md | 5 +- architecture_explore.md | 8 +- .../usb_passthrough_operator_guide.rst | 3 + .../usb_passthrough_operator_guide.rst | 3 +- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/usb_passthrough_panel.py | 94 ++++++------ .../headless/test_usb_passthrough_requests.py | 135 ++++++++++++++++++ 9 files changed, 213 insertions(+), 50 deletions(-) create mode 100644 test/unit_test/headless/test_usb_passthrough_requests.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 717f41a7a..5a93e4a98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI: the USB passthrough panel's List shared, Open and remote REST fetch run as one + cancellable task with a 30 s deadline (`REQUEST_DEADLINE_S`) and **Stop run** in the Actions + menu, which also stops a local listing; a late answer is dropped and a second request says + *Already running*. `_thread`, `_run_async`, `_fail` and `_fail_remote` are gone; `_requests` + is the task. + - GUI: the USB Browser tab's Fetch and Open run as one cancellable task with a 30 s deadline (`REQUEST_DEADLINE_S`) and **Stop run** in the Actions menu; a stopped, timed-out or abandoned request's answer is dropped, and a second request while one runs says *Already running* diff --git a/Progress.md b/Progress.md index 42577b874..012e9fd9a 100644 --- a/Progress.md +++ b/Progress.md @@ -540,10 +540,11 @@ F 還缺: 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: - 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)已遷移。仍直接使用 `start_worker` 的面板分兩類: + 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 + USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)已遷移。仍直接使用 `start_worker` 的面板分兩類: - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`computer_use_tab`、`config_sync_tab`、 `dag_tab`、`healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - - 沒有 Stop/期限:`usb_passthrough_panel` 列舉以外的 loopback/遠端操作,以及 `admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 + - 沒有 Stop/期限:`admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 55c35cb00..4e181f549 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,876 | +| 程式碼總行數 | 235,884 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1394,7 +1394,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | | usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 277 | 檢視端 USB 裝置瀏覽器。 | -| usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 770 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | +| usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | | diagnostics | `diagnostics_tab.py` | 235 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,628 | +| `gui/` | 160 | 42,636 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,188 | -| **總計** | **1,525** | **235,131** | +| **總計** | **1,525** | **235,139** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst b/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst index 67e06786e..b80b69b51 100644 --- a/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst +++ b/docs/source/Eng/doc/operations_layer/usb_passthrough_operator_guide.rst @@ -389,6 +389,9 @@ What is *not* shipped yet (WebRTC)* and the List / Open buttons run against the live WebRTC viewer's host (via ``registry.webrtc_usb_client()``); pick *Local (loopback)* for same-machine use. You can also drive it from Python. + The panel's List, Open and remote REST fetch run one at a time, with + **Stop run** in the Actions menu and a 30 s deadline, so a peer that + stops answering no longer holds the panel; a late answer is dropped. - Windows WinUSB and macOS IOKit transfer paths are written but not yet validated against real hardware. Do not use in production until the Phase 2e hardware test matrix passes. diff --git a/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst b/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst index 16ca1d5fd..85b3ad7f5 100644 --- a/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst +++ b/docs/source/Zh/doc/operations_layer/usb_passthrough_operator_guide.rst @@ -349,7 +349,8 @@ JSON action 範例:: / ``open`` / ``resume``\ )。*USB 分享* 面板有 **來源** 下拉:選 *遠端(WebRTC)* 時 List / Open 會對 live WebRTC viewer 的主機操作 (經 ``registry.webrtc_usb_client()``\ );選 *本機(loopback)* 則走同機。 - 亦可從 Python 驅動。 + 亦可從 Python 驅動。面板的 List、Open 與遠端 REST 抓取一次只跑一個, + Actions 選單有\ **停止執行**\ ,期限 30 秒,不再回應的對端不會卡住面板;遲來的回應會被丟棄。 - Windows WinUSB 與 macOS IOKit 的 transfer 路徑已寫但尚未對實體硬體 驗證。在 Phase 2e 硬體測試矩陣通過前請勿用於 production。 - Phase 2e 外部安全審查尚未簽核;feature flag 必須維持顯式 opt-in。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index fba50bf5c..ca5f11f4d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -420,3 +420,11 @@ - **Docs:** both `usb_passthrough_operator_guide.rst`, `CHANGELOG.md`. - **Files:** `gui/usb_browser_tab.py`, the tests, the docs, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-18 · 2026-11-14 · The USB passthrough panel's use requests get a Stop and a deadline · #done #gui #usb + +- **What:** the last `Progress.md` › F3 USB panel with no Stop. The passthrough panel's *Fetch shared*, *Open selected* (over the loopback or the live WebRTC `UsbChannelClient`) and the remote REST fetch shared one bare worker: no Stop, no deadline, and a request made while another was out was silently ignored, so a WebRTC peer that stopped answering held the panel. They now run as one `TabTask` (`_requests`, tagged `shared` / `open` / `remote`) with `REQUEST_DEADLINE_S = 30.0` and **Stop run** in the Actions menu, which also stops a local listing still running. Stop, the deadline and `dispose()` free the panel at once and drop the late answer; a second request says *Already running*; a timeout says so. The open work returns `(vid, pid, descriptor)` (`_probe_labelled`), so no callback holds the panel. Errors keep their two texts: the remote fetch's *Fetch failed*, the use requests' *Open failed*. +- **Tests:** `test_usb_passthrough_requests.py` (6, against a slow fake WebRTC client: Stop drops a listing still out, an open past its deadline says so, a second request is refused visibly, a finished open shows the descriptor, a failed remote fetch shows the fetch error, `dispose()` drops the answer; four fail on the old panel). USB, GUI, dispose, worker, lifecycle and Actions-menu tests: 1855 passed, 14 skipped. +- **Docs:** both `usb_passthrough_operator_guide.rst`, `CHANGELOG.md`. +- **Files:** `gui/usb_passthrough_panel.py`, the test, the docs, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 662b5ffa2..c9e40d9f8 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-18 | 2026-11-14 | The USB passthrough panel's use requests get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-17 | 2026-11-14 | The USB Browser's Fetch and Open get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-16 | 2026-11-14 | A stopped admin broadcast reports per host whether it was sent | #done #gui #admin | [2026-11-b](2026-11-b.md) | | U-20261114-15 | 2026-11-14 | Stop and closing the tab cancel an email Poll Now between mailboxes | #done #gui #triggers | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/usb_passthrough_panel.py b/je_auto_control/gui/usb_passthrough_panel.py index 2bc3c9090..07d9d1df6 100644 --- a/je_auto_control/gui/usb_passthrough_panel.py +++ b/je_auto_control/gui/usb_passthrough_panel.py @@ -12,8 +12,11 @@ The widget is a thin wrapper: every action calls the headless :class:`UsbLoopback`, :class:`UsbAcl`, and ``list_usb_devices`` — no USB -business logic lives here. Blocking calls run on a worker thread so the -GUI stays responsive. +business logic lives here. Blocking calls run off the GUI thread as +:class:`~je_auto_control.gui._tab_task.TabTask` work: the local listing, and +one use request at a time (list shared, open, remote fetch) with a deadline +and **Stop run** in the Actions menu. A stopped, timed-out or abandoned +request's answer is dropped. """ from __future__ import annotations @@ -32,7 +35,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui._tab_task import TabTask -from je_auto_control.gui._worker_thread import CallWorker as _CallWorker, WorkerHandle, start_worker +from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.gui.adaptive.responsive import ResponsiveBox from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( @@ -59,6 +62,8 @@ def _t(key: str) -> str: _DESC_REQUEST = 0x06 _DESC_VALUE = 0x0100 _DESC_LENGTH = 18 +#: How long one use request (list shared, open, remote fetch) may take before the panel gives up on it. +REQUEST_DEADLINE_S = 30.0 @@ -91,7 +96,10 @@ def __init__(self, parent: Optional[QWidget] = None, *, ) self._share = _ShareState() self.destroyed.connect(self._share.release) - self._thread: Optional[WorkerHandle] = None + # One use request at a time: list shared, open a device, fetch a remote host. + self._requests = TabTask(self) + self._requests.result.connect(self._show_outcome) + self._requests.error.connect(self._show_request_error) # Closing the loopback joins its pump thread; done off the GUI thread. self._share_op = SlowOp(self) self._host_badge = _StatusBadge() @@ -150,6 +158,7 @@ def menu_actions(self) -> list: ("usb_share_fetch_shared", self._list_shared), ("usb_share_open_selected", self._open_selected), ("usb_share_remote_fetch", self._fetch_remote), + ("task_stop", self._on_stop), ] def _build_host_section(self) -> QWidget: @@ -412,8 +421,8 @@ def _list_shared(self) -> None: client = self._use_client_or_warn() if client is None: return - self._viewer_status.setText(_t("usb_share_listing")) - self._run_async(client.list_devices, self._apply_shared, self._fail) + if self._start(client.list_devices, "shared"): + self._viewer_status.setText(_t("usb_share_listing")) def _apply_shared(self, devices: List[dict]) -> None: self._viewer_status.setText( @@ -439,14 +448,10 @@ def _open_selected(self) -> None: vid = self._cell(self._shared_table, row, 0) pid = self._cell(self._shared_table, row, 1) serial = self._cell(self._shared_table, row, 3) or None - self._viewer_status.setText( - _t("usb_share_opening").format(vid=vid, pid=pid), - ) - self._run_async( - lambda: _probe_device(client, vid, pid, serial), - functools.partial(self._opened, vid, pid), - self._fail, - ) + if self._start(functools.partial(_probe_labelled, client, vid, pid, serial), "open"): + self._viewer_status.setText( + _t("usb_share_opening").format(vid=vid, pid=pid), + ) def _opened(self, vid: str, pid: str, descriptor: bytes) -> None: self._viewer_status.setText( @@ -460,37 +465,35 @@ def _opened(self, vid: str, pid: str, descriptor: bytes) -> None: def _fetch_remote(self) -> None: url = self._remote_url.text().strip() token = self._remote_token.text().strip() - self._viewer_status.setText(_t("usb_browser_fetching")) - self._run_async( - lambda: fetch_remote_devices(base_url=url, token=token), - self._apply_shared, self._fail_remote, - ) - - def _fail_remote(self, message: str) -> None: - self._viewer_status.setText( - _t("usb_browser_fetch_failed").format(error=message), - ) - - def _fail(self, message: str) -> None: - self._viewer_status.setText( - _t("usb_share_open_failed").format(error=message), - ) - - # --- worker plumbing --------------------------------------------------- + if self._start(functools.partial(fetch_remote_devices, base_url=url, token=token), "remote"): + self._viewer_status.setText(_t("usb_browser_fetching")) + + # --- request plumbing -------------------------------------------------- + + def _start(self, work: Callable[[], Any], tag: str) -> bool: + if self._requests.start(work, tag=tag, timeout_s=REQUEST_DEADLINE_S): + return True + self._viewer_status.setText(_t("task_busy")) + return False + + def _on_stop(self) -> None: + stopped = self._requests.stop() + stopped = self._listing.stop() or stopped + if stopped: + self._viewer_status.setText(_t("task_stopped")) + + def _show_outcome(self, value: Any) -> None: + if self._requests.tag == "open": + self._opened(*value) + else: + self._apply_shared(value) - def _run_async(self, fn: Callable[[], Any], - on_done: Callable[[Any], None], - on_fail: Callable[[str], None]) -> None: - if self._thread is not None: + def _show_request_error(self, error: object) -> None: + if isinstance(error, TaskTimeout): + self._viewer_status.setText(_t("task_timed_out")) return - # start_worker runs on_done / on_fail on the GUI thread, where they may - # touch widgets, and holds them weakly: pass methods (or partials of - # them), not lambdas over this panel. - self._thread = start_worker(self, _CallWorker(fn), on_done=on_done, - on_fail=on_fail, on_thread_done=self._on_thread_done) - - def _on_thread_done(self) -> None: - self._thread = None + key = "usb_browser_fetch_failed" if self._requests.tag == "remote" else "usb_share_open_failed" + self._viewer_status.setText(_t(key).format(error=error)) # --- helpers ----------------------------------------------------------- @@ -562,6 +565,11 @@ def _default_remote_client() -> Optional[Any]: return registry.webrtc_usb_client() +def _probe_labelled(client: Any, vid: str, pid: str, serial: Optional[str]) -> tuple: + """Probe the device; return ``(vid, pid, descriptor)`` for the status line.""" + return vid, pid, _probe_device(client, vid, pid, serial) + + def _probe_device(client: Any, vid: str, pid: str, serial: Optional[str]) -> bytes: """Open the device, read its descriptor as a liveness proof, close. diff --git a/test/unit_test/headless/test_usb_passthrough_requests.py b/test/unit_test/headless/test_usb_passthrough_requests.py new file mode 100644 index 000000000..9a562267e --- /dev/null +++ b/test/unit_test/headless/test_usb_passthrough_requests.py @@ -0,0 +1,135 @@ +"""The USB passthrough panel's use requests: a Stop, a deadline, and no late answer. + +List shared, Open and the remote REST fetch ran on one bare worker: no Stop, +no deadline, and a request made while another was out was silently ignored. A +WebRTC peer that stopped answering held the panel until its own timeout. They +now run as one :class:`~je_auto_control.gui._tab_task.TabTask`. +""" +import os +import threading + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +panel_mod = pytest.importorskip("je_auto_control.gui.usb_passthrough_panel", + reason="gui stack (webrtc extra) not importable") + +from PySide6.QtWidgets import QApplication # noqa: E402 + +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 +from je_auto_control.utils.usb.passthrough import UsbAcl # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) +_DEVICE = {"vendor_id": "1050", "product_id": "0407", "product": "Key", "serial": "S1"} + + +def _t(key): + return language_wrapper.translate(key, key) + + +class _Handle: + def control_transfer(self, **_kwargs): + return b"\x12\x01\x00\x02" + + def close(self): + pass + + +class _SlowClient: + """A remote USB client that answers once ``release`` is set.""" + + def __init__(self): + self.release, self.asked = threading.Event(), threading.Event() + + def list_devices(self): + self.asked.set() + self.release.wait(30.0) + return [_DEVICE] + + def open(self, **_kwargs): + self.asked.set() + self.release.wait(30.0) + return _Handle() + + +@pytest.fixture +def remote(tmp_path): + client = _SlowClient() + panel = panel_mod.UsbPassthroughPanel(acl=UsbAcl(path=tmp_path / "acl.json"), + remote_client_provider=lambda: client) + panel._source_combo.setCurrentIndex(1) # Remote (WebRTC) + yield panel, client + client.release.set() + panel.deleteLater() + + +def _menu(panel, key): + return dict(panel.menu_actions())[key] + + +def test_stop_drops_a_listing_still_out(remote): + panel, client = remote + _menu(panel, "usb_share_fetch_shared")() + assert client.asked.wait(10.0) + _menu(panel, "task_stop")() + assert panel._viewer_status.text() == _t("task_stopped") + assert not panel._requests.running + client.release.set() + assert pump_until(lambda: panel._shared_table.rowCount() != 0, timeout=0.5) is False + assert panel._viewer_status.text() == _t("task_stopped") + + +def test_an_open_past_its_deadline_says_so(remote, monkeypatch): + panel, client = remote + monkeypatch.setattr(panel_mod, "REQUEST_DEADLINE_S", 0.05) + client.release.set() + _menu(panel, "usb_share_fetch_shared")() + assert pump_until(lambda: panel._shared_table.rowCount() == 1) + client.release.clear() + panel._shared_table.selectRow(0) + _menu(panel, "usb_share_open_selected")() + assert pump_until(lambda: panel._viewer_status.text() == _t("task_timed_out")) + + +def test_a_second_request_while_one_is_out_is_refused_visibly(remote): + panel, client = remote + _menu(panel, "usb_share_fetch_shared")() + assert client.asked.wait(10.0) + _menu(panel, "usb_share_remote_fetch")() + assert panel._viewer_status.text() == _t("task_busy") + + +def test_a_finished_open_shows_the_descriptor(remote): + panel, client = remote + client.release.set() + _menu(panel, "usb_share_fetch_shared")() + assert pump_until(lambda: panel._shared_table.rowCount() == 1) + panel._shared_table.selectRow(0) + _menu(panel, "usb_share_open_selected")() + assert pump_until(lambda: panel._viewer_status.text().startswith( + _t("usb_share_opened").split("{", 1)[0])) + assert "1050" in panel._viewer_status.text() + + +def test_a_failed_remote_fetch_shows_the_fetch_error(remote, monkeypatch): + panel, _client = remote + + def fetch(**_kwargs): + raise ValueError("unexpected response shape") + + monkeypatch.setattr(panel_mod, "fetch_remote_devices", fetch) + _menu(panel, "usb_share_remote_fetch")() + assert pump_until(lambda: panel._viewer_status.text() == _t("usb_browser_fetch_failed").format( + error="unexpected response shape")) + + +def test_disposing_the_panel_drops_the_answer(remote): + panel, client = remote + _menu(panel, "usb_share_fetch_shared")() + assert client.asked.wait(10.0) + panel.dispose() + assert not panel._requests.running + client.release.set() + assert pump_until(lambda: panel._shared_table.rowCount() != 0, timeout=0.5) is False From 4d830833f6cf6eb0a27382424158b8d9b4b286ba Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 13:35:15 +0800 Subject: [PATCH 085/161] Run Computer Use on the shared task without freeing it mid-step A plain TabTask Stop frees the tab at once, but a Computer Use run still finishing its step drives the mouse. start_until_stopped hands the work a stop event and stays running until the work returns, so a second run cannot start beside the first. --- CHANGELOG.md | 5 + Progress.md | 5 +- architecture_explore.md | 8 +- docs/updates/2026-11-b.md | 7 ++ docs/updates/README.md | 1 + je_auto_control/gui/_tab_task.py | 41 ++++++- je_auto_control/gui/computer_use_tab.py | 65 ++++------- .../headless/test_gui_panel_dispose.py | 2 +- .../headless/test_gui_worker_owner_death.py | 5 +- .../headless/test_tab_task_until_stopped.py | 108 ++++++++++++++++++ 10 files changed, 193 insertions(+), 54 deletions(-) create mode 100644 test/unit_test/headless/test_tab_task_until_stopped.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a93e4a98..9955c6666 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI internals: `TabTask.start_until_stopped(work)` runs `work(stop_event)`; Stop sets the + event and the task stays running until the work returns, with its outcome. The Computer Use + tab runs on it (`_thread`, `_stop_event` and `_ComputerUseWorker` are gone; `_run` is the + task), and a failure of any type now reaches its status line as `Type: message`. + - GUI: the USB passthrough panel's List shared, Open and remote REST fetch run as one cancellable task with a 30 s deadline (`REQUEST_DEADLINE_S`) and **Stop run** in the Actions menu, which also stops a local listing; a late answer is dropped and a second request says diff --git a/Progress.md b/Progress.md index 012e9fd9a..668abfd79 100644 --- a/Progress.md +++ b/Progress.md @@ -541,8 +541,9 @@ F 還缺: AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 - USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)已遷移。仍直接使用 `start_worker` 的面板分兩類: - - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`computer_use_tab`、`config_sync_tab`、 + USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, + `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)已遷移。仍直接使用 `start_worker` 的面板分兩類: + - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`config_sync_tab`、 `dag_tab`、`healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - 沒有 Stop/期限:`admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, diff --git a/architecture_explore.md b/architecture_explore.md index 4e181f549..976881327 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,884 | +| 程式碼總行數 | 235,900 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1363,7 +1363,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | | llm_planner | `llm_planner_tab.py` | 196 | 自然語言描述 → 預覽 → 執行。 | -| computer_use | `computer_use_tab.py` | 185 | 從 GUI 啟動 Anthropic 閉環 agent。 | +| computer_use | `computer_use_tab.py` | 164 | 從 GUI 啟動 Anthropic 閉環 agent。 | | agent_tasks | `agent_tasks_tab.py` | 618 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | | scheduler | `scheduler_tab.py` | 174 | 註冊間隔式 action JSON 執行。 | | hotkeys | `hotkeys_tab.py` | 166 | 將全域熱鍵綁到 action 檔。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,636 | +| `gui/` | 160 | 42,652 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,188 | -| **總計** | **1,525** | **235,139** | +| **總計** | **1,525** | **235,155** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index ca5f11f4d..805c5e1c8 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -428,3 +428,10 @@ - **Docs:** both `usb_passthrough_operator_guide.rst`, `CHANGELOG.md`. - **Files:** `gui/usb_passthrough_panel.py`, the test, the docs, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-19 · 2026-11-14 · Computer Use runs on the shared task and stays busy until a stopped run ends · #done #gui #agent + +- **What:** the first of the `Progress.md` › F3 panels that already cancelled on their own. Plain `TabTask` work cannot carry these: its Stop frees the tab at once, and a Computer Use run still finishing its step drives the mouse, so a second Run could start a second agent beside it. `TabTask.start_until_stopped(work)` hands `work` a `threading.Event` instead; `stop()` sets it, `stopping` reports it, and the task stays running until `work` returns, whose outcome then arrives as usual. Handle cancellation (the tab destroyed, the application exiting) sets the event too. It takes no deadline: the work's own limits bound it. The Computer Use tab now runs `run_computer_use` through it (`_run`); `_ComputerUseWorker`, `_thread` and `_stop_event` are gone. Run while a stopped run unwinds still says *already running*; a failure of any type, not only `AgentBackendError` / `ValueError` / `RuntimeError`, reaches the status line as `Type: message`. +- **Tests:** `test_tab_task_until_stopped.py` (4: Stop sets the event and the task stays busy, refusing a second start, until the work returns its result; destroying the owner sets the event; the tab's Stop, a refused Run while unwinding and the outcome shown afterwards; an error named by type). The two `TabTask` tests fail on the old code; the two tab tests guard behaviour the old tab already had. `test_gui_panel_dispose.py` and `test_gui_worker_owner_death.py` follow the rename. Computer use, task, worker, dispose, lifecycle and Actions-menu tests: 628 passed, 8 skipped. +- **Files:** `gui/_tab_task.py`, `gui/computer_use_tab.py`, the tests, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index c9e40d9f8..a32f151af 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-19 | 2026-11-14 | Computer Use runs on the shared task and stays busy until a stopped run ends | #done #gui #agent | [2026-11-b](2026-11-b.md) | | U-20261114-18 | 2026-11-14 | The USB passthrough panel's use requests get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-17 | 2026-11-14 | The USB Browser's Fetch and Open get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-16 | 2026-11-14 | A stopped admin broadcast reports per host whether it was sent | #done #gui #admin | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_tab_task.py b/je_auto_control/gui/_tab_task.py index a43252336..6241a7639 100644 --- a/je_auto_control/gui/_tab_task.py +++ b/je_auto_control/gui/_tab_task.py @@ -16,6 +16,10 @@ it never waits for the worker, so a script that drives this GUI cannot deadlock it -- and the run's end arrives as an ``ExecutionStopped`` error once the worker has really unwound, which is when the tab is free again. + Work started with :meth:`TabTask.start_until_stopped` is handed a stop + event instead: Stop sets it and the task stays running until the work has + returned, with what it did, so the tab is not free while that work still + drives the machine. Other work binds a headless cancellation scope. Cooperative backends stop at their next checkpoint; late results from noncooperative work are dropped. @@ -24,6 +28,7 @@ work needs from the widgets first and pass plain values. """ import functools +import threading from typing import Any, Callable, Optional from PySide6.QtCore import QObject, Signal @@ -49,6 +54,7 @@ def __init__(self, owner: QObject) -> None: self.task: Optional[TaskHandle] = None self.tag = "" self._stop_token: Optional[StopToken] = None + self._stop_event: Optional[threading.Event] = None @property def running(self) -> bool: @@ -58,7 +64,11 @@ def running(self) -> bool: @property def stopping(self) -> bool: """Whether the running script was asked to stop and is still unwinding.""" - return self.task is not None and self._stop_token is not None and self._stop_token.stopped + if self.task is None: + return False + if self._stop_event is not None: + return self._stop_event.is_set() + return self._stop_token is not None and self._stop_token.stopped def start(self, work: Callable[[], Any], *, tag: str = "", timeout_s: Optional[float] = None, discard: Optional[Callable[[Any], object]] = None) -> bool: @@ -76,8 +86,24 @@ def start_script(self, work: Callable[[], Any], *, tag: str = "") -> bool: self._submit(functools.partial(_call_stoppable, self._stop_token, work), tag, None, None) return True + def start_until_stopped(self, work: Callable[[threading.Event], Any], *, tag: str = "") -> bool: + """Run ``work(stop_event)`` off the GUI thread; ``False`` when a task is already running. + + For work that ends itself at its next step once the event is set and + returns what it did, such as an agent run or a DAG. :meth:`stop` sets + the event; the task stays running until ``work`` returns and its + outcome arrives as usual. The tab being destroyed, or the application + exiting, sets the event too. There is no deadline: the work's own + limits bound it. + """ + if self.task is not None: + return False + self._stop_event = threading.Event() + self._submit(functools.partial(_call_until_stopped, self._stop_event, work), tag, None, None) + return True + def stop(self) -> bool: - """Stop the running script, or cancel other work; return whether anything was running. + """Stop the running script, set the stop event, or cancel other work; return whether anything was running. Never blocks. A script ends at its next checkpoint and reports ``ExecutionStopped`` through :attr:`error`; calling this again while @@ -88,6 +114,9 @@ def stop(self) -> bool: if self._stop_token is not None: self._stop_token.stop("stopped from the GUI") return True + if self._stop_event is not None: + self._stop_event.set() + return True return self.task.cancel() def _submit(self, work: Callable[[CancellationToken], Any], tag: str, @@ -104,6 +133,7 @@ def _submit(self, work: Callable[[CancellationToken], Any], tag: str, def _on_finished(self) -> None: self.task = None self._stop_token = None + self._stop_event = None self.finished.emit() @@ -116,6 +146,13 @@ def _call_plain(work: Callable[[], Any], token: CancellationToken) -> Any: return work() +def _call_until_stopped(stop: threading.Event, work: Callable[[threading.Event], Any], + token: CancellationToken) -> Any: + """Worker thread: hand ``work`` the stop event, which handle cancellation also sets.""" + token.on_cancel(stop.set) + return work(stop) + + def _call_stoppable(stop: StopToken, work: Callable[[], Any], token: CancellationToken) -> Any: """Worker thread: run ``work`` inside a stoppable run bound to ``stop``.""" # The tab was destroyed, or the application is exiting: stop the script too. diff --git a/je_auto_control/gui/computer_use_tab.py b/je_auto_control/gui/computer_use_tab.py index 5ffae3454..11d45d6ac 100644 --- a/je_auto_control/gui/computer_use_tab.py +++ b/je_auto_control/gui/computer_use_tab.py @@ -1,9 +1,15 @@ -"""Computer-Use tab: launch Anthropic's closed-loop agent from the GUI.""" +"""Computer-Use tab: launch Anthropic's closed-loop agent from the GUI. + +The run is a :class:`~je_auto_control.gui._tab_task.TabTask` started with +``start_until_stopped``: Stop ends it before its next step, and the tab stays +busy until it has, so a second run cannot start while the first still drives +the mouse. Closing the tab stops the run the same way and drops its outcome. +""" +import functools import json import threading from typing import Optional -from PySide6.QtCore import QObject, Signal from PySide6.QtWidgets import ( QFormLayout, QLabel, QLineEdit, QMessageBox, QSpinBox, QTextEdit, QVBoxLayout, QWidget, @@ -11,12 +17,11 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) -from je_auto_control.utils.agent.backends import AgentBackendError from je_auto_control.utils.agent.computer_use import ( result_to_dict, run_computer_use, ) @@ -26,28 +31,9 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -class _ComputerUseWorker(QObject): - """Runs ``run_computer_use`` off the Qt thread.""" - - finished = Signal(dict) - failed = Signal(str) - - def __init__(self, params: dict, stop_event: threading.Event) -> None: - super().__init__() - self._params = dict(params) - self._stop_event = stop_event - - def request_stop(self) -> None: - """End the run before its next step (thread-safe).""" - self._stop_event.set() - - def run(self) -> None: - try: - result = run_computer_use(**self._params, stop_event=self._stop_event) - except (AgentBackendError, ValueError, RuntimeError) as error: - self.failed.emit(f"{type(error).__name__}: {error}") - return - self.finished.emit(result_to_dict(result)) +def _run_agent(params: dict, stop_event: threading.Event) -> dict: + """Worker thread: run the agent until it finishes, hits a limit or ``stop_event`` is set.""" + return result_to_dict(run_computer_use(**params, stop_event=stop_event)) class ComputerUseTab(TranslatableMixin, QWidget): @@ -70,8 +56,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._output = QTextEdit() self._output.setReadOnly(True) self._status = QLabel() - self._thread: Optional[WorkerHandle] = None - self._stop_event = threading.Event() + # Stop ends the run before its next step; the tab stays busy until it has. + self._run = TabTask(self) + self._run.result.connect(self._on_worker_finished) + self._run.error.connect(self._on_worker_failed) self._build_layout() def retranslate(self) -> None: @@ -141,7 +129,7 @@ def _on_run(self) -> None: _t("computer_use_goal_required"), ) return - if self._thread is not None and self._thread.isRunning(): + if self._run.running: self._status.setText(_t("computer_use_already_running")) return params = { @@ -155,20 +143,11 @@ def _on_run(self) -> None: self._spawn_worker(params) def _spawn_worker(self, params: dict) -> None: - self._stop_event = threading.Event() - self._thread = start_worker( - self, _ComputerUseWorker(params, self._stop_event), - on_done=self._on_worker_finished, - on_fail=self._on_worker_failed, on_thread_done=self._on_thread_done) + self._run.start_until_stopped(functools.partial(_run_agent, dict(params))) def _on_stop(self) -> None: - if self._thread is None: - return - self._stop_event.set() - self._status.setText(_t("computer_use_stopping")) - - def _on_thread_done(self) -> None: - self._thread = None + if self._run.stop(): + self._status.setText(_t("computer_use_stopping")) def _on_worker_finished(self, data: dict) -> None: ok = bool(data.get("succeeded")) @@ -178,8 +157,8 @@ def _on_worker_finished(self, data: dict) -> None: json.dumps(data, indent=2, ensure_ascii=False, default=str), ) - def _on_worker_failed(self, message: str) -> None: - self._status.setText(f"{_t('computer_use_error')}: {message}") + def _on_worker_failed(self, error: object) -> None: + self._status.setText(f"{_t('computer_use_error')}: {type(error).__name__}: {error}") __all__ = ["ComputerUseTab"] diff --git a/test/unit_test/headless/test_gui_panel_dispose.py b/test/unit_test/headless/test_gui_panel_dispose.py index dd332fc9b..71a07ba6d 100644 --- a/test/unit_test/headless/test_gui_panel_dispose.py +++ b/test/unit_test/headless/test_gui_panel_dispose.py @@ -275,7 +275,7 @@ def run(stop_event=None, **_params): before = tab._status.text() tab.dispose() assert seen[0].is_set() - assert pump_until(lambda: tab._thread is None) # the thread's end is still booked + assert pump_until(lambda: not tab._run.running) # the run's end is still booked assert tab._status.text() == before assert tab._output.toPlainText() == "" tab.dispose() diff --git a/test/unit_test/headless/test_gui_worker_owner_death.py b/test/unit_test/headless/test_gui_worker_owner_death.py index dc29e613e..ff382372a 100644 --- a/test/unit_test/headless/test_gui_worker_owner_death.py +++ b/test/unit_test/headless/test_gui_worker_owner_death.py @@ -101,7 +101,7 @@ def test_the_tabs_run_their_job_and_clear_the_guard(monkeypatch, which): monkeypatch.setattr(mod, "result_to_dict", lambda result: {"succeeded": True}) tab = mod.ComputerUseTab() tab._spawn_worker({"goal": "g"}) # noqa: SLF001 - guard = "_thread" + guard = "task" elif which == "dag": from je_auto_control.gui import dag_tab as mod @@ -120,7 +120,8 @@ def failing_run(definition, max_parallel, stop_event=None): tab._description.setPlainText("do it") # noqa: SLF001 tab._on_plan() # noqa: SLF001 guard = "task" - holder = tab._plans if which == "llm_planner" else tab # noqa: SLF001 + holder = {"llm_planner": getattr(tab, "_plans", None), "computer_use": getattr(tab, "_run", None)}.get( + which, tab) # noqa: SLF001 assert getattr(holder, guard) is not None assert _pump_until(app, lambda: getattr(holder, guard) is None), "the guard never cleared" assert seen diff --git a/test/unit_test/headless/test_tab_task_until_stopped.py b/test/unit_test/headless/test_tab_task_until_stopped.py new file mode 100644 index 000000000..6f92cd47f --- /dev/null +++ b/test/unit_test/headless/test_tab_task_until_stopped.py @@ -0,0 +1,108 @@ +"""Work that stops at its next step keeps the tab busy until it has, then reports what it did. + +Computer use drives the mouse. A Stop that freed the tab at once would let a +second run start while the first was still finishing its step, so +:meth:`TabTask.start_until_stopped` hands the work a stop event instead and +stays running until the work returns. +""" +import os +import threading + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 + +from je_auto_control.gui import computer_use_tab # noqa: E402 +from je_auto_control.gui._tab_task import TabTask # noqa: E402 +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) + + +def _t(key): + return language_wrapper.translate(key, key) + + +class _Step: + """Work that waits for its stop event, then for ``finish``, and returns what it saw.""" + + def __init__(self): + self.stopped, self.finish = threading.Event(), threading.Event() + + def __call__(self, stop_event): + assert stop_event.wait(30.0) + self.stopped.set() + self.finish.wait(30.0) # the step in progress, still running after the Stop + return "stopped after one step" + + +@pytest.fixture +def owner(): + widget = QWidget() + yield widget + widget.deleteLater() + + +def test_stop_sets_the_event_and_the_task_stays_busy_until_the_work_returns(owner): + task, work, results = TabTask(owner), _Step(), [] + task.result.connect(results.append) + assert task.start_until_stopped(work) + assert task.stop() is True + assert work.stopped.wait(10.0) + assert task.running and task.stopping + assert task.start_until_stopped(_Step()) is False # no second run while the first unwinds + work.finish.set() + assert pump_until(lambda: not task.running) + assert results == ["stopped after one step"] + assert task.stopping is False + + +def test_destroying_the_owner_sets_the_event(): + import shiboken6 + owner, work = QWidget(), _Step() + assert TabTask(owner).start_until_stopped(work) + shiboken6.delete(owner) + try: + assert work.stopped.wait(10.0) + finally: + work.finish.set() + + +def test_computer_use_stop_waits_for_the_run_and_shows_its_outcome(monkeypatch): + work = _Step() + monkeypatch.setattr(computer_use_tab, "run_computer_use", lambda stop_event=None, **_params: work(stop_event)) + monkeypatch.setattr(computer_use_tab, "result_to_dict", lambda result: {"succeeded": False, "detail": result}) + tab = computer_use_tab.ComputerUseTab() + try: + tab._goal_input.setText("open the editor") + actions = dict(tab.menu_actions()) + actions["computer_use_run_btn"]() + actions["computer_use_stop_btn"]() + assert tab._status.text() == _t("computer_use_stopping") + assert work.stopped.wait(10.0) + actions["computer_use_run_btn"]() # still finishing its step + assert tab._status.text() == _t("computer_use_already_running") + work.finish.set() + assert pump_until(lambda: tab._status.text() == _t("computer_use_failure")) + assert "stopped after one step" in tab._output.toPlainText() + finally: + work.finish.set() + tab.deleteLater() + + +def test_a_computer_use_error_names_its_type(monkeypatch): + def run(stop_event=None, **_params): + raise ValueError("no API key") + + monkeypatch.setattr(computer_use_tab, "run_computer_use", run) + tab = computer_use_tab.ComputerUseTab() + try: + tab._goal_input.setText("open the editor") + dict(tab.menu_actions())["computer_use_run_btn"]() + assert pump_until(lambda: tab._status.text() == f"{_t('computer_use_error')}: ValueError: no API key") + finally: + tab.deleteLater() From fbc18c81ae81cfdefd0b89cca4fc2de077e75b47 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 13:51:05 +0800 Subject: [PATCH 086/161] Run the DAG Runner on the shared task without freeing it mid-run A DAG Stop stops scheduling and lets running nodes finish, so the tab must stay busy until run_dag returns. The worker becomes a plain callable built on the GUI thread, keeping the caller's context, and runs through start_until_stopped. --- CHANGELOG.md | 5 ++ Progress.md | 4 +- architecture_explore.md | 8 +- docs/updates/2026-11-b.md | 7 ++ docs/updates/README.md | 1 + je_auto_control/gui/dag_tab.py | 83 +++++++++---------- .../headless/test_agent_dag_background_gui.py | 2 +- .../headless/test_dag_managed_gui.py | 24 ++---- .../headless/test_gui_panel_dispose.py | 2 +- .../headless/test_gui_worker_owner_death.py | 5 +- .../headless/test_tab_task_until_stopped.py | 33 +++++++- 11 files changed, 99 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9955c6666..776674832 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI internals: the DAG Runner tab runs on `TabTask.start_until_stopped`. `_DagWorker` is no + longer a `QObject`: it is built on the GUI thread (keeping that context) and called with the + stop event, returning the result instead of emitting `finished` / `failed`. `_thread` and + `_stop_event` are gone; `_run` is the task. A failure of any type reaches the status line. + - GUI internals: `TabTask.start_until_stopped(work)` runs `work(stop_event)`; Stop sets the event and the task stays running until the work returns, with its outcome. The Computer Use tab runs on it (`_thread`, `_stop_event` and `_ComputerUseWorker` are gone; `_run` is the diff --git a/Progress.md b/Progress.md index 668abfd79..6dfb9953c 100644 --- a/Progress.md +++ b/Progress.md @@ -542,9 +542,9 @@ F 還缺: Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, - `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)已遷移。仍直接使用 `start_worker` 的面板分兩類: + `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)已遷移。仍直接使用 `start_worker` 的面板分兩類: - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`config_sync_tab`、 - `dag_tab`、`healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 + `healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - 沒有 Stop/期限:`admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, diff --git a/architecture_explore.md b/architecture_explore.md index 976881327..c49839614 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,900 | +| 程式碼總行數 | 235,895 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1383,7 +1383,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | window_manager | `window_tab.py` | 139 | 列出、聚焦、關閉視窗。 | | plugins | `plugins_tab.py` | 85 | 從使用者目錄載入額外 `AC_` 指令。 | | webrunner | `webrunner_tab.py` | 203 | 從 GUI 驅動 `je_web_runner`。 | -| dag_runner | `dag_tab.py` | 371 | 編輯、驗證、執行跨主機 DAG。 | +| dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | | remote_desktop | `remote_desktop/`(40 檔) | 8,368 | 見下。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,652 | +| `gui/` | 160 | 42,647 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,188 | -| **總計** | **1,525** | **235,155** | +| **總計** | **1,525** | **235,150** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 805c5e1c8..2ef541a56 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -435,3 +435,10 @@ - **Tests:** `test_tab_task_until_stopped.py` (4: Stop sets the event and the task stays busy, refusing a second start, until the work returns its result; destroying the owner sets the event; the tab's Stop, a refused Run while unwinding and the outcome shown afterwards; an error named by type). The two `TabTask` tests fail on the old code; the two tab tests guard behaviour the old tab already had. `test_gui_panel_dispose.py` and `test_gui_worker_owner_death.py` follow the rename. Computer use, task, worker, dispose, lifecycle and Actions-menu tests: 628 passed, 8 skipped. - **Files:** `gui/_tab_task.py`, `gui/computer_use_tab.py`, the tests, `CHANGELOG.md`, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-20 · 2026-11-14 · The DAG Runner runs on the shared task and stays busy until a stopped run ends · #done #gui #dag + +- **What:** the second `Progress.md` › F3 panel that already cancelled on its own, onto `TabTask.start_until_stopped` (U-20261114-19). A DAG Stop stops scheduling, asks managed nodes to pause and lets running nodes finish, so the tab must stay busy until `run_dag` returns. `_DagWorker` is now a plain callable: built on the GUI thread, where it captures the context (so a run carries the caller's authorization, not an ambient one at call time), and called on the worker thread with the task's stop event. The tab tags each request `run` / `inspect` / `batch` and routes the outcome by tag, as the three `on_done` slots did. `_thread` and `_stop_event` are gone; `_run` is the task. A failure of any type, not only `AutoControlException` / `RuntimeError`, reaches the status line as `Type: message`. +- **Tests:** `test_tab_task_until_stopped.py` gains the DAG tab case (Stop shows *stopping*, Run while unwinding says *already running*, the run's outcome is shown afterwards). `test_dag_managed_gui.py`'s two worker tests call the worker instead of connecting `finished`; `test_gui_panel_dispose.py`, `test_agent_dag_background_gui.py` and `test_gui_worker_owner_death.py` follow the rename. DAG, task, worker, dispose and Actions-menu tests: 448 passed, 8 skipped. +- **Files:** `gui/dag_tab.py`, the tests, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index a32f151af..7950312b7 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-20 | 2026-11-14 | The DAG Runner runs on the shared task and stays busy until a stopped run ends | #done #gui #dag | [2026-11-b](2026-11-b.md) | | U-20261114-19 | 2026-11-14 | Computer Use runs on the shared task and stays busy until a stopped run ends | #done #gui #agent | [2026-11-b](2026-11-b.md) | | U-20261114-18 | 2026-11-14 | The USB passthrough panel's use requests get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | | U-20261114-17 | 2026-11-14 | The USB Browser's Fetch and Open get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/dag_tab.py b/je_auto_control/gui/dag_tab.py index 0e72bd8dd..b89c0bfd9 100644 --- a/je_auto_control/gui/dag_tab.py +++ b/je_auto_control/gui/dag_tab.py @@ -1,11 +1,17 @@ -"""DAG Runner tab: edit, validate, and execute cross-host DAGs.""" +"""DAG Runner tab: edit, validate, and execute cross-host DAGs. + +Requests run as a :class:`~je_auto_control.gui._tab_task.TabTask` started with +``start_until_stopped``: Stop stops scheduling (managed nodes are asked to +pause, running nodes finish), and the tab stays busy until the run has ended +and shows what it did. Closing the tab stops it the same way. +""" import json import threading from functools import partial from contextvars import copy_context -from typing import Any, Callable, Optional +from typing import Any, Optional -from PySide6.QtCore import QObject, Qt, Signal +from PySide6.QtCore import Qt from PySide6.QtWidgets import ( QFileDialog, QLabel, QSpinBox, QPlainTextEdit, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout, QWidget, @@ -15,7 +21,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.responsive import ResponsiveBox, fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role @@ -27,7 +33,6 @@ ) from je_auto_control.utils.agent_runtime.api import inspect_agent_dag, manage_agent_dag from je_auto_control.utils.dag.managed_tasks import managed_stop_scope -from je_auto_control.utils.exception.exceptions import AutoControlException _COLUMNS = ("id", "host", "status", "task_id", "duration_ms", "error") @@ -37,31 +42,22 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -class _DagWorker(QObject): - finished = Signal(object) - failed = Signal(str) +class _DagWorker: + """One DAG request: built on the GUI thread, whose context it keeps, and called on the worker thread.""" def __init__(self, definition: dict, max_parallel: int, - stop_event: threading.Event, *, inspect_only: bool = False, + stop_event: Optional[threading.Event] = None, *, inspect_only: bool = False, batch_id: str = "", batch_operation: str | dict = "") -> None: - super().__init__() self._definition = definition self._max_parallel = max_parallel - self._stop_event = stop_event + self._stop_event = stop_event if stop_event is not None else threading.Event() self._context = copy_context() self._mode = (inspect_only, batch_id, batch_operation) - def request_stop(self) -> None: - """Stop scheduling; managed nodes request owned pause, other running nodes finish.""" - self._stop_event.set() - - def run(self) -> None: - try: - result = self._context.run(self._execute) - except (AutoControlException, RuntimeError) as error: - self.failed.emit(f"{type(error).__name__}: {error}") - return - self.finished.emit(result) + def __call__(self, stop_event: threading.Event) -> DagRunResult | dict: + """Run the request; setting ``stop_event`` stops scheduling, and managed nodes are asked to pause.""" + self._stop_event = stop_event + return self._context.run(self._execute) def _execute(self) -> DagRunResult | dict: inspect_only, batch_id, batch_operation = self._mode @@ -116,8 +112,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._max_parallel.setValue(4) self._status_label = QLabel() self._table = QTableWidget(0, len(_COLUMNS)) - self._thread: Optional[WorkerHandle] = None - self._stop_event = threading.Event() + self._run = TabTask(self) + self._run.result.connect(self._show_outcome) + self._run.error.connect(self._on_worker_failed) self._inspection_source = "" self._inspection_output = QPlainTextEdit() self._inspection_output.setReadOnly(True) @@ -237,7 +234,7 @@ def _request_run(self, *, inspect_only: bool, batch_operation: str = "") -> None definition = {} if batch_operation in {"get", "pause_batch"} else self._parse_editor() if definition is None: return - if self._thread is not None and self._thread.isRunning(): + if self._run.running: self._status_label.setText(_t("dag_already_running")) return if batch_operation in {"run_continuation", "continue_background"} and not self._continuation_current(): @@ -247,7 +244,6 @@ def _request_run(self, *, inspect_only: bool, batch_operation: str = "") -> None self._spawn_worker(definition, inspect_only=inspect_only, batch_operation=batch_operation) def _spawn_worker(self, definition: dict, *, inspect_only: bool = False, batch_operation: str = "") -> None: - self._stop_event = threading.Event() operation: str | dict = batch_operation if batch_operation in {"review_continuation", "run_continuation", "continue_background"}: try: @@ -261,30 +257,29 @@ def _spawn_worker(self, definition: dict, *, inspect_only: bool = False, batch_o payload = {} operation = {"operation": batch_operation, "request": payload} worker = _DagWorker(definition, int(self._max_parallel.value()), - self._stop_event, inspect_only=inspect_only, + inspect_only=inspect_only, batch_id=self._batch_id.text(), batch_operation=operation) self._inspection_source = self._editor.toPlainText() self.setProperty("dag_batch_source", self._batch_id.text()) self._inspection_output.clear() - on_done: Callable[[Any], None] if batch_operation and batch_operation != "run_continuation": - on_done = self._on_batch_finished - elif inspect_only: - on_done = self._on_inspection_finished + tag = "batch" else: - on_done = self._on_worker_finished - self._thread = start_worker( - self, worker, on_done=on_done, - on_fail=self._on_worker_failed, on_thread_done=self._on_thread_done) + tag = "inspect" if inspect_only else "run" + self._run.start_until_stopped(worker, tag=tag) def _on_stop(self) -> None: - if self._thread is None: - return - self._stop_event.set() - self._status_label.setText(_t("dag_stopping")) - - def _on_thread_done(self) -> None: - self._thread = None + if self._run.stop(): + self._status_label.setText(_t("dag_stopping")) + + def _show_outcome(self, result: Any) -> None: + tag = self._run.tag + if tag == "batch": + self._on_batch_finished(result) + elif tag == "inspect": + self._on_inspection_finished(result) + else: + self._on_worker_finished(result) def _parse_editor(self) -> Optional[dict]: raw = self._editor.toPlainText().strip() @@ -344,8 +339,8 @@ def _on_worker_finished(self, result: DagRunResult) -> None: ) self._populate_table(result) - def _on_worker_failed(self, message: str) -> None: - self._status_label.setText(f"{_t('dag_error')}: {message}") + def _on_worker_failed(self, error: object) -> None: + self._status_label.setText(f"{_t('dag_error')}: {type(error).__name__}: {error}") def _populate_table(self, result: DagRunResult) -> None: nodes = list(result.nodes.values()) diff --git a/test/unit_test/headless/test_agent_dag_background_gui.py b/test/unit_test/headless/test_agent_dag_background_gui.py index 36a869410..014f5a979 100644 --- a/test/unit_test/headless/test_agent_dag_background_gui.py +++ b/test/unit_test/headless/test_agent_dag_background_gui.py @@ -51,7 +51,7 @@ def delayed(worker): def accepted_and_view_worker_finished(): app.processEvents() accepted = read(instance, batch)["background"] is not None - return accepted and (tab._thread is None or not tab._thread.isRunning()) + return accepted and not tab._run.running until(accepted_and_view_worker_finished) tab.close() diff --git a/test/unit_test/headless/test_dag_managed_gui.py b/test/unit_test/headless/test_dag_managed_gui.py index 0f1ab0ee9..692a1fed9 100644 --- a/test/unit_test/headless/test_dag_managed_gui.py +++ b/test/unit_test/headless/test_dag_managed_gui.py @@ -38,39 +38,27 @@ def test_dag_gui_worker_does_not_borrow_ambient_admin_authority(monkeypatch): from je_auto_control.gui.dag_tab import _DagWorker from je_auto_control.utils.admin import admin_client - app = QApplication.instance() or QApplication([]) monkeypatch.setattr(admin_client, "default_admin_console", lambda: pytest.fail("GUI borrowed host credentials")) with authorization_scope(AuthorizationContext("caller", "operator")): - worker = _DagWorker(definition(host="remote"), 1, threading.Event()) - outcomes = [] - worker.finished.connect(outcomes.append) + worker = _DagWorker(definition(host="remote"), 1) admin = AuthorizationContext("ambient", "admin") with authorization_scope(admin): - worker.run() + outcome = worker(threading.Event()) # runs in the context captured at construction assert current_authorization() is admin - assert len(outcomes) == 1 - assert not outcomes[0].succeeded - assert "manage_hosts" in outcomes[0].nodes["one"].error - worker.deleteLater() - app.processEvents() + assert not outcome.succeeded + assert "manage_hosts" in outcome.nodes["one"].error def test_dag_inspection_worker_calls_only_inspection(monkeypatch): from je_auto_control.gui import dag_tab - app = QApplication.instance() or QApplication([]) calls = [] monkeypatch.setattr(dag_tab, "run_dag", lambda *_args, **_kwargs: pytest.fail("inspection submitted tasks")) monkeypatch.setattr(dag_tab, "inspect_agent_dag", lambda graph: calls.append(graph) or {"inspection_only": True}) graph = definition() - worker = dag_tab._DagWorker(graph, 1, threading.Event(), inspect_only=True) - results = [] - worker.finished.connect(results.append) - worker.run() + worker = dag_tab._DagWorker(graph, 1, inspect_only=True) + assert worker(threading.Event()) == {"inspection_only": True} assert calls == [graph] - assert results == [{"inspection_only": True}] - worker.deleteLater() - app.processEvents() @pytest.mark.parametrize("changed", [False, True]) diff --git a/test/unit_test/headless/test_gui_panel_dispose.py b/test/unit_test/headless/test_gui_panel_dispose.py index 71a07ba6d..700de9e0e 100644 --- a/test/unit_test/headless/test_gui_panel_dispose.py +++ b/test/unit_test/headless/test_gui_panel_dispose.py @@ -295,7 +295,7 @@ def run(_definition, max_parallel=1, stop_event=None): assert pump_until(lambda: bool(seen)) tab.dispose() assert seen[0].is_set() - assert pump_until(lambda: tab._thread is None) + assert pump_until(lambda: not tab._run.running) assert tab._table.rowCount() == 0 diff --git a/test/unit_test/headless/test_gui_worker_owner_death.py b/test/unit_test/headless/test_gui_worker_owner_death.py index ff382372a..78dfa2960 100644 --- a/test/unit_test/headless/test_gui_worker_owner_death.py +++ b/test/unit_test/headless/test_gui_worker_owner_death.py @@ -112,7 +112,7 @@ def failing_run(definition, max_parallel, stop_event=None): monkeypatch.setattr(mod, "run_dag", failing_run) tab = mod.DagTab() tab._spawn_worker({"nodes": []}) # noqa: SLF001 - guard = "_thread" + guard = "task" else: from je_auto_control.gui import llm_planner_tab as mod monkeypatch.setattr(mod, "plan_actions", lambda *a, **kw: seen.append("plan") or [["AC_x", {}]]) @@ -120,7 +120,8 @@ def failing_run(definition, max_parallel, stop_event=None): tab._description.setPlainText("do it") # noqa: SLF001 tab._on_plan() # noqa: SLF001 guard = "task" - holder = {"llm_planner": getattr(tab, "_plans", None), "computer_use": getattr(tab, "_run", None)}.get( + holder = {"llm_planner": getattr(tab, "_plans", None), "computer_use": getattr(tab, "_run", None), + "dag": getattr(tab, "_run", None)}.get( which, tab) # noqa: SLF001 assert getattr(holder, guard) is not None assert _pump_until(app, lambda: getattr(holder, guard) is None), "the guard never cleared" diff --git a/test/unit_test/headless/test_tab_task_until_stopped.py b/test/unit_test/headless/test_tab_task_until_stopped.py index 6f92cd47f..dbb8249cc 100644 --- a/test/unit_test/headless/test_tab_task_until_stopped.py +++ b/test/unit_test/headless/test_tab_task_until_stopped.py @@ -1,7 +1,8 @@ """Work that stops at its next step keeps the tab busy until it has, then reports what it did. -Computer use drives the mouse. A Stop that freed the tab at once would let a -second run start while the first was still finishing its step, so +Computer use drives the mouse, and a DAG run keeps scheduling until it +notices. A Stop that freed the tab at once would let a second run start while +the first was still finishing its step, so :meth:`TabTask.start_until_stopped` hands the work a stop event instead and stays running until the work returns. """ @@ -15,7 +16,7 @@ from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 -from je_auto_control.gui import computer_use_tab # noqa: E402 +from je_auto_control.gui import computer_use_tab, dag_tab # noqa: E402 from je_auto_control.gui._tab_task import TabTask # noqa: E402 from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 from headless._qt_settle import pump_until # noqa: E402 @@ -106,3 +107,29 @@ def run(stop_event=None, **_params): assert pump_until(lambda: tab._status.text() == f"{_t('computer_use_error')}: ValueError: no API key") finally: tab.deleteLater() + + +def test_a_dag_stop_waits_for_the_run_and_shows_what_it_did(monkeypatch): + import types + work = _Step() + + def run(_definition, max_parallel=1, stop_event=None): + work(stop_event) + return types.SimpleNamespace(succeeded=False, elapsed_s=0.5, nodes={}) + + monkeypatch.setattr(dag_tab, "run_dag", run) + tab = dag_tab.DagTab() + try: + tab._editor.setPlainText('{"nodes": []}') + actions = dict(tab.menu_actions()) + actions["dag_run_btn"]() + tab._on_stop() + assert tab._status_label.text() == _t("dag_stopping") + assert work.stopped.wait(10.0) + actions["dag_run_btn"]() # the run is still unwinding + assert tab._status_label.text() == _t("dag_already_running") + work.finish.set() + assert pump_until(lambda: tab._status_label.text() == _t("dag_failure").replace("{seconds}", "0.50")) + finally: + work.finish.set() + tab.deleteLater() From 8549f33e555c6a4253db0519dfdf84af876fb199 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 13:59:01 +0800 Subject: [PATCH 087/161] Let the admin console's poll and thumbnails stop at the hosts not reached Both probed every host, three seconds each, on bare workers: closing the tab only dropped the answer after every host had been tried. They now observe the caller's cancellation scope, and the tab runs them as tasks with Stop polling and a deadline. --- CHANGELOG.md | 7 + Progress.md | 9 +- architecture_explore.md | 16 +-- .../operations_layer/operations_layer_doc.rst | 9 +- .../operations_layer/operations_layer_doc.rst | 7 +- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/admin_console_tab.py | 98 +++++-------- .../gui/language_wrapper/english.py | 1 + .../gui/language_wrapper/japanese.py | 1 + .../language_wrapper/simplified_chinese.py | 1 + .../language_wrapper/traditional_chinese.py | 1 + je_auto_control/utils/admin/admin_client.py | 29 +++- .../headless/test_admin_broadcast_stop.py | 3 +- .../test_admin_console_thumbnails_gui.py | 16 +-- .../headless/test_admin_poll_cancel.py | 134 ++++++++++++++++++ .../headless/test_gui_worker_threads.py | 4 +- 17 files changed, 248 insertions(+), 97 deletions(-) create mode 100644 test/unit_test/headless/test_admin_poll_cancel.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 776674832..e4ebfec89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- `AdminConsoleClient.poll_all` and `fetch_thumbnails` observe a bound cancellation scope: once + cancelled, hosts not reached yet are skipped and `CancelledError` is raised after the requests + already out return. Unscoped calls (`AC_admin_poll`, scripts) are unchanged. GUI: the Admin + Console tab's health poll and thumbnail round are cancellable tasks with a 60 s deadline + (`POLL_DEADLINE_S`) and **Stop polling** in the Actions menu; `_PollWorker`, + `_ThumbnailWorker`, `_poll_thread` and `_thumb_thread` are gone (`_polls`, `_thumbs`). + - GUI internals: the DAG Runner tab runs on `TabTask.start_until_stopped`. `_DagWorker` is no longer a `QObject`: it is built on the GUI thread (keeping that context) and called with the stop event, returning the result instead of emitting `finished` / `failed`. `_thread` and diff --git a/Progress.md b/Progress.md index 6dfb9953c..3f87d25fc 100644 --- a/Progress.md +++ b/Progress.md @@ -542,10 +542,11 @@ F 還缺: Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, - `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)已遷移。仍直接使用 `start_worker` 的面板分兩類: - - 已有自己的取消(stop event 或 Cancel 動作),只差改用共用 controller:`config_sync_tab`、 - `healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - - 沒有 Stop/期限:`admin_console_tab` 的健康輪詢與縮圖(每台 3 秒 HTTP 期限,結果在分頁關閉後丟棄)。 + `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)、 + Admin Console 的健康輪詢與縮圖(U-20261114-21)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 + (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`、 + `healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 + 它們的 worker 以 Qt signal 回報進度,`TabTask` 尚無進度通道,遷移前須先補上。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index c49839614..afb0d2201 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,895 | +| 程式碼總行數 | 235,888 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,11 +537,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,043 行。 +> 6 個套件、約 32,062 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `utils/admin/` | 452 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | +| `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | | `utils/remote_desktop/` | 16,736 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | @@ -1336,7 +1336,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,515 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,519 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1389,7 +1389,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | remote_desktop | `remote_desktop/`(40 檔) | 8,368 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | -| admin_console | `admin_console_tab.py` | 360 | 管理多個遠端 AutoControl REST 端點。 | +| admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | | usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,647 | +| `gui/` | 160 | 42,621 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1563,8 +1563,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,188 | -| **總計** | **1,525** | **235,150** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | +| **總計** | **1,525** | **235,143** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index a52fcef06..32211ed25 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -446,7 +446,10 @@ Persistence: hosts are saved to ``~/.je_auto_control/admin_hosts.json`` Health probe uses ``/sessions`` (an authenticated endpoint), so a host with the wrong token shows up as unhealthy with an ``HTTP 401`` error -rather than a misleading "reachable but useless" status. +rather than a misleading "reachable but useless" status. ``poll_all`` and +``fetch_thumbnails`` observe the caller's cancellation scope too: once it is +cancelled, the hosts not reached yet are skipped and ``CancelledError`` is +raised when the requests already out have returned. Executor commands:: @@ -456,7 +459,9 @@ Executor commands:: GUI: *Admin Console* tab — register host form, hosts table with health/latency/jobs columns, broadcast textarea. **Stop broadcast** skips the hosts not sent to yet; the results still list every host, and the line under -them reads *Sent to n of m hosts; k not sent.* +them reads *Sent to n of m hosts; k not sent.* **Stop polling** ends a health +poll or a thumbnail round still out at the hosts in flight; each has a 60 s +deadline, and closing the tab ends them the same way. Audit log hash chain diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index e0fd1e388..00af2ed81 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -391,7 +391,9 @@ Headless:: 模式 0600)。建構時自動 reload。 健康探測使用 ``/sessions``(已認證的端點),所以 token 錯誤的主機會 -顯示為 ``HTTP 401`` 不健康狀態,而非誤導性的「可達但無用」。 +顯示為 ``HTTP 401`` 不健康狀態,而非誤導性的「可達但無用」。``poll_all`` 與 +``fetch_thumbnails`` 也會遵守呼叫端的取消範圍:取消後尚未探測的主機會略過, +已送出的請求回來後丟出 ``CancelledError``。 Executor 指令:: @@ -400,7 +402,8 @@ Executor 指令:: GUI:*Admin Console* 分頁 — 註冊主機表單、含健康/延遲/任務數欄位的 主機表、廣播文字框。\ **停止廣播**\ 會略過尚未送出的主機;結果仍列出每台主機, -下方一行顯示「已送往 n/m 台主機;k 台未送出。」 +下方一行顯示「已送往 n/m 台主機;k 台未送出。」\ **停止輪詢**\ 會讓進行中的健康輪詢或縮圖更新 +停在正在處理的主機;兩者各有 60 秒期限,關閉分頁也會同樣結束它們。 稽核紀錄雜湊鏈 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 2ef541a56..cc0f37cf4 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -442,3 +442,11 @@ - **Tests:** `test_tab_task_until_stopped.py` gains the DAG tab case (Stop shows *stopping*, Run while unwinding says *already running*, the run's outcome is shown afterwards). `test_dag_managed_gui.py`'s two worker tests call the worker instead of connecting `finished`; `test_gui_panel_dispose.py`, `test_agent_dag_background_gui.py` and `test_gui_worker_owner_death.py` follow the rename. DAG, task, worker, dispose and Actions-menu tests: 448 passed, 8 skipped. - **Files:** `gui/dag_tab.py`, the tests, `CHANGELOG.md`, `Progress.md`. - **Open items:** the panels still on a bare worker, named in `Progress.md` › F3. + +## U-20261114-21 · 2026-11-14 · The admin console's poll and thumbnails stop at the hosts not reached yet · #done #gui #admin + +- **What:** the last `Progress.md` › F3 panel with no Stop. The Admin Console's health poll and its thumbnail round probe every host, `max_parallel` at a time with 3 s per request, and ran on bare workers: closing the tab only dropped the answer once every host had been tried. `poll_all` and `fetch_thumbnails` now share `_map_unless_cancelled`, which reads the caller's cancellation token in the caller's thread (the pool's threads do not see the scope), skips the hosts not reached once it is cancelled, and raises `CancelledError` after the requests already out return. Unscoped callers (`AC_admin_poll`, scripts) see no change. The tab runs both as `TabTask`s (`_polls`, `_thumbs`) with `POLL_DEADLINE_S = 60.0` and **Stop polling** in the Actions menu (a new key in all four catalogues), which cancels both. A stopped poll shows nothing; a timed-out one says so in the usual warning; a failed thumbnail round is logged and shows placeholders, as an empty answer did. A timer tick while a round is out is skipped, as before. +- **Tests:** `test_admin_poll_cancel.py` (7: unscoped poll and thumbnail rounds reach every host; a scope cancelled during the first host skips the other two for both; the tab's Stop polling ends the poll at the host in flight without a warning; closing the tab ends a thumbnail round; a poll past its deadline says so; five fail on the old code). `test_admin_console_thumbnails_gui.py` drives the tab's refresh instead of the removed worker; `test_gui_worker_threads.py` follows the rename. Admin, catalogue, worker, dispose and Actions-menu tests: 337 passed, 8 skipped. +- **Docs:** both `operations_layer_doc.rst` (multi-host admin console), `CHANGELOG.md`. +- **Files:** `utils/admin/admin_client.py`, `gui/admin_console_tab.py`, the four catalogues, the tests, the docs, `Progress.md`. +- **Open items:** the panels that cancel on their own but not through the shared controller, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 7950312b7..22639c08c 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-21 | 2026-11-14 | The admin console's poll and thumbnails stop at the hosts not reached yet | #done #gui #admin | [2026-11-b](2026-11-b.md) | | U-20261114-20 | 2026-11-14 | The DAG Runner runs on the shared task and stays busy until a stopped run ends | #done #gui #dag | [2026-11-b](2026-11-b.md) | | U-20261114-19 | 2026-11-14 | Computer Use runs on the shared task and stays busy until a stopped run ends | #done #gui #agent | [2026-11-b](2026-11-b.md) | | U-20261114-18 | 2026-11-14 | The USB passthrough panel's use requests get a Stop and a deadline | #done #gui #usb | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/admin_console_tab.py b/je_auto_control/gui/admin_console_tab.py index 47a7f4474..69a411e84 100644 --- a/je_auto_control/gui/admin_console_tab.py +++ b/je_auto_control/gui/admin_console_tab.py @@ -4,13 +4,17 @@ Stop skips the hosts not sent to yet and still shows every host's row, with ``sent`` saying whether the actions went there; closing the tab does the same skipping and drops the rows. + +The health poll and the thumbnail fetch are tasks too, with a deadline and +**Stop polling** in the Actions menu: stopping either, or closing the tab, +skips the hosts not reached yet and drops the answer. """ import functools import json import threading from typing import Dict, List, Optional -from PySide6.QtCore import QObject, QSize, QTimer, Qt, Signal +from PySide6.QtCore import QSize, QTimer, Qt from PySide6.QtGui import QIcon, QImage, QPixmap from PySide6.QtWidgets import ( QGroupBox, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QListWidget, @@ -21,60 +25,26 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui._tab_task import TabTask -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.responsive import ResponsiveBox from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) +from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.utils.admin.admin_client import ( - AdminConsoleClient, default_admin_console, + default_admin_console, ) +from je_auto_control.utils.logging.logging_instance import autocontrol_logger + +#: How long one poll or thumbnail round may take before the tab gives up on it. +POLL_DEADLINE_S = 60.0 def _t(key: str) -> str: return language_wrapper.translate(key, key) -class _PollWorker(QObject): - """Background poller — runs ``client.poll_all`` off the GUI thread.""" - - finished = Signal(list) - failed = Signal(str) - - def __init__(self, client: AdminConsoleClient, - labels: Optional[List[str]] = None) -> None: - super().__init__() - self._client = client - self._labels = labels - - def run(self) -> None: - try: - result = self._client.poll_all(labels=self._labels) - except (OSError, RuntimeError, ValueError) as error: - self.failed.emit(str(error)) - return - self.finished.emit(result) - - -class _ThumbnailWorker(QObject): - """Phase 6.5 GUI: poll fetch_thumbnails off the GUI thread.""" - - finished = Signal(dict) - - def __init__(self, client: AdminConsoleClient) -> None: - super().__init__() - self._client = client - - def run(self) -> None: - try: - result = self._client.fetch_thumbnails() - except (OSError, RuntimeError, ValueError): - result = {} - self.finished.emit(result) - - class AdminConsoleTab(TranslatableMixin, QWidget): """Thin Qt surface over :class:`AdminConsoleClient`.""" @@ -99,7 +69,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._actions_input.setPlaceholderText('[["AC_get_mouse_position"]]') self._broadcast_output = QTextEdit() self._broadcast_output.setReadOnly(True) - self._poll_thread: Optional[WorkerHandle] = None + # Closing the tab, Stop polling or the deadline skip the hosts not reached yet. + self._polls = TabTask(self) + self._polls.result.connect(self._apply_poll_result) + self._polls.error.connect(self._apply_poll_failure) self._broadcast_status = QLabel() self._broadcast_status.setWordWrap(True) set_role(self._broadcast_status, "hint") @@ -121,7 +94,9 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._thumb_interval.valueChanged.connect(self._on_thumb_interval_changed) self._thumb_timer = QTimer(self) self._thumb_timer.timeout.connect(self._refresh_thumbnails) - self._thumb_thread: Optional[WorkerHandle] = None + self._thumbs = TabTask(self) + self._thumbs.result.connect(self._apply_thumbnails) + self._thumbs.error.connect(self._on_thumbnails_failed) self._build_layout() self._refresh_table() self._apply_thumb_interval() @@ -158,6 +133,7 @@ def menu_actions(self) -> list: ("admin_add", self._on_add), ("admin_remove", self._on_remove), ("admin_refresh", self._on_refresh), + ("admin_poll_stop", self._on_poll_stop), ("admin_thumb_refresh_now", self._refresh_thumbnails), ("admin_broadcast_run", self._on_broadcast), ("admin_broadcast_stop", self._on_broadcast_stop), @@ -215,12 +191,12 @@ def _on_remove(self) -> None: self._refresh_table() def _on_refresh(self) -> None: - if self._poll_thread is not None: - return - self._poll_thread = start_worker( - self, _PollWorker(self._client), - on_done=self._apply_poll_result, on_fail=self._apply_poll_failure, - on_thread_done=self._on_poll_thread_done) + self._polls.start(self._client.poll_all, timeout_s=POLL_DEADLINE_S) + + def _on_poll_stop(self) -> None: + """Cancel the poll and the thumbnail fetch still out; the hosts not reached yet are skipped.""" + self._polls.stop() + self._thumbs.stop() def _on_broadcast(self) -> None: text = self._actions_input.toPlainText().strip() @@ -266,12 +242,10 @@ def _show_broadcast_error(self, error: object) -> None: def _apply_poll_result(self, statuses: list) -> None: self._refresh_table(statuses=statuses) - def _apply_poll_failure(self, message: str) -> None: + def _apply_poll_failure(self, error: object) -> None: + message = _t("task_timed_out") if isinstance(error, TaskTimeout) else str(error) QMessageBox.warning(self, _t("admin_refresh"), message) - def _on_poll_thread_done(self) -> None: - self._poll_thread = None - # --- live thumbnails (Phase 6.5 GUI) ------------------------------- def _on_thumb_interval_changed(self, _value: int) -> None: @@ -285,17 +259,13 @@ def _apply_thumb_interval(self) -> None: self._thumb_timer.start(seconds * 1000) def _refresh_thumbnails(self) -> None: - if self._thumb_thread is not None: - return - # start_worker releases the worker and its relay on finish, so one - # poll tick no longer leaves one of each behind. - self._thumb_thread = start_worker( - self, _ThumbnailWorker(self._client), - on_done=self._apply_thumbnails, - on_thread_done=self._on_thumb_thread_done) - - def _on_thumb_thread_done(self) -> None: - self._thumb_thread = None + # A tick while the previous fetch is still out is skipped. + self._thumbs.start(self._client.fetch_thumbnails, timeout_s=POLL_DEADLINE_S) + + def _on_thumbnails_failed(self, error: object) -> None: + # A failed round shows every host as a placeholder, as an empty answer does. + autocontrol_logger.info("admin: thumbnail round failed: %r", error) + self._apply_thumbnails({}) def _apply_thumbnails(self, png_by_label: Dict[str, Optional[bytes]]) -> None: """Paint every host as one tile; placeholder when fetch failed.""" diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index d9cdc844e..36cbf6798 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -426,6 +426,7 @@ "admin_add": "Add", "admin_remove": _REMOVE_SELECTED, "admin_refresh": "Poll all", + "admin_poll_stop": "Stop polling", "admin_label": "Label:", "admin_url": "Base URL:", "admin_token": _TOKEN_LABEL, diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index eee9a654c..ff81fa7c4 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -320,6 +320,7 @@ "admin_add": "追加", "admin_remove": _REMOVE_SEL_FW, "admin_refresh": "全件ポーリング", + "admin_poll_stop": "ポーリングを停止", "admin_label": "ラベル:", "admin_url": "ベース URL:", "admin_token": _TOKEN_LABEL, diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 3da7b163a..1e306c49c 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -291,6 +291,7 @@ "admin_add": "添加", "admin_remove": "移除所选", "admin_refresh": "全部轮询", + "admin_poll_stop": "停止轮询", "admin_label": "标签:", "admin_url": "基础 URL:", "admin_token": "令牌:", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index 7d6f47cac..c1cc1ab26 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -298,6 +298,7 @@ "admin_add": "新增", "admin_remove": "移除所選", "admin_refresh": "全部輪詢", + "admin_poll_stop": "停止輪詢", "admin_label": "標籤:", "admin_url": "基底 URL:", "admin_token": "權杖:", diff --git a/je_auto_control/utils/admin/admin_client.py b/je_auto_control/utils/admin/admin_client.py index 3488cc8ca..0c1a51eb2 100644 --- a/je_auto_control/utils/admin/admin_client.py +++ b/je_auto_control/utils/admin/admin_client.py @@ -133,11 +133,16 @@ def remove_host(self, label: str) -> bool: return removed def poll_all(self, *, labels: Optional[List[str]] = None) -> List[HostStatus]: + """Probe every host (or ``labels``), ``max_parallel`` at a time; one status per host. + + Inside a cancelled cancellation scope the hosts not probed yet are + skipped and :class:`concurrent.futures.CancelledError` is raised once + the probes already out have returned. + """ targets = self._resolve_targets(labels) if not targets: return [] - with ThreadPoolExecutor(max_workers=self._max_parallel) as pool: - return list(pool.map(self._poll_one, targets)) + return self._map_unless_cancelled(self._poll_one, targets) def fetch_thumbnails(self, *, labels: Optional[List[str]] = None, ) -> Dict[str, Optional[bytes]]: @@ -145,7 +150,9 @@ def fetch_thumbnails(self, *, labels: Optional[List[str]] = None, Returns ``label → png_bytes`` (or ``None`` on a host that errored). The Cross-host Dashboard polls this on a timer and - scales the resulting image down to a thumbnail tile. + scales the resulting image down to a thumbnail tile. A cancelled + cancellation scope skips the hosts not reached yet and raises + :class:`concurrent.futures.CancelledError`, as :meth:`poll_all` does. """ import base64 targets = self._resolve_targets(labels) @@ -170,9 +177,21 @@ def grab(host: AdminHost) -> tuple: except ValueError: # binascii.Error is one return host.label, None + return dict(self._map_unless_cancelled(grab, targets)) + + def _map_unless_cancelled(self, call: Callable[[AdminHost], Any], targets: List[AdminHost]) -> List[Any]: + """``call`` over ``targets`` in the pool; a cancelled scope skips the rest and raises ``CancelledError``.""" + # Read in the caller's thread: the pool's threads do not see its scope. + token = current_cancellation_token() + + def one(host: AdminHost) -> Any: + return None if token is not None and token.is_cancelled else call(host) + with ThreadPoolExecutor(max_workers=self._max_parallel) as pool: - results = list(pool.map(grab, targets)) - return dict(results) + results = list(pool.map(one, targets)) + if token is not None: + token.checkpoint() + return results def broadcast_execute(self, actions: List[Any], *, labels: Optional[List[str]] = None, diff --git a/test/unit_test/headless/test_admin_broadcast_stop.py b/test/unit_test/headless/test_admin_broadcast_stop.py index 1e4494b4a..f1f737c8b 100644 --- a/test/unit_test/headless/test_admin_broadcast_stop.py +++ b/test/unit_test/headless/test_admin_broadcast_stop.py @@ -20,7 +20,8 @@ def console(tmp_path): # One host at a time, so "not reached yet" is well defined. client = AdminConsoleClient(persist_path=tmp_path / "hosts.json", max_parallel=1) for label in _HOSTS: - client.add_host(label, f"http://{label}.example", "tok") # NOSONAR python:S5332 # reason: no network, _http_post is faked + # No network: the HTTP call is faked. + client.add_host(label, f"http://{label}.example", "tok") # NOSONAR python:S5332 return client diff --git a/test/unit_test/headless/test_admin_console_thumbnails_gui.py b/test/unit_test/headless/test_admin_console_thumbnails_gui.py index 7985e6150..662215e8a 100644 --- a/test/unit_test/headless/test_admin_console_thumbnails_gui.py +++ b/test/unit_test/headless/test_admin_console_thumbnails_gui.py @@ -95,20 +95,18 @@ def test_thumb_interval_zero_stops_the_timer(populated_admin_tab): assert tab._thumb_timer.interval() == 15_000 # noqa: SLF001 -def test_thumbnail_worker_pulls_through_admin_client(populated_admin_tab): - """The headless worker calls fetch_thumbnails and emits the result.""" - from je_auto_control.gui.admin_console_tab import _ThumbnailWorker - _tab, client = populated_admin_tab +def test_thumbnail_refresh_pulls_through_admin_client(populated_admin_tab): + """A refresh calls fetch_thumbnails off the GUI thread and paints its result.""" + from headless._qt_settle import pump_until + tab, client = populated_admin_tab png = _png_bytes() - captured = [] with patch.object( client.__class__, "fetch_thumbnails", return_value={"alpha": png, "beta": None}, ): - worker = _ThumbnailWorker(client) - worker.finished.connect(captured.append) - worker.run() # run synchronously — no QThread in this test - assert captured == [{"alpha": png, "beta": None}] + tab._refresh_thumbnails() # noqa: SLF001 + assert pump_until(lambda: not tab._thumbs.running) # noqa: SLF001 + assert tab._thumbnails.count() == 2 # noqa: SLF001 def test_apply_thumbnails_from_worker_result(populated_admin_tab): diff --git a/test/unit_test/headless/test_admin_poll_cancel.py b/test/unit_test/headless/test_admin_poll_cancel.py new file mode 100644 index 000000000..c65056964 --- /dev/null +++ b/test/unit_test/headless/test_admin_poll_cancel.py @@ -0,0 +1,134 @@ +"""The admin console's health poll and thumbnail fetch stop at the hosts not reached yet. + +Both probed every host, ``max_parallel`` at a time with 3 s per request, on +bare workers: closing the tab or wanting the poll to end left it to finish +every host. They now observe the caller's cancellation scope, and the tab runs +them as cancellable tasks with **Stop polling** and a deadline. +""" +import os +import threading +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.admin.admin_client import AdminConsoleClient +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope + +_HOSTS = ("alpha", "beta", "gamma") + + +@pytest.fixture +def console(tmp_path): + client = AdminConsoleClient(persist_path=tmp_path / "hosts.json", max_parallel=1) + for label in _HOSTS: + # No network: the HTTP call is faked. + client.add_host(label, f"http://{label}.example", "tok") # NOSONAR python:S5332 + return client + + +def _fake_get(console, monkeypatch, on_get=None): + asked = [] + + def get(host, path): + asked.append((host.label, path)) + if on_get is not None: + on_get(host) + return {"sessions": []} if path == "/sessions" else {"jobs": []} + + monkeypatch.setattr(console, "_http_get", get) + return asked + + +def _hosts(asked): + return sorted({label for label, _path in asked}) + + +def test_an_unscoped_poll_reaches_every_host(console, monkeypatch): + asked = _fake_get(console, monkeypatch) + statuses = console.poll_all() + assert [status.label for status in statuses] == list(_HOSTS) + assert _hosts(asked) == list(_HOSTS) + + +def test_a_poll_cancelled_during_the_first_host_skips_the_rest(console, monkeypatch): + token = CancellationToken(task_id=1) + asked = _fake_get(console, monkeypatch, on_get=lambda host: token.cancel()) + with cancellation_scope(token), pytest.raises(CancelledError): + console.poll_all() + assert _hosts(asked) == ["alpha"] + + +def test_a_thumbnail_round_cancelled_during_the_first_host_skips_the_rest(console, monkeypatch): + token = CancellationToken(task_id=2) + asked = _fake_get(console, monkeypatch, on_get=lambda host: token.cancel()) + with cancellation_scope(token), pytest.raises(CancelledError): + console.fetch_thumbnails() + assert asked == [("alpha", "/screenshot")] + + +def test_an_unscoped_thumbnail_round_reaches_every_host(console, monkeypatch): + asked = _fake_get(console, monkeypatch) + assert console.fetch_thumbnails() == {label: None for label in _HOSTS} + assert [label for label, _path in asked] == list(_HOSTS) + + +@pytest.fixture +def held_tab(console, monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + from je_auto_control.gui import admin_console_tab + + entered, release = threading.Event(), threading.Event() + + def hold(host): + entered.set() + release.wait(10.0) + + asked = _fake_get(console, monkeypatch, on_get=hold) + monkeypatch.setattr(admin_console_tab, "default_admin_console", lambda: console) + warnings = [] + monkeypatch.setattr(admin_console_tab.QMessageBox, "warning", lambda *args: warnings.append(args)) + tab = admin_console_tab.AdminConsoleTab() + tab._thumb_timer.stop() + yield tab, asked, entered, release, warnings + release.set() + tab.deleteLater() + + +def test_stop_polling_ends_the_poll_at_the_host_in_flight(held_tab): + from headless._qt_settle import pump_until + tab, asked, entered, release, warnings = held_tab + actions = dict(tab.menu_actions()) + actions["admin_refresh"]() + assert entered.wait(10.0) + actions["admin_poll_stop"]() + assert not tab._polls.running + release.set() + assert pump_until(lambda: len(_hosts(asked)) > 1, timeout=0.5) is False + assert _hosts(asked) == ["alpha"] + assert warnings == [] # a stopped poll is not a failure + + +def test_closing_the_tab_ends_the_thumbnail_round(held_tab): + from headless._qt_settle import pump_until + tab, asked, entered, release, _warnings = held_tab + tab._refresh_thumbnails() + assert entered.wait(10.0) + tab.dispose() + assert not tab._thumbs.running + release.set() + assert pump_until(lambda: len(asked) > 1, timeout=0.5) is False + assert asked == [("alpha", "/screenshot")] + + +def test_a_poll_past_its_deadline_says_so(held_tab, monkeypatch): + from headless._qt_settle import pump_until + from je_auto_control.gui import admin_console_tab + from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper + tab, _asked, _entered, _release, warnings = held_tab + monkeypatch.setattr(admin_console_tab, "POLL_DEADLINE_S", 0.05) + tab._on_refresh() + assert pump_until(lambda: bool(warnings)) + assert warnings[0][-1] == language_wrapper.translate("task_timed_out", "task_timed_out") diff --git a/test/unit_test/headless/test_gui_worker_threads.py b/test/unit_test/headless/test_gui_worker_threads.py index 1ef79fb91..bf8053a1a 100644 --- a/test/unit_test/headless/test_gui_worker_threads.py +++ b/test/unit_test/headless/test_gui_worker_threads.py @@ -87,10 +87,10 @@ def test_admin_console_refresh_actually_polls(qapp, tmp_path, monkeypatch): tab._thumb_timer.stop() # noqa: SLF001 tab._on_refresh() # noqa: SLF001 tab._refresh_thumbnails() # noqa: SLF001 - assert _pump(qapp, lambda: tab._poll_thread is None and tab._thumb_thread is None) # noqa: SLF001 + assert _pump(qapp, lambda: not tab._polls.running and not tab._thumbs.running) # noqa: SLF001 assert sorted(polled) == [1, 2], "the workers were collected before run()" tab._on_refresh() # noqa: SLF001 # and the guard lets a second refresh run - assert _pump(qapp, lambda: tab._poll_thread is None) # noqa: SLF001 + assert _pump(qapp, lambda: not tab._polls.running) # noqa: SLF001 assert polled.count(1) == 2 tab.deleteLater() From 14f68be7a5c41b7186c56eab1ebebb5253ea5bda Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 14:02:55 +0800 Subject: [PATCH 088/161] Run the self-healing comparison panel on the shared task The worker keeps its captured context, deferred authority and terminal outcome, but is now a plain callable that start_until_stopped hands the stop event; Cancel and the panel's destruction set it, and the panel stays busy until the comparison has unwound. --- CHANGELOG.md | 5 ++ Progress.md | 4 +- architecture_explore.md | 8 +-- docs/updates/2026-11-b.md | 7 +++ docs/updates/README.md | 1 + .../gui/healing_evaluation_panel.py | 28 ++++------- .../gui/healing_evaluation_worker.py | 18 +++---- .../test_self_healing_evaluation_gui.py | 49 +++++++++++++++---- 8 files changed, 75 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4ebfec89..911906ab3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI internals: the self-healing comparison panel runs on `TabTask.start_until_stopped`. + `HealingEvaluationWorker` is no longer a `QObject`: it is called with the stop event and + returns its `HealingEvaluationOutcome` (`run`, `finished` and the `_handle` / `_worker` + attributes are gone; `_task` is the task). Cancel still publishes no partial comparison. + - `AdminConsoleClient.poll_all` and `fetch_thumbnails` observe a bound cancellation scope: once cancelled, hosts not reached yet are skipped and `CancelledError` is raised after the requests already out return. Unscoped calls (`AC_admin_poll`, scripts) are unchanged. GUI: the Admin diff --git a/Progress.md b/Progress.md index 3f87d25fc..615aa9276 100644 --- a/Progress.md +++ b/Progress.md @@ -543,9 +543,9 @@ F 還缺: 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)、 - Admin Console 的健康輪詢與縮圖(U-20261114-21)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 + Admin Console 的健康輪詢與縮圖(U-20261114-21)、自我修復比對面板(U-20261114-22)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`、 - `healing_evaluation_panel`、`journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 + `journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 它們的 worker 以 Qt signal 回報進度,`TabTask` 尚無進度通道,遷移前須先補上。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, diff --git a/architecture_explore.md b/architecture_explore.md index afb0d2201..b9f74c3da 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,888 | +| 程式碼總行數 | 235,874 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1358,7 +1358,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | | vlm | `vlm_tab.py` | 150 | 用文字描述 UI 元素,交由模型定位。 | -| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 954 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | +| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 940 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,621 | +| `gui/` | 160 | 42,607 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,525** | **235,143** | +| **總計** | **1,525** | **235,129** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index cc0f37cf4..ec423ab24 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -450,3 +450,10 @@ - **Docs:** both `operations_layer_doc.rst` (multi-host admin console), `CHANGELOG.md`. - **Files:** `utils/admin/admin_client.py`, `gui/admin_console_tab.py`, the four catalogues, the tests, the docs, `Progress.md`. - **Open items:** the panels that cancel on their own but not through the shared controller, named in `Progress.md` › F3. + +## U-20261114-22 · 2026-11-14 · The self-healing comparison panel runs on the shared task · #done #gui #healing + +- **What:** the first of the five `Progress.md` › F3 panels that cancel through their own worker. `HealingEvaluationWorker` keeps everything that made it safe -- the caller's context and deferred authority captured on the GUI thread, a checkpoint before any file read and after the comparison, one terminal `HealingEvaluationOutcome` and scrubbed error text -- but is now a plain callable: `TabTask.start_until_stopped` calls it with the task's stop event, which Cancel sets and which the panel's destruction sets through handle cancellation (it used to connect `destroyed` to `request_stop` by hand). The panel stays busy until the comparison has unwound, so Run while it unwinds says *busy*, and a cancelled comparison ends as *cancelled* with no partial report. The generation guard still drops a result from a changed selection. This worker reports no progress, so it needed no progress channel. +- **Tests:** `test_self_healing_evaluation_gui.py` follows the change (the destruction test captures the stop event through the worker's `__call__`) and gains Cancel keeping the panel busy until the comparison unwinds and then showing *cancelled*. Healing, task, worker, dispose and Actions-menu tests: 318 passed, 8 skipped. +- **Files:** `gui/healing_evaluation_worker.py`, `gui/healing_evaluation_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the four panels named in `Progress.md` › F3, whose workers report progress. diff --git a/docs/updates/README.md b/docs/updates/README.md index 22639c08c..bfbcfb94b 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-22 | 2026-11-14 | The self-healing comparison panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | | U-20261114-21 | 2026-11-14 | The admin console's poll and thumbnails stop at the hosts not reached yet | #done #gui #admin | [2026-11-b](2026-11-b.md) | | U-20261114-20 | 2026-11-14 | The DAG Runner runs on the shared task and stays busy until a stopped run ends | #done #gui #dag | [2026-11-b](2026-11-b.md) | | U-20261114-19 | 2026-11-14 | Computer Use runs on the shared task and stays busy until a stopped run ends | #done #gui #agent | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/healing_evaluation_panel.py b/je_auto_control/gui/healing_evaluation_panel.py index 6c540d1b3..be8d9d48c 100644 --- a/je_auto_control/gui/healing_evaluation_panel.py +++ b/je_auto_control/gui/healing_evaluation_panel.py @@ -13,7 +13,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.responsive import fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.healing_evaluation_worker import HealingEvaluationOutcome, HealingEvaluationWorker @@ -77,8 +77,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() self._generation = 0 - self._handle: Optional[WorkerHandle] = None - self._worker: Optional[HealingEvaluationWorker] = None + # Cancel stops the comparison at its next checkpoint; closing the panel does too. + self._task = TabTask(self) + self._task.result.connect(self._completed) + self._task.error.connect(self._failed) self._report: Optional[HealingComparison] = None self._path = QLineEdit() self._summary, self._cases = _table(_SUMMARY), _table(_CASES) @@ -152,7 +154,7 @@ def _clear(self) -> None: def evaluate(self) -> None: """Start one background comparison after authorizing the owning caller.""" - if self._handle is not None: + if self._task.running: self._set_status("busy") return try: @@ -162,26 +164,16 @@ def evaluate(self) -> None: return self._generation += 1 self._clear() - worker = HealingEvaluationWorker(self._generation, self._path.text().strip()) - self._worker = worker - # pylint: disable-next=no-member # reason: PySide binds the Qt signal at runtime - self.destroyed.connect(worker.request_stop) self._set_status("running") - self._handle = start_worker(self, worker, on_done=self._completed, - on_thread_done=self._thread_done, on_fail=self._failed) + self._task.start_until_stopped(HealingEvaluationWorker(self._generation, self._path.text().strip())) @Slot() def cancel(self) -> None: """Request stop without blocking the GUI or publishing partial results.""" - if self._worker is not None: - self._worker.request_stop() - - def _thread_done(self) -> None: - self._handle = None - self._worker = None + self._task.stop() - def _failed(self, error: str) -> None: - self._set_status("error", error) + def _failed(self, error: object) -> None: + self._set_status("error", str(error)) @Slot(object) def _completed(self, outcome: HealingEvaluationOutcome) -> None: diff --git a/je_auto_control/gui/healing_evaluation_worker.py b/je_auto_control/gui/healing_evaluation_worker.py index fe9d2a508..85de7a3a1 100644 --- a/je_auto_control/gui/healing_evaluation_worker.py +++ b/je_auto_control/gui/healing_evaluation_worker.py @@ -6,8 +6,6 @@ from threading import Event from typing import Literal, Optional -from PySide6.QtCore import QObject, Signal, Slot - from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.secret_scope import scrub_secret_text from je_auto_control.utils.rbac.deferred import DeferredAuthorization @@ -26,19 +24,15 @@ class HealingEvaluationOutcome: error: str = "" -class HealingEvaluationWorker(QObject): - """Perform local comparison off the GUI thread with cooperative checkpoints.""" - - finished = Signal(object) +class HealingEvaluationWorker: + """One local comparison: built on the GUI thread, called off it with cooperative checkpoints.""" def __init__(self, request_id: int, path: str) -> None: - super().__init__() self._request_id, self._path = request_id, path self._stop = Event() self._context = copy_context() self._authority = DeferredAuthorization.capture() - @Slot() def request_stop(self) -> None: """Request stop between file reads and comparison pairs without blocking Qt.""" self._stop.set() @@ -47,10 +41,10 @@ def _checkpoint(self, _count: int) -> None: if self._stop.is_set(): raise CancelledError() - @Slot() - def run(self) -> None: - """Emit a terminal outcome under the captured caller context.""" - self.finished.emit(self._context.run(self._evaluate)) + def __call__(self, stop_event: Event) -> HealingEvaluationOutcome: + """Return a terminal outcome under the captured caller context; ``stop_event`` stops it.""" + self._stop = stop_event + return self._context.run(self._evaluate) def _evaluate(self) -> HealingEvaluationOutcome: try: diff --git a/test/unit_test/headless/test_self_healing_evaluation_gui.py b/test/unit_test/headless/test_self_healing_evaluation_gui.py index 4c6956dd7..0c7da8fc2 100644 --- a/test/unit_test/headless/test_self_healing_evaluation_gui.py +++ b/test/unit_test/headless/test_self_healing_evaluation_gui.py @@ -28,8 +28,7 @@ def panel(app): widget = HealingEvaluationPanel() yield widget widget.cancel() - if widget._handle is not None: - assert widget._handle.wait(5) + until(app, lambda: not widget._task.running) widget.deleteLater() app.processEvents() @@ -45,14 +44,14 @@ def until(app, predicate): def test_panel_starts_empty_and_exposes_only_actions(panel): assert panel.findChildren(QPushButton) == [] assert panel._summary.rowCount() == panel._cases.rowCount() == 0 - assert panel._handle is None + assert not panel._task.running assert len(panel.menu_actions()) == 5 def test_background_comparison_details_and_shared_exports(panel, app, tmp_path, monkeypatch): panel._path.setText(str(DATASET)) panel.evaluate() - until(app, lambda: panel._report is not None and panel._handle is None) + until(app, lambda: panel._report is not None and not panel._task.running) assert panel._summary.rowCount() == 2 assert panel._cases.rowCount() == 10 panel._cases.setCurrentCell(0, 0) @@ -82,7 +81,7 @@ def slow(*_args, **_kwargs): assert started.wait(5) panel._path.setText("different.json") release.set() - until(app, lambda: panel._handle is None) + until(app, lambda: not panel._task.running) assert panel._report is None assert panel._cases.rowCount() == 0 assert thread_ids[0] != get_ident() @@ -98,7 +97,6 @@ def forbidden(*_args, **_kwargs): assert worker._evaluate().status == "error" worker.request_stop() assert worker._evaluate().status == "cancelled" - worker.deleteLater() def test_panel_destruction_requests_stop_without_touching_dead_widgets(app, monkeypatch): @@ -111,14 +109,47 @@ def slow(*_args, **_kwargs): return report monkeypatch.setattr("je_auto_control.gui.healing_evaluation_worker.evaluate_healing_manifest", slow) + stops, done = [], Event() + real_call = HealingEvaluationWorker.__call__ + + def call(self, stop_event): + stops.append(stop_event) + try: + return real_call(self, stop_event) + finally: + done.set() + + monkeypatch.setattr(HealingEvaluationWorker, "__call__", call) widget = HealingEvaluationPanel() widget._path.setText(str(DATASET)) widget.evaluate() assert started.wait(5) - handle, worker = widget._handle, widget._worker widget.deleteLater() QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) - assert worker._stop.is_set() + assert stops[0].is_set() release.set() - assert handle.wait(5) + assert done.wait(5) app.processEvents() + + +def test_cancel_keeps_the_panel_busy_until_the_comparison_unwinds(panel, app, monkeypatch): + started, release = Event(), Event() + report = evaluate_healing_manifest(DATASET) + + def slow(*_args, **_kwargs): + started.set() + assert release.wait(5) + return report + + monkeypatch.setattr("je_auto_control.gui.healing_evaluation_worker.evaluate_healing_manifest", slow) + panel._path.setText(str(DATASET)) + panel.evaluate() + assert started.wait(5) + dict(panel.menu_actions())["healing_eval_cancel"]() + assert panel._task.running and panel._task.stopping + panel.evaluate() # still unwinding: no second comparison + assert panel._state == "busy" + release.set() + until(app, lambda: not panel._task.running) + assert panel._state == "cancelled" # the checkpoint after the read saw the stop + assert panel._report is None From 68a65e9650e09744f7cc397af524d40b11ad5dfb Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 14:12:33 +0800 Subject: [PATCH 089/161] Run the journal browser on the shared task and relay its progress TabTask gains a progress signal, and start_until_stopped can hand the work a report callable. The journal reader becomes a plain callable on it, keeping its captured authority, record-boundary checkpoints and single terminal outcome. --- CHANGELOG.md | 6 + Progress.md | 6 +- architecture_explore.md | 12 +- docs/updates/2026-11-b.md | 7 + docs/updates/README.md | 1 + je_auto_control/gui/_tab_task.py | 23 +++- je_auto_control/gui/journal_browser.py | 45 ++++--- je_auto_control/gui/journal_browser_worker.py | 31 +++-- .../headless/test_journal_browser_gui.py | 121 +++++++++--------- .../headless/test_self_healing_runtime_gui.py | 15 ++- .../headless/test_tab_task_until_stopped.py | 25 ++++ 11 files changed, 176 insertions(+), 116 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 911906ab3..b5f081073 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI internals: `TabTask` relays `progress`; `start_until_stopped(work, reports=True)` calls + `work(stop_event, report)`. The journal browser (Run History, Self-Healing) runs on it: + `JournalReadWorker` is no longer a `QObject` and is called with the stop event and a report + that receives `(request_id, scanned)` (`run`, `finished`, `progress` and the browser's + `_handle` / `_worker` are gone; `_task` is the task). + - GUI internals: the self-healing comparison panel runs on `TabTask.start_until_stopped`. `HealingEvaluationWorker` is no longer a `QObject`: it is called with the stop event and returns its `HealingEvaluationOutcome` (`run`, `finished` and the `_handle` / `_worker` diff --git a/Progress.md b/Progress.md index 615aa9276..ce8614bdb 100644 --- a/Progress.md +++ b/Progress.md @@ -543,10 +543,10 @@ F 還缺: 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)、 - Admin Console 的健康輪詢與縮圖(U-20261114-21)、自我修復比對面板(U-20261114-22)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 + Admin Console 的健康輪詢與縮圖(U-20261114-21)、自我修復比對面板(U-20261114-22)、 + journal browser(U-20261114-23,`TabTask` 加上進度通道)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`、 - `journal_browser`、`journal_candidate_panel`、`template_candidate_panel`。 - 它們的 worker 以 Qt signal 回報進度,`TabTask` 尚無進度通道,遷移前須先補上。 + `journal_candidate_panel`、`template_candidate_panel`。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index b9f74c3da..79323cbec 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,874 | +| 程式碼總行數 | 235,897 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1333,8 +1333,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_candidate_worker.py` | 147 | 背景產碼、差異呈現、審閱匯出/匯入驗證、權限與取消。 | | `journal_candidate_panel.py` | 225 | 程式、差異、來源與排除項目的審閱;Actions 明確匯入與匯出。 | | `journal_candidate_dialog.py` | 97 | Recording Editor/Builder 共用模型外審閱視窗,保護編輯基準並隨擁有者關閉。 | -| `journal_browser.py` | 250 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | -| `journal_browser_worker.py` | 85 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | +| `journal_browser.py` | 257 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | +| `journal_browser_worker.py` | 88 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | | `language_wrapper/` | 8,519 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | @@ -1378,7 +1378,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | device_matrix | `device_matrix_tab.py` | 139 | 一份 action list 跨多裝置平行執行。 | | mobile | `mobile_tab.py` | 222 | Android/iOS 裝置工作階段:設定報告、擷取、手勢、輸入與能力矩陣。 | | media_checks | `media_checks_tab.py` | 129 | 音訊活動與影片動態斷言。 | -| run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 823 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | +| run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 833 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | | profiler | `profiler_tab.py` | 141 | 視覺化逐動作耗時熱點。 | | window_manager | `window_tab.py` | 139 | 列出、聚焦、關閉視窗。 | | plugins | `plugins_tab.py` | 85 | 從使用者目錄載入額外 `AC_` 指令。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,607 | +| `gui/` | 160 | 42,630 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,525** | **235,129** | +| **總計** | **1,525** | **235,152** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index ec423ab24..7112b8ff7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -457,3 +457,10 @@ - **Tests:** `test_self_healing_evaluation_gui.py` follows the change (the destruction test captures the stop event through the worker's `__call__`) and gains Cancel keeping the panel busy until the comparison unwinds and then showing *cancelled*. Healing, task, worker, dispose and Actions-menu tests: 318 passed, 8 skipped. - **Files:** `gui/healing_evaluation_worker.py`, `gui/healing_evaluation_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** the four panels named in `Progress.md` › F3, whose workers report progress. + +## U-20261114-23 · 2026-11-14 · The journal browser runs on the shared task, which now relays progress · #done #gui #journal + +- **What:** the next `Progress.md` › F3 panel with its own worker, and the progress channel the remaining ones need. `TabTask` now has a `progress` signal relayed from the task handle (delivered on the GUI thread, dropped once the owner is gone or the task cancelled); `start_until_stopped(work, reports=True)` calls `work(stop_event, report)`, where `report` is the handle's `report_progress`. The scope-based `cancellation_progress` was not used for this: binding a cancellation scope around every stop-event task would cap the DAG runner's poll intervals through `cancellation_timeout`. `JournalReadWorker` keeps its captured context and deferred authority, its record-boundary checkpoints and its single scrubbed terminal outcome, but is now a plain callable reporting `(request_id, scanned)` every hundred records. The browser (embedded in Run History and Self-Healing) stays busy until a cancelled read has unwound, still queues `open_source` behind it, and its destruction sets the stop event through handle cancellation instead of a hand-connected `destroyed`. +- **Tests:** `test_tab_task_until_stopped.py` gains reported progress arriving on the GUI thread and dropped after the owner is destroyed. `test_journal_browser_gui.py` calls the worker directly and waits on `_task`; the stop-between-records test now also checks the reports; the destruction test captures the stop event through `__call__`. `test_self_healing_runtime_gui.py` waits on the embedded browser's `_task`. Journal, history, healing, task, worker, dispose and Actions-menu tests: 844 passed, 8 skipped, and the self-healing runtime file 12 passed after its fixture change. +- **Files:** `gui/_tab_task.py`, `gui/journal_browser.py`, `gui/journal_browser_worker.py`, the tests, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the three panels named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index bfbcfb94b..cc9ca3db4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-23 | 2026-11-14 | The journal browser runs on the shared task, which now relays progress | #done #gui #journal | [2026-11-b](2026-11-b.md) | | U-20261114-22 | 2026-11-14 | The self-healing comparison panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | | U-20261114-21 | 2026-11-14 | The admin console's poll and thumbnails stop at the hosts not reached yet | #done #gui #admin | [2026-11-b](2026-11-b.md) | | U-20261114-20 | 2026-11-14 | The DAG Runner runs on the shared task and stays busy until a stopped run ends | #done #gui #dag | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_tab_task.py b/je_auto_control/gui/_tab_task.py index 6241a7639..1f4639410 100644 --- a/je_auto_control/gui/_tab_task.py +++ b/je_auto_control/gui/_tab_task.py @@ -7,8 +7,8 @@ * **One run at a time.** :meth:`TabTask.start` refuses while a task is running, so a second click (or a script that clicks this window's own Run action) does not start a nested run. -* **Outcomes on the GUI thread.** ``result`` / ``error`` / ``finished`` are - relayed from the task's handle; :attr:`TabTask.tag` says which command the +* **Outcomes on the GUI thread.** ``result`` / ``error`` / ``finished`` (and + ``progress``, for work that reports it) are relayed from the task's handle; :attr:`TabTask.tag` says which command the outcome belongs to. :attr:`TabTask.task` is ``None`` again before ``finished`` is emitted. * **Stop.** A script run (:meth:`TabTask.start_script`) is a stoppable @@ -48,6 +48,7 @@ class TabTask(QObject): result = Signal(object) error = Signal(object) finished = Signal() + progress = Signal(object) def __init__(self, owner: QObject) -> None: super().__init__(owner) @@ -86,7 +87,7 @@ def start_script(self, work: Callable[[], Any], *, tag: str = "") -> bool: self._submit(functools.partial(_call_stoppable, self._stop_token, work), tag, None, None) return True - def start_until_stopped(self, work: Callable[[threading.Event], Any], *, tag: str = "") -> bool: + def start_until_stopped(self, work: Callable[..., Any], *, tag: str = "", reports: bool = False) -> bool: """Run ``work(stop_event)`` off the GUI thread; ``False`` when a task is already running. For work that ends itself at its next step once the event is set and @@ -94,12 +95,15 @@ def start_until_stopped(self, work: Callable[[threading.Event], Any], *, tag: st the event; the task stays running until ``work`` returns and its outcome arrives as usual. The tab being destroyed, or the application exiting, sets the event too. There is no deadline: the work's own - limits bound it. + limits bound it. With ``reports`` the work is called + ``work(stop_event, report)``; each ``report(value)`` arrives as + :attr:`progress` on the GUI thread, while the tab lives. """ if self.task is not None: return False self._stop_event = threading.Event() - self._submit(functools.partial(_call_until_stopped, self._stop_event, work), tag, None, None) + call = _call_until_stopped_reporting if reports else _call_until_stopped + self._submit(functools.partial(call, self._stop_event, work), tag, None, None) return True def stop(self) -> bool: @@ -128,6 +132,7 @@ def _submit(self, work: Callable[[CancellationToken], Any], tag: str, self.task = handle handle.result.connect(self.result) handle.error.connect(self.error) + handle.progress.connect(self.progress) handle.finished.connect(self._on_finished) def _on_finished(self) -> None: @@ -153,6 +158,14 @@ def _call_until_stopped(stop: threading.Event, work: Callable[[threading.Event], return work(stop) +def _call_until_stopped_reporting(stop: threading.Event, + work: Callable[[threading.Event, Callable[[object], None]], Any], + token: CancellationToken) -> Any: + """Worker thread: as :func:`_call_until_stopped`, also handing ``work`` the handle's progress report.""" + token.on_cancel(stop.set) + return work(stop, token.report_progress) + + def _call_stoppable(stop: StopToken, work: Callable[[], Any], token: CancellationToken) -> Any: """Worker thread: run ``work`` inside a stoppable run bound to ``stop``.""" # The tab was destroyed, or the application is exiting: stop the script too. diff --git a/je_auto_control/gui/journal_browser.py b/je_auto_control/gui/journal_browser.py index 9433d6aec..462ab3380 100644 --- a/je_auto_control/gui/journal_browser.py +++ b/je_auto_control/gui/journal_browser.py @@ -1,4 +1,9 @@ -"""Read-only lifecycle snapshots and provenance links for journal inspection.""" +"""Read-only lifecycle snapshots and provenance links for journal inspection. + +A read runs as a :class:`~je_auto_control.gui._tab_task.TabTask` started with +``start_until_stopped``: Cancel, and the view being destroyed, stop it at the +next validated-record boundary, and the view stays busy until it has. +""" from __future__ import annotations import json @@ -13,7 +18,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.journal_browser_worker import JournalReadOutcome, JournalReadRequest, JournalReadWorker from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.exception.exceptions import AutoControlException @@ -32,8 +37,11 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() self._generation = 0 - self._handle: Optional[WorkerHandle] = None - self._worker: Optional[JournalReadWorker] = None + self._task = TabTask(self) + self._task.result.connect(self._received) + self._task.error.connect(self._task_failed) + self._task.progress.connect(self._progress) + self._task.finished.connect(self._thread_done) self._pending_source: Optional[Context] = None self._events: list[dict[str, object]] = [] self._step_source = False @@ -140,14 +148,14 @@ def set_source(self, path: str, run_id: str, step_id: str) -> None: def open_source(self, path: str, run_id: str, step_id: str) -> None: """Inspect this target after any older reader stops, retaining the caller's context.""" self.set_source(path, run_id, step_id) - if self._handle is not None: + if self._task.running: self._pending_source = copy_context() else: self.read() def browse(self) -> None: """Choose a source file without reading or rewriting it.""" - if self._handle is not None: + if self._task.running: return try: authorize_command("AC_journal_read") @@ -162,7 +170,7 @@ def browse(self) -> None: def read(self) -> None: """Launch bounded inspection; one active reader belongs to this widget.""" - if self._handle is not None: + if self._task.running: return self._clear_events() try: @@ -177,21 +185,15 @@ def read(self) -> None: self._generation += 1 request = JournalReadRequest(self._generation, path, self._run_id.text() or None, self._limit.value(), self._step_id.text() or None) - worker = JournalReadWorker(request) - self._worker = worker - worker.progress.connect(self._progress) - # pylint: disable-next=no-member # reason: PySide binds this Qt signal at runtime - self.destroyed.connect(worker.request_stop) self._set_busy(True) self._set_status("journal_reading") - self._handle = start_worker(self, worker, on_done=self._received, - on_thread_done=self._thread_done, on_fail=self._failed) + self._task.start_until_stopped(JournalReadWorker(request), reports=True) def cancel(self) -> None: """Ask the current reader to stop at its next validated-record boundary.""" self._pending_source = None - if self._worker is not None: - self._worker.request_stop() + if self._task.running: + self._task.stop() self._set_status("journal_cancelling") # pylint: disable-next=invalid-name # reason: Qt override @@ -208,8 +210,11 @@ def _set_busy(self, busy: bool) -> None: for control in (self._path, self._run_id, self._step_id, self._limit, self._links): control.setEnabled(not busy) - @Slot(int, int) - def _progress(self, request_id: int, count: int) -> None: + @Slot(object) + def _progress(self, value: object) -> None: + if not isinstance(value, tuple) or len(value) != 2: # the worker reports (request_id, scanned) + return + request_id, count = value if request_id == self._generation and self._status_key != "journal_cancelling": self._set_status("journal_progress", str(count)) @@ -235,9 +240,11 @@ def _failed(self, message: str) -> None: self._clear_events() self._set_status("journal_error", scrub_secret_text(message)) + def _task_failed(self, error: object) -> None: + self._failed(str(error)) + def _thread_done(self) -> None: pending, self._pending_source = self._pending_source, None - self._handle = self._worker = None self._set_busy(False) if self._status_key in ("journal_reading", "journal_progress", "journal_cancelling"): self._set_status("journal_interrupted") diff --git a/je_auto_control/gui/journal_browser_worker.py b/je_auto_control/gui/journal_browser_worker.py index 032a30f35..21d5712d4 100644 --- a/je_auto_control/gui/journal_browser_worker.py +++ b/je_auto_control/gui/journal_browser_worker.py @@ -6,9 +6,7 @@ from contextvars import copy_context from dataclasses import dataclass, field from threading import Event -from typing import Literal, Optional - -from PySide6.QtCore import QObject, Signal, Slot +from typing import Callable, Literal, Optional from je_auto_control.utils.action_journal.inspection import inspect_journal from je_auto_control.utils.exception.exceptions import AutoControlException @@ -38,36 +36,41 @@ class JournalReadOutcome: error: str = "" -class JournalReadWorker(QObject): - """Read off the GUI thread; callbacks carry only IDs, counts and sanitized data.""" +def _no_report(_value: object) -> None: + """Progress sink for a worker run without one.""" + + +class JournalReadWorker: + """Read off the GUI thread; reports carry only IDs, counts and sanitized data. - finished = Signal(object) - progress = Signal(int, int) + Built on the GUI thread, which captures the caller's context and authority, + and called on a worker thread with the stop event and a progress report; + each report is ``(request_id, scanned)`` every hundred records. + """ def __init__(self, request: JournalReadRequest) -> None: - super().__init__() self._request = request self._stop = Event() + self._report: Callable[[object], None] = _no_report self._context = copy_context() self._authority = DeferredAuthorization.capture() self._scanned = 0 - @Slot() def request_stop(self) -> None: """Request cancellation without blocking the GUI or closing another thread's handle.""" self._stop.set() - @Slot() - def run(self) -> None: - """Emit exactly one terminal result for ordinary errors or cooperative cancellation.""" - self.finished.emit(self._context.run(self._inspect)) + def __call__(self, stop_event: Event, report: Callable[[object], None] = _no_report) -> JournalReadOutcome: + """Return exactly one terminal result for ordinary errors or cooperative cancellation.""" + self._stop, self._report = stop_event, report + return self._context.run(self._inspect) def _checkpoint(self, count: int) -> None: if self._stop.is_set(): raise CancelledError() self._scanned = count if count % 100 == 0: - self.progress.emit(self._request.request_id, count) + self._report((self._request.request_id, count)) def _inspect(self) -> JournalReadOutcome: request = self._request diff --git a/test/unit_test/headless/test_journal_browser_gui.py b/test/unit_test/headless/test_journal_browser_gui.py index 5fd85d340..eb19b8f0c 100644 --- a/test/unit_test/headless/test_journal_browser_gui.py +++ b/test/unit_test/headless/test_journal_browser_gui.py @@ -25,8 +25,7 @@ def browser(app): widget = JournalBrowser() yield widget widget.cancel() - if widget._handle is not None: - widget._handle.wait(5) + _until(app, lambda: not widget._task.running) widget.deleteLater() app.processEvents() @@ -69,7 +68,7 @@ def inspect(path, **_kwargs): browser.close() finally: release.set() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert calls == ["old.jsonl"] assert browser._events == [] if next_action == "viewer": @@ -78,7 +77,7 @@ def inspect(path, **_kwargs): def test_browser_has_only_inputs_and_views_until_an_action(browser): assert browser.findChildren(QPushButton) == [] - assert browser._handle is None + assert not browser._task.running assert browser._table.rowCount() == 0 assert browser._limit.minimum() == 1 assert browser._limit.maximum() == 10000 @@ -91,7 +90,7 @@ def test_real_read_keeps_lifecycle_snapshots_and_source(browser, app, tmp_path): original = path.read_bytes() browser._path.setText(str(path)) browser.read() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._table.rowCount() == 2 assert [row["status"] for row in browser._events] == ["incomplete", "ok"] browser._table.selectRow(1) @@ -104,13 +103,13 @@ def test_links_select_run_without_automatic_file_io(browser, app, tmp_path): _journal(path, "one") _journal(path, "two") browser.set_links([JournalLink(1, str(path), "one"), JournalLink(1, str(path), "two")]) - assert browser._handle is None + assert not browser._task.running assert browser._table.rowCount() == 0 browser._links.setCurrentIndex(2) assert browser._run_id.text() == "two" browser._limit.setValue(1) browser.read() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert len(browser._events) == 1 assert browser._events[0]["run_id"] == "two" assert browser._events[0]["status"] == "incomplete" @@ -121,13 +120,11 @@ def forbidden(*args, **kwargs): pytest.fail("cancelled worker opened a file") monkeypatch.setattr("je_auto_control.gui.journal_browser_worker.inspect_journal", forbidden) worker = JournalReadWorker(JournalReadRequest(1, "unused", None, 100)) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.request_stop() - worker.run() - assert outcomes[0].status == "cancelled" - assert outcomes[0].events == [] - worker.deleteLater() + stop = threading.Event() + stop.set() + outcome = worker(stop) + assert outcome.status == "cancelled" + assert outcome.events == [] def test_worker_rechecks_captured_viewer_authority(app, monkeypatch): @@ -135,12 +132,8 @@ def test_worker_rechecks_captured_viewer_authority(app, monkeypatch): monkeypatch.setattr("je_auto_control.gui.journal_browser_worker.inspect_journal", lambda *a, **k: calls.append(1)) with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): worker = JournalReadWorker(JournalReadRequest(1, "unused", None, 100)) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "error" + assert worker(threading.Event()).status == "error" assert calls == [] - worker.deleteLater() def test_worker_retains_enclosing_path_policy(app, tmp_path): @@ -148,12 +141,9 @@ def test_worker_retains_enclosing_path_policy(app, tmp_path): allowed.mkdir() with ac.journal_scope(ac.ActionJournal(allowed / "outer.jsonl"), path_policy=ac.PathPolicy([allowed])): worker = JournalReadWorker(JournalReadRequest(1, str(tmp_path / "outside.jsonl"), None, 100)) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "error" - assert "PathNotAllowedError" in outcomes[0].error - worker.deleteLater() + outcome = worker(threading.Event()) + assert outcome.status == "error" + assert "PathNotAllowedError" in outcome.error def test_worker_progress_cancels_between_records(app, monkeypatch): @@ -165,13 +155,16 @@ def inspect(path, **kwargs): return [] monkeypatch.setattr("je_auto_control.gui.journal_browser_worker.inspect_journal", inspect) worker = JournalReadWorker(JournalReadRequest(1, "unused", None, 100)) - worker.progress.connect(lambda request, count: worker.request_stop() if count == 100 else None) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "cancelled" + stop, reports = threading.Event(), [] + + def report(value): + reports.append(value) + if value == (1, 100): + stop.set() + + assert worker(stop, report).status == "cancelled" + assert reports == [(1, 0), (1, 100)] assert max(scanned) <= 101 - worker.deleteLater() def _blocked_reader(monkeypatch): @@ -192,10 +185,10 @@ def test_cancel_does_not_block_gui(browser, app, monkeypatch): try: assert entered.wait(2) browser.cancel() - assert browser._handle.isRunning() + assert browser._task.running # Cancel returns at once; the read unwinds behind it finally: release.set() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._events == [] assert browser._status_key == "journal_cancelled" @@ -209,7 +202,7 @@ def test_changing_target_discards_stale_completion(browser, app, monkeypatch): browser.set_links([JournalLink(7, "new", "new-run")]) finally: release.set() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._path.text() == "new" assert browser._run_id.text() == "new-run" assert browser._events == [] @@ -218,18 +211,28 @@ def test_changing_target_discards_stale_completion(browser, app, monkeypatch): def test_destroying_owner_requests_stop_and_drops_late_results(app, monkeypatch): entered, release = _blocked_reader(monkeypatch) + stops, done = [], threading.Event() + real_call = JournalReadWorker.__call__ + + def call(self, stop_event, report): + stops.append(stop_event) + try: + return real_call(self, stop_event, report) + finally: + done.set() + + monkeypatch.setattr(JournalReadWorker, "__call__", call) widget = JournalBrowser() widget._path.setText("unused") widget.read() - handle, worker = widget._handle, widget._worker try: assert entered.wait(2) widget.deleteLater() QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) - assert worker._stop.is_set() + assert stops[0].is_set() finally: release.set() - assert handle.wait(5) + assert done.wait(5) app.processEvents() @@ -237,7 +240,7 @@ def test_viewer_is_refused_before_worker_creation(browser): browser._path.setText("private.jsonl") with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): browser.read() - assert browser._handle is None + assert not browser._task.running assert browser._status_key == "journal_error" @@ -246,11 +249,11 @@ def test_corrupt_read_clears_previous_snapshots(browser, app, tmp_path): _journal(path) browser._path.setText(str(path)) browser.read() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._events path.write_text("invalid\n", encoding="utf-8") browser.read() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._events == [] assert browser._table.rowCount() == 0 assert browser._status_key == "journal_error" @@ -273,7 +276,7 @@ def test_history_menu_loads_links_without_reading(app, monkeypatch, tmp_path): actions["journal_selected_run"]() assert tab._journal._path.text() == str(tmp_path / "events.jsonl") assert tab._journal._run_id.text() == "chosen" - assert tab._journal._handle is None + assert not tab._journal._task.running finally: tab.deleteLater() store.close() @@ -286,10 +289,10 @@ def test_close_requests_cancellation_before_deferred_deletion(browser, app, monk try: assert entered.wait(2) browser.close() - assert browser._worker._stop.is_set() + assert browser._task.stopping finally: release.set() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._status_key == "journal_cancelled" @@ -308,12 +311,9 @@ def test_worker_refreshes_store_backed_owner_before_io(app, monkeypatch, tmp_pat def forbidden(*args, **kwargs): pytest.fail("revoked owner read private data") monkeypatch.setattr("je_auto_control.gui.journal_browser_worker.inspect_journal", forbidden) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "error" - assert outcomes[0].events == [] - worker.deleteLater() + outcome = worker(threading.Event()) + assert outcome.status == "error" + assert outcome.events == [] def test_history_retranslates_browser_and_preserves_state(app, monkeypatch, tmp_path): @@ -364,7 +364,7 @@ def forbidden(*args, **kwargs): with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): browser.browse() assert browser._status_key == "journal_error" - assert browser._handle is None + assert not browser._task.running def test_worker_masks_errors_in_active_captured_context(app, monkeypatch): @@ -373,16 +373,13 @@ def test_worker_masks_errors_in_active_captured_context(app, monkeypatch): def fail(*args, **kwargs): raise ValueError(secret) monkeypatch.setattr("je_auto_control.gui.journal_browser_worker.inspect_journal", fail) - outcomes = [] with secret_log_scope(): remember_secret(secret) worker = JournalReadWorker(JournalReadRequest(1, "unused", None, 100)) - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "error" - assert secret not in outcomes[0].error - assert "***" in outcomes[0].error - worker.deleteLater() + outcome = worker(threading.Event()) + assert outcome.status == "error" + assert secret not in outcome.error + assert "***" in outcome.error def test_error_details_are_plain_text(browser): @@ -406,7 +403,7 @@ def inspect(path, **kwargs): monkeypatch.setattr("je_auto_control.gui.journal_browser_worker.inspect_journal", inspect) browser._path.setText("unused") browser.read() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert calls assert set(calls) == {gui_ident} @@ -419,16 +416,14 @@ def test_history_close_cancels_its_child_reader(app, monkeypatch, tmp_path): tab = history_module.RunHistoryTab() tab._journal._path.setText("unused") tab._journal.read() - handle = tab._journal._handle try: assert entered.wait(2) tab.close() - assert tab._journal._worker._stop.is_set() + assert tab._journal._task.stopping assert not tab._timer.isActive() finally: release.set() - assert handle.wait(5) - app.processEvents() + _until(app, lambda: not tab._journal._task.running) tab.deleteLater() store.close() @@ -442,7 +437,7 @@ def test_lookup_error_invalidates_an_older_read(browser, app, monkeypatch): browser.report_error("new history lookup failed") finally: release.set() - _until(app, lambda: browser._handle is None) + _until(app, lambda: not browser._task.running) assert browser._events == [] assert browser._status_key == "journal_error" assert "new history lookup failed" in browser._status.text() diff --git a/test/unit_test/headless/test_self_healing_runtime_gui.py b/test/unit_test/headless/test_self_healing_runtime_gui.py index b1bf02f8f..41da9c079 100644 --- a/test/unit_test/headless/test_self_healing_runtime_gui.py +++ b/test/unit_test/headless/test_self_healing_runtime_gui.py @@ -1,5 +1,6 @@ """Offscreen live locator inputs and evidence browsing without native capture/input.""" import json +import time import pytest @@ -24,8 +25,10 @@ def forbidden(*_a, **_k): view = SelfHealingTab() yield view, log view._source.cancel() - if view._source._handle is not None: - view._source._handle.wait(5) + deadline = time.monotonic() + 5 + while view._source._task.running and time.monotonic() < deadline: + app.processEvents() + time.sleep(.005) view.deleteLater() app.processEvents() @@ -172,10 +175,10 @@ def inspect(*args, **kwargs): view._on_source() app = QApplication.instance() deadline = time.monotonic() + 5 - while view._source._handle is not None and time.monotonic() < deadline: + while view._source._task.running and time.monotonic() < deadline: app.processEvents() time.sleep(0.005) - assert view._source._handle is None + assert not view._source._task.running assert view._views.currentWidget() is view._source assert view._source._step_source view._source.retranslate() @@ -219,9 +222,9 @@ def inspect(_path, **kwargs): release.set() app = QApplication.instance() deadline = time.monotonic() + 5 - while view._source._handle is not None and time.monotonic() < deadline: + while view._source._task.running and time.monotonic() < deadline: app.processEvents() time.sleep(0.005) - assert view._source._handle is None + assert not view._source._task.running assert calls == ["first", "second"] assert [row["step_id"] for row in view._source._events] == ["second"] diff --git a/test/unit_test/headless/test_tab_task_until_stopped.py b/test/unit_test/headless/test_tab_task_until_stopped.py index dbb8249cc..d3caed9ff 100644 --- a/test/unit_test/headless/test_tab_task_until_stopped.py +++ b/test/unit_test/headless/test_tab_task_until_stopped.py @@ -133,3 +133,28 @@ def run(_definition, max_parallel=1, stop_event=None): finally: work.finish.set() tab.deleteLater() + + +def test_reported_progress_reaches_the_gui_thread_and_stops_with_the_owner(): + import shiboken6 + owner = QWidget() + task, seen, threads = TabTask(owner), [], [] + gui = threading.get_ident() + task.progress.connect(lambda value: (seen.append(value), threads.append(threading.get_ident()))) + reported, go_on = threading.Event(), threading.Event() + + def work(stop_event, report): + report(1) + report(2) + reported.set() + assert go_on.wait(30.0) + report(3) # after the owner is gone: dropped + return "done" + + assert task.start_until_stopped(work, reports=True) + assert reported.wait(10.0) + assert pump_until(lambda: seen == [1, 2]) + assert set(threads) == {gui} + shiboken6.delete(owner) + go_on.set() + assert pump_until(lambda: len(seen) > 2, timeout=0.5) is False From 39ffea0f7bfbf7378e22a8983b9ace2f6c9cbf9c Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 14:16:50 +0800 Subject: [PATCH 090/161] Run the journal candidate panel on the shared task The worker keeps its captured authority, its checkpoints and the rule that a committed export reports success, but becomes a plain callable given the stop event and a progress report; the panel stays busy until cancelled work has unwound. --- CHANGELOG.md | 6 ++ Progress.md | 4 +- architecture_explore.md | 10 ++-- docs/updates/2026-11-b.md | 7 +++ docs/updates/README.md | 1 + .../gui/journal_candidate_panel.py | 39 +++++++------ .../gui/journal_candidate_worker.py | 31 +++++----- .../headless/test_codegen_journal_gui.py | 57 +++++++++++++------ 8 files changed, 99 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5f081073..e5beaad13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI internals: the journal candidate panel (Script Builder › review from journal) runs on + `TabTask.start_until_stopped(..., reports=True)`. `JournalCandidateWorker` is no longer a + `QObject`: it is called with the stop event and a report of `(request_id, count)` and returns + its `JournalCandidateOutcome` (`run`, `finished`, `progress` and the panel's `_handle` / + `_worker` are gone; `_task` is the task). A committed export still reports success. + - GUI internals: `TabTask` relays `progress`; `start_until_stopped(work, reports=True)` calls `work(stop_event, report)`. The journal browser (Run History, Self-Healing) runs on it: `JournalReadWorker` is no longer a `QObject` and is called with the stop event and a report diff --git a/Progress.md b/Progress.md index ce8614bdb..4bd280749 100644 --- a/Progress.md +++ b/Progress.md @@ -544,9 +544,9 @@ F 還缺: USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)、 Admin Console 的健康輪詢與縮圖(U-20261114-21)、自我修復比對面板(U-20261114-22)、 - journal browser(U-20261114-23,`TabTask` 加上進度通道)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 + journal browser(U-20261114-23,`TabTask` 加上進度通道)、journal candidate 面板(U-20261114-24)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`、 - `journal_candidate_panel`、`template_candidate_panel`。 + `template_candidate_panel`。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 79323cbec..8a8754b0d 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,897 | +| 程式碼總行數 | 235,903 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1330,8 +1330,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `task_controller.py` | 270 | 共用 owner-bound task/typed outcome-progress;獨立 token、弱回呼、dispatch 身分更新與銷毀後結果隔離。工作綁定獨立 cancellation scope;其餘面板遷移另列進度。 | | `template_candidate_panel.py` | 241 | 預覽原始/候選縮圖、檢視驗證並明確接受/回復。 | | `template_candidate_worker.py` | 122 | 背景檔案操作、延後權限檢查與提交前取消;完成寫入不重標為取消。 | -| `journal_candidate_worker.py` | 147 | 背景產碼、差異呈現、審閱匯出/匯入驗證、權限與取消。 | -| `journal_candidate_panel.py` | 225 | 程式、差異、來源與排除項目的審閱;Actions 明確匯入與匯出。 | +| `journal_candidate_worker.py` | 150 | 背景產碼、差異呈現、審閱匯出/匯入驗證、權限與取消。 | +| `journal_candidate_panel.py` | 228 | 程式、差異、來源與排除項目的審閱;Actions 明確匯入與匯出。 | | `journal_candidate_dialog.py` | 97 | Recording Editor/Builder 共用模型外審閱視窗,保護編輯基準並隨擁有者關閉。 | | `journal_browser.py` | 257 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 88 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,630 | +| `gui/` | 160 | 42,636 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,525** | **235,152** | +| **總計** | **1,525** | **235,158** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 7112b8ff7..852ec1904 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -464,3 +464,10 @@ - **Tests:** `test_tab_task_until_stopped.py` gains reported progress arriving on the GUI thread and dropped after the owner is destroyed. `test_journal_browser_gui.py` calls the worker directly and waits on `_task`; the stop-between-records test now also checks the reports; the destruction test captures the stop event through `__call__`. `test_self_healing_runtime_gui.py` waits on the embedded browser's `_task`. Journal, history, healing, task, worker, dispose and Actions-menu tests: 844 passed, 8 skipped, and the self-healing runtime file 12 passed after its fixture change. - **Files:** `gui/_tab_task.py`, `gui/journal_browser.py`, `gui/journal_browser_worker.py`, the tests, `CHANGELOG.md`, `Progress.md`. - **Open items:** the three panels named in `Progress.md` › F3. + +## U-20261114-24 · 2026-11-14 · The journal candidate panel runs on the shared task · #done #gui #codegen + +- **What:** the next `Progress.md` › F3 panel with its own worker, on the progress channel from U-20261114-23. `JournalCandidateWorker` (generate a candidate from a journal, export its review archive, import it into the Script Builder) keeps its captured context and deferred authority, the authorization check before any I/O, its record-boundary checkpoints, the rule that an export already committed reports success even if a stop arrives after it, and one scrubbed terminal outcome; it is now a plain callable that `start_until_stopped(..., reports=True)` hands the stop event and a `(request_id, count)` report. The panel stays busy until cancelled work has unwound, and its destruction sets the stop event through handle cancellation instead of a hand-connected `destroyed`. +- **Tests:** `test_codegen_journal_gui.py` calls the worker directly and waits on `_task`, and gains progress shown on the panel with Cancel keeping it busy until the generation unwinds and then *cancelled*. Codegen, journal, candidate, Script Builder, worker, dispose and Actions-menu tests: 735 passed, 9 skipped. +- **Files:** `gui/journal_candidate_worker.py`, `gui/journal_candidate_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** the two panels named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index cc9ca3db4..3005473d5 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-24 | 2026-11-14 | The journal candidate panel runs on the shared task | #done #gui #codegen | [2026-11-b](2026-11-b.md) | | U-20261114-23 | 2026-11-14 | The journal browser runs on the shared task, which now relays progress | #done #gui #journal | [2026-11-b](2026-11-b.md) | | U-20261114-22 | 2026-11-14 | The self-healing comparison panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | | U-20261114-21 | 2026-11-14 | The admin console's poll and thumbnails stop at the hosts not reached yet | #done #gui #admin | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/journal_candidate_panel.py b/je_auto_control/gui/journal_candidate_panel.py index 97e7786a0..78a5d7ebf 100644 --- a/je_auto_control/gui/journal_candidate_panel.py +++ b/je_auto_control/gui/journal_candidate_panel.py @@ -8,7 +8,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.journal_candidate_worker import ( CandidateOperation, JournalCandidateOutcome, JournalCandidateTask, JournalCandidateWorker, ) @@ -35,8 +35,12 @@ def __init__(self, parent: Optional[QWidget] = None, *, baseline: str = "[]", self._candidate: Optional[CandidateScript] = None self._generation = 0 self._operation: CandidateOperation = "generate" - self._handle: Optional[WorkerHandle] = None - self._worker: Optional[JournalCandidateWorker] = None + # Cancel and the view's destruction stop the work at its next checkpoint; it stays busy until then. + self._task = TabTask(self) + self._task.result.connect(self._received) + self._task.error.connect(self._task_failed) + self._task.progress.connect(self._progress) + self._task.finished.connect(self._thread_done) self._path, self._run_id = QLineEdit(), QLineEdit() self._target, self._style = QComboBox(), QComboBox() self._target.addItems(["pytest", "python", "robot"]) @@ -101,7 +105,7 @@ def _inputs_changed(self, *_args: object) -> None: self._set_status("idle") def _browse(self) -> None: - if self._handle is not None: + if self._task.running: return try: authorize_command("AC_generate_candidate_from_log") @@ -128,7 +132,7 @@ def _export(self) -> None: if self._candidate is None: self._set_status("review_required") return - if self._handle is not None: + if self._task.running: return try: authorize_command("AC_generate_candidate_from_log") @@ -139,7 +143,7 @@ def _export(self) -> None: self._failed(str(error)) def _start(self, operation: CandidateOperation, output: str = "") -> None: - if self._handle is not None: + if self._task.running: return self._generation += 1 self._operation = operation @@ -150,22 +154,19 @@ def _start(self, operation: CandidateOperation, output: str = "") -> None: task = JournalCandidateTask(self._generation, operation, output or self._path.text().strip(), self._run_id.text(), self._target.currentText(), self._style.currentText(), self._baseline, self._candidate) - worker = JournalCandidateWorker(task) - self._worker = worker - worker.progress.connect(self._progress) - # pylint: disable-next=no-member # reason: PySide binds this Qt signal at runtime - self.destroyed.connect(worker.request_stop) self._busy(True) self._set_status("running") - self._handle = start_worker(self, worker, on_done=self._received, - on_thread_done=self._thread_done, on_fail=self._failed) + self._task.start_until_stopped(JournalCandidateWorker(task), reports=True) def _busy(self, busy: bool) -> None: for control in (self._path, self._run_id, self._target, self._style): control.setEnabled(not busy) - @Slot(int, int) - def _progress(self, request_id: int, count: int) -> None: + @Slot(object) + def _progress(self, value: object) -> None: + if not isinstance(value, tuple) or len(value) != 2: # the worker reports (request_id, count) + return + request_id, count = value if request_id == self._generation and self._status_key != "cancelling": self._set_status("progress", str(count)) @@ -201,12 +202,14 @@ def _apply_result(self, outcome: JournalCandidateOutcome) -> None: def cancel(self) -> None: """Request stop; completed atomic exports remain committed.""" - if self._worker is not None: - self._worker.request_stop() + if self._task.running: + self._task.stop() self._set_status("cancelling") + def _task_failed(self, error: object) -> None: + self._failed(str(error)) + def _thread_done(self) -> None: - self._worker = self._handle = None self._busy(False) if self._status_key in ("running", "progress", "cancelling"): self._set_status("interrupted") diff --git a/je_auto_control/gui/journal_candidate_worker.py b/je_auto_control/gui/journal_candidate_worker.py index 5c0fbd338..50934e937 100644 --- a/je_auto_control/gui/journal_candidate_worker.py +++ b/je_auto_control/gui/journal_candidate_worker.py @@ -7,9 +7,7 @@ from dataclasses import dataclass, field from hashlib import sha256 from threading import Event -from typing import Literal, Optional, cast - -from PySide6.QtCore import QObject, Signal, Slot +from typing import Callable, Literal, Optional, cast from je_auto_control.utils.action_journal.events import ActionEvent from je_auto_control.utils.action_journal.redaction import sanitize_event @@ -66,21 +64,26 @@ class JournalCandidateOutcome: truncated: bool = False -class JournalCandidateWorker(QObject): - """Run under the registrant's authority and context, with stop checks before irreversible export.""" +def _no_report(_value: object) -> None: + """Progress sink for a worker run without one.""" + + +class JournalCandidateWorker: + """Run under the registrant's authority and context, with stop checks before irreversible export. - finished = Signal(object) - progress = Signal(int, int) + Built on the GUI thread, which captures that context and authority, and + called on a worker thread with the stop event and a progress report; each + report is ``(request_id, count)`` every hundred records. + """ def __init__(self, task: JournalCandidateTask) -> None: - super().__init__() self._task = task self._count = 0 self._stop = Event() + self._report: Callable[[object], None] = _no_report self._context = copy_context() self._authority = DeferredAuthorization.capture() - @Slot() def request_stop(self) -> None: """Request cooperative cancellation without blocking the GUI.""" self._stop.set() @@ -90,12 +93,12 @@ def _checkpoint(self, count: int) -> None: raise CancelledError() self._count = max(self._count, count) if self._count % 100 == 0: - self.progress.emit(self._task.request_id, self._count) + self._report((self._task.request_id, self._count)) - @Slot() - def run(self) -> None: - """Emit one result under captured authority; successful committed exports stay successful.""" - self.finished.emit(self._context.run(self._perform)) + def __call__(self, stop_event: Event, report: Callable[[object], None] = _no_report) -> JournalCandidateOutcome: + """Return one result under captured authority; successful committed exports stay successful.""" + self._stop, self._report = stop_event, report + return self._context.run(self._perform) def _perform(self) -> JournalCandidateOutcome: try: diff --git a/test/unit_test/headless/test_codegen_journal_gui.py b/test/unit_test/headless/test_codegen_journal_gui.py index bae0c1080..89c495700 100644 --- a/test/unit_test/headless/test_codegen_journal_gui.py +++ b/test/unit_test/headless/test_codegen_journal_gui.py @@ -23,8 +23,7 @@ def panel(app): view = JournalCandidatePanel() yield view view.cancel() - if view._handle is not None: - view._handle.wait(5) + idle(app, view) view.close() view.deleteLater() app.processEvents() @@ -32,10 +31,10 @@ def panel(app): def idle(app, panel): deadline = time.monotonic() + 5 - while panel._handle is not None and time.monotonic() < deadline: + while panel._task.running and time.monotonic() < deadline: app.processEvents() time.sleep(.005) - assert panel._handle is None + assert not panel._task.running def test_review_shows_code_diff_manifest_and_warnings_offscreen(journal, panel, app): @@ -131,13 +130,10 @@ def forbidden(*_args, **_kwargs): monkeypatch.setattr("je_auto_control.gui.journal_candidate_worker.generate_candidate_from_log", forbidden) with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): worker = JournalCandidateWorker(JournalCandidateTask(1, "generate", "private.jsonl", "selected")) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "error" - assert outcomes[0].candidate is None - worker.deleteLater() - app.processEvents() + import threading + outcome = worker(threading.Event()) + assert outcome.status == "error" + assert outcome.candidate is None def test_completed_export_is_not_relabelled_cancelled(journal, app, tmp_path, monkeypatch): @@ -157,13 +153,9 @@ def export(*args, **kwargs): return result monkeypatch.setattr(module, "write_candidate_archive", export) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "ok" + import threading + assert worker(threading.Event()).status == "ok" # stopped after the archive was committed assert output.exists() - worker.deleteLater() - app.processEvents() def test_close_cancels_generation_and_discards_late_result(journal, panel, app, monkeypatch): @@ -212,3 +204,34 @@ def test_owned_dialog_retranslates_and_releases_language_listener(app): owner.close() owner.deleteLater() app.processEvents() + + +def test_progress_shows_and_cancel_keeps_the_panel_busy_until_it_unwinds(journal, panel, app, monkeypatch): + import threading + from je_auto_control.gui import journal_candidate_worker as module + fixtures.append_step(journal, "kept") + reported, release = threading.Event(), threading.Event() + + def slow(*_args, observer=None, **_kwargs): + observer(100) + reported.set() + assert release.wait(5) + observer(101) # the next record boundary sees the stop + pytest.fail("the generation went past a stopped checkpoint") + + monkeypatch.setattr(module, "generate_candidate_from_log", slow) + panel._path.setText(str(journal.path)) + panel._run_id.setText("selected") + panel._start_generate() + assert reported.wait(5) + deadline = time.monotonic() + 5 + while panel._status_key != "progress" and time.monotonic() < deadline: + app.processEvents() + time.sleep(.005) + assert (panel._status_key, panel._status_value) == ("progress", "100") + panel.cancel() + assert panel._task.running and panel._status_key == "cancelling" + release.set() + idle(app, panel) + assert panel._status_key == "cancelled" + assert panel._candidate is None From e69c219350d8560d83103b3371297bd47c018770 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 14:19:56 +0800 Subject: [PATCH 091/161] Run the template candidate panel on the shared task The worker keeps its captured authority, its checkpoints before atomic writes and the rule that a committed transition reports success, but becomes a plain callable given the stop event and a progress report. --- CHANGELOG.md | 6 ++ Progress.md | 6 +- architecture_explore.md | 12 ++-- docs/updates/2026-11-b.md | 7 +++ docs/updates/README.md | 1 + .../gui/template_candidate_panel.py | 37 ++++++------ .../gui/template_candidate_worker.py | 31 +++++----- .../headless/test_template_candidate_gui.py | 60 +++++++++++++------ 8 files changed, 103 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5beaad13..2789ebfa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI internals: the template candidate panel (Self-Healing) runs on + `TabTask.start_until_stopped(..., reports=True)`. `TemplateCandidateWorker` is no longer a + `QObject`: it is called with the stop event and a report of `(request_id, count)` and returns + its `TemplateCandidateOutcome` (`run`, `finished`, `progress` and the panel's `_handle` / + `_worker` are gone; `_task` is the task). A committed acceptance still reports success. + - GUI internals: the journal candidate panel (Script Builder › review from journal) runs on `TabTask.start_until_stopped(..., reports=True)`. `JournalCandidateWorker` is no longer a `QObject`: it is called with the stop event and a report of `(request_id, count)` and returns diff --git a/Progress.md b/Progress.md index 4bd280749..308bd118a 100644 --- a/Progress.md +++ b/Progress.md @@ -544,9 +544,9 @@ F 還缺: USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)、 Admin Console 的健康輪詢與縮圖(U-20261114-21)、自我修復比對面板(U-20261114-22)、 - journal browser(U-20261114-23,`TabTask` 加上進度通道)、journal candidate 面板(U-20261114-24)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 - (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`、 - `template_candidate_panel`。 + journal browser(U-20261114-23,`TabTask` 加上進度通道)、journal candidate 面板(U-20261114-24)、 + template candidate 面板(U-20261114-25)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 + (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 8a8754b0d..347612432 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,903 | +| 程式碼總行數 | 235,909 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1328,8 +1328,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `_daemon_thread.py` | 79 | `DaemonThread`:`QThread` 的替代品,保留遠端桌面 worker 用到的介面(`start`/`run`/`isRunning`/`wait`/`requestInterruption`/`started`/`finished`),但 `run()` 跑在 daemon `threading.Thread` 上,刪除物件或程式結束都不會銷毀執行中的執行緒。 | | `_worker_thread.py` | 273 | `start_worker()`:在 daemon `threading.Thread` 上執行 `QObject` worker 的 `run()`(沒有 `QThread` 可被銷毀),並經由分頁擁有的中繼物件回報結果(回呼一律在 GUI 執行緒;worker 沒處理的例外也送到 `on_fail`);worker 留在模組登錄表直到 GUI 執行緒看到它結束,啟動失敗回復登記並保留原失敗;回傳 `WorkerHandle`(`isRunning()`);程式結束時先呼叫 worker 的 `request_stop()`,最多等 10 秒,仍在跑的隨行程結束。 | | `task_controller.py` | 270 | 共用 owner-bound task/typed outcome-progress;獨立 token、弱回呼、dispatch 身分更新與銷毀後結果隔離。工作綁定獨立 cancellation scope;其餘面板遷移另列進度。 | -| `template_candidate_panel.py` | 241 | 預覽原始/候選縮圖、檢視驗證並明確接受/回復。 | -| `template_candidate_worker.py` | 122 | 背景檔案操作、延後權限檢查與提交前取消;完成寫入不重標為取消。 | +| `template_candidate_panel.py` | 244 | 預覽原始/候選縮圖、檢視驗證並明確接受/回復。 | +| `template_candidate_worker.py` | 125 | 背景檔案操作、延後權限檢查與提交前取消;完成寫入不重標為取消。 | | `journal_candidate_worker.py` | 150 | 背景產碼、差異呈現、審閱匯出/匯入驗證、權限與取消。 | | `journal_candidate_panel.py` | 228 | 程式、差異、來源與排除項目的審閱;Actions 明確匯入與匯出。 | | `journal_candidate_dialog.py` | 97 | Recording Editor/Builder 共用模型外審閱視窗,保護編輯基準並隨擁有者關閉。 | @@ -1358,7 +1358,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | | vlm | `vlm_tab.py` | 150 | 用文字描述 UI 元素,交由模型定位。 | -| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 940 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | +| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 946 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,636 | +| `gui/` | 160 | 42,642 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,525** | **235,158** | +| **總計** | **1,525** | **235,164** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 852ec1904..0b373f405 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -471,3 +471,10 @@ - **Tests:** `test_codegen_journal_gui.py` calls the worker directly and waits on `_task`, and gains progress shown on the panel with Cancel keeping it busy until the generation unwinds and then *cancelled*. Codegen, journal, candidate, Script Builder, worker, dispose and Actions-menu tests: 735 passed, 9 skipped. - **Files:** `gui/journal_candidate_worker.py`, `gui/journal_candidate_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** the two panels named in `Progress.md` › F3. + +## U-20261114-25 · 2026-11-14 · The template candidate panel runs on the shared task · #done #gui #healing + +- **What:** the next `Progress.md` › F3 panel with its own worker. `TemplateCandidateWorker` (create, preview, verify, accept and revert a replacement template) keeps its captured context and deferred authority, its checkpoints before atomic writes, the rule that a transition already committed reports success even if a stop arrives after it, and one scrubbed terminal outcome; it is now a plain callable that `start_until_stopped(..., reports=True)` hands the stop event and a `(request_id, count)` report. The panel stays busy until cancelled work has unwound, and its destruction sets the stop event through handle cancellation. +- **Tests:** `test_template_candidate_gui.py` calls the worker directly and waits on `_task`, and gains progress shown on the panel with Cancel keeping it busy until verification unwinds and then *cancelled*. Template, healing, worker, dispose and Actions-menu tests: 390 passed, 8 skipped. +- **Files:** `gui/template_candidate_worker.py`, `gui/template_candidate_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `config_sync_tab`, named in `Progress.md` › F3. diff --git a/docs/updates/README.md b/docs/updates/README.md index 3005473d5..4cbd9468b 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-25 | 2026-11-14 | The template candidate panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | | U-20261114-24 | 2026-11-14 | The journal candidate panel runs on the shared task | #done #gui #codegen | [2026-11-b](2026-11-b.md) | | U-20261114-23 | 2026-11-14 | The journal browser runs on the shared task, which now relays progress | #done #gui #journal | [2026-11-b](2026-11-b.md) | | U-20261114-22 | 2026-11-14 | The self-healing comparison panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/template_candidate_panel.py b/je_auto_control/gui/template_candidate_panel.py index b895ae1d6..7c08b2b39 100644 --- a/je_auto_control/gui/template_candidate_panel.py +++ b/je_auto_control/gui/template_candidate_panel.py @@ -10,7 +10,7 @@ ) from je_auto_control.gui._i18n_helpers import TranslatableMixin -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.template_candidate_worker import ( CandidateOperation, TemplateCandidateOutcome, TemplateCandidateRequest, TemplateCandidateWorker, @@ -36,8 +36,12 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._generation = 0 self._updating = False self._operation: CandidateOperation = "preview" - self._handle: Optional[WorkerHandle] = None - self._worker: Optional[TemplateCandidateWorker] = None + # Cancel and the view's destruction stop the work at its next checkpoint; it stays busy until then. + self._task = TabTask(self) + self._task.result.connect(self._received) + self._task.error.connect(self._task_failed) + self._task.progress.connect(self._progress) + self._task.finished.connect(self._thread_done) self._template, self._candidate, self._bundle, self._dataset = (QLineEdit() for _ in range(4)) self._revision = QLineEdit() self._revision.setReadOnly(True) @@ -122,7 +126,7 @@ def _dataset_changed(self, *_args) -> None: self._set_status("idle") def _browse(self, name: str) -> None: - if self._handle is not None: + if self._task.running: return try: authorize_command("AC_template_candidate_preview") @@ -141,7 +145,7 @@ def _browse(self, name: str) -> None: control.setText(path) def _start(self, operation: CandidateOperation) -> None: - if self._handle is not None: + if self._task.running: return if operation in ("accept", "revert") and not self._revision.text(): self._set_status("review_required") @@ -153,28 +157,25 @@ def _start(self, operation: CandidateOperation) -> None: self._candidate.text().strip(), self._bundle.text().strip(), self._dataset.text().strip(), self._revision.text(), float(self._threshold.value())) - worker = TemplateCandidateWorker(request) - self._worker = worker - worker.progress.connect(self._progress) - # pylint: disable-next=no-member # reason: PySide binds this signal at runtime - self.destroyed.connect(worker.request_stop) self._set_busy(True) self._set_status("running") - self._handle = start_worker(self, worker, on_done=self._received, - on_thread_done=self._thread_done, on_fail=self._failed) + self._task.start_until_stopped(TemplateCandidateWorker(request), reports=True) def cancel(self) -> None: """Request cooperative stop; an already committed transition remains committed.""" - if self._worker is not None: - self._worker.request_stop() + if self._task.running: + self._task.stop() self._set_status("cancelling") def _set_busy(self, busy: bool) -> None: for control in (self._template, self._candidate, self._bundle, self._dataset, self._threshold): control.setEnabled(not busy) - @Slot(int, int) - def _progress(self, request_id: int, count: int) -> None: + @Slot(object) + def _progress(self, value: object) -> None: + if not isinstance(value, tuple) or len(value) != 2: # the worker reports (request_id, count) + return + request_id, count = value if request_id == self._generation and self._status_key != "cancelling": self._set_status("progress", str(count)) @@ -220,8 +221,10 @@ def _show_preview(self, outcome: TemplateCandidateOutcome) -> None: label.setPixmap(image.scaled(400, 240, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) + def _task_failed(self, error: object) -> None: + self._failed(str(error)) + def _thread_done(self) -> None: - self._handle = self._worker = None self._set_busy(False) if self._status_key in ("running", "progress", "cancelling"): self._set_status("interrupted") diff --git a/je_auto_control/gui/template_candidate_worker.py b/je_auto_control/gui/template_candidate_worker.py index 724036168..46714345a 100644 --- a/je_auto_control/gui/template_candidate_worker.py +++ b/je_auto_control/gui/template_candidate_worker.py @@ -4,9 +4,7 @@ from contextvars import copy_context from dataclasses import dataclass from threading import Event -from typing import Literal, Optional - -from PySide6.QtCore import QObject, Signal, Slot +from typing import Callable, Literal, Optional from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.secret_scope import scrub_secret_text @@ -51,21 +49,26 @@ class TemplateCandidateOutcome: error: str = "" -class TemplateCandidateWorker(QObject): - """Run under captured authority; cancellation checkpoints stop before atomic writes.""" +def _no_report(_value: object) -> None: + """Progress sink for a worker run without one.""" + + +class TemplateCandidateWorker: + """Run under captured authority; cancellation checkpoints stop before atomic writes. - finished = Signal(object) - progress = Signal(int, int) + Built on the GUI thread, which captures that context and authority, and + called on a worker thread with the stop event and a progress report; each + report is ``(request_id, count)`` at every checkpoint. + """ def __init__(self, request: TemplateCandidateRequest) -> None: - super().__init__() self._request = request self._stop = Event() + self._report: Callable[[object], None] = _no_report self._context = copy_context() self._authority = DeferredAuthorization.capture() self._last_count = 0 - @Slot() def request_stop(self) -> None: """Request cooperative stop before the next candidate operation checkpoint.""" self._stop.set() @@ -74,12 +77,12 @@ def _checkpoint(self, count: int) -> None: if self._stop.is_set(): raise CancelledError() self._last_count = max(self._last_count, count) - self.progress.emit(self._request.request_id, self._last_count) + self._report((self._request.request_id, self._last_count)) - @Slot() - def run(self) -> None: - """Emit one outcome; a successful committed write is never relabelled cancelled afterward.""" - self.finished.emit(self._context.run(self._perform)) + def __call__(self, stop_event: Event, report: Callable[[object], None] = _no_report) -> TemplateCandidateOutcome: + """Return one outcome; a successful committed write is never relabelled cancelled afterward.""" + self._stop, self._report = stop_event, report + return self._context.run(self._perform) def _perform(self) -> TemplateCandidateOutcome: request = self._request diff --git a/test/unit_test/headless/test_template_candidate_gui.py b/test/unit_test/headless/test_template_candidate_gui.py index ee8100b77..fdb3ac66c 100644 --- a/test/unit_test/headless/test_template_candidate_gui.py +++ b/test/unit_test/headless/test_template_candidate_gui.py @@ -27,18 +27,17 @@ def panel(app): view = TemplateCandidatePanel() yield view view.cancel() - if view._handle is not None: - view._handle.wait(5) + until_idle(app, view) view.deleteLater() app.processEvents() def until_idle(app, panel): deadline = time.monotonic() + 5 - while panel._handle is not None and time.monotonic() < deadline: + while panel._task.running and time.monotonic() < deadline: app.processEvents() time.sleep(0.005) - assert panel._handle is None + assert not panel._task.running def test_actions_complete_preview_verify_accept_and_revert(panel, app, revision_files): @@ -75,7 +74,7 @@ def test_actions_complete_preview_verify_accept_and_revert(panel, app, revision_ def test_preview_is_required_before_gui_acceptance(panel): panel._start("accept") - assert panel._handle is None + assert not panel._task.running assert panel._status_key == "review_required" @@ -101,12 +100,10 @@ def forbidden(*_args, **_kwargs): request = TemplateCandidateRequest(1, "preview", "", "", "private.json", "", "", 0.9) with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): worker = TemplateCandidateWorker(request) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "error" - assert outcomes[0].data is None - worker.deleteLater() + import threading + outcome = worker(threading.Event()) + assert outcome.status == "error" + assert outcome.data is None def test_committed_acceptance_is_not_relabelled_cancelled(app, monkeypatch, revision_files): @@ -122,13 +119,11 @@ def committed(*args, **kwargs): return result monkeypatch.setattr("je_auto_control.gui.template_candidate_worker.accept_template_candidate", committed) - outcomes = [] - worker.finished.connect(outcomes.append) - worker.run() - assert outcomes[0].status == "ok" - assert outcomes[0].data["changed"] is True + import threading + outcome = worker(threading.Event()) # stopped after the acceptance was committed + assert outcome.status == "ok" + assert outcome.data["changed"] is True assert target.read_bytes() == (FIXTURES / "new.png").read_bytes() - worker.deleteLater() def test_close_cancels_active_read_and_discards_late_result(panel, app, monkeypatch, revision_files): @@ -156,3 +151,34 @@ def blocked(*args, **kwargs): until_idle(app, panel) assert panel._details.toPlainText() == "" assert panel._status_key != "eligible" + + +def test_progress_shows_and_cancel_keeps_the_panel_busy_until_it_unwinds(panel, app, monkeypatch, revision_files): + import threading + from je_auto_control.gui import template_candidate_worker as module + _, bundle, dataset = revision_files + create(revision_files) + reported, release = threading.Event(), threading.Event() + + def slow(*_args, observer=None, **_kwargs): + observer(3) + reported.set() + assert release.wait(5) + observer(4) # the next checkpoint sees the stop + pytest.fail("verification went past a stopped checkpoint") + + monkeypatch.setattr(module, "verify_template_candidate", slow) + panel._bundle.setText(str(bundle)) + panel._dataset.setText(str(dataset)) + panel._start("verify") + assert reported.wait(5) + deadline = time.monotonic() + 5 + while panel._status_key != "progress" and time.monotonic() < deadline: + app.processEvents() + time.sleep(0.005) + assert (panel._status_key, panel._status_value) == ("progress", "3") + panel.cancel() + assert panel._task.running and panel._status_key == "cancelling" + release.set() + until_idle(app, panel) + assert panel._status_key == "cancelled" From 7d6195156f5bd134a45488fa3ac4208490278f1e Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 14:26:28 +0800 Subject: [PATCH 092/161] Run Config Sync on the shared task, leaving no panel on a bare worker The worker keeps its refreshed authority, secret masking and guarded delivery, but becomes a plain callable given the stop event. No GUI module outside the task controllers calls start_worker any more. --- CHANGELOG.md | 5 ++ Progress.md | 14 +--- architecture_explore.md | 10 +-- docs/updates/2026-11-b.md | 7 ++ docs/updates/README.md | 1 + je_auto_control/gui/config_sync_tab.py | 24 +++--- je_auto_control/gui/config_sync_worker.py | 21 +++-- .../headless/test_config_sync_gui.py | 79 +++++++------------ .../headless/test_sync_profile_gui.py | 14 ++-- 9 files changed, 81 insertions(+), 94 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2789ebfa4..f8884f09a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI internals: the Config Sync tab runs on `TabTask.start_until_stopped`. `ConfigSyncWorker` + is no longer a `QObject`: it is called with the stop event and returns its `SyncUIOutcome`; + the tab keeps it for `deliver` (`run`, `finished` and the tab's `_handle` are gone; `_task` + is the task). No GUI module outside the task controllers calls `start_worker` any more. + - GUI internals: the template candidate panel (Self-Healing) runs on `TabTask.start_until_stopped(..., reports=True)`. `TemplateCandidateWorker` is no longer a `QObject`: it is called with the stop event and a report of `(request_id, count)` and returns diff --git a/Progress.md b/Progress.md index 308bd118a..973ae92ed 100644 --- a/Progress.md +++ b/Progress.md @@ -536,17 +536,9 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 -- **F3** 還缺共用 `TaskController` 接入其餘面板、backend timeout/cancel 傳遞與關閉生命週期遷移, - 包含 Quick Connect 的同步啟停、已進入傳輸的取消與同頁 session generation 隔離。 - AI Locator 與 LLM Planner 的 Plan(U-20261114-13)、兩個 USB 裝置列舉(U-20261114-14)、 - Email Triggers 的 Poll Now(U-20261114-15)、Admin Console 的 broadcast(U-20261114-16,維護者 2026-11-14 決定: - 停止時逐台回報已執行或未送出)、USB Browser 的 Fetch/Open(U-20261114-17)、 - USB passthrough 面板的 List/Open/遠端抓取(U-20261114-18)、Computer Use 的執行(U-20261114-19, - `TabTask.start_until_stopped`:Stop 後等工作真的結束才空出分頁)、DAG Runner(U-20261114-20)、 - Admin Console 的健康輪詢與縮圖(U-20261114-21)、自我修復比對面板(U-20261114-22)、 - journal browser(U-20261114-23,`TabTask` 加上進度通道)、journal candidate 面板(U-20261114-24)、 - template candidate 面板(U-20261114-25)已遷移。仍直接使用 `start_worker` 的面板都已有自己的取消 - (Cancel 動作、關閉時 `request_stop`、generation 擋掉舊結果),只差改用共用 controller:`config_sync_tab`。 +- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移,包含 Quick Connect 的同步啟停、 + 已進入傳輸的取消與同頁 session generation 隔離。分頁的背景工作已全部改走共用 `TaskController` + (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 diff --git a/architecture_explore.md b/architecture_explore.md index 347612432..4aa277d32 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,909 | +| 程式碼總行數 | 235,914 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1314,8 +1314,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `workspace_details.py` | 97 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 171 | Explicit transfer requests and consent preparation with revision-bound background observations. | -| `config_sync_worker.py` | 131 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | -| `config_sync_tab.py` | 423 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | +| `config_sync_worker.py` | 130 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | +| `config_sync_tab.py` | 429 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | | `_auto_click_tab.py` | 321 | 獨立自動點擊分頁;快照工作參數,以 TabTask 執行與取消。 | | `_screenshot_tab.py` | 180 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | | `_image_detect_tab.py` | 158 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | @@ -1543,7 +1543,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,642 | +| `gui/` | 160 | 42,647 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1564,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,525** | **235,164** | +| **總計** | **1,525** | **235,169** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 0b373f405..9360ecf5f 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -478,3 +478,10 @@ - **Tests:** `test_template_candidate_gui.py` calls the worker directly and waits on `_task`, and gains progress shown on the panel with Cancel keeping it busy until verification unwinds and then *cancelled*. Template, healing, worker, dispose and Actions-menu tests: 390 passed, 8 skipped. - **Files:** `gui/template_candidate_worker.py`, `gui/template_candidate_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `config_sync_tab`, named in `Progress.md` › F3. + +## U-20261114-26 · 2026-11-14 · Config Sync runs on the shared task; no panel uses a bare worker · #done #gui #sync + +- **What:** the last `Progress.md` › F3 panel on a bare worker. `ConfigSyncWorker` keeps everything that made it safe -- the caller's context and DRIVE authority captured on the GUI thread and refreshed at every core checkpoint, the secret masking scope, committed writes staying successful after a late stop, and `deliver`, which applies a result on the GUI thread under the refreshed authority and refuses a stopped `preferences` delivery -- but is now a plain callable that `start_until_stopped` hands the stop event. The tab keeps the worker until the task's `finished` so `deliver` still runs against it, stays busy until a cancelled request has unwound, and its destruction sets the stop event through handle cancellation. With this, no GUI module outside `tab_task_controller.py` and `task_controller.py` calls `start_worker`; the F3 entry in `Progress.md` keeps only the backend cancel propagation and lifecycle work. +- **Tests:** `test_config_sync_gui.py` and `test_sync_profile_gui.py` call the worker with its own stop event (so a `request_stop()` made before the call still counts) and wait on `_task`; the cancel test now also checks a second `begin` while the first unwinds says *busy*. Sync, config, worker, dispose, main-window and Actions-menu tests: 795 passed, 43 skipped. +- **Files:** `gui/config_sync_worker.py`, `gui/config_sync_tab.py`, the tests, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › F3 (backend cancel propagation, Quick Connect lifecycle, session generation isolation). diff --git a/docs/updates/README.md b/docs/updates/README.md index 4cbd9468b..a59f7e479 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-26 | 2026-11-14 | Config Sync runs on the shared task; no panel uses a bare worker | #done #gui #sync | [2026-11-b](2026-11-b.md) | | U-20261114-25 | 2026-11-14 | The template candidate panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | | U-20261114-24 | 2026-11-14 | The journal candidate panel runs on the shared task | #done #gui #codegen | [2026-11-b](2026-11-b.md) | | U-20261114-23 | 2026-11-14 | The journal browser runs on the shared task, which now relays progress | #done #gui #journal | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/config_sync_tab.py b/je_auto_control/gui/config_sync_tab.py index 86c92fc45..ac8bf6757 100644 --- a/je_auto_control/gui/config_sync_tab.py +++ b/je_auto_control/gui/config_sync_tab.py @@ -14,7 +14,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.adaptive.responsive import ResponsiveBox, fit_columns from je_auto_control.gui.adaptive.surfaces import Card, set_role -from je_auto_control.gui._worker_thread import WorkerHandle, start_worker +from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.config_sync_worker import ConfigSyncWorker, SyncUIOutcome, SyncUIRequest from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.utils.config_sync.adapter_schema import AdapterKind, KINDS @@ -45,7 +45,11 @@ def __init__(self, parent: Optional[QWidget] = None, *, path_policy: Optional[Pa self._policy = path_policy self._generation = 0 self._worker: Optional[ConfigSyncWorker] = None - self._handle: Optional[WorkerHandle] = None + # Cancel and the tab's destruction stop the request at its next checkpoint; it stays busy until then. + self._task = TabTask(self) + self._task.result.connect(self._received) + self._task.error.connect(self._task_failed) + self._task.finished.connect(self._thread_done) self._reviewed: Optional[dict[str, dict[str, object]]] = None self._row_ids: list[str] = [] self._last_sync: object = None @@ -230,7 +234,7 @@ def _resolution_options(self) -> dict[str, object]: def begin(self, operation: str) -> None: """Snapshot one explicit menu operation and run it outside the GUI thread.""" - if self._handle is not None: + if self._task.running: self._set_status('busy') return try: @@ -245,15 +249,14 @@ def begin(self, operation: str) -> None: self._value.setEnabled(False) self._deleted.setEnabled(False) self._set_status('running') - self._handle = start_worker(self, self._worker, on_done=self._received, - on_thread_done=self._thread_done, on_fail=self._failed) + self._task.start_until_stopped(self._worker) except (AutoControlException, ValueError, TypeError, RuntimeError) as error: self._failed(scrub_secret_text(str(error))) def cancel(self) -> None: """Request cooperative stop; durable completed operations keep their result.""" - if self._worker is not None: - self._worker.request_stop() + if self._task.running: + self._task.stop() self._set_status('cancelling') def _received(self, outcome: SyncUIOutcome) -> None: @@ -324,7 +327,7 @@ def _inspect_loaded_kind(self, profile: LoadedSyncProfile) -> None: self._set_status('done') def _use_loaded_profile(self, operation: Callable[[LoadedSyncProfile], None]) -> None: - if self._handle is not None: + if self._task.running: self._set_status('busy') return try: @@ -405,8 +408,11 @@ def _failed(self, error: str) -> None: self._details.clear() self._set_status('error', scrub_secret_text(error)) + def _task_failed(self, error: object) -> None: + self._failed(str(error)) + def _thread_done(self) -> None: - self._handle = self._worker = None + self._worker = None for control in (self._form, self._load_form, self._heads, self._value, self._deleted): control.setEnabled(True) if self._status_key in {'running', 'cancelling'}: diff --git a/je_auto_control/gui/config_sync_worker.py b/je_auto_control/gui/config_sync_worker.py index 67d8905ac..fccdb0c32 100644 --- a/je_auto_control/gui/config_sync_worker.py +++ b/je_auto_control/gui/config_sync_worker.py @@ -8,8 +8,6 @@ from threading import Event from typing import Callable, Literal, Optional, cast -from PySide6.QtCore import QObject, Signal, Slot - from je_auto_control.utils.config_sync.contract import ConfigSyncError, _encoded from je_auto_control.utils.config_sync.profile_commands import profile_parameters from je_auto_control.utils.config_sync.profile_load import load_sync_profile @@ -55,20 +53,21 @@ def _object(text: str) -> dict[str, object]: return cast(dict[str, object], value) -class ConfigSyncWorker(QObject): - """Refresh captured DRIVE authority at every core checkpoint and again before GUI delivery.""" +class ConfigSyncWorker: + """Refresh captured DRIVE authority at every core checkpoint and again before GUI delivery. - finished = Signal(object) + Built on the GUI thread, which captures that context and authority, called + on a worker thread with the stop event, and kept by the tab so that + :meth:`deliver` applies the result under the same authority. + """ def __init__(self, request: SyncUIRequest, *, path_policy: Optional[PathPolicy] = None) -> None: - super().__init__() self._request = request self._stop = Event() self._context = copy_context() self._authority = DeferredAuthorization.capture() self._policy = path_policy - @Slot() def request_stop(self) -> None: """Stop before the next checkpoint; an already committed write is not rolled back.""" self._stop.set() @@ -93,10 +92,10 @@ def apply() -> None: callback() self._context.run(apply) - @Slot() - def run(self) -> None: - """Emit one scrubbed outcome after releasing the captured execution context.""" - self.finished.emit(self._context.run(self._perform)) + def __call__(self, stop_event: Event) -> SyncUIOutcome: + """Return one scrubbed outcome after releasing the captured execution context.""" + self._stop = stop_event + return self._context.run(self._perform) def _perform(self) -> SyncUIOutcome: request = self._request diff --git a/test/unit_test/headless/test_config_sync_gui.py b/test/unit_test/headless/test_config_sync_gui.py index 1b5c92765..41dbd575e 100644 --- a/test/unit_test/headless/test_config_sync_gui.py +++ b/test/unit_test/headless/test_config_sync_gui.py @@ -34,26 +34,22 @@ def panel(app, tmp_path, monkeypatch): view = ConfigSyncTab() yield view view.cancel() - if view._handle is not None: - assert view._handle.wait(5) + idle(app, view) view.deleteLater() app.processEvents() def idle(app, view): deadline = time.monotonic() + 10 - while view._handle is not None and time.monotonic() < deadline: + while view._task.running and time.monotonic() < deadline: app.processEvents() time.sleep(0.005) - assert view._handle is None + assert not view._task.running def run(worker): - results = [] - worker.finished.connect(results.append) - worker.run() - assert len(results) == 1 - return results[0] + # The worker's own event, so a request_stop() made before the call still counts. + return worker(worker._stop) def test_constructing_sync_is_inert_and_local_actions_run_off_the_gui_thread(panel, app, tmp_path, monkeypatch): @@ -90,7 +86,7 @@ def test_review_selection_resolves_all_heads_and_configuration_change_discards_r panel._configuration.setPlainText(json.dumps(config)) panel._kind.setCurrentText('workspace') panel.begin('preferences') - assert panel._handle is None + assert not panel._task.running assert panel._status_key == 'error' panel.begin('review') idle(app, panel) @@ -154,8 +150,7 @@ def test_loopback_sync_does_not_apply_preferences_until_explicit_reviewed_action assert settings.value('workspace/theme') is None finally: view.cancel() - if view._handle is not None: - view._handle.wait(5) + idle(app, view) window.close() window.deleteLater() app.processEvents() @@ -194,6 +189,9 @@ def delayed(*_args, **_kwargs): panel.begin('preferences') assert entered.wait(5) panel.cancel() + assert panel._task.running # busy until the request has unwound + panel.begin('preferences') + assert panel._status_key == 'busy' release.set() idle(app, panel) assert applied == [] @@ -220,15 +218,12 @@ def committed(*_args, **_kwargs): return {'captured': 1} monkeypatch.setattr(config_sync_worker, '_sync_workspace', committed) - try: - assert run(worker).status == 'ok' - with pytest.raises(CancelledError): - worker.deliver(lambda: pytest.fail('stopped preferences must not be delivered'), require_active=True) - delivered = [] - worker.deliver(lambda: delivered.append(context.get())) - assert delivered == ['registrant'] - finally: - worker.deleteLater() + assert run(worker).status == 'ok' + with pytest.raises(CancelledError): + worker.deliver(lambda: pytest.fail('stopped preferences must not be delivered'), require_active=True) + delivered = [] + worker.deliver(lambda: delivered.append(context.get())) + assert delivered == ['registrant'] def test_viewer_and_pre_cancelled_workers_do_not_enter_core(app, monkeypatch): @@ -237,12 +232,8 @@ def test_viewer_and_pre_cancelled_workers_do_not_enter_core(app, monkeypatch): viewer = ConfigSyncWorker(SyncUIRequest(1, 'status', '{}')) stopped = ConfigSyncWorker(SyncUIRequest(2, 'capture', '{}')) stopped.request_stop() - try: - assert run(viewer).status == 'error' - assert run(stopped).status == 'cancelled' - finally: - viewer.deleteLater() - stopped.deleteLater() + assert run(viewer).status == 'error' + assert run(stopped).status == 'cancelled' def test_network_failure_masks_declared_secret_while_local_worker_never_resolves_it(app, monkeypatch): @@ -263,18 +254,14 @@ def failure(*_args, **_kwargs): monkeypatch.setattr(config_sync_worker, '_sync_workspace', failure) network = ConfigSyncWorker(SyncUIRequest(1, 'sync', '{}', '{"secret_env":"SYNC_UI_TEST_SECRET"}')) local = ConfigSyncWorker(SyncUIRequest(2, 'status', '{}', '{"secret_env":"SYNC_UI_TEST_SECRET"}')) - try: - outcome = run(network) - assert outcome.status == 'error' - assert secret not in outcome.error - assert '***' in outcome.error - assert accesses == ['SYNC_UI_TEST_SECRET'] - accesses.clear() - assert run(local).status == 'error' - assert accesses == [] - finally: - network.deleteLater() - local.deleteLater() + outcome = run(network) + assert outcome.status == 'error' + assert secret not in outcome.error + assert '***' in outcome.error + assert accesses == ['SYNC_UI_TEST_SECRET'] + accesses.clear() + assert run(local).status == 'error' + assert accesses == [] def test_live_store_revocation_blocks_checkpoint_and_queued_delivery(app, tmp_path, monkeypatch): @@ -289,12 +276,9 @@ def revoked(*_args, **kwargs): pytest.fail('revoked checkpoint must stop') monkeypatch.setattr(config_sync_worker, '_sync_workspace', revoked) - try: - assert run(worker).status == 'error' - with pytest.raises(AutoControlException): - worker.deliver(lambda: pytest.fail('revoked delivery must stop')) - finally: - worker.deleteLater() + assert run(worker).status == 'error' + with pytest.raises(AutoControlException): + worker.deliver(lambda: pytest.fail('revoked delivery must stop')) @pytest.mark.parametrize('text', ['[]', '{"value":NaN}', '{' * 1500, ' ' * (1024 * 1024 + 1)], @@ -302,7 +286,4 @@ def revoked(*_args, **kwargs): def test_worker_rejects_invalid_or_unbounded_json_before_core_io(app, monkeypatch, text): monkeypatch.setattr(config_sync_worker, '_sync_workspace', lambda *_a, **_k: pytest.fail('invalid input')) worker = ConfigSyncWorker(SyncUIRequest(1, 'status', text)) - try: - assert run(worker).status == 'error' - finally: - worker.deleteLater() + assert run(worker).status == 'error' diff --git a/test/unit_test/headless/test_sync_profile_gui.py b/test/unit_test/headless/test_sync_profile_gui.py index 72e9070bd..c5c5fe6c7 100644 --- a/test/unit_test/headless/test_sync_profile_gui.py +++ b/test/unit_test/headless/test_sync_profile_gui.py @@ -36,8 +36,7 @@ def window(app, tmp_path, monkeypatch): yield view panel = view.auto_control_gui_widget.tab_registry.open('config_sync') panel.cancel() - if panel._handle is not None: - assert panel._handle.wait(5) + idle(app, panel) view.close() view.deleteLater() app.processEvents() @@ -177,13 +176,10 @@ def committed(*args, **kwargs): return profile monkeypatch.setattr(config_sync_worker, 'load_sync_profile', committed) - try: - outcome = run(worker) - assert outcome.status == 'ok' - assert outcome.profile.directory.is_dir() - assert outcome.profile.hotkeys[0].enabled is False - finally: - worker.deleteLater() + outcome = run(worker) + assert outcome.status == 'ok' + assert outcome.profile.directory.is_dir() + assert outcome.profile.hotkeys[0].enabled is False @pytest.mark.parametrize('command,parameters', [('AC_literal', {}), From 4187713f98ac833d42cb85b5d1ebcbeb2e3724d5 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 15:06:41 +0800 Subject: [PATCH 093/161] Show every page's background work in Execution details Only Diagnostics published execution details. Every page's background work now runs on TabTask, so the task publishes it for the page it runs on: running, stopping, then succeeded, cancelled or the error, with reported progress. Also fix the thumbnail probe that still read the attribute removed when the poll became a task. --- CHANGELOG.md | 7 + Progress.md | 2 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 13 +- .../doc/new_features/v223_features_doc.rst | 8 +- .../Zh/doc/new_features/v223_features_doc.rst | 5 +- docs/updates/2026-11-b.md | 9 ++ docs/updates/README.md | 1 + je_auto_control/gui/_tab_task.py | 37 ++++- je_auto_control/gui/_task_details.py | 111 +++++++++++++ je_auto_control/gui/admin_console_tab.py | 2 +- je_auto_control/gui/workspace.py | 11 +- je_auto_control/gui/workspace_details.py | 21 ++- pyproject.toml | 1 + .../headless/test_r3_gui_thread_marshal.py | 11 +- .../headless/test_tab_task_details.py | 146 ++++++++++++++++++ 18 files changed, 364 insertions(+), 27 deletions(-) create mode 100644 je_auto_control/gui/_task_details.py create mode 100644 test/unit_test/headless/test_tab_task_details.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f8884f09a..b56187de3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- GUI: every page that runs background work through `TabTask` publishes it to **View → + Execution details**: running, stopping, then succeeded, cancelled or error (with the error + text, or the timeout message), with reported progress. `TabTask(owner, details=False)` opts + out (the Admin Console's thumbnail timer does). New `gui/_task_details.py`; + `workspace_details.details_sources()` announces sources created after a view bound to a page, + and `WorkspaceShell` rebinds to them. + - GUI internals: the Config Sync tab runs on `TabTask.start_until_stopped`. `ConfigSyncWorker` is no longer a `QObject`: it is called with the stop event and returns its `SyncUIOutcome`; the tab keeps it for `deliver` (`run`, `finished` and the tab's `_handle` are gone; `_task` diff --git a/Progress.md b/Progress.md index 973ae92ed..79342aa92 100644 --- a/Progress.md +++ b/Progress.md @@ -532,7 +532,7 @@ D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製 H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 F 還缺: -- **F2 其餘**:Diagnostics 以外面板的執行詳情,以及各面板的空白/錯誤/permission states 尚未全面交付。 +- **F2 其餘**:各面板的空白/錯誤/permission states 尚未全面交付(執行詳情已由 `TabTask` 為所有背景工作的頁面發布,U-20261114-27)。 - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 diff --git a/README.md b/README.md index 04cd78e93..915bda920 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ Auto Click, Record and Script Executor own their controls and background tasks. Of the three tabs open at start, only Record is built then; Script Builder and Remote Desktop are built the first time they are selected, which roughly halves start-up time and memory. -View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there; other pages explicitly say when details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. +View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there, and so does every other page that runs work in the background (a model request, a USB listing, a broadcast, a DAG run, a journal read): running, stopping, then completed, cancelled or the error, with progress where the work reports it. A page that has run nothing yet says details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index ad4780ff5..fe34c791d 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -43,7 +43,7 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, 启动时打开的三个标签页只先创建 Record;Script Builder 与 Remote Desktop 在第一次被选中时才创建,启动时间与内存约减半。 -View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态;其他分页尚未提供时会明确显示。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 +View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态,其他在后台执行工作的分页(模型请求、USB 列举、广播、DAG 执行、日志读取)也会:执行中、停止中,然后是完成、已取消或错误,工作有回报进度时一并显示。尚未执行过工作的分页会明确显示没有详情。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 26eec4106..25772e369 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -43,7 +43,7 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, 啟動時開著的三個分頁只先建立 Record;Script Builder 與 Remote Desktop 在第一次被選取時才建立,啟動時間與記憶體約減半。 -View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態;其他分頁尚未提供時會明確顯示。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 +View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態,其他在背景執行工作的分頁(模型請求、USB 列舉、廣播、DAG 執行、日誌讀取)也會:執行中、停止中,然後是完成、已取消或錯誤,工作有回報進度時一併顯示。尚未執行過工作的分頁會明確顯示沒有詳情。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 diff --git a/architecture_explore.md b/architecture_explore.md index 4aa277d32..74eafb0ec 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,537 | -| 程式碼總行數 | 235,914 | +| Python 模組總數(含周邊子專案) | 1,538 | +| 程式碼總行數 | 236,080 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1310,8 +1310,9 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `adaptive/overlay.py` | 102 | A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed. `OverlayDrawer`:Escape 或點擊遮罩關閉。 | | `_arrow_icons.py` | 76 | Chevrons for drop-down lists and spin boxes, drawn in code and handed to the style sheet. 以導覽列的線條圖示畫出、依主題色快取成檔案;寫不進快取時不放置子控制項,保留樣式原生箭頭。 | | `adaptive_window.py` | 179 | Rearrange the main window's navigation and details panes as the window's width class changes. `AdaptiveWindowLayout`:expanded 兩側停靠;medium 詳情改抽屜;compact 導覽改圖示欄+抽屜。「想要停靠導覽」與寬度是否允許分開記錄,窄視窗不會改寫使用者偏好。 | -| `workspace.py` | 567 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | -| `workspace_details.py` | 97 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 提供第一個實際 publisher;僅訂閱目前頁面。 | +| `workspace.py` | 576 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | +| `workspace_details.py` | 116 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 與每個 `TabTask` 都是 publisher;僅訂閱目前頁面,`details_sources()` 通知綁定後才建立的來源。 | +| `_task_details.py` | 111 | Execution details a TabTask publishes for the page it runs on. 由子面板往上找出工作區的分頁、第一次執行時建立來源,發布執行中/停止中/完成/已取消/錯誤與回報的進度。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 171 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 130 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | @@ -1543,7 +1544,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 160 | 42,647 | +| `gui/` | 161 | 42,813 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1564,7 +1565,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,525** | **235,169** | +| **總計** | **1,526** | **235,335** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 7e77006f9..e38ea0336 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -203,7 +203,13 @@ Execution details **View → Execution details** (``Ctrl+Shift+D``) expands a scrollable right pane. It starts collapsed. Diagnostics publishes actual run progress, stop requests, -results and errors; pages without a publisher show an explicit unavailable state. +results and errors, and so does every page that runs background work through a +``TabTask`` (``je_auto_control.gui._tab_task``) -- also when the work belongs to +a panel inside the page: *Running*, *Stopping* while a stopped run unwinds, +then *Completed*, *Cancelled* or *Error* with the error text (a deadline reads +*Took too long and was stopped.*), and progress where the work reports it. +Periodic refreshes, such as the Admin Console's thumbnails, do not publish. A +page that has not run anything shows an explicit unavailable state. Switching or closing a page disconnects its updates, including queued old results. The pane does not start work or own cancellation. Use the page's Actions menu. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index 8e79d5751..25c9a600c 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -194,7 +194,10 @@ Remote Desktop 生命週期 ~~~~~~~~ **View → 執行詳情** (``Ctrl+Shift+D``)展開可捲動的右側詳情,初始為收合。 -診斷分頁提供實際執行進度、停止要求、結果與錯誤;未提供詳情的分頁會明確顯示。 +診斷分頁提供實際執行進度、停止要求、結果與錯誤;其他透過 ``TabTask``\ (``je_auto_control.gui._tab_task``\ ) +執行背景工作的分頁也會提供,工作屬於頁面內的子面板時亦同:*執行中*、已停止但仍在收尾時為 *停止中*, +之後為 *完成*、*已取消* 或附錯誤文字的 *錯誤*\ (超過期限顯示「Took too long and was stopped.」的對應翻譯), +工作有回報進度時一併顯示。週期性更新(例如 Admin Console 的縮圖)不會發布。尚未執行過工作的分頁會明確顯示沒有詳情。 切換或關閉分頁會斷開更新,包含已排隊的舊結果。詳情不啟動工作,也不持有取消權限; 操作仍使用分頁的 Actions 選單。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 9360ecf5f..16a59dbd9 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -485,3 +485,12 @@ - **Tests:** `test_config_sync_gui.py` and `test_sync_profile_gui.py` call the worker with its own stop event (so a `request_stop()` made before the call still counts) and wait on `_task`; the cancel test now also checks a second `begin` while the first unwinds says *busy*. Sync, config, worker, dispose, main-window and Actions-menu tests: 795 passed, 43 skipped. - **Files:** `gui/config_sync_worker.py`, `gui/config_sync_tab.py`, the tests, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › F3 (backend cancel propagation, Quick Connect lifecycle, session generation isolation). + +## U-20261114-27 · 2026-11-14 · Every page that runs background work reports it in Execution details · #done #gui #workspace + +- **What:** half of `Progress.md` › F2 *其餘*: execution details for the pages other than Diagnostics. With every page's background work on `TabTask` (U-20261114-13 to -26), the task publishes it: new `gui/_task_details.py` finds the page the task runs on -- the widget the workspace holds in a tab's scroll area, walking up from a nested panel such as Run History's journal browser -- creates its `ExecutionDetailsSource` on the first run, and publishes *running*; *stopping* when a script or stop-event run was asked to stop and is unwinding; then *succeeded*, *cancelled* (plain work cancelled, a stopped run whatever it returned, the owner gone) or *error* with `Type: message` scrubbed of secrets and capped at 500 characters (a deadline gives the *Took too long* text). Progress reported as a `TaskProgress` fills the bar; a `(request_id, count)` report updates the count. `TabTask(owner, details=False)` opts out; the Admin Console's thumbnail timer does. Because a page now gains its source after the workspace bound to it, `workspace_details.details_sources()` announces every new source and `WorkspaceShell` rebinds when the current page gets one. A page that has not run anything still shows the explicit unavailable state. +- **Also:** `test_r3_gui_thread_marshal.py`'s thumbnail probe, a subprocess the earlier GUI runs did not exercise, still read the `_thumb_thread` removed in U-20261114-21; it now checks the tab task and the worker registry. +- **Tests:** `test_tab_task_details.py` (7, in a real `WorkspaceShell` with the task on a panel nested in the page: nothing before a run, running then succeeded, an error with its text, a deadline, plain Stop cancelled at once, a stop-event run with reported progress going stopping then cancelled, `details=False` publishing nothing, and the owner fallback off the workspace). Workspace, GUI, tab, dispose, details, Diagnostics and main-window tests: 1526 passed, 30 skipped before the probe fix, which then passed. +- **Docs:** the three READMEs, both `v223_features_doc.rst` (Execution details), `CHANGELOG.md`. +- **Files:** `gui/_task_details.py` (in the strict mypy tier, `pyproject.toml`), `gui/_tab_task.py`, `gui/workspace.py`, `gui/workspace_details.py`, `gui/admin_console_tab.py`, the tests, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › F2 *其餘* (empty, error and permission states per panel). diff --git a/docs/updates/README.md b/docs/updates/README.md index a59f7e479..ed3bf2a15 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-27 | 2026-11-14 | Every page that runs background work reports it in Execution details | #done #gui #workspace | [2026-11-b](2026-11-b.md) | | U-20261114-26 | 2026-11-14 | Config Sync runs on the shared task; no panel uses a bare worker | #done #gui #sync | [2026-11-b](2026-11-b.md) | | U-20261114-25 | 2026-11-14 | The template candidate panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | | U-20261114-24 | 2026-11-14 | The journal candidate panel runs on the shared task | #done #gui #codegen | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_tab_task.py b/je_auto_control/gui/_tab_task.py index 1f4639410..5ac6963d8 100644 --- a/je_auto_control/gui/_tab_task.py +++ b/je_auto_control/gui/_tab_task.py @@ -22,6 +22,10 @@ drives the machine. Other work binds a headless cancellation scope. Cooperative backends stop at their next checkpoint; late results from noncooperative work are dropped. +* **Execution details.** Each run is published to the workspace's details + pane for the page the task runs on (:mod:`je_auto_control.gui._task_details`): + running, stopping, then succeeded, cancelled or error, with reported + progress. Periodic background work passes ``details=False``. The object keeps no reference to its tab beyond Qt parentage, and the work it is given must not hold a widget (the controller refuses it): read what the @@ -33,6 +37,7 @@ from PySide6.QtCore import QObject, Signal +from je_auto_control.gui._task_details import TaskDetails from je_auto_control.gui.tab_task_controller import CancellationToken, TaskHandle, task_controller from je_auto_control.utils.exception.cancellation import ( CancellationToken as CoreCancellationToken, cancellation_scope, @@ -50,12 +55,13 @@ class TabTask(QObject): finished = Signal() progress = Signal(object) - def __init__(self, owner: QObject) -> None: + def __init__(self, owner: QObject, *, details: bool = True) -> None: super().__init__(owner) self.task: Optional[TaskHandle] = None self.tag = "" self._stop_token: Optional[StopToken] = None self._stop_event: Optional[threading.Event] = None + self._details = TaskDetails(self) if details else None @property def running(self) -> bool: @@ -117,11 +123,13 @@ def stop(self) -> bool: return False if self._stop_token is not None: self._stop_token.stop("stopped from the GUI") - return True - if self._stop_event is not None: + elif self._stop_event is not None: self._stop_event.set() - return True - return self.task.cancel() + else: + return self.task.cancel() + if self._details is not None: + self._details.stopping() + return True def _submit(self, work: Callable[[CancellationToken], Any], tag: str, timeout_s: Optional[float], discard: Optional[Callable[[Any], object]]) -> None: @@ -133,12 +141,31 @@ def _submit(self, work: Callable[[CancellationToken], Any], tag: str, handle.result.connect(self.result) handle.error.connect(self.error) handle.progress.connect(self.progress) + if self._details is not None: + handle.result.connect(self._note_result) + handle.error.connect(self._note_error) + handle.progress.connect(self._note_progress) + self._details.started() handle.finished.connect(self._on_finished) + def _note_result(self, _value: object) -> None: + if self._details is not None: + self._details.noted("result") + + def _note_error(self, error: object) -> None: + if self._details is not None: + self._details.noted("error", error) + + def _note_progress(self, value: object) -> None: + if self._details is not None: + self._details.progressed(value) + def _on_finished(self) -> None: self.task = None self._stop_token = None self._stop_event = None + if self._details is not None: + self._details.finished() self.finished.emit() diff --git a/je_auto_control/gui/_task_details.py b/je_auto_control/gui/_task_details.py new file mode 100644 index 000000000..b055e641c --- /dev/null +++ b/je_auto_control/gui/_task_details.py @@ -0,0 +1,111 @@ +"""Execution details a :class:`~je_auto_control.gui._tab_task.TabTask` publishes for the page it runs on. + +The workspace's details pane shows what the current page's +:class:`~je_auto_control.gui.workspace_details.ExecutionDetailsSource` +publishes. A tab task finds its page -- the widget the workspace holds as a +tab, which may be an ancestor of the panel that owns the task -- and creates +that source the first time it runs, so every page that runs background work +reports it: running, stopping, then succeeded, cancelled or error, with the +progress the work reports. +""" +from typing import Optional, Tuple + +from PySide6.QtCore import QObject, Qt +from PySide6.QtWidgets import QScrollArea, QStackedWidget, QTabWidget, QWidget + +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper +from je_auto_control.gui.tab_task_controller import TaskTimeout +from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsSource, ExecutionPhase +from je_auto_control.utils.executor.run_control import ExecutionStopped +from je_auto_control.utils.logging.secret_scope import scrub_secret_text + +#: The longest error text the details pane is given. +SUMMARY_LIMIT = 500 + + +def page_of(owner: QWidget) -> QWidget: + """The workspace page ``owner`` sits on, or ``owner`` itself when it is on no tab page.""" + current = owner + while True: + viewport = current.parentWidget() + if viewport is None: + return owner + scroll = viewport.parentWidget() + if isinstance(scroll, QScrollArea) and scroll.widget() is current: + stack = scroll.parentWidget() + if isinstance(stack, QStackedWidget) and isinstance(stack.parentWidget(), QTabWidget): + return current + current = viewport + + +def details_source_for(owner: QWidget) -> ExecutionDetailsSource: + """The details source of ``owner``'s page, created on first use.""" + page = page_of(owner) + found = page.findChild(ExecutionDetailsSource, options=Qt.FindChildOption.FindDirectChildrenOnly) + return found if isinstance(found, ExecutionDetailsSource) else ExecutionDetailsSource(page) + + +def _counts(value: object) -> Optional[Tuple[int, int]]: + """``(completed, total)`` from a reported progress value; ``None`` when it carries no count.""" + completed, total = getattr(value, "completed", None), getattr(value, "total", None) + if isinstance(completed, int): + return completed, total if isinstance(total, int) else 0 + if isinstance(value, tuple) and len(value) == 2 and isinstance(value[1], int): + return value[1], 0 # (request_id, count): a count with no known total + return None + + +class TaskDetails: + """Turns one tab task's lifecycle into execution details for its page.""" + + def __init__(self, task: QObject) -> None: + self._task = task + self._outcome: Optional[Tuple[str, object]] = None + self._stopped = False + self._completed = self._total = 0 + + def started(self) -> None: + """A run began.""" + self._outcome, self._stopped = None, False + self._completed = self._total = 0 + self._publish("running") + + def stopping(self) -> None: + """Stop was requested for a run that unwinds before it ends.""" + self._stopped = True + self._publish("stopping") + + def progressed(self, value: object) -> None: + """The work reported progress.""" + counts = _counts(value) + if counts is not None: + self._completed, self._total = counts + self._publish("stopping" if self._stopped else "running") + + def noted(self, kind: str, value: object = None) -> None: + """Remember the run's outcome (``"result"`` or ``"error"``) until it finishes.""" + self._outcome = (kind, value) + + def finished(self) -> None: + """The run ended: publish how.""" + kind, error = self._outcome or ("", None) + if kind == "error" and not isinstance(error, ExecutionStopped): + if isinstance(error, TaskTimeout): + summary = language_wrapper.translate("task_timed_out", "task_timed_out") + else: + summary = scrub_secret_text(f"{type(error).__name__}: {error}")[:SUMMARY_LIMIT] + self._publish("error", summary) + elif kind == "result" and not self._stopped: + self._publish("succeeded") + else: # cancelled, stopped, or the owner went away + self._publish("cancelled") + + def _publish(self, phase: ExecutionPhase, summary: str = "") -> None: + owner = self._task.parent() + if not isinstance(owner, QWidget): + return + total = self._total if phase in ("running", "stopping") else 0 + details_source_for(owner).publish(ExecutionDetails(phase, summary, self._completed, total)) + + +__all__ = ["SUMMARY_LIMIT", "TaskDetails", "details_source_for", "page_of"] diff --git a/je_auto_control/gui/admin_console_tab.py b/je_auto_control/gui/admin_console_tab.py index 69a411e84..6246846bb 100644 --- a/je_auto_control/gui/admin_console_tab.py +++ b/je_auto_control/gui/admin_console_tab.py @@ -94,7 +94,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._thumb_interval.valueChanged.connect(self._on_thumb_interval_changed) self._thumb_timer = QTimer(self) self._thumb_timer.timeout.connect(self._refresh_thumbnails) - self._thumbs = TabTask(self) + self._thumbs = TabTask(self, details=False) # a timer tick, not a run to report self._thumbs.result.connect(self._apply_thumbnails) self._thumbs.error.connect(self._on_thumbnails_failed) self._build_layout() diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index f5fdf21d3..ee74ee05b 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -11,7 +11,9 @@ from je_auto_control.gui.adaptive.responsive import fit_to_width from je_auto_control.gui.adaptive.surfaces import add_page_header, retranslate_surfaces from je_auto_control.gui.tab_registry import MenuActions, TabEntry, TabRegistry, WidgetFactory -from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsPane, ExecutionDetailsSource +from je_auto_control.gui.workspace_details import ( + ExecutionDetails, ExecutionDetailsPane, ExecutionDetailsSource, details_sources, +) from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper @@ -243,6 +245,7 @@ def closed(page: QWidget) -> None: shell._detach_closed_tab(page) self.destroyed.connect(registry.subscribe_close(closed)) self.tabs.currentChanged.connect(self._on_current_tab_changed) + details_sources().appeared.connect(self._on_details_source_appeared) for entry in registry.entries: if entry.default_visible: self.show_tab(entry.key) @@ -309,6 +312,12 @@ def _bind_details(self) -> None: self._details_connection = source.changed.connect(self._on_details_changed) self.details.display(source.snapshot, selected=True) + @Slot(object) + def _on_details_source_appeared(self, source: ExecutionDetailsSource) -> None: + """The current page gained a source after it was bound: show what it publishes.""" + if self._details_source is None and source.parent() is self.tabs.currentWidget(): + self._bind_details() + @Slot(object) def _on_details_changed(self, snapshot: ExecutionDetails) -> None: source = None if self._details_source is None else self._details_source() diff --git a/je_auto_control/gui/workspace_details.py b/je_auto_control/gui/workspace_details.py index 07a753f63..2534818c8 100644 --- a/je_auto_control/gui/workspace_details.py +++ b/je_auto_control/gui/workspace_details.py @@ -1,6 +1,6 @@ """Immutable execution snapshots and a passive, scrollable workspace detail view.""" from dataclasses import dataclass -from typing import Literal +from typing import Literal, Optional from PySide6.QtCore import QObject, Qt, Signal from PySide6.QtWidgets import QLabel, QProgressBar, QScrollArea, QVBoxLayout, QWidget @@ -21,6 +21,23 @@ class ExecutionDetails: total: int = 0 +class _SourceNotifier(QObject): + """Announces each new :class:`ExecutionDetailsSource`, so a view showing its page can bind to it.""" + + appeared = Signal(object) + + +_NOTIFIER: Optional[_SourceNotifier] = None + + +def details_sources() -> _SourceNotifier: + """The process-wide notifier whose ``appeared`` carries every source created after it.""" + global _NOTIFIER # pylint: disable=global-statement # reason: one GUI-thread notifier, made on first use + if _NOTIFIER is None: + _NOTIFIER = _SourceNotifier() + return _NOTIFIER + + class ExecutionDetailsSource(QObject): """A page-owned snapshot publisher updated on the GUI thread.""" @@ -29,6 +46,8 @@ class ExecutionDetailsSource(QObject): def __init__(self, parent: QWidget) -> None: super().__init__(parent) self._snapshot = ExecutionDetails() + # A page can gain its source after the view bound to it (a tab task's first run). + details_sources().appeared.emit(self) @property def snapshot(self) -> ExecutionDetails: diff --git a/pyproject.toml b/pyproject.toml index 205ad597e..190f89adc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -368,6 +368,7 @@ module = [ "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", "je_auto_control.gui.workspace_details", + "je_auto_control.gui._task_details", "je_auto_control.gui.remote_desktop.webrtc_panel_state", "je_auto_control.gui.remote_desktop.view_lifetime", "je_auto_control.gui.remote_desktop.view_approvals", diff --git a/test/unit_test/headless/test_r3_gui_thread_marshal.py b/test/unit_test/headless/test_r3_gui_thread_marshal.py index 88cbacbfa..0d01fe31f 100644 --- a/test/unit_test/headless/test_r3_gui_thread_marshal.py +++ b/test/unit_test/headless/test_r3_gui_thread_marshal.py @@ -178,19 +178,16 @@ def check_thumbnail_reaped(): tab._thumb_timer.stop() tab._refresh_thumbnails() - handle = tab._thumb_thread - assert handle is not None, "no thumbnail worker was started" - # The registry holds the worker until the GUI thread has seen it end, so - # closing the tab mid-poll cannot collect it. - assert handle in worker_mod._RUNNING, "the worker is not held by the registry" + # The round runs as a tab task, whose worker the registry holds until the + # GUI thread has seen it end, so closing the tab mid-poll cannot collect it. + assert tab._thumbs.running, "no thumbnail round was started" # With no hosts the poll returns at once; the end is queued to the GUI thread. - assert pump_until(lambda: tab._thumb_thread is None), "_on_thumb_thread_done did not run" + assert pump_until(lambda: not tab._thumbs.running), "the thumbnail round never finished" app.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) # Without the release the registry would grow by one worker per poll tick. released = pump_until(lambda: worker_mod.running_threads() == before) assert released, "a worker lingers in the registry" - assert not handle.isRunning() for name, check in [ diff --git a/test/unit_test/headless/test_tab_task_details.py b/test/unit_test/headless/test_tab_task_details.py new file mode 100644 index 000000000..cdbf99a5e --- /dev/null +++ b/test/unit_test/headless/test_tab_task_details.py @@ -0,0 +1,146 @@ +"""Every page that runs background work reports it in the workspace's execution details. + +Only Diagnostics published execution details; every other page showed +*This feature does not publish execution details* whatever it was doing. A +:class:`~je_auto_control.gui._tab_task.TabTask` now publishes each run for the +page it runs on -- also when the task belongs to a panel nested inside the page. +""" +import os +import threading + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtCore import QEvent # noqa: E402 +from PySide6.QtWidgets import QApplication, QVBoxLayout, QWidget # noqa: E402 + +from je_auto_control.gui._task_details import page_of # noqa: E402 +from je_auto_control.gui._tab_task import TabTask # noqa: E402 +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 +from je_auto_control.utils.exception.cancellation import TaskProgress # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) + + +class _Page(QWidget): + """A page whose task belongs to a panel inside it, as Run History's journal browser does.""" + + def __init__(self, details=True): + super().__init__() + self.panel = QWidget() + QVBoxLayout(self).addWidget(self.panel) + self.task = TabTask(self.panel, details=details) + + +@pytest.fixture +def shell(): + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + registry = TabRegistry([TabEntry("work", "work", _Page), + TabEntry("quiet", "quiet", lambda: _Page(details=False))]) + widget = WorkspaceShell(registry) + widget.activate_tab("work") + yield widget + widget.deleteLater() + _APP.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +def _phase(shell): + snapshot = shell.details.snapshot + return None if snapshot is None else snapshot.phase + + +def _held(): + entered, release = threading.Event(), threading.Event() + + def work(): + entered.set() + assert release.wait(10.0) + return "done" + return work, entered, release + + +def test_a_page_shows_its_run_and_then_that_it_succeeded(shell): + page = shell.tabs.currentWidget() + assert shell.details.snapshot is None # no run yet: nothing published + work, entered, release = _held() + assert page.task.start(work) + assert entered.wait(10.0) + assert _phase(shell) == "running" + release.set() + assert pump_until(lambda: _phase(shell) == "succeeded") + + +def test_a_failed_run_says_why(shell): + page = shell.tabs.currentWidget() + + def fail(): + raise ValueError("no such host") + + assert page.task.start(fail) + assert pump_until(lambda: _phase(shell) == "error") + assert shell.details.snapshot.summary == "ValueError: no such host" + + +def test_a_run_past_its_deadline_says_so(shell): + page = shell.tabs.currentWidget() + work, _entered, release = _held() + try: + assert page.task.start(work, timeout_s=0.05) + assert pump_until(lambda: _phase(shell) == "error") + assert shell.details.snapshot.summary == language_wrapper.translate("task_timed_out", "task_timed_out") + finally: + release.set() + + +def test_stopping_plain_work_shows_it_cancelled_at_once(shell): + page = shell.tabs.currentWidget() + work, entered, release = _held() + try: + assert page.task.start(work) + assert entered.wait(10.0) + page.task.stop() + assert _phase(shell) == "cancelled" + finally: + release.set() + + +def test_work_that_unwinds_shows_stopping_then_cancelled_with_its_progress(shell): + page = shell.tabs.currentWidget() + reported, release = threading.Event(), threading.Event() + + def work(stop_event, report): + report(TaskProgress(1, 2, 5)) + reported.set() + assert stop_event.wait(10.0) + assert release.wait(10.0) + return "partial" + + assert page.task.start_until_stopped(work, reports=True) + assert reported.wait(10.0) + assert pump_until(lambda: shell.details.snapshot.completed == 2) + assert (shell.details.snapshot.phase, shell.details.snapshot.total) == ("running", 5) + page.task.stop() + assert _phase(shell) == "stopping" + release.set() + assert pump_until(lambda: _phase(shell) == "cancelled") # what it did, but it was stopped + + +def test_a_task_built_without_details_publishes_nothing(shell): + shell.activate_tab("quiet") + page = shell.tabs.currentWidget() + assert page.task.start(lambda: "done") + assert pump_until(lambda: not page.task.running) + assert shell.details.snapshot is None + + +def test_off_the_workspace_a_task_reports_on_its_own_owner(): + owner = QWidget() + child = QWidget(owner) + try: + assert page_of(child) is child + finally: + owner.deleteLater() From 2574ce163f8d0c778ba48f3ca463509ce89c35e7 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 15:21:44 +0800 Subject: [PATCH 094/161] Update Claude.md --- CLAUDE.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 076a43b4c..22764adfe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -228,3 +228,9 @@ Workspace rule shared by every repository under `D:\Codes` (full text: `D:\Codes - Every git worktree created for a task must be finished off: merge its branch back into the branch it was started from, then remove the worktree (`git worktree remove `) and delete its branch (`git branch -d `). - Do not leave worktrees behind when the work is done; check `git worktree list` before ending the task. - If a worktree cannot be merged yet, say so explicitly instead of leaving it behind silently. + +## Test scope: run only what the change touches + +When a change needs testing, run only the tests related to it: the test files for the modules you edited, plus the tests that directly depend on them (for example a golden-file or docs-sync test that reads what you changed). Do not re-run the whole suite. + +This takes precedence over any other line in this file that asks for the whole suite to be run locally. Run the whole suite only when the user asks for it. From 71fde4bf9c850708b2c3f246735d6dfd3aaee675 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 16:12:03 +0800 Subject: [PATCH 095/161] Let empty tables, lists and trees say so A page waiting for its first command showed a blank grid, with nothing to tell an empty result from one still to come. The workspace now gives every item view an empty state that hides as soon as a row arrives. --- CHANGELOG.md | 6 + Progress.md | 3 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 13 ++- .../doc/new_features/v224_features_doc.rst | 7 ++ .../Zh/doc/new_features/v224_features_doc.rst | 4 + docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/adaptive/empty_views.py | 99 ++++++++++++++++ .../gui/language_wrapper/english.py | 2 + .../gui/language_wrapper/japanese.py | 2 + .../language_wrapper/simplified_chinese.py | 2 + .../language_wrapper/traditional_chinese.py | 2 + je_auto_control/gui/workspace.py | 2 + .../headless/test_gui_empty_views.py | 108 ++++++++++++++++++ 17 files changed, 255 insertions(+), 10 deletions(-) create mode 100644 je_auto_control/gui/adaptive/empty_views.py create mode 100644 test/unit_test/headless/test_gui_empty_views.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b56187de3..ee18be646 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI: every table, list and tree on a workspace page shows an empty state (*Nothing to show + yet.*) while it has no rows. New `gui/adaptive/empty_views.py` (`show_empty_states`, + `NO_EMPTY_STATE` to opt a view out); two new catalogue keys, `empty_view` and + `empty_view_hint`. Each such view gains an `EmptyState` child named `EmptyViewState` on its + viewport. + - GUI: every page that runs background work through `TabTask` publishes it to **View → Execution details**: running, stopping, then succeeded, cancelled or error (with the error text, or the timeout message), with reported progress. `TabTask(owner, details=False)` opts diff --git a/Progress.md b/Progress.md index 79342aa92..1e2d02df0 100644 --- a/Progress.md +++ b/Progress.md @@ -532,7 +532,8 @@ D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製 H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 F 還缺: -- **F2 其餘**:各面板的空白/錯誤/permission states 尚未全面交付(執行詳情已由 `TabTask` 為所有背景工作的頁面發布,U-20261114-27)。 +- **F2 其餘**:各面板的錯誤/permission states 尚未全面交付(執行詳情已由 `TabTask` 為所有背景工作的頁面發布,U-20261114-27; + 空的表格/清單/樹狀清單已有空白狀態,U-20261114-28)。 - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 diff --git a/README.md b/README.md index 915bda920..16b30496e 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Of the three tabs open at start, only Record is built then; Script Builder and R View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there, and so does every other page that runs work in the background (a model request, a USB listing, a broadcast, a DAG run, a journal read): running, stopping, then completed, cancelled or the error, with progress where the work reports it. A page that has run nothing yet says details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. -Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. +Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. An empty table, list or tree says *Nothing to show yet* until its first row arrives, instead of showing a blank grid. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. WebRTC statistics polling starts in the background and discards late samples after it stops. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index fe34c791d..cda6090b1 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -45,7 +45,7 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态,其他在后台执行工作的分页(模型请求、USB 列举、广播、DAG 执行、日志读取)也会:执行中、停止中,然后是完成、已取消或错误,工作有回报进度时一并显示。尚未执行过工作的分页会明确显示没有详情。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 -每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 +每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。空的表格、列表或树状清单会显示「暂无内容。」,直到第一笔数据出现,不再只显示空白格线。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 WebRTC 统计轮询在后台启动,停止后会丢弃延迟到达的样本。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 25772e369..7b3f8d39b 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -45,7 +45,7 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態,其他在背景執行工作的分頁(模型請求、USB 列舉、廣播、DAG 執行、日誌讀取)也會:執行中、停止中,然後是完成、已取消或錯誤,工作有回報進度時一併顯示。尚未執行過工作的分頁會明確顯示沒有詳情。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 -每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 +每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。空的表格、清單或樹狀清單會顯示「目前沒有內容。」,直到第一筆資料出現,不再只顯示空白格線。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 WebRTC 統計輪詢在背景啟動,停止後會捨棄晚到的樣本。 diff --git a/architecture_explore.md b/architecture_explore.md index 74eafb0ec..d4e5d1be3 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,538 | -| 程式碼總行數 | 236,080 | +| Python 模組總數(含周邊子專案) | 1,539 | +| 程式碼總行數 | 236,189 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1305,12 +1305,13 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | | `adaptive/responsive.py` | 189 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`ResponsiveSplitter`(同上但分隔線可拖曳)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行、表格最後一欄延展填滿),工作區放入每頁時跑一次;`fit_columns` 依內容定欄寬後重新延展最後一欄。 | | `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | +| `adaptive/empty_views.py` | 99 | Empty tables, lists and trees say so instead of showing a blank grid. 工作區替每頁的表格/清單/樹狀清單加上 `EmptyState` 覆蓋層,沒有任何列時顯示、第一列出現即隱藏;略過表頭與下拉選單內的清單。 | | `adaptive/style.py` | 117 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | | `adaptive/glyphs.py` | 66 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | | `adaptive/overlay.py` | 102 | A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed. `OverlayDrawer`:Escape 或點擊遮罩關閉。 | | `_arrow_icons.py` | 76 | Chevrons for drop-down lists and spin boxes, drawn in code and handed to the style sheet. 以導覽列的線條圖示畫出、依主題色快取成檔案;寫不進快取時不放置子控制項,保留樣式原生箭頭。 | | `adaptive_window.py` | 179 | Rearrange the main window's navigation and details panes as the window's width class changes. `AdaptiveWindowLayout`:expanded 兩側停靠;medium 詳情改抽屜;compact 導覽改圖示欄+抽屜。「想要停靠導覽」與寬度是否允許分開記錄,窄視窗不會改寫使用者偏好。 | -| `workspace.py` | 576 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | +| `workspace.py` | 578 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | | `workspace_details.py` | 116 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 與每個 `TabTask` 都是 publisher;僅訂閱目前頁面,`details_sources()` 通知綁定後才建立的來源。 | | `_task_details.py` | 111 | Execution details a TabTask publishes for the page it runs on. 由子面板往上找出工作區的分頁、第一次執行時建立來源,發布執行中/停止中/完成/已取消/錯誤與回報的進度。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | @@ -1337,7 +1338,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 257 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 88 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,519 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,527 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1544,7 +1545,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 161 | 42,813 | +| `gui/` | 162 | 42,922 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1565,7 +1566,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,526** | **235,335** | +| **總計** | **1,527** | **235,444** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v224_features_doc.rst b/docs/source/Eng/doc/new_features/v224_features_doc.rst index 46911079a..b1f6ea359 100644 --- a/docs/source/Eng/doc/new_features/v224_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v224_features_doc.rst @@ -61,6 +61,13 @@ What every page gets needed 1,464 px for one command label), form labels move above their field when both do not fit, long notes wrap, and a table's last column takes the width its other columns leave. +* **Empty views say so.** The same pass gives every table, list and tree on + the page an empty state (``gui.adaptive.empty_views.show_empty_states``): + *Nothing to show yet.* with a hint to run a command from the Actions menu, + shown while the view has no rows and hidden as soon as one arrives. It lets + clicks through, follows a replaced model, and skips header views and the + lists inside drop-downs; a view with the ``_jeNoEmptyState`` property set is + left alone. Building blocks --------------- diff --git a/docs/source/Zh/doc/new_features/v224_features_doc.rst b/docs/source/Zh/doc/new_features/v224_features_doc.rst index ccbf48aa6..5e5336341 100644 --- a/docs/source/Zh/doc/new_features/v224_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v224_features_doc.rst @@ -51,6 +51,10 @@ GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一 * **會縮小的控制項。** 分頁第一次顯示時會經過一次調整:下拉選單不再以最長項目決定寬度 (Mobile 曾因一個指令名稱需要 1,464 px)、表單放不下時標籤移到欄位上方、長說明自動換行, 表格最後一欄延展填滿其餘欄位留下的寬度。 +* **空的檢視會說明。** 同一次調整也替頁面上的每個表格、清單與樹狀清單加上空白狀態 + (``gui.adaptive.empty_views.show_empty_states``\ ):沒有任何列時顯示「目前沒有內容。」與 + 「從 Actions 選單執行指令」的提示,第一列出現就隱藏。它不攔截滑鼠、會跟著替換的 model, + 略過表頭與下拉選單內的清單;設定了 ``_jeNoEmptyState`` 屬性的檢視不受影響。 元件 ---- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 16a59dbd9..0afabd315 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -494,3 +494,11 @@ - **Docs:** the three READMEs, both `v223_features_doc.rst` (Execution details), `CHANGELOG.md`. - **Files:** `gui/_task_details.py` (in the strict mypy tier, `pyproject.toml`), `gui/_tab_task.py`, `gui/workspace.py`, `gui/workspace_details.py`, `gui/admin_console_tab.py`, the tests, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › F2 *其餘* (empty, error and permission states per panel). + +## U-20261114-28 · 2026-11-14 · Empty tables, lists and trees say so · #done #gui #adaptive + +- **What:** the empty-state part of `Progress.md` › F2 *其餘*. `adaptive/surfaces.py` had an `EmptyState` that no page used, so a table waiting for its first command showed a blank grid, often headers only, with nothing to tell an empty result from one still to come. New `adaptive/empty_views.py`: `show_empty_states(root)` gives every item view under a page an overlay `EmptyState` (*Nothing to show yet.* / *Results appear here once you run a command from the Actions menu.*, new `empty_view` / `empty_view_hint` keys in all four catalogues) on its viewport, shown while the model has no rows (or there is no model) and hidden as soon as one arrives. It follows `rowsInserted`, `rowsRemoved`, `modelReset` and `layoutChanged`, notices a replaced model when the viewport next paints, re-centres on resize, lets the mouse through, and skips header views, the lists inside combo boxes and any view with the `_jeNoEmptyState` property. The workspace runs it after `fit_to_width` on every page it opens; `retranslate_surfaces` already re-reads every `EmptyState` on a language switch. +- **Tests:** `test_gui_empty_views.py` (5: an empty table shows the message until a row arrives and again when emptied; the overlay lets clicks through and stays inside the viewport; a replaced model is followed; headers, a combo's list and an opted-out view are left alone and a second pass adds nothing; the workspace gives its pages empty states). Workspace, GUI, tab, dispose, details, main-window, catalogue, admin, USB, journal, history and DAG tests: 2918 passed, 30 skipped. +- **Docs:** the three READMEs, both `v224_features_doc.rst` (controls that shrink), `CHANGELOG.md`. +- **Files:** `gui/adaptive/empty_views.py`, `gui/workspace.py`, the four catalogues, the test, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › F2 *其餘* (error and permission states per panel). diff --git a/docs/updates/README.md b/docs/updates/README.md index ed3bf2a15..20a624455 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-28 | 2026-11-14 | Empty tables, lists and trees say so | #done #gui #adaptive | [2026-11-b](2026-11-b.md) | | U-20261114-27 | 2026-11-14 | Every page that runs background work reports it in Execution details | #done #gui #workspace | [2026-11-b](2026-11-b.md) | | U-20261114-26 | 2026-11-14 | Config Sync runs on the shared task; no panel uses a bare worker | #done #gui #sync | [2026-11-b](2026-11-b.md) | | U-20261114-25 | 2026-11-14 | The template candidate panel runs on the shared task | #done #gui #healing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/adaptive/empty_views.py b/je_auto_control/gui/adaptive/empty_views.py new file mode 100644 index 000000000..63cca9722 --- /dev/null +++ b/je_auto_control/gui/adaptive/empty_views.py @@ -0,0 +1,99 @@ +"""Empty tables, lists and trees say so instead of showing a blank grid. + +:func:`show_empty_states` puts an :class:`~je_auto_control.gui.adaptive.surfaces.EmptyState` +over every item view on a page while the view's model has no rows, and hides +it as soon as a row arrives. The workspace runs it once on each page it opens, +after :func:`~je_auto_control.gui.adaptive.responsive.fit_to_width`. The +overlay lets the mouse through, follows the view's size, and notices a model +being replaced as well as rows being added, removed or reset. +""" +from typing import Optional + +from PySide6.QtCore import QAbstractItemModel, QEvent, QObject, Qt +from PySide6.QtWidgets import QAbstractItemView, QComboBox, QHeaderView, QWidget + +from je_auto_control.gui.adaptive.surfaces import EmptyState + +#: Dynamic property set on a view that already has an overlay, or that must not get one. +NO_EMPTY_STATE = "_jeNoEmptyState" + +_MODEL_SIGNALS = ("rowsInserted", "rowsRemoved", "modelReset", "layoutChanged") + + +class _EmptyOverlay(QObject): + """Shows ``state`` over ``view``'s viewport while the model is empty.""" + + def __init__(self, view: QAbstractItemView, message_key: str, hint_key: str) -> None: + super().__init__(view) + self._view = view + self._model: Optional[QAbstractItemModel] = None + self.state = EmptyState(message_key, hint_key, view.viewport()) + self.state.setObjectName("EmptyViewState") + self.state.hint.setWordWrap(True) + self.state.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) + view.viewport().installEventFilter(self) + self.refresh() + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 # reason: Qt override + """Re-place the overlay when the viewport resizes; notice a replaced model when it paints.""" + if event.type() in (QEvent.Type.Resize, QEvent.Type.Show, QEvent.Type.Paint): + if event.type() != QEvent.Type.Paint or self._view.model() is not self._model: + self.refresh() + return False + + def refresh(self) -> None: + """Watch the view's current model and show the overlay only while it has no rows.""" + model = self._view.model() + if model is not self._model: + self._rewire(model) + empty = model is None or model.rowCount() == 0 + if empty: + viewport = self._view.viewport() + height = min(self.state.sizeHint().height(), viewport.height()) + self.state.setGeometry(0, max(0, (viewport.height() - height) // 2), viewport.width(), height) + if self.state.isVisibleTo(self._view.viewport()) != empty: + self.state.setVisible(empty) + + def _model_changed(self, *_args: object) -> None: + self.refresh() + + def _rewire(self, model: Optional[QAbstractItemModel]) -> None: + if self._model is not None: + for name in _MODEL_SIGNALS: + try: + getattr(self._model, name).disconnect(self._model_changed) + except (RuntimeError, TypeError): # reason: the old model is gone or was never connected + pass + self._model = model + if model is not None: + for name in _MODEL_SIGNALS: + getattr(model, name).connect(self._model_changed) + + +def _inside_combo(view: QWidget, root: QWidget) -> bool: + parent = view.parentWidget() + while parent is not None and parent is not root: + if isinstance(parent, QComboBox): + return True + parent = parent.parentWidget() + return False + + +def show_empty_states(root: QWidget, message_key: str = "empty_view", hint_key: str = "empty_view_hint") -> int: + """Give every item view under ``root`` an empty state; return how many were given one. + + Header views and the drop-down lists of combo boxes are left alone, as is + a view whose :data:`NO_EMPTY_STATE` property is set. Calling it again only + reaches views added since. + """ + added = 0 + for view in root.findChildren(QAbstractItemView): + if isinstance(view, QHeaderView) or view.property(NO_EMPTY_STATE) or _inside_combo(view, root): + continue + view.setProperty(NO_EMPTY_STATE, True) + _EmptyOverlay(view, message_key, hint_key) + added += 1 + return added + + +__all__ = ["NO_EMPTY_STATE", "show_empty_states"] diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index 36cbf6798..3405e71b2 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -1491,6 +1491,8 @@ "task_stopped": "Stopped.", "task_stop": "Stop run", "task_timed_out": "Took too long and was stopped.", + "empty_view": "Nothing to show yet.", + "empty_view_hint": "Results appear here once you run a command from the Actions menu.", "stop_playback": "Stop playback", "record_playing": "Playing back...", "rd_file_sending": "Sending {name}...", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index ff81fa7c4..3b4a8dae5 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -1387,6 +1387,8 @@ "task_stopped": "停止しました。", "task_stop": "実行を停止", "task_timed_out": "時間がかかりすぎたため停止しました。", + "empty_view": "まだ表示する内容はありません。", + "empty_view_hint": "Actions メニューからコマンドを実行すると、結果がここに表示されます。", "stop_playback": "再生を停止", "record_playing": "再生中...", "rd_file_sending": "{name} を送信中...", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 1e306c49c..0a84a4d91 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1351,6 +1351,8 @@ "task_stopped": "已停止。", "task_stop": "停止执行", "task_timed_out": "执行超时,已停止。", + "empty_view": "暂无内容。", + "empty_view_hint": "从 Actions 菜单执行命令后,结果会显示在这里。", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在发送 {name}...", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index c1cc1ab26..e0551273e 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1359,6 +1359,8 @@ "task_stopped": "已停止。", "task_stop": "停止執行", "task_timed_out": "執行逾時,已停止。", + "empty_view": "目前沒有內容。", + "empty_view_hint": "從 Actions 選單執行指令後,結果會顯示在這裡。", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在傳送 {name}...", diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index ee74ee05b..11eaa2b71 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -8,6 +8,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.adaptive.overlay import OverlayDrawer +from je_auto_control.gui.adaptive.empty_views import show_empty_states from je_auto_control.gui.adaptive.responsive import fit_to_width from je_auto_control.gui.adaptive.surfaces import add_page_header, retranslate_surfaces from je_auto_control.gui.tab_registry import MenuActions, TabEntry, TabRegistry, WidgetFactory @@ -372,6 +373,7 @@ def _dress(self, key: str, page: QWidget) -> None: if entry is not None: add_page_header(page, entry.title_key, f"{entry.title_key}_subtitle") fit_to_width(page) + show_empty_states(page) def _drop_unbuilt(self, key: str) -> bool: """Close a start-up tab that was never built; ``False`` when ``key`` has none.""" diff --git a/test/unit_test/headless/test_gui_empty_views.py b/test/unit_test/headless/test_gui_empty_views.py new file mode 100644 index 000000000..8fd008f38 --- /dev/null +++ b/test/unit_test/headless/test_gui_empty_views.py @@ -0,0 +1,108 @@ +"""An empty table, list or tree on a page says so, and stops saying so when rows arrive. + +Pages showed a blank grid (often with headers only) until a command filled +it, with nothing to tell an empty result from one still to come. +""" +import os + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtCore import QStringListModel, Qt # noqa: E402 +from PySide6.QtWidgets import ( # noqa: E402 + QApplication, QComboBox, QListView, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, +) + +from je_auto_control.gui.adaptive.empty_views import NO_EMPTY_STATE, show_empty_states # noqa: E402 +from je_auto_control.gui.adaptive.surfaces import EmptyState # noqa: E402 +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) + + +@pytest.fixture +def page(): + widget = QWidget() + widget.resize(600, 400) + yield widget + widget.deleteLater() + + +def _state(view): + found = view.viewport().findChild(EmptyState, "EmptyViewState") + assert found is not None, "the view has no empty state" + return found + + +def test_an_empty_table_shows_the_message_until_a_row_arrives(page): + table = QTableWidget(0, 3) + QVBoxLayout(page).addWidget(table) + assert show_empty_states(page) == 1 + page.show() + _APP.processEvents() + state = _state(table) + assert state.isVisible() + assert state.message.text() == language_wrapper.translate("empty_view", "empty_view") + table.setRowCount(1) + table.setItem(0, 0, QTableWidgetItem("x")) + assert not state.isVisible() + table.setRowCount(0) + assert state.isVisible() + + +def test_the_overlay_lets_clicks_through_and_stays_inside_the_view(page): + table = QTableWidget(0, 2) + QVBoxLayout(page).addWidget(table) + show_empty_states(page) + page.show() + _APP.processEvents() + state = _state(table) + assert state.testAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) + viewport = table.viewport().rect() + assert viewport.contains(state.geometry()) + + +def test_a_replaced_model_is_followed(page): + view = QListView() + QVBoxLayout(page).addWidget(view) + show_empty_states(page) + page.show() + _APP.processEvents() + assert _state(view).isVisible() # no model at all + view.setModel(QStringListModel(["one"], view)) + view.viewport().repaint() + _APP.processEvents() + assert not _state(view).isVisible() + + +def test_headers_combo_lists_and_opted_out_views_are_left_alone(page): + layout = QVBoxLayout(page) + table = QTableWidget(0, 1) + combo = QComboBox() + quiet = QTableWidget(0, 1) + quiet.setProperty(NO_EMPTY_STATE, True) + for widget in (table, combo, quiet): + layout.addWidget(widget) + assert show_empty_states(page) == 1 # the table only: not its headers, the combo's list, or quiet + assert show_empty_states(page) == 0 # a second pass adds nothing + assert quiet.viewport().findChild(EmptyState) is None + + +def test_the_workspace_gives_its_pages_empty_states(): + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + + def build(): + widget = QWidget() + QVBoxLayout(widget).addWidget(QTableWidget(0, 2)) + return widget + + shell = WorkspaceShell(TabRegistry([TabEntry("hosts", "hosts", build)])) + try: + shell.activate_tab("hosts") + table = shell.tabs.currentWidget().findChild(QTableWidget) + assert table.viewport().findChild(EmptyState, "EmptyViewState") is not None + finally: + shell.deleteLater() From d7dfd8dc5a253a9cd747eedf319dc8c32620e321 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 16:41:44 +0800 Subject: [PATCH 096/161] Give every page a banner for a failed run and for refused commands A failure or an RBAC refusal showed only in each panel's own status line, if it had one. A banner under the page header now reports the last failed run, and inside an RBAC scope names the commands the active role cannot run. --- CHANGELOG.md | 8 + Progress.md | 2 - README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 39 ++--- .../doc/new_features/v224_features_doc.rst | 9 ++ .../Zh/doc/new_features/v224_features_doc.rst | 5 + docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + je_auto_control/gui/_task_details.py | 41 ++--- je_auto_control/gui/adaptive/page_banner.py | 149 ++++++++++++++++++ je_auto_control/gui/adaptive/surfaces.py | 5 +- je_auto_control/gui/config_sync_tab.py | 3 + je_auto_control/gui/diagnostics_tab.py | 3 + .../gui/healing_evaluation_panel.py | 3 + je_auto_control/gui/journal_browser.py | 3 + .../gui/journal_candidate_panel.py | 3 + .../gui/language_wrapper/english.py | 4 + .../gui/language_wrapper/japanese.py | 5 + .../language_wrapper/simplified_chinese.py | 4 + .../language_wrapper/traditional_chinese.py | 4 + je_auto_control/gui/mcp_discovery_view.py | 3 + .../gui/template_candidate_panel.py | 3 + je_auto_control/gui/theme.py | 4 + je_auto_control/gui/workspace.py | 4 + je_auto_control/utils/rbac/policy.py | 19 ++- .../headless/test_gui_page_banner.py | 148 +++++++++++++++++ 28 files changed, 441 insertions(+), 45 deletions(-) create mode 100644 je_auto_control/gui/adaptive/page_banner.py create mode 100644 test/unit_test/headless/test_gui_page_banner.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ee18be646..6a521553c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- GUI: every workspace page has a banner under its header (`gui/adaptive/page_banner.py`): a + failed background run (*The last run failed:*), a run refused by RBAC (*Not permitted:*), and, + inside an RBAC scope, the commands the active role cannot run. Panels declare theirs in a + `REQUIRED_COMMANDS` class attribute (journal browser, self-healing comparison, journal and + template candidates, Config Sync, Diagnostics, MCP discovery). New + `utils.rbac.policy.refused_commands(names, context=None)`; four new catalogue keys + (`page_banner_*`). + - GUI: every table, list and tree on a workspace page shows an empty state (*Nothing to show yet.*) while it has no rows. New `gui/adaptive/empty_views.py` (`show_empty_states`, `NO_EMPTY_STATE` to opt a view out); two new catalogue keys, `empty_view` and diff --git a/Progress.md b/Progress.md index 1e2d02df0..818909ddf 100644 --- a/Progress.md +++ b/Progress.md @@ -532,8 +532,6 @@ D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製 H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 F 還缺: -- **F2 其餘**:各面板的錯誤/permission states 尚未全面交付(執行詳情已由 `TabTask` 為所有背景工作的頁面發布,U-20261114-27; - 空的表格/清單/樹狀清單已有空白狀態,U-20261114-28)。 - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 diff --git a/README.md b/README.md index 16b30496e..a43ff1648 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Of the three tabs open at start, only Record is built then; Script Builder and R View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there, and so does every other page that runs work in the background (a model request, a USB listing, a broadcast, a DAG run, a journal read): running, stopping, then completed, cancelled or the error, with progress where the work reports it. A page that has run nothing yet says details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. -Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. An empty table, list or tree says *Nothing to show yet* until its first row arrives, instead of showing a blank grid. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. +Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. An empty table, list or tree says *Nothing to show yet* until its first row arrives, instead of showing a blank grid. A banner under the page title says when the page's last run failed (the next run clears it) and, when the GUI runs inside an RBAC scope, which of the page's commands the active role cannot run; it has a Dismiss link. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. WebRTC statistics polling starts in the background and discards late samples after it stops. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index cda6090b1..6e0f0ce4c 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -45,7 +45,7 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态,其他在后台执行工作的分页(模型请求、USB 列举、广播、DAG 执行、日志读取)也会:执行中、停止中,然后是完成、已取消或错误,工作有回报进度时一并显示。尚未执行过工作的分页会明确显示没有详情。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 -每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。空的表格、列表或树状清单会显示「暂无内容。」,直到第一笔数据出现,不再只显示空白格线。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 +每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。空的表格、列表或树状清单会显示「暂无内容。」,直到第一笔数据出现,不再只显示空白格线。页面标题下方的横幅会说明该页上次执行失败(下次执行时清除),GUI 在 RBAC 范围内执行时也会说明当前角色无法执行该页的哪些指令;横幅附有关闭链接。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 WebRTC 统计轮询在后台启动,停止后会丢弃延迟到达的样本。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 7b3f8d39b..5e4fa29f0 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -45,7 +45,7 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態,其他在背景執行工作的分頁(模型請求、USB 列舉、廣播、DAG 執行、日誌讀取)也會:執行中、停止中,然後是完成、已取消或錯誤,工作有回報進度時一併顯示。尚未執行過工作的分頁會明確顯示沒有詳情。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 -每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。空的表格、清單或樹狀清單會顯示「目前沒有內容。」,直到第一筆資料出現,不再只顯示空白格線。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 +每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。空的表格、清單或樹狀清單會顯示「目前沒有內容。」,直到第一筆資料出現,不再只顯示空白格線。頁面標題下方的橫幅會說明該頁上次執行失敗(下次執行時清除),GUI 在 RBAC 範圍內執行時也會說明目前角色無法執行該頁的哪些指令;橫幅附有關閉連結。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 WebRTC 統計輪詢在背景啟動,停止後會捨棄晚到的樣本。 diff --git a/architecture_explore.md b/architecture_explore.md index d4e5d1be3..539d42dc0 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,539 | -| 程式碼總行數 | 236,189 | +| Python 模組總數(含周邊子專案) | 1,540 | +| 程式碼總行數 | 236,407 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,463 行。 +> 13 個套件、約 4,478 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -674,7 +674,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/governance/` | 243 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | -| `utils/rbac/` | 1,716 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | +| `utils/rbac/` | 1,731 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | @@ -1299,25 +1299,26 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | -| `theme.py` | 247 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | +| `theme.py` | 251 | 設計 token(`ThemeTokens`:顏色、狀態色、圓角、間距、字族)、深色與淺色兩組值、由 token 產生的樣式表(卡片、頁首、`role` 屬性)、隨字級縮放的標題字階(`type_scale_rules`)與對應的 `QPalette`;不載入圖檔或字型檔。 | | `adaptive/__init__.py` | 9 | Adaptive layout building blocks shared by the window and every page. 只匯出 Qt-free 的 `WidthClass`/`classify`。 | | `adaptive/breakpoints.py` | 46 | Width classes for the adaptive window, with hysteresis so a resize near a boundary does not flicker. compact(<800)/medium/expanded(≥1200),邊界前後 24 px 不反覆切換;不匯入 Qt。 | | `adaptive/flow_layout.py` | 166 | A layout that places items left to right and wraps them onto the next line when the row is full. 最小寬度只等於最寬的一項。 | | `adaptive/responsive.py` | 189 | Containers that rearrange by width, and the pass that stops a page's controls from forcing it wide. `ResponsiveBox`(窄時上下堆疊)、`ResponsiveSplitter`(同上但分隔線可拖曳)、`fit_to_width`(下拉選單不再以最長項目定寬、表單窄時標籤移到欄位上方、長標籤換行、表格最後一欄延展填滿),工作區放入每頁時跑一次;`fit_columns` 依內容定欄寬後重新延展最後一欄。 | -| `adaptive/surfaces.py` | 160 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | +| `adaptive/surfaces.py` | 163 | Cards, page headers and empty states: the shared surfaces every page is built from. `Card`、`PageHeader`(標題+`_subtitle` 說明,缺字串時隱藏)、`EmptyState`、`add_page_header`、`retranslate_surfaces`。 | | `adaptive/empty_views.py` | 99 | Empty tables, lists and trees say so instead of showing a blank grid. 工作區替每頁的表格/清單/樹狀清單加上 `EmptyState` 覆蓋層,沒有任何列時顯示、第一列出現即隱藏;略過表頭與下拉選單內的清單。 | +| `adaptive/page_banner.py` | 149 | A banner at the top of a page: the last run's error, or what the active role cannot run. 工作區在頁首下方放一個隱藏的 `PageBanner`;`TabTask` 回報失敗或被 RBAC 拒絕的執行,顯示頁面時以 `refused_commands` 檢查子面板的 `REQUIRED_COMMANDS`;也提供 `page_of`。 | | `adaptive/style.py` | 117 | Fusion with check boxes and radio buttons drawn from the palette's accent. `AdaptiveStyle`:Fusion 的指示器外框在深色主題下幾乎看不見,改以向量繪製。 | | `adaptive/glyphs.py` | 66 | Small line icons drawn in code, so the navigation rail ships no image files and follows the theme. 選單、搜尋、詳情三個圖示,1x/2x/3x。 | | `adaptive/overlay.py` | 102 | A drawer that slides a panel over part of a host widget, dimming the rest until it is dismissed. `OverlayDrawer`:Escape 或點擊遮罩關閉。 | | `_arrow_icons.py` | 76 | Chevrons for drop-down lists and spin boxes, drawn in code and handed to the style sheet. 以導覽列的線條圖示畫出、依主題色快取成檔案;寫不進快取時不放置子控制項,保留樣式原生箭頭。 | | `adaptive_window.py` | 179 | Rearrange the main window's navigation and details panes as the window's width class changes. `AdaptiveWindowLayout`:expanded 兩側停靠;medium 詳情改抽屜;compact 導覽改圖示欄+抽屜。「想要停靠導覽」與寬度是否允許分開記錄,窄視窗不會改寫使用者偏好。 | -| `workspace.py` | 578 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | +| `workspace.py` | 582 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | | `workspace_details.py` | 116 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 與每個 `TabTask` 都是 publisher;僅訂閱目前頁面,`details_sources()` 通知綁定後才建立的來源。 | -| `_task_details.py` | 111 | Execution details a TabTask publishes for the page it runs on. 由子面板往上找出工作區的分頁、第一次執行時建立來源,發布執行中/停止中/完成/已取消/錯誤與回報的進度。 | +| `_task_details.py` | 116 | Execution details a TabTask publishes for the page it runs on. 由子面板往上找出工作區的分頁、第一次執行時建立來源,發布執行中/停止中/完成/已取消/錯誤與回報的進度。 | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 171 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 130 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | -| `config_sync_tab.py` | 429 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | +| `config_sync_tab.py` | 432 | Lazy Actions-menu workspace synchronization, causal review and explicit live preference application. | | `_auto_click_tab.py` | 321 | 獨立自動點擊分頁;快照工作參數,以 TabTask 執行與取消。 | | `_screenshot_tab.py` | 180 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | | `_image_detect_tab.py` | 158 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | @@ -1330,15 +1331,15 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `_daemon_thread.py` | 79 | `DaemonThread`:`QThread` 的替代品,保留遠端桌面 worker 用到的介面(`start`/`run`/`isRunning`/`wait`/`requestInterruption`/`started`/`finished`),但 `run()` 跑在 daemon `threading.Thread` 上,刪除物件或程式結束都不會銷毀執行中的執行緒。 | | `_worker_thread.py` | 273 | `start_worker()`:在 daemon `threading.Thread` 上執行 `QObject` worker 的 `run()`(沒有 `QThread` 可被銷毀),並經由分頁擁有的中繼物件回報結果(回呼一律在 GUI 執行緒;worker 沒處理的例外也送到 `on_fail`);worker 留在模組登錄表直到 GUI 執行緒看到它結束,啟動失敗回復登記並保留原失敗;回傳 `WorkerHandle`(`isRunning()`);程式結束時先呼叫 worker 的 `request_stop()`,最多等 10 秒,仍在跑的隨行程結束。 | | `task_controller.py` | 270 | 共用 owner-bound task/typed outcome-progress;獨立 token、弱回呼、dispatch 身分更新與銷毀後結果隔離。工作綁定獨立 cancellation scope;其餘面板遷移另列進度。 | -| `template_candidate_panel.py` | 244 | 預覽原始/候選縮圖、檢視驗證並明確接受/回復。 | +| `template_candidate_panel.py` | 247 | 預覽原始/候選縮圖、檢視驗證並明確接受/回復。 | | `template_candidate_worker.py` | 125 | 背景檔案操作、延後權限檢查與提交前取消;完成寫入不重標為取消。 | | `journal_candidate_worker.py` | 150 | 背景產碼、差異呈現、審閱匯出/匯入驗證、權限與取消。 | -| `journal_candidate_panel.py` | 228 | 程式、差異、來源與排除項目的審閱;Actions 明確匯入與匯出。 | +| `journal_candidate_panel.py` | 231 | 程式、差異、來源與排除項目的審閱;Actions 明確匯入與匯出。 | | `journal_candidate_dialog.py` | 97 | Recording Editor/Builder 共用模型外審閱視窗,保護編輯基準並隨擁有者關閉。 | -| `journal_browser.py` | 257 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | +| `journal_browser.py` | 260 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 88 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,527 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,544 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1360,7 +1361,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | | vlm | `vlm_tab.py` | 150 | 用文字描述 UI 元素,交由模型定位。 | -| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 946 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | +| self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 952 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | @@ -1380,7 +1381,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | device_matrix | `device_matrix_tab.py` | 139 | 一份 action list 跨多裝置平行執行。 | | mobile | `mobile_tab.py` | 222 | Android/iOS 裝置工作階段:設定報告、擷取、手勢、輸入與能力矩陣。 | | media_checks | `media_checks_tab.py` | 129 | 音訊活動與影片動態斷言。 | -| run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 833 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | +| run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 836 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | | profiler | `profiler_tab.py` | 141 | 視覺化逐動作耗時熱點。 | | window_manager | `window_tab.py` | 139 | 列出、聚焦、關閉視窗。 | | plugins | `plugins_tab.py` | 85 | 從使用者目錄載入額外 `AC_` 指令。 | @@ -1397,7 +1398,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 277 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | -| diagnostics | `diagnostics_tab.py` | 235 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | +| diagnostics | `diagnostics_tab.py` | 238 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1545,7 +1546,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 162 | 42,922 | +| `gui/` | 163 | 43,125 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1565,8 +1566,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,207 | -| **總計** | **1,527** | **235,444** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | +| **總計** | **1,528** | **235,662** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v224_features_doc.rst b/docs/source/Eng/doc/new_features/v224_features_doc.rst index b1f6ea359..f9fcff0ce 100644 --- a/docs/source/Eng/doc/new_features/v224_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v224_features_doc.rst @@ -68,6 +68,15 @@ What every page gets clicks through, follows a replaced model, and skips header views and the lists inside drop-downs; a view with the ``_jeNoEmptyState`` property set is left alone. +* **Page banner.** Every page gets a banner under its header + (``gui.adaptive.page_banner``), hidden until there is something to say. A + background run on the page that fails shows *The last run failed:* with the + error, and the next run clears it; a run the RBAC layer refuses shows *Not + permitted:* instead. When the GUI runs inside an RBAC scope, opening a page + checks the commands its panels declare in ``REQUIRED_COMMANDS`` against the + active role (``utils.rbac.policy.refused_commands``) and names the ones it + cannot run. The banner's *Dismiss* is a link, not a button: a page's + commands stay in the Actions menu. Building blocks --------------- diff --git a/docs/source/Zh/doc/new_features/v224_features_doc.rst b/docs/source/Zh/doc/new_features/v224_features_doc.rst index 5e5336341..1cb93c745 100644 --- a/docs/source/Zh/doc/new_features/v224_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v224_features_doc.rst @@ -55,6 +55,11 @@ GUI 正以一組共用的自適應元件重新設計,讓每個分頁外觀一 (``gui.adaptive.empty_views.show_empty_states``\ ):沒有任何列時顯示「目前沒有內容。」與 「從 Actions 選單執行指令」的提示,第一列出現就隱藏。它不攔截滑鼠、會跟著替換的 model, 略過表頭與下拉選單內的清單;設定了 ``_jeNoEmptyState`` 屬性的檢視不受影響。 +* **頁面橫幅。** 每頁標題下方都有一個橫幅(``gui.adaptive.page_banner``\ ),有事要說明時才出現。 + 頁面上的背景執行失敗時顯示「上次執行失敗:」與錯誤,下次執行時清除;被 RBAC 拒絕的執行改顯示「未獲許可:」。 + GUI 在 RBAC 範圍內執行時,開啟頁面會以目前角色檢查子面板在 ``REQUIRED_COMMANDS`` 宣告的指令 + (``utils.rbac.policy.refused_commands``\ ),列出無法執行的指令。橫幅的「關閉」是連結而不是按鈕: + 頁面的指令仍在 Actions 選單。 元件 ---- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 0afabd315..17ca9c1ac 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -502,3 +502,11 @@ - **Docs:** the three READMEs, both `v224_features_doc.rst` (controls that shrink), `CHANGELOG.md`. - **Files:** `gui/adaptive/empty_views.py`, `gui/workspace.py`, the four catalogues, the test, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › F2 *其餘* (error and permission states per panel). + +## U-20261114-29 · 2026-11-14 · A page banner for a failed run and for what the role cannot run · #done #gui #rbac + +- **What:** the last of `Progress.md` › F2 *其餘*, error and permission states per panel; the maintainer chose (2026-11-14) one shared page banner. New `gui/adaptive/page_banner.py`: the workspace puts a hidden `PageBanner` under each page's header (`add_page_banner`, after `add_page_header`). A tab task's run that fails shows *The last run failed:* with the same scrubbed `Type: message` the execution details get, and the page's next run clears it; an `AuthorizationError` shows as the permission kind, *Not permitted:*. When the workspace shows a page (`_bind_details`, so on every tab switch) it checks the commands the page and its panels declare in a `REQUIRED_COMMANDS` class attribute against the active role, through the new headless `utils.rbac.policy.refused_commands(names, context=None)` -- the rule `authorize_command` applies, without raising: nothing outside an RBAC scope, nothing for a command `COMMAND_CAPABILITIES` does not list -- and names what it cannot run (*Your role (viewer) cannot run AC_journal_read here.*). The seven panels that authorize commands themselves declare them: journal browser, self-healing comparison, journal candidate, template candidate, Config Sync, Diagnostics, MCP discovery. The GUI opens no RBAC scope of its own, so the permission banner appears when an embedder or another surface runs the GUI inside one. *Dismiss* is a link, since a page's commands live in the Actions menu; the banner retranslates with `retranslate_surfaces`, and the theme draws it with a danger or warning edge (`QFrame[role="banner"][kind=...]`). `page_of` moved from `gui/_task_details.py` into the banner module, which both use. Each panel's own status line is unchanged. +- **Tests:** `test_gui_page_banner.py` (6: `refused_commands` by role, unscoped and for an unlisted command; the banner under the header and hidden; a viewer told on opening and an admin not; a failed run reported and cleared by the next; a refused run as the permission kind; Dismiss and a language switch). Workspace, theme, surfaces, catalogues, RBAC, the seven panels, page widths, Actions menu, task, empty-view, codegen and template tests: 2133 passed, 41 skipped. +- **Docs:** the three READMEs, both `v224_features_doc.rst`, `CHANGELOG.md`. +- **Files:** `gui/adaptive/page_banner.py`, `gui/adaptive/surfaces.py`, `gui/_task_details.py`, `gui/workspace.py`, `gui/theme.py`, the seven panels, `utils/rbac/policy.py`, the four catalogues, the test, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** none in F2 *其餘*; `Progress.md` › F2 keeps the mixed-DPI and font review. diff --git a/docs/updates/README.md b/docs/updates/README.md index 20a624455..319cb5b20 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-29 | 2026-11-14 | A page banner for a failed run and for what the role cannot run | #done #gui #rbac | [2026-11-b](2026-11-b.md) | | U-20261114-28 | 2026-11-14 | Empty tables, lists and trees say so | #done #gui #adaptive | [2026-11-b](2026-11-b.md) | | U-20261114-27 | 2026-11-14 | Every page that runs background work reports it in Execution details | #done #gui #workspace | [2026-11-b](2026-11-b.md) | | U-20261114-26 | 2026-11-14 | Config Sync runs on the shared task; no panel uses a bare worker | #done #gui #sync | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_task_details.py b/je_auto_control/gui/_task_details.py index b055e641c..5dff595ca 100644 --- a/je_auto_control/gui/_task_details.py +++ b/je_auto_control/gui/_task_details.py @@ -2,7 +2,8 @@ The workspace's details pane shows what the current page's :class:`~je_auto_control.gui.workspace_details.ExecutionDetailsSource` -publishes. A tab task finds its page -- the widget the workspace holds as a +publishes, and the page's :class:`~je_auto_control.gui.adaptive.page_banner.PageBanner` +reports a failed run. A tab task finds its page -- the widget the workspace holds as a tab, which may be an ancestor of the panel that owns the task -- and creates that source the first time it runs, so every page that runs background work reports it: running, stopping, then succeeded, cancelled or error, with the @@ -11,33 +12,20 @@ from typing import Optional, Tuple from PySide6.QtCore import QObject, Qt -from PySide6.QtWidgets import QScrollArea, QStackedWidget, QTabWidget, QWidget +from PySide6.QtWidgets import QWidget +from je_auto_control.gui.adaptive.page_banner import PageBanner, page_banner, page_of from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsSource, ExecutionPhase from je_auto_control.utils.executor.run_control import ExecutionStopped from je_auto_control.utils.logging.secret_scope import scrub_secret_text +from je_auto_control.utils.rbac.authorization import AuthorizationError #: The longest error text the details pane is given. SUMMARY_LIMIT = 500 -def page_of(owner: QWidget) -> QWidget: - """The workspace page ``owner`` sits on, or ``owner`` itself when it is on no tab page.""" - current = owner - while True: - viewport = current.parentWidget() - if viewport is None: - return owner - scroll = viewport.parentWidget() - if isinstance(scroll, QScrollArea) and scroll.widget() is current: - stack = scroll.parentWidget() - if isinstance(stack, QStackedWidget) and isinstance(stack.parentWidget(), QTabWidget): - return current - current = viewport - - def details_source_for(owner: QWidget) -> ExecutionDetailsSource: """The details source of ``owner``'s page, created on first use.""" page = page_of(owner) @@ -65,10 +53,13 @@ def __init__(self, task: QObject) -> None: self._completed = self._total = 0 def started(self) -> None: - """A run began.""" + """A run began; it clears the banner's report of the last one.""" self._outcome, self._stopped = None, False self._completed = self._total = 0 self._publish("running") + banner = self._banner() + if banner is not None: + banner.clear("error") def stopping(self) -> None: """Stop was requested for a run that unwinds before it ends.""" @@ -95,11 +86,25 @@ def finished(self) -> None: else: summary = scrub_secret_text(f"{type(error).__name__}: {error}")[:SUMMARY_LIMIT] self._publish("error", summary) + self._report(error, summary) elif kind == "result" and not self._stopped: self._publish("succeeded") else: # cancelled, stopped, or the owner went away self._publish("cancelled") + def _banner(self) -> Optional[PageBanner]: + owner = self._task.parent() + return page_banner(owner) if isinstance(owner, QWidget) else None + + def _report(self, error: object, summary: str) -> None: + banner = self._banner() + if banner is None: + return + if isinstance(error, AuthorizationError): + banner.show_refusal(summary) + else: + banner.show_error(summary) + def _publish(self, phase: ExecutionPhase, summary: str = "") -> None: owner = self._task.parent() if not isinstance(owner, QWidget): diff --git a/je_auto_control/gui/adaptive/page_banner.py b/je_auto_control/gui/adaptive/page_banner.py new file mode 100644 index 000000000..f8aa7d2e1 --- /dev/null +++ b/je_auto_control/gui/adaptive/page_banner.py @@ -0,0 +1,149 @@ +"""A banner at the top of a page: the last run's error, or what the active role cannot run. + +The workspace puts one :class:`PageBanner` under each page's header. It stays +hidden until there is something to say: + +* **Error** -- a background run on the page failed (published by the page's + tab tasks); the next run clears it. +* **Permission** -- the active RBAC role cannot run a command the page's + panels declare in ``REQUIRED_COMMANDS``, checked when the page is shown, + or a run was refused by the RBAC layer. + +The banner has a *Dismiss* link rather than a button: a page's commands live +in the Actions menu, and its views hold no buttons of their own. +""" +from typing import Iterable, List, Optional + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QBoxLayout, QFrame, QHBoxLayout, QLabel, QScrollArea, QStackedWidget, QTabWidget, QWidget + +from je_auto_control.gui.adaptive.surfaces import page_header +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper +from je_auto_control.utils.rbac.authorization import current_authorization +from je_auto_control.utils.rbac.policy import refused_commands + +_BANNER_NAME = "PageBanner" + + +def page_of(owner: QWidget) -> QWidget: + """The workspace page ``owner`` sits on, or ``owner`` itself when it is on no tab page.""" + current = owner + while True: + viewport = current.parentWidget() + if viewport is None: + return owner + scroll = viewport.parentWidget() + if isinstance(scroll, QScrollArea) and scroll.widget() is current: + stack = scroll.parentWidget() + if isinstance(stack, QStackedWidget) and isinstance(stack.parentWidget(), QTabWidget): + return current + current = viewport + + +class PageBanner(QFrame): + """One message about the page as a whole; hidden while there is none.""" + + def __init__(self, parent: Optional[QWidget] = None) -> None: + super().__init__(parent) + self.setObjectName(_BANNER_NAME) + self.setProperty("role", "banner") + self.kind = "" + self._key = "" + self._values: dict[str, str] = {} + layout = QHBoxLayout(self) + layout.setContentsMargins(12, 8, 12, 8) + self.message = QLabel() + self.message.setTextFormat(Qt.TextFormat.PlainText) # error text is never markup + self.message.setWordWrap(True) + self.message.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.dismiss = QLabel() + self.dismiss.setTextFormat(Qt.TextFormat.RichText) + self.dismiss.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse + | Qt.TextInteractionFlag.LinksAccessibleByKeyboard) + self.dismiss.linkActivated.connect(self._dismissed) + layout.addWidget(self.message, stretch=1) + layout.addWidget(self.dismiss, alignment=Qt.AlignmentFlag.AlignTop) + self.hide() + + def show_error(self, detail: str) -> None: + """Say that the page's last run failed, and why.""" + self._show("error", "page_banner_error", detail=detail) + + def show_refusal(self, detail: str) -> None: + """Say that the RBAC layer refused a run, and why.""" + self._show("permission", "page_banner_refused", detail=detail) + + def show_permission(self, role: str, commands: Iterable[str]) -> None: + """Say which of the page's commands the active role cannot run.""" + self._show("permission", "page_banner_permission", role=role, commands=", ".join(commands)) + + def clear(self, kind: str = "") -> None: + """Hide the banner; with ``kind``, only when it is showing that kind.""" + if not kind or kind == self.kind: + self.kind = "" + self.hide() + + def retranslate(self) -> None: + """Re-read the message and the link in the active language.""" + translate = language_wrapper.translate + if self._key: + self.message.setText(translate(self._key, self._key).format(**self._values)) + self.dismiss.setText(f'{translate("page_banner_dismiss", "page_banner_dismiss")}') + + def _show(self, kind: str, key: str, **values: str) -> None: + self.kind, self._key, self._values = kind, key, values + self.setProperty("kind", kind) + self.style().unpolish(self) + self.style().polish(self) + self.retranslate() + self.show() + + def _dismissed(self, _link: str) -> None: + self.clear() + + +def add_page_banner(page: QWidget) -> Optional[PageBanner]: + """Put a hidden :class:`PageBanner` under ``page``'s header; ``None`` when its layout cannot take one.""" + existing = page_banner(page) + if existing is not None: + return existing + layout = page.layout() + if not isinstance(layout, QBoxLayout) or layout.direction() != QBoxLayout.Direction.TopToBottom: + return None + header = page_header(page) + after_header = header is not None and layout.indexOf(header) == 0 + banner = PageBanner(page) + layout.insertWidget(1 if after_header else 0, banner) + return banner + + +def page_banner(widget: QWidget) -> Optional[PageBanner]: + """The banner of the page ``widget`` sits on, or ``None``.""" + found = page_of(widget).findChild(PageBanner, _BANNER_NAME, Qt.FindChildOption.FindDirectChildrenOnly) + return found if isinstance(found, PageBanner) else None + + +def required_commands(page: QWidget) -> List[str]: + """Every ``AC_*`` command the page and its panels declare in ``REQUIRED_COMMANDS``, once each.""" + seen: List[str] = [] + for widget in (page, *page.findChildren(QWidget)): + for name in getattr(type(widget), "REQUIRED_COMMANDS", ()): + if name not in seen: + seen.append(name) + return seen + + +def refresh_permission(page: QWidget) -> None: + """Show or clear the page's permission banner for the active role.""" + banner = page_banner(page) + if banner is None: + return + refused = refused_commands(required_commands(page)) + caller = current_authorization() + if refused and caller is not None: + banner.show_permission(caller.role, refused) + else: + banner.clear("permission") + + +__all__ = ["PageBanner", "add_page_banner", "page_banner", "page_of", "refresh_permission", "required_commands"] diff --git a/je_auto_control/gui/adaptive/surfaces.py b/je_auto_control/gui/adaptive/surfaces.py index 5f769b70d..3ecdb9f13 100644 --- a/je_auto_control/gui/adaptive/surfaces.py +++ b/je_auto_control/gui/adaptive/surfaces.py @@ -151,7 +151,10 @@ def add_page_header(page: QWidget, title_key: str, subtitle_key: str = "") -> Op def retranslate_surfaces(root: QWidget) -> None: - """Re-read every card title, page header and empty state under ``root`` in the active language.""" + """Re-read every card title, page header, page banner and empty state under ``root`` in the active language.""" + from je_auto_control.gui.adaptive.page_banner import PageBanner # reason: page_banner imports this module + for banner in root.findChildren(PageBanner): + banner.retranslate() for header in root.findChildren(PageHeader): header.retranslate() for card in root.findChildren(Card): diff --git a/je_auto_control/gui/config_sync_tab.py b/je_auto_control/gui/config_sync_tab.py index ac8bf6757..add7fe7a2 100644 --- a/je_auto_control/gui/config_sync_tab.py +++ b/je_auto_control/gui/config_sync_tab.py @@ -39,6 +39,9 @@ def _t(key: str) -> str: class ConfigSyncTab(TranslatableMixin, QWidget): """No connection, source capture, activation or credential lookup occurs when the tab is constructed.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ('AC_sync_workspace',) + def __init__(self, parent: Optional[QWidget] = None, *, path_policy: Optional[PathPolicy] = None) -> None: super().__init__(parent) self._tr_init() diff --git a/je_auto_control/gui/diagnostics_tab.py b/je_auto_control/gui/diagnostics_tab.py index 86cc5a27d..225b3eb4d 100644 --- a/je_auto_control/gui/diagnostics_tab.py +++ b/je_auto_control/gui/diagnostics_tab.py @@ -59,6 +59,9 @@ def _diagnostic_work(runner: Callable[[], DiagnosticsReport], token: Cancellatio class DiagnosticsTab(TranslatableMixin, QWidget): """Run :func:`run_diagnostics` and render the results.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ("AC_diagnose",) + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() diff --git a/je_auto_control/gui/healing_evaluation_panel.py b/je_auto_control/gui/healing_evaluation_panel.py index be8d9d48c..649fc075e 100644 --- a/je_auto_control/gui/healing_evaluation_panel.py +++ b/je_auto_control/gui/healing_evaluation_panel.py @@ -73,6 +73,9 @@ def _case_row(row: HealingAttempt) -> list[str]: class HealingEvaluationPanel(TranslatableMixin, QWidget): """Run comparisons through Actions; show explicit populations and selected case details.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ("AC_self_heal_evaluate",) + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() diff --git a/je_auto_control/gui/journal_browser.py b/je_auto_control/gui/journal_browser.py index 462ab3380..ba385fd4d 100644 --- a/je_auto_control/gui/journal_browser.py +++ b/je_auto_control/gui/journal_browser.py @@ -33,6 +33,9 @@ class JournalBrowser(TranslatableMixin, QWidget): """Inspect an explicit file or a selected history link without executing its contents.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ("AC_journal_read",) + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() diff --git a/je_auto_control/gui/journal_candidate_panel.py b/je_auto_control/gui/journal_candidate_panel.py index 78a5d7ebf..3ea42b40f 100644 --- a/je_auto_control/gui/journal_candidate_panel.py +++ b/je_auto_control/gui/journal_candidate_panel.py @@ -27,6 +27,9 @@ def _t(key: str) -> str: class JournalCandidatePanel(TranslatableMixin, QWidget): """Review a journal candidate before choosing a separate import or archive export.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ("AC_generate_candidate_from_log",) + def __init__(self, parent: Optional[QWidget] = None, *, baseline: str = "[]", on_import: Optional[Callable[[CandidateScript], None]] = None) -> None: super().__init__(parent) diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index 3405e71b2..89806ee30 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -1493,6 +1493,10 @@ "task_timed_out": "Took too long and was stopped.", "empty_view": "Nothing to show yet.", "empty_view_hint": "Results appear here once you run a command from the Actions menu.", + "page_banner_error": "The last run failed: {detail}", + "page_banner_refused": "Not permitted: {detail}", + "page_banner_permission": "Your role ({role}) cannot run {commands} here. Ask an administrator for access.", + "page_banner_dismiss": "Dismiss", "stop_playback": "Stop playback", "record_playing": "Playing back...", "rd_file_sending": "Sending {name}...", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index 3b4a8dae5..71a349d89 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -1389,6 +1389,11 @@ "task_timed_out": "時間がかかりすぎたため停止しました。", "empty_view": "まだ表示する内容はありません。", "empty_view_hint": "Actions メニューからコマンドを実行すると、結果がここに表示されます。", + "page_banner_error": "前回の実行は失敗しました:{detail}", + "page_banner_refused": "許可されていません:{detail}", + "page_banner_permission": ("現在のロール({role})ではこのページの {commands} を実行できません。" + "管理者にアクセスを依頼してください。"), + "page_banner_dismiss": "閉じる", "stop_playback": "再生を停止", "record_playing": "再生中...", "rd_file_sending": "{name} を送信中...", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 0a84a4d91..b49456459 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1353,6 +1353,10 @@ "task_timed_out": "执行超时,已停止。", "empty_view": "暂无内容。", "empty_view_hint": "从 Actions 菜单执行命令后,结果会显示在这里。", + "page_banner_error": "上次执行失败:{detail}", + "page_banner_refused": "未获许可:{detail}", + "page_banner_permission": "你的角色({role})无法在此执行 {commands}。请向管理员申请权限。", + "page_banner_dismiss": "关闭", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在发送 {name}...", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index e0551273e..6d4aabb15 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1361,6 +1361,10 @@ "task_timed_out": "執行逾時,已停止。", "empty_view": "目前沒有內容。", "empty_view_hint": "從 Actions 選單執行指令後,結果會顯示在這裡。", + "page_banner_error": "上次執行失敗:{detail}", + "page_banner_refused": "未獲許可:{detail}", + "page_banner_permission": "你的角色({role})無法在此執行 {commands}。請向管理員申請權限。", + "page_banner_dismiss": "關閉", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在傳送 {name}...", diff --git a/je_auto_control/gui/mcp_discovery_view.py b/je_auto_control/gui/mcp_discovery_view.py index 95755e6f2..8386686fc 100644 --- a/je_auto_control/gui/mcp_discovery_view.py +++ b/je_auto_control/gui/mcp_discovery_view.py @@ -19,6 +19,9 @@ class MCPDiscoveryView(QWidget): """Inspect the local default registry without starting a server or granting access.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ("AC_mcp_tool_search",) + def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) self.query, self.name = QLineEdit(), QLineEdit() diff --git a/je_auto_control/gui/template_candidate_panel.py b/je_auto_control/gui/template_candidate_panel.py index 7c08b2b39..6917a3aea 100644 --- a/je_auto_control/gui/template_candidate_panel.py +++ b/je_auto_control/gui/template_candidate_panel.py @@ -30,6 +30,9 @@ def _t(key: str) -> str: class TemplateCandidatePanel(TranslatableMixin, QWidget): """Operate only through Actions, with a concrete reviewed revision before file transitions.""" + #: Checked against the active RBAC role when the page is shown (the page banner says what is refused). + REQUIRED_COMMANDS = ("AC_template_candidate_preview",) + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() diff --git a/je_auto_control/gui/theme.py b/je_auto_control/gui/theme.py index 655449a10..e4a733239 100644 --- a/je_auto_control/gui/theme.py +++ b/je_auto_control/gui/theme.py @@ -148,6 +148,10 @@ def type_scale_rules(point_size: int) -> str: QLabel[role="sectionTitle"] {{ font-weight: 600; color: {text}; }} QLabel[role="emptyMessage"] {{ color: {text_muted}; }} QLabel[role="danger"] {{ color: {danger}; }} +QFrame[role="banner"] {{ background-color: {surface}; border: 1px solid {border}; border-left: 4px solid {border}; + border-radius: {radius_large}px; }} +QFrame[role="banner"][kind="error"] {{ border-color: {danger}; }} +QFrame[role="banner"][kind="permission"] {{ border-color: {warning}; }} QLabel[role="success"] {{ color: {success}; }} QLabel[role="warning"] {{ color: {warning}; }} QLabel[role="accent"] {{ color: {accent}; }} diff --git a/je_auto_control/gui/workspace.py b/je_auto_control/gui/workspace.py index 11eaa2b71..c41dc7016 100644 --- a/je_auto_control/gui/workspace.py +++ b/je_auto_control/gui/workspace.py @@ -9,6 +9,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.adaptive.overlay import OverlayDrawer from je_auto_control.gui.adaptive.empty_views import show_empty_states +from je_auto_control.gui.adaptive.page_banner import add_page_banner, refresh_permission from je_auto_control.gui.adaptive.responsive import fit_to_width from je_auto_control.gui.adaptive.surfaces import add_page_header, retranslate_surfaces from je_auto_control.gui.tab_registry import MenuActions, TabEntry, TabRegistry, WidgetFactory @@ -303,6 +304,8 @@ def _bind_details(self) -> None: self._details_connection = None self._details_source = None page = self.tabs.currentWidget() + if page is not None: + refresh_permission(page) source = None if page is None else page.findChild( ExecutionDetailsSource, options=Qt.FindChildOption.FindDirectChildrenOnly, ) @@ -372,6 +375,7 @@ def _dress(self, key: str, page: QWidget) -> None: entry = self._find_entry(key) if entry is not None: add_page_header(page, entry.title_key, f"{entry.title_key}_subtitle") + add_page_banner(page) fit_to_width(page) show_empty_states(page) diff --git a/je_auto_control/utils/rbac/policy.py b/je_auto_control/utils/rbac/policy.py index 4acf0456d..98fa0b65a 100644 --- a/je_auto_control/utils/rbac/policy.py +++ b/je_auto_control/utils/rbac/policy.py @@ -29,7 +29,7 @@ from __future__ import annotations from collections.abc import Mapping -from typing import Any, Dict, Iterator, Optional, Tuple +from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple from je_auto_control.utils.rbac.authorization import ( AuthorizationContext, AuthorizationError, current_authorization, @@ -416,6 +416,21 @@ def authorize_command(name: Any) -> None: f"has role {context.role!r}", capability=needed) +def refused_commands(names: Iterable[str], + context: Optional[AuthorizationContext] = None) -> List[str]: + """The ``names`` that :func:`authorize_command` would refuse for ``context``, in order. + + ``context`` defaults to the current caller; outside any RBAC scope nothing + is refused, and a command not listed in :data:`COMMAND_CAPABILITIES` never + is -- the same rule ``authorize_command`` applies, without raising. + """ + caller = context if context is not None else current_authorization() + if caller is None: + return [] + return [name for name in names + if name in COMMAND_CAPABILITIES and not caller.allows(COMMAND_CAPABILITIES[name])] + + def denied_command_in(payload: Any, context: AuthorizationContext) -> Optional[Tuple[str, str]]: """``(command, capability)`` for the first privileged command ``context`` may not run. @@ -456,5 +471,5 @@ def _leading_names(node: Any, depth: int) -> Iterator[str]: "COMMAND_CAPABILITIES", "DATA_ROUTES", "DATA_TOOLS", "REST_ROUTE_CAPABILITIES", "TOOL_CAPABILITIES", "authorize_command", "capability_for_command", "capability_for_route", - "capability_for_tool", "denied_command_in", + "capability_for_tool", "denied_command_in", "refused_commands", ] diff --git a/test/unit_test/headless/test_gui_page_banner.py b/test/unit_test/headless/test_gui_page_banner.py new file mode 100644 index 000000000..e8f368050 --- /dev/null +++ b/test/unit_test/headless/test_gui_page_banner.py @@ -0,0 +1,148 @@ +"""A page says when its last run failed, and when the active role cannot run its commands. + +A failure or an RBAC refusal used to show only in each panel's own status +line, in its own words, or not at all on pages without one. The workspace now +gives every page a banner under its header for both. +""" +import os +import threading + +import pytest + +from je_auto_control.utils.rbac import AuthorizationContext, Role, authorization_scope +from je_auto_control.utils.rbac.authorization import AuthorizationError +from je_auto_control.utils.rbac.policy import refused_commands + + +def test_refused_commands_follow_the_role_and_ignore_unscoped_callers(): + assert refused_commands(["AC_journal_read", "AC_diagnose"]) == [] # no RBAC scope + viewer = AuthorizationContext("viewer", Role.VIEWER) + refused = refused_commands(["AC_journal_read", "AC_not_a_listed_command"], viewer) + assert refused == ["AC_journal_read"] # an unlisted one never is + admin = AuthorizationContext("admin", Role.ADMIN) + assert refused_commands(["AC_journal_read"], admin) == [] + with authorization_scope(viewer): + assert refused_commands(["AC_journal_read"]) == ["AC_journal_read"] + + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtCore import QEvent # noqa: E402 +from PySide6.QtWidgets import QApplication, QVBoxLayout, QWidget # noqa: E402 + +from je_auto_control.gui._tab_task import TabTask # noqa: E402 +from je_auto_control.gui.adaptive.page_banner import PageBanner, page_banner # noqa: E402 +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) + + +class _Reader(QWidget): + """A panel that needs journal access, inside a page, running a task.""" + + REQUIRED_COMMANDS = ("AC_journal_read",) + + def __init__(self, parent=None): + super().__init__(parent) + self.task = TabTask(self) + + +class _Page(QWidget): + def __init__(self): + super().__init__() + self.reader = _Reader() + QVBoxLayout(self).addWidget(self.reader) + + +@pytest.fixture +def shell(): + from je_auto_control.gui.tab_registry import TabEntry, TabRegistry + from je_auto_control.gui.workspace import WorkspaceShell + widget = WorkspaceShell(TabRegistry([TabEntry("journal", "tab_run_history", _Page), + TabEntry("other", "other", QWidget)])) + yield widget + widget.deleteLater() + _APP.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + + +def _t(key): + return language_wrapper.translate(key, key) + + +def _banner(shell): + banner = page_banner(shell.tabs.currentWidget()) + assert isinstance(banner, PageBanner) + return banner + + +def test_the_banner_sits_under_the_header_and_starts_hidden(shell): + shell.activate_tab("journal") + page = shell.tabs.currentWidget() + banner = _banner(shell) + assert page.layout().indexOf(banner) == 1 # the header is at 0 + assert banner.isHidden() + + +def test_a_role_that_cannot_run_the_page_is_told_so_when_it_opens(shell): + with authorization_scope(AuthorizationContext("viewer", Role.VIEWER)): + shell.activate_tab("journal") + banner = _banner(shell) + assert not banner.isHidden() and banner.kind == "permission" + assert banner.message.text() == _t("page_banner_permission").format(role="viewer", commands="AC_journal_read") + shell.activate_tab("other") + with authorization_scope(AuthorizationContext("admin", Role.ADMIN)): + shell.activate_tab("journal") # shown again: the admin may + assert banner.isHidden() + + +def test_a_failed_run_is_reported_and_the_next_run_clears_it(shell): + shell.activate_tab("journal") + task = shell.tabs.currentWidget().reader.task + banner = _banner(shell) + + def fail(): + raise ValueError("journal is corrupt") + + assert task.start(fail) + assert pump_until(lambda: not banner.isHidden()) + assert banner.kind == "error" + assert banner.message.text() == _t("page_banner_error").format(detail="ValueError: journal is corrupt") + release = threading.Event() + assert task.start(lambda: release.wait(10.0)) + assert banner.isHidden() # a new run clears the old report + release.set() + assert pump_until(lambda: not task.running) + assert banner.isHidden() + + +def test_a_refused_run_is_a_permission_banner(shell): + shell.activate_tab("journal") + task = shell.tabs.currentWidget().reader.task + + def refuse(): + raise AuthorizationError("AC_journal_read needs the 'drive_input' capability", capability="drive_input") + + assert task.start(refuse) + banner = _banner(shell) + assert pump_until(lambda: not banner.isHidden()) + assert banner.kind == "permission" + assert "drive_input" in banner.message.text() + + +def test_dismiss_hides_the_banner_and_the_text_follows_the_language(shell): + shell.activate_tab("journal") + banner = _banner(shell) + banner.show_error("boom") + previous = language_wrapper.language + try: + language_wrapper.reset_language("Traditional_Chinese") + from je_auto_control.gui.adaptive.surfaces import retranslate_surfaces + retranslate_surfaces(shell.tabs.currentWidget()) # what a language switch runs on each page + assert banner.message.text() == language_wrapper.translate("page_banner_error", "").format(detail="boom") + assert "關閉" in banner.dismiss.text() + finally: + language_wrapper.reset_language(previous) + banner.dismiss.linkActivated.emit("dismiss") + assert banner.isHidden() From c38abde36f5daf67b3734ab14be734d636dd0b2f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 16:49:06 +0800 Subject: [PATCH 097/161] Restyle once on a theme switch, and measure the GUI against the release Measured against main, the redesigned GUI starts in 1.37 s instead of 2.10 s with 115 MB instead of 179 MB, but a theme switch with every tab open took 1.9 s: the window's style sheet was set twice, once for the theme and again for the font. Setting it once brings it to 0.95 s. Add the feature parity gate the F4 plan called for. --- CHANGELOG.md | 4 ++ Progress.md | 2 +- architecture_explore.md | 8 +-- .../doc/new_features/v223_features_doc.rst | 5 ++ .../Zh/doc/new_features/v223_features_doc.rst | 3 + docs/updates/2026-11-b.md | 12 ++++ docs/updates/README.md | 1 + je_auto_control/gui/main_window.py | 6 +- .../headless/test_gui_feature_parity.py | 72 +++++++++++++++++++ .../headless/test_r3_gui_main_window.py | 27 +++++++ 10 files changed, 133 insertions(+), 7 deletions(-) create mode 100644 test/unit_test/headless/test_gui_feature_parity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a521553c..be0f8e240 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- GUI: switching theme restyles the window once instead of twice (the theme's style sheet, + then again with the font rules); with every tab open the switch took 1.9 s on `dev` and + now takes 0.95 s, the release's level. + - GUI: every workspace page has a banner under its header (`gui/adaptive/page_banner.py`): a failed background run (*The last run failed:*), a run refused by RBAC (*Not permitted:*), and, inside an RBAC scope, the commands the active role cannot run. Panels declare theirs in a diff --git a/Progress.md b/Progress.md index 818909ddf..686d2a608 100644 --- a/Progress.md +++ b/Progress.md @@ -547,7 +547,7 @@ F 還缺: 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 -- **F4** 已有 `benchmarks/gui_startup.py` 與 `gui_workloads.py`,仍缺完整啟動/記憶體基準對照、mixed-DPI 與功能對等驗收。 +- **F4** 啟動/記憶體基準對照與功能對等測試已交付(U-20261114-30);仍缺 mixed-DPI 驗收(需要第二台不同縮放的螢幕)。 - **F3 session 所有權**:GUI 斷線及丟棄 offer 路徑仍須在背景排程前取得原始 session 清理物件; peer 建構及畫面來源訂閱的部分失敗所有權仍須補齊。 - **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 diff --git a/architecture_explore.md b/architecture_explore.md index 539d42dc0..a09cb89f0 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,540 | -| 程式碼總行數 | 236,407 | +| 程式碼總行數 | 236,409 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1295,7 +1295,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | -| `main_window.py` | 463 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合,窄視窗時改為抽屜,由 `adaptive_window.py` 安排)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | +| `main_window.py` | 465 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合,窄視窗時改為抽屜,由 `adaptive_window.py` 安排)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | | `navigation.py` | 212 | `NavigationPanel`:品牌標題、搜尋框 + 依分類的功能樹,列出每個已註冊分頁(開啟中的以粗體標示),只回報被選的鍵,開啟分頁仍由視窗負責。停靠面板與窄視窗抽屜各有一個實例。 | @@ -1546,7 +1546,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 163 | 43,125 | +| `gui/` | 163 | 43,127 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,736 | | `utils/executor/` | 11 | 10,752 | @@ -1567,7 +1567,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,528** | **235,662** | +| **總計** | **1,528** | **235,664** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index e38ea0336..ec59bfa8c 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -117,6 +117,11 @@ restyled afterwards and ``theme_deferred_longest_turn_ms`` the longest single turn of that. ``--compare`` sets two reports side by side and refuses when the workload or the environment differs. +To compare against another checkout with the same interpreter, run that +checkout's copy of the scripts with ``PYTHONPATH`` set to its root: the +editable install's finder comes after the path entries, so the checkout's +package is the one imported. + Background work in a tab ------------------------ diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index 25c9a600c..a558cac7c 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -112,6 +112,9 @@ GUI 設定檔): 時間,``theme_deferred_longest_turn_ms`` 是其中最長的一輪。``--compare`` 把兩份 報告並排,工作量或環境不同時拒絕比較。 +要用同一個直譯器比較另一份 checkout,從那份 checkout 執行它自己的腳本,並把 ``PYTHONPATH`` +設為它的根目錄:editable 安裝的 finder 排在路徑項目之後,所以載入的是那份 checkout 的套件。 + 分頁裡的背景工作 ---------------- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 17ca9c1ac..daae42d0f 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -510,3 +510,15 @@ - **Docs:** the three READMEs, both `v224_features_doc.rst`, `CHANGELOG.md`. - **Files:** `gui/adaptive/page_banner.py`, `gui/adaptive/surfaces.py`, `gui/_task_details.py`, `gui/workspace.py`, `gui/theme.py`, the seven panels, `utils/rbac/policy.py`, the four catalogues, the test, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** none in F2 *其餘*; `Progress.md` › F2 keeps the mixed-DPI and font review. + +## U-20261114-30 · 2026-11-14 · GUI startup and memory measured against the release, and the theme switch halved · #done #gui #benchmark + +- **What:** `Progress.md` › F4's baseline comparison and parity gate. `main` (3582a67b, release 1.2.1) was checked out as a detached worktree and both benchmarks were run from each checkout with the same interpreter and PySide6 6.12.0, offscreen, on this machine (Windows 11): `PYTHONPATH` set to the checkout's root wins over the editable install, whose finder is appended after the path entries. `--compare` reported the two comparable (no environment difference). Medians, `main` → `dev`: + - `gui_startup.py --runs 5`: `startup_ms` 2,103.8 → 1,374.1, `import_gui` 1,239.1 → 351.5, `build_window` 719.7 → 901.7, first frame 45.0 → 32.3, RSS 178.6 → 114.9 MB, modules loaded 586 → 515, tabs built at start 8 → 1. + - `gui_workloads.py` (all 51 tabs opened, revisited, searched, theme switched): first opens 3,358.8 → 4,344.2 ms in all, of which Remote Desktop, Screenshot and Script Builder (+939 ms) were built at startup on `main` and are now paid on first open; the other tabs add 25-50 ms each for the redesign's page pass (header, banner, fit-to-width, empty states). Tab switch 7.5 → 12.1 ms, search 1.4 → 1.8 ms, RSS with every tab open 235.0 → 254.8 MB, idle event-loop p95 1.2 → 0.8 ms. + - **A regression found and fixed:** a theme switch took 940.5 ms on `main` and 1,917.2 ms on `dev`. `set_theme` set the window's style sheet twice -- the theme, then again with the font rules appended -- so every widget on every open page was repolished twice, and the redesign's pages carry more widgets and a larger sheet. `main` did the same; it now passes the font size to `apply_theme` and sets the sheet once. Re-measured: 946.5 ms, with the longest event-loop stall 1,881.6 → 962.7 ms. +- **Parity:** new `test_gui_feature_parity.py` (4): a new window opens on Record, Script Builder and Remote Desktop; every catalogued tab has a unique key and resolves to a class; Remote Desktop without the `webrtc` extra says it is unavailable, how to install it and the underlying error; importing the package loads no Qt. `test_r3_gui_main_window.py` gains a theme switch setting the style sheet exactly once (fails on the old code). +- **Tests:** theme, adaptive, workspace layout and navigation, main-window, collapsible-section, execution-details and parity tests: 79 passed. +- **Docs:** both `v223_features_doc.rst` (how to measure another checkout), `CHANGELOG.md`. +- **Files:** `gui/main_window.py`, the tests, the docs, `Progress.md`. The worktree was removed afterwards. +- **Open items:** `Progress.md` › F4 (mixed-DPI acceptance, which needs a second screen at another scale). diff --git a/docs/updates/README.md b/docs/updates/README.md index 319cb5b20..cc011b767 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-30 | 2026-11-14 | GUI startup and memory measured against the release, and the theme switch halved | #done #gui #benchmark | [2026-11-b](2026-11-b.md) | | U-20261114-29 | 2026-11-14 | A page banner for a failed run and for what the role cannot run | #done #gui #rbac | [2026-11-b](2026-11-b.md) | | U-20261114-28 | 2026-11-14 | Empty tables, lists and trees say so | #done #gui #adaptive | [2026-11-b](2026-11-b.md) | | U-20261114-27 | 2026-11-14 | Every page that runs background work reports it in Execution details | #done #gui #workspace | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/main_window.py b/je_auto_control/gui/main_window.py index c18b07b26..12135f727 100644 --- a/je_auto_control/gui/main_window.py +++ b/je_auto_control/gui/main_window.py @@ -253,8 +253,10 @@ def set_theme(self, name: str) -> None: """Switch to the theme called ``name`` (``dark`` or ``light``), keeping the text size.""" tokens = theme_named(name) self._theme_name = tokens.name - self._theme_stylesheet = apply_theme(self, tokens) - self._apply_font_pt(self._user_font_pt) + # One style sheet with the font rules already appended: setting the theme + # and then the font restyled every widget on every open page twice. + point_size = self._user_font_pt if self._user_font_pt > 0 else self._detect_auto_font_pt() + self._theme_stylesheet = apply_theme(self, tokens, point_size=point_size) self._adaptive.set_glyph_colour(tokens.text) def apply_workspace_preferences(self, values: dict[str, object]) -> None: diff --git a/test/unit_test/headless/test_gui_feature_parity.py b/test/unit_test/headless/test_gui_feature_parity.py new file mode 100644 index 000000000..330f73e66 --- /dev/null +++ b/test/unit_test/headless/test_gui_feature_parity.py @@ -0,0 +1,72 @@ +"""The redesigned GUI keeps every feature reachable, opens on the default workflow, and explains what it cannot offer. + +Plan F4's parity gate: the three tabs a new window shows, every catalogued tab +still resolving to a class, a feature whose optional extra is missing saying +why and how to install it, and the facade staying Qt-free. +""" +import importlib +import os +import subprocess # nosec B404 # reason: starts this interpreter on a literal probe +import sys + +import pytest + +from je_auto_control.gui.tab_registry import TAB_SPECS + + +def test_a_new_window_opens_on_the_default_workflow(): + assert [spec.key for spec in TAB_SPECS if spec.default_visible] == ["record", "script_builder", "remote_desktop"] + + +def test_every_catalogued_tab_has_a_unique_key_and_resolves_to_a_class(): + keys = [spec.key for spec in TAB_SPECS] + assert len(keys) == len(set(keys)) + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + unresolved = [] + for spec in TAB_SPECS: + if not spec.module: # built by the main widget itself (Remote Desktop) + continue + try: + module = importlib.import_module(spec.module) + except ImportError as error: # an optional extra this environment lacks + if "webrtc" in spec.module or "remote_desktop" in spec.module: + continue + unresolved.append(f"{spec.key}: {error!r}") + continue + if not isinstance(getattr(module, spec.class_name, None), type): + unresolved.append(f"{spec.key}: {spec.module}.{spec.class_name} is not a class") + assert unresolved == [] + + +def test_a_feature_without_its_extra_says_why_and_how_to_install_it(monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication, QLabel + QApplication.instance() or QApplication([]) + from je_auto_control.gui import main_widget + + real_import = __import__ + + def no_webrtc(name, *args, **kwargs): + if name == "je_auto_control.gui.remote_desktop_tab": + raise ImportError("No module named 'aiortc'") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr("builtins.__import__", no_webrtc) + page = main_widget.AutoControlGUIWidget._build_remote_desktop_tab() + try: + text = " ".join(label.text() for label in page.findChildren(QLabel)) + assert "unavailable" in text + assert "pip install je_auto_control[webrtc]" in text + assert "aiortc" in text # the underlying reason, not only the advice + finally: + page.deleteLater() + + +def test_importing_the_package_loads_no_qt(): + probe = "import sys, je_auto_control; print(any('PySide6' in name for name in sys.modules))" + # argv is this interpreter plus a literal probe. No shell. + done = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, # nosec B603 # reason: literal argv + check=False, timeout=120) + assert done.returncode == 0, done.stderr + assert done.stdout.strip() == "False" diff --git a/test/unit_test/headless/test_r3_gui_main_window.py b/test/unit_test/headless/test_r3_gui_main_window.py index 22a37bf5f..0da867305 100644 --- a/test/unit_test/headless/test_r3_gui_main_window.py +++ b/test/unit_test/headless/test_r3_gui_main_window.py @@ -49,3 +49,30 @@ def test_apply_font_pt_keeps_theme_across_size_changes(qapp): assert "font-size: 12pt" not in sheet # old rule fully replaced finally: window.deleteLater() + + +def test_a_theme_switch_restyles_the_window_once(qapp): + # Setting the theme's sheet and then the font's restyled every widget on + # every open page twice; with all tabs open that doubled the switch. + import types + + class _Counting(QMainWindow): + def __init__(self): + super().__init__() + self.sheets = [] + + def setStyleSheet(self, sheet): # noqa: N802 # reason: Qt override + self.sheets.append(sheet) + super().setStyleSheet(sheet) + + window = _Counting() + window._user_font_pt = 14 + window._adaptive = types.SimpleNamespace(set_glyph_colour=lambda colour: None) + try: + AutoControlGUIUI.set_theme(window, "light") + assert len(window.sheets) == 1 + assert "font-size: 14pt" in window.sheets[0] # the font rule rides along + assert window._theme_stylesheet in window.sheets[0] + assert "font-size: 14pt" not in window._theme_stylesheet # kept without it, for size changes + finally: + window.deleteLater() From 0a435e00521718aaecc5d8e07ff996b4a2cd4096 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 16:54:20 +0800 Subject: [PATCH 098/161] Keep a minidump when python.exe crashes in Windows CI The freed-thread-state abort seen on Windows 3.14.8 left only the Python lines faulthandler prints; Linux jobs already run under GDB. Windows Error Reporting now writes a minidump of a crashed python.exe into the native artifact the job retains after a failure. --- .github/workflows/dev.yml | 17 +++++++++++++++++ .github/workflows/quality.yml | 17 +++++++++++++++++ Progress.md | 5 ++++- .../Eng/doc/new_features/v2_features_doc.rst | 4 +++- .../Zh/doc/new_features/v2_features_doc.rst | 3 ++- docs/source/getting_started/run_in_ci.rst | 6 ++++-- docs/updates/2026-11-b.md | 9 +++++++++ docs/updates/README.md | 1 + .../headless/test_ci_native_diagnostics.py | 6 ++++++ 9 files changed, 63 insertions(+), 5 deletions(-) diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index 90f072a30..6f16eb888 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -94,6 +94,23 @@ jobs: python -m pytest -v --tb=short --timeout=30 test/unit_test/headless/test_ci_native_diagnostics.py + # Windows leaves no core file, so a native crash (the freed-thread-state + # abort seen on 3.14.8) has shown only the Python lines faulthandler + # prints. Windows Error Reporting's LocalDumps writes a minidump of a + # crashed python.exe -- every thread's native stack -- into the folder + # the next steps retain, even when the suite fails. + - name: Keep native crash dumps (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + $dumps = Join-Path $env:RUNNER_TEMP 'autocontrol-native\dumps' + New-Item -ItemType Directory -Force -Path $dumps | Out-Null + $key = 'HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\python.exe' + New-Item -Path $key -Force | Out-Null + New-ItemProperty -Path $key -Name DumpFolder -PropertyType ExpandString -Value $dumps -Force | Out-Null + New-ItemProperty -Path $key -Name DumpType -PropertyType DWord -Value 1 -Force | Out-Null + New-ItemProperty -Path $key -Name DumpCount -PropertyType DWord -Value 5 -Force | Out-Null + - name: Run headless pytest suite shell: bash run: >- diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index a45ba6d95..07e89e307 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -161,6 +161,23 @@ jobs: python -m pytest -v --tb=short --timeout=30 test/unit_test/headless/test_ci_native_diagnostics.py + # Windows leaves no core file, so a native crash (the freed-thread-state + # abort seen on 3.14.8) has shown only the Python lines faulthandler + # prints. Windows Error Reporting's LocalDumps writes a minidump of a + # crashed python.exe -- every thread's native stack -- into the folder + # the next steps retain, even when the suite fails. + - name: Keep native crash dumps (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + $dumps = Join-Path $env:RUNNER_TEMP 'autocontrol-native\dumps' + New-Item -ItemType Directory -Force -Path $dumps | Out-Null + $key = 'HKLM:\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\python.exe' + New-Item -Path $key -Force | Out-Null + New-ItemProperty -Path $key -Name DumpFolder -PropertyType ExpandString -Value $dumps -Force | Out-Null + New-ItemProperty -Path $key -Name DumpType -PropertyType DWord -Value 1 -Force | Out-Null + New-ItemProperty -Path $key -Name DumpCount -PropertyType DWord -Value 5 -Force | Out-Null + # Paths come from `testpaths` in pyproject.toml. Do NOT pass an explicit # path here: an argument overrides testpaths, which previously meant the # flow_control tests were configured to run but silently never did. diff --git a/Progress.md b/Progress.md index 686d2a608..40c95d72b 100644 --- a/Progress.md +++ b/Progress.md @@ -550,7 +550,10 @@ F 還缺: - **F4** 啟動/記憶體基準對照與功能對等測試已交付(U-20261114-30);仍缺 mixed-DPI 驗收(需要第二台不同縮放的螢幕)。 - **F3 session 所有權**:GUI 斷線及丟棄 offer 路徑仍須在背景排程前取得原始 session 清理物件; peer 建構及畫面來源訂閱的部分失敗所有權仍須補齊。 -- **F3 Windows 原生釋放驗收**:`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。 +- **F3 Windows 原生釋放驗收**(`BLOCKED`:等 CI 再次發生):`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort + 尚缺 Windows 原生堆疊與獨立根因確認。CI 的 Windows 工作現在會把 `python.exe` 當掉時的 minidump 存進 + `native--` artifact 的 `dumps/`(U-20261114-31);本機 Python 3.14.7 連跑二十次未重現, + 最近的 Windows 3.11/3.14 CI 也未再出現。下次 CI 發生時以該 dump 判讀根因。 **只記未完成的事。** 完成的工作記在 [docs/updates/](docs/updates/README.md)(每月一個批次檔, 索引與查詢指令在它的 README),相容性變更寫進 [CHANGELOG.md](CHANGELOG.md);完成的項目 diff --git a/docs/source/Eng/doc/new_features/v2_features_doc.rst b/docs/source/Eng/doc/new_features/v2_features_doc.rst index 096977b23..332a2029c 100644 --- a/docs/source/Eng/doc/new_features/v2_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v2_features_doc.rst @@ -656,7 +656,9 @@ returns. Native compositor/dialog, restore and restart acceptance remain open. The repository's dev/main headless jobs retain merged test output and runtime versions even after a native failure. Linux runs under GDB for all-thread -native backtraces; other platforms retain Python faulthandler output. The +native backtraces; Windows has Windows Error Reporting write a minidump of a +crashed ``python.exe`` (every thread's native stack) into the same artifact; +macOS retains Python faulthandler output. The ``native--`` artifacts expire after seven days. Failed child exits still fail CI. Linux first checks the runner outside the suite's debugger; literal argv and handled SIGINT are preserved. See diff --git a/docs/source/Zh/doc/new_features/v2_features_doc.rst b/docs/source/Zh/doc/new_features/v2_features_doc.rst index 93fbc553c..460044d06 100644 --- a/docs/source/Zh/doc/new_features/v2_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v2_features_doc.rst @@ -552,7 +552,8 @@ D-Bus 寫入與回覆共用預算,connect/驗證/Hello 中斷時,即使 repo 的 dev/main 無頭工作在原生失敗後仍保留合併測試輸出與執行環境版本。 -Linux 經 GDB 擷取各執行緒原生堆疊,其他平台保留 Python faulthandler 輸出。 +Linux 經 GDB 擷取各執行緒原生堆疊;Windows 由 Windows Error Reporting 把當掉的 ``python.exe`` +的 minidump(各執行緒原生堆疊)寫進同一個 artifact;macOS 保留 Python faulthandler 輸出。 ``native--`` artifact 保留七天;子行程失敗仍使 CI 失敗。 Linux 先在完整套件的 debugger 外檢查工具,保留原始 argv 與已處理的 SIGINT。 重現方法見 :doc:`/getting_started/run_in_ci`。蒐集證據不代表完成尚缺的 portal/原生生命週期驗收。 diff --git a/docs/source/getting_started/run_in_ci.rst b/docs/source/getting_started/run_in_ci.rst index 25f540bc7..d754b166c 100644 --- a/docs/source/getting_started/run_in_ci.rst +++ b/docs/source/getting_started/run_in_ci.rst @@ -61,8 +61,10 @@ with ``curl /health``. The dev/main headless jobs also retain ``native--`` artifacts for seven days, even when tests fail. ``process.log`` combines stdout/stderr; ``runtime.json`` records package/runtime versions and the child exit status. -Linux runs under GDB and retains all-thread native backtraces. Other systems -retain Python faulthandler output. Neither ordinary failure nor native abort +Linux runs under GDB and retains all-thread native backtraces. On Windows the +job first sets Windows Error Reporting's ``LocalDumps`` for ``python.exe`` to +``dumps/`` inside the artifact, so a native crash leaves a minidump with every +thread's native stack. macOS retains Python faulthandler output. Neither ordinary failure nor native abort is converted into a passing job. Native root-cause acceptance remains separate from collecting the evidence. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index daae42d0f..fadb7568b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -522,3 +522,12 @@ - **Docs:** both `v223_features_doc.rst` (how to measure another checkout), `CHANGELOG.md`. - **Files:** `gui/main_window.py`, the tests, the docs, `Progress.md`. The worktree was removed afterwards. - **Open items:** `Progress.md` › F4 (mixed-DPI acceptance, which needs a second screen at another scale). + +## U-20261114-31 · 2026-11-14 · Windows CI keeps a minidump of a crashed python.exe · #done #ci #native-diagnostics + +- **What:** a step toward `Progress.md` › F3 *Windows 原生釋放驗收*, the freed-thread-state abort in `test_remote_desktop_host_id.py` seen on Windows with Python 3.14.8 (U-20261021 era), which still lacks a native stack. Linux jobs run the suite under GDB; Windows kept only the Python lines faulthandler prints. Both `quality.yml` and `dev.yml` now set Windows Error Reporting's `LocalDumps` for `python.exe` (minidump, at most five) to `autocontrol-native\dumps` before the suite, inside the folder the *Retain native test diagnostics* step uploads even after a failure, so the next native crash leaves every thread's native stack in the `native--` artifact. The runner creates its artifact folder with `exist_ok`, so the folder made first does not stop it. +- **Reproduction attempt:** twenty consecutive runs of `test_remote_desktop_host_id.py` with `-X faulthandler` on this machine (Windows 11, Python 3.14.7) all passed (15 tests each); the recent Windows 3.11 and 3.14 CI runs did not abort either. The root cause therefore stays open in `Progress.md`, now marked as waiting for the next occurrence in CI. +- **Tests:** `test_ci_native_diagnostics.py`'s workflow contract also checks, for both workflows, that the Windows dump step runs before the suite, configures `LocalDumps\python.exe` and `DumpFolder`, and points into the uploaded folder (fails without the step). All ten test files that read the workflows: 103 passed, 5 skipped (Linux GDB only). +- **Docs:** `getting_started/run_in_ci.rst`, both `v2_features_doc.rst`. +- **Files:** `.github/workflows/quality.yml`, `.github/workflows/dev.yml`, the test, the docs, `Progress.md`. +- **Open items:** `Progress.md` › F3 *Windows 原生釋放驗收* (read the dump once CI catches the abort). diff --git a/docs/updates/README.md b/docs/updates/README.md index cc011b767..3fdcf5103 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-31 | 2026-11-14 | Windows CI keeps a minidump of a crashed python.exe | #done #ci #native-diagnostics | [2026-11-b](2026-11-b.md) | | U-20261114-30 | 2026-11-14 | GUI startup and memory measured against the release, and the theme switch halved | #done #gui #benchmark | [2026-11-b](2026-11-b.md) | | U-20261114-29 | 2026-11-14 | A page banner for a failed run and for what the role cannot run | #done #gui #rbac | [2026-11-b](2026-11-b.md) | | U-20261114-28 | 2026-11-14 | Empty tables, lists and trees say so | #done #gui #adaptive | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/test_ci_native_diagnostics.py b/test/unit_test/headless/test_ci_native_diagnostics.py index d0cf68b1a..b1e9f4d88 100644 --- a/test/unit_test/headless/test_ci_native_diagnostics.py +++ b/test/unit_test/headless/test_ci_native_diagnostics.py @@ -119,3 +119,9 @@ def test_ci_workflows_keep_native_diagnostics_after_failure(name): assert upload['with']['path'] in runner['run'] assert ('python -m coverage run -m pytest' if name == 'quality.yml' else 'python -m pytest') in runner['run'] assert any('gdb' in step.get('run', '') and step.get('if') == "runner.os == 'Linux'" for step in steps) + # Windows: crash minidumps land inside the retained folder, configured before the suite starts. + dumps = next(step for step in steps if step.get('name') == 'Keep native crash dumps (Windows)') + assert dumps['if'] == "runner.os == 'Windows'" + assert steps.index(dumps) < steps.index(runner) + assert 'LocalDumps\python.exe' in dumps['run'] and 'DumpFolder' in dumps['run'] + assert "autocontrol-native\dumps" in dumps['run'] and upload['with']['path'].endswith('autocontrol-native') From 2cd4412b62d95f9075b83aa084b601784fce0f5b Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 17:17:12 +0800 Subject: [PATCH 099/161] Start, stop and disconnect Quick Connect off the GUI thread Stopping a host or closing a viewer joins its threads for up to two seconds, and Quick Connect and the Viewer tab did both in the button slot. The registry can now free a slot at once and hand back the blocking shutdown, which runs on a worker; a new connect closes the session it replaces on its own worker before connecting. --- CHANGELOG.md | 8 + Progress.md | 4 +- architecture_explore.md | 29 +-- .../Eng/doc/new_features/new_features_doc.rst | 5 + .../doc/new_features/v223_features_doc.rst | 10 +- .../Zh/doc/new_features/new_features_doc.rst | 4 +- .../Zh/doc/new_features/v223_features_doc.rst | 6 +- docs/updates/2026-11-b.md | 11 ++ docs/updates/README.md | 1 + .../gui/remote_desktop/_connect_task.py | 23 ++- .../gui/remote_desktop/_host_ops.py | 39 ++++ .../gui/remote_desktop/connection_screen.py | 81 +++++--- .../gui/remote_desktop/host_panel.py | 34 +--- .../gui/remote_desktop/viewer_panel.py | 11 +- .../utils/remote_desktop/registry.py | 17 ++ pyproject.toml | 1 + .../headless/test_quick_connect_offthread.py | 182 ++++++++++++++++++ .../test_remote_clipboard_delivery_gui.py | 5 +- .../test_remote_desktop_quick_connect.py | 10 +- .../test_remote_registry_owners_gui.py | 6 +- 20 files changed, 399 insertions(+), 88 deletions(-) create mode 100644 je_auto_control/gui/remote_desktop/_host_ops.py create mode 100644 test/unit_test/headless/test_quick_connect_offthread.py diff --git a/CHANGELOG.md b/CHANGELOG.md index be0f8e240..7c5797c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- Remote desktop: `remote_desktop_registry.detach(slot, by, only_own=False)` frees a slot at + once and returns the blocking shutdown of what it held (or `None`), for a caller that must + not block. GUI: Quick Connect starts and stops its host off the GUI thread (*Starting…* / + *Stopping…* meanwhile); Quick Connect's and the Viewer tab's Disconnect, and a connect that + replaces a session, close the old one on a worker. `connect_viewer` takes `before=`, run on + its worker ahead of the connect. The Host panel's start/stop helpers moved to + `gui/remote_desktop/_host_ops.py`. + - GUI: switching theme restyles the window once instead of twice (the theme's style sheet, then again with the font rules); with every tab open the switch took 1.9 s on `dev` and now takes 0.95 s, the release's level. diff --git a/Progress.md b/Progress.md index 40c95d72b..74c6112c6 100644 --- a/Progress.md +++ b/Progress.md @@ -535,8 +535,8 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 -- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移,包含 Quick Connect 的同步啟停、 - 已進入傳輸的取消與同頁 session generation 隔離。分頁的背景工作已全部改走共用 `TaskController` +- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移,包含已進入傳輸的取消與同頁 session generation 隔離 + (Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒,U-20261114-32)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, diff --git a/architecture_explore.md b/architecture_explore.md index a09cb89f0..4c22b912b 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,540 | -| 程式碼總行數 | 236,409 | +| Python 模組總數(含周邊子專案) | 1,541 | +| 程式碼總行數 | 236,488 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,062 行。 +> 6 個套件、約 32,079 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,736 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,753 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,736 行/77 檔) +#### `utils/remote_desktop/`(16,753 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -835,7 +835,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `viewer.py` | 743 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | -| `registry.py` | 564 | `AC_remote_*` 指令使用的行程級單例。 | +| `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | | `webrtc_transport.py` | 421 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | | `multi_viewer.py` | 464 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | @@ -1389,7 +1389,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,368 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,430 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1407,7 +1407,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,40 檔/8,368 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,430 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1422,10 +1422,11 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `webrtc_dialogs.py` | 524 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | -| `connection_screen.py` | 673 | Quick Connect —— AnyDesk 風格單畫面入口。 | -| `viewer_panel.py` | 594 | 「控制另一台機器」子分頁。 | +| `connection_screen.py` | 704 | Quick Connect —— AnyDesk 風格單畫面入口。 | +| `viewer_panel.py` | 599 | 「控制另一台機器」子分頁。 | | `webrtc_known_hosts.py` | 339 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | -| `host_panel.py` | 420 | 「分享這台機器」子分頁。 | +| `host_panel.py` | 396 | 「分享這台機器」子分頁。 | +| `_host_ops.py` | 39 | Start and stop the machine's remote-desktop host on a worker thread. Host 面板與 Quick Connect 共用的 `replace_host`/`stop_host`/`release_host`。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | | `webrtc_workers.py` | 237 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | | `tab.py` | 180 | 外層容器分頁。 | @@ -1546,9 +1547,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 163 | 43,127 | +| `gui/` | 164 | 43,189 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,736 | +| `utils/remote_desktop/` | 77 | 16,753 | | `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1567,7 +1568,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,528** | **235,664** | +| **總計** | **1,529** | **235,743** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/new_features_doc.rst b/docs/source/Eng/doc/new_features/new_features_doc.rst index b5bce86ca..70e37b32e 100644 --- a/docs/source/Eng/doc/new_features/new_features_doc.rst +++ b/docs/source/Eng/doc/new_features/new_features_doc.rst @@ -804,6 +804,11 @@ from ``je_auto_control.utils.remote_desktop.registry.new_owner(label)``. ``stop_host`` / ``disconnect_viewer`` (and the ``ws`` pair) take an optional ``owner=`` that limits them to that owner's host or viewer. ``on_displaced(slot, by)`` runs on the thread that did the replacing. +``detach(slot, by, only_own=False)`` is ``evict`` (or, with ``only_own``, +``release``) split in two for a caller that must not block: the slot is free +when it returns, and it hands back the call that stops what the slot held +(joining its threads) -- or ``None`` -- to run on a worker; the displaced owner +is told when that call runs. GUI: **Remote Desktop** tab opens to the **Quick Connect** screen (AnyDesk-style) by default — huge Host ID on one side, a single input diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index ec59bfa8c..14a5bb9d4 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -167,9 +167,13 @@ outcome arrives -- the tab shows "Stopping…" meanwhile -- and ``on_done`` runs on the GUI thread once it is false again, which is where the code that used to follow the blocking call goes. The Scheduler, Triggers, Hotkeys, E-mail Triggers, Webhooks, REST API and USB Sharing tabs and the Remote Desktop host -panel stop (and, where a start first stops, start) this way. The WebRTC panels -let go of their session at once and hand its shutdown to a ``StopQueue``, so -the next session can start while the old one closes. Callbacks are held +panel stop (and, where a start first stops, start) this way, and so does Quick +Connect's *Start hosting* / *Stop*, whose badge reads *Starting…* / *Stopping…* +meanwhile. The WebRTC panels let go of their session at once and hand its +shutdown to a ``StopQueue``, so the next session can start while the old one +closes; Quick Connect's and the Viewer tab's *Disconnect* now do the same +through ``registry.detach``, and a new connect closes the session it replaces +on its own worker before connecting. Callbacks are held weakly: pass a method and ``args=``, not a ``functools.partial`` or a lambda that closes over the tab. diff --git a/docs/source/Zh/doc/new_features/new_features_doc.rst b/docs/source/Zh/doc/new_features/new_features_doc.rst index 5a16151f5..ea4ed0cf0 100644 --- a/docs/source/Zh/doc/new_features/new_features_doc.rst +++ b/docs/source/Zh/doc/new_features/new_features_doc.rst @@ -731,7 +731,9 @@ on_displaced)``、``owned(slot, owner)``、``release(slot, owner)``、 ``je_auto_control.utils.remote_desktop.registry.new_owner(label)`` 產生。 ``stop_host``/``disconnect_viewer``(以及 ``ws`` 那一組)多了可選的 ``owner=``,只在該 owner 擁有時才動作。``on_displaced(slot, by)`` -在執行取代動作的那個執行緒上被呼叫。 +在執行取代動作的那個執行緒上被呼叫。``detach(slot, by, only_own=False)`` 是把 ``evict``\ (加上 +``only_own`` 時為 ``release``\ )拆成兩半,給不能阻塞的呼叫端:回傳時 slot 已經空出,並回傳停止原佔用者 +(會 join 它的執行緒)的呼叫或 ``None``,交給 worker 執行;被取代的 owner 在那個呼叫執行時收到通知。 GUI:\ **Remote Desktop**\ 分頁預設打開的是 **快速連線** (AnyDesk 風格)— 一邊是超大本機 Host ID,另一邊一個輸入框接受 diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index a558cac7c..a62259338 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -157,8 +157,10 @@ GUI 設定檔): 為 true——分頁這時顯示「正在停止…」——而 ``on_done`` 會在 ``busy`` 變回 false 之後於 GUI 執行緒執行,原本接在阻塞呼叫後面的程式碼就放在這裡。排程、觸發器、熱鍵、E-mail 觸發器、Webhooks、REST API、USB Sharing 分頁與遠端桌面的 host 面板都這樣停止(需要 -先停再啟動的也這樣啟動)。WebRTC 面板則是立刻放掉工作階段,把它的關閉交給 -``StopQueue``,所以舊的還在關閉時就能開始下一個。回呼以弱參照持有:請傳方法與 +先停再啟動的也這樣啟動),Quick Connect 的「開始主持」/「停止」也一樣,期間狀態顯示「正在啟動…」/ +「正在停止…」。WebRTC 面板則是立刻放掉工作階段,把它的關閉交給 +``StopQueue``,所以舊的還在關閉時就能開始下一個;Quick Connect 與 Viewer 分頁的「中斷連線」 +現在也經 ``registry.detach`` 這樣做,新的連線會先在自己的 worker 上關掉被取代的工作階段再連線。回呼以弱參照持有:請傳方法與 ``args=``,不要傳 ``functools.partial`` 或閉包抓著分頁的 lambda。 這是 GUI 內部 API(會 import ``PySide6``),套件 facade 不會重新匯出;分頁所呼叫的 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index fadb7568b..9a448c28f 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -531,3 +531,14 @@ - **Docs:** `getting_started/run_in_ci.rst`, both `v2_features_doc.rst`. - **Files:** `.github/workflows/quality.yml`, `.github/workflows/dev.yml`, the test, the docs, `Progress.md`. - **Open items:** `Progress.md` › F3 *Windows 原生釋放驗收* (read the dump once CI catches the abort). + +## U-20261114-32 · 2026-11-14 · Quick Connect starts, stops and disconnects off the GUI thread · #done #gui #remote-desktop + +- **What:** `Progress.md` › F3's *Quick Connect 的同步啟停*. Quick Connect called `registry.evict(SLOT_HOST)` and `host.start()` in *Start hosting*, `registry.evict` in *Stop*, and `registry.release` for both viewer slots in *Disconnect* and before every connect -- each stop or disconnect joins the old host's or viewer's threads (up to 2 s), on the GUI thread. The Viewer tab did the same in its connect and Disconnect. + - New headless `remote_desktop_registry.detach(slot, by, only_own=False)`: `evict` (or `release`) split in two. The slot is emptied under the lock and is free when it returns; the call it returns runs the old occupant's `stop` / `disconnect` and tells its displaced owner, wherever the caller runs it. `None` when the slot held nothing (or, with `only_own`, someone else's session). + - Quick Connect's *Start hosting* and *Stop* run on a `SlowOp` with the Host panel's helpers, now shared in `gui/remote_desktop/_host_ops.py` (`replace_host`, `stop_host`, `release_host`); the badge reads *Starting…* / *Stopping…* while one is out, a second click is ignored, and a start still out when the screen is disposed is cancelled with its host released. *Disconnect* frees both viewer slots at once and hands their shutdown to a `StopQueue`. A connect that replaces a session frees the slot at once and passes the old session's shutdown to `connect_viewer(..., before=...)`, which runs it on the connect's worker before connecting, so the old viewer lets go of its seat first; it runs even when the connect was cancelled, and a failure is logged. + - The Viewer tab's connect and Disconnect use `detach` the same way. No Remote Desktop GUI module calls `evict` / `release` on the GUI thread any more; only `_host_ops.py` does, on a worker. +- **Tests:** new `test_quick_connect_offthread.py` (6: `detach` frees the slot before closing and tells the displaced owner when its call runs; `only_own` and an empty slot; Quick Connect's Stop returns within 0.5 s against a host whose stop blocks, shows *Stopping…*, and stops it on a worker; Disconnect frees the session at once and closes it on a worker; `before` runs on the connect's worker ahead of the connect; the Viewer tab's Disconnect likewise). Existing tests that checked the registry right after `_start_hosting()` / `_stop_hosting()` wait for the `SlowOp` (`test_remote_desktop_quick_connect.py`, `test_remote_registry_owners_gui.py`); the clipboard retention test lets the queued shutdown finish before checking the viewer was freed without GC. Remote Desktop, registry, clipboard, dispose, off-thread and Quick Connect tests: 1394 passed, 12 skipped; the wider registry / worker / controller / slow-stop set: 3421 passed, 18 skipped. +- **Docs:** both `new_features_doc.rst` (registry API), both `v223_features_doc.rst` (slow stops), `CHANGELOG.md`. +- **Files:** `utils/remote_desktop/registry.py`, `gui/remote_desktop/_host_ops.py` (strict mypy tier, `pyproject.toml`), `gui/remote_desktop/host_panel.py`, `gui/remote_desktop/connection_screen.py`, `gui/remote_desktop/viewer_panel.py`, `gui/remote_desktop/_connect_task.py`, the tests, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › F3 (cancelling a transfer already under way, same-page session generation isolation, backend cancel propagation). diff --git a/docs/updates/README.md b/docs/updates/README.md index 3fdcf5103..d0b25275e 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-32 | 2026-11-14 | Quick Connect starts, stops and disconnects off the GUI thread | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-31 | 2026-11-14 | Windows CI keeps a minidump of a crashed python.exe | #done #ci #native-diagnostics | [2026-11-b](2026-11-b.md) | | U-20261114-30 | 2026-11-14 | GUI startup and memory measured against the release, and the theme switch halved | #done #gui #benchmark | [2026-11-b](2026-11-b.md) | | U-20261114-29 | 2026-11-14 | A page banner for a failed run and for what the role cannot run | #done #gui #rbac | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/_connect_task.py b/je_auto_control/gui/remote_desktop/_connect_task.py index 5eca352a0..353b8a8f0 100644 --- a/je_auto_control/gui/remote_desktop/_connect_task.py +++ b/je_auto_control/gui/remote_desktop/_connect_task.py @@ -8,7 +8,7 @@ task-controller worker, and handed back on the GUI thread. """ import functools -from typing import Any, Callable +from typing import Any, Callable, Optional from PySide6.QtCore import QObject @@ -28,8 +28,16 @@ def _disconnect_quietly(viewer: Any) -> None: autocontrol_logger.debug("dropping an unused viewer: %r", error) -def _connect(viewer: Any, timeout_s: float, token: CancellationToken) -> Any: - """Worker thread: connect ``viewer`` and return it.""" +def _connect(viewer: Any, timeout_s: float, before: Optional[Callable[[], Any]], + token: CancellationToken) -> Any: + """Worker thread: run ``before`` (always), then connect ``viewer`` and return it.""" + if before is not None: + # The previous session's shutdown: it lets go of its seat before this + # one connects, and it runs even when the connect was cancelled. + try: + before() + except (OSError, RuntimeError) as error: + autocontrol_logger.warning("closing the previous remote-desktop session failed: %r", error) # connect() takes a timeout but no cancel signal: a cancelled attempt # runs out its timeout, and the viewer it produced is disconnected by # the task's ``discard``. @@ -41,16 +49,19 @@ def _connect(viewer: Any, timeout_s: float, token: CancellationToken) -> Any: def connect_viewer(owner: QObject, viewer: Any, *, on_connected: Callable[[Any], None], on_failed: Callable[[Exception], None], - timeout_s: float = CONNECT_TIMEOUT_S) -> TaskHandle: + timeout_s: float = CONNECT_TIMEOUT_S, + before: Optional[Callable[[], Any]] = None) -> TaskHandle: """Run ``viewer.connect`` off the GUI thread for ``owner``; return the task. ``on_connected(viewer)`` or ``on_failed(error)`` runs on the GUI thread, and only while ``owner`` exists; both are held weakly, so pass methods of the panel (or a ``functools.partial`` of one), never a closure over it. Cancelling the task, or destroying ``owner``, disconnects a viewer that - connects anyway. + connects anyway. ``before`` -- typically the shutdown of the session this + one replaces, from ``registry.detach`` + -- runs on the same worker first, so it does not hold the GUI thread. """ - handle = task_controller().submit(functools.partial(_connect, viewer, timeout_s), + handle = task_controller().submit(functools.partial(_connect, viewer, timeout_s, before), owner=owner, discard=_disconnect_quietly) handle.result.connect(weak_slot(on_connected)) handle.error.connect(weak_slot(on_failed)) diff --git a/je_auto_control/gui/remote_desktop/_host_ops.py b/je_auto_control/gui/remote_desktop/_host_ops.py new file mode 100644 index 000000000..99dccbb78 --- /dev/null +++ b/je_auto_control/gui/remote_desktop/_host_ops.py @@ -0,0 +1,39 @@ +"""Start and stop the machine's remote-desktop host on a worker thread. + +Stopping a host joins its threads (up to 2 s), and starting one stops the +host already running first, so both used to hold the GUI thread for that +long. The Host panel and the Quick Connect screen hand these to a +:class:`~je_auto_control.gui._slow_op.SlowOp` instead. +""" +from typing import Any, Callable + +from je_auto_control.utils.remote_desktop.registry import SLOT_HOST, registry + + +def replace_host(owner: str, build: Callable[[], Any], + on_displaced: Callable[[str, str], None]) -> Any: + """Worker thread: stop the running host, start the new one and register it for ``owner``. + + In this order because the old host has to let go of its port before the + new one binds it; the stop joins the old host's threads (2 s). + """ + # Whoever started the running host is told it was replaced. Viewers + # are left alone: they belong to other panels or to a script. + registry.evict(SLOT_HOST, by=owner) + host = build() + host.start() + registry.adopt(SLOT_HOST, host, owner, on_displaced) + return host + + +def stop_host(owner: str) -> bool: + """Worker thread: stop the machine's host, whoever started it.""" + return registry.evict(SLOT_HOST, by=owner) + + +def release_host(owner: str, _host: Any) -> None: + """A host that came up for a panel that is gone: nobody is left to stop it.""" + registry.release(SLOT_HOST, owner) + + +__all__ = ["release_host", "replace_host", "stop_host"] diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 8b44d36da..b9056443c 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -31,10 +31,12 @@ from je_auto_control.gui.adaptive.responsive import ResponsiveBox from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui._dispose import release_resources +from je_auto_control.gui._slow_op import SlowOp, StopQueue, stop_each from je_auto_control.gui._weak_call import WeakCall from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui.remote_desktop.view_approvals import ApprovalRequest as _ApprovalRequest, ViewApprovals from je_auto_control.gui.remote_desktop._connect_task import connect_viewer +from je_auto_control.gui.remote_desktop._host_ops import release_host, replace_host, stop_host from je_auto_control.gui.remote_desktop.connection_recent import _RecentConnectionsMixin from je_auto_control.gui.remote_desktop._helpers import ( _StatusBadge, _build_verifying_client_context, _t, @@ -148,6 +150,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: # and replay it the moment the window is created. self._pending_frame: Optional[bytes] = None self._connect_task: Optional[TaskHandle] = None # the connect in progress, off-thread + # Starting and stopping the host join threads; so does closing a viewer. + self._host_op = SlowOp(self) + self._stops = StopQueue(self) + self._host_pending = "" self._uploads = TabTask(self) # dropped files going to the host, off-thread self._uploads.error.connect(self._on_upload_failed) self._uploads.finished.connect(self._refresh_status) @@ -182,6 +188,9 @@ def dispose(self) -> None: """ self._view.retire() self._approvals.retire() + # A host start still out is cancelled and the host it brings up released; + # sessions already let go of keep closing on the stop queue. + release_resources(self._host_op) release_resources(self, self._cancel_pending_connect, self._close_screen_window) def retranslate(self) -> None: @@ -302,19 +311,28 @@ def _start_hosting(self) -> None: if not token: self._generate_token() token = self._host_token.text().strip() - registry.evict(SLOT_HOST, by=self._owner) - try: - host = RemoteDesktopHost( - token=token, bind="127.0.0.1", port=0, - fps=10.0, quality=70, - on_pending_viewer=self._approvals.request, - ) - host.start() - except (OSError, ValueError, RuntimeError) as error: - QMessageBox.warning(self, _t("rd_quick_start_host"), str(error)) - return - registry.adopt(SLOT_HOST, host, self._owner, self._view.callback("_on_displaced")) + build = functools.partial( + RemoteDesktopHost, token=token, bind="127.0.0.1", port=0, fps=10.0, quality=70, + on_pending_viewer=self._approvals.request, + ) + if self._host_op.run( + functools.partial(replace_host, self._owner, build, self._view.callback("_on_displaced")), + on_done=self._on_host_changed, on_error=self._on_host_start_failed, + discard=functools.partial(release_host, self._owner)): + self._host_pending = "gui_op_starting" + self._refresh_status() + + def _on_host_changed(self, _outcome: object = None) -> None: + """GUI thread: a start or stop finished; repaint from the registry.""" + self._refresh_status() + + def _on_host_start_failed(self, error: Exception) -> None: self._refresh_status() + QMessageBox.warning(self, _t("rd_quick_start_host"), str(error)) + + def _on_host_stop_failed(self, error: Exception) -> None: + self._refresh_status() + QMessageBox.warning(self, _t("rd_quick_stop_host"), str(error)) def _host_approval_callback(self, pending: PendingViewer): """Bridge incoming viewers to a GUI Allow/View-only/Deny dialog. @@ -374,11 +392,9 @@ def _show_approval_dialog(self, request: _ApprovalRequest) -> None: def _stop_hosting(self) -> None: # Stops the host the badge shows, whoever started it; see _HostPanel._stop. - try: - registry.evict(SLOT_HOST, by=self._owner) - except (OSError, RuntimeError) as error: - QMessageBox.warning(self, _t("rd_quick_stop_host"), str(error)) - return + if self._host_op.run(functools.partial(stop_host, self._owner), on_done=self._on_host_changed, + on_error=self._on_host_stop_failed): + self._host_pending = "gui_op_stopping" self._refresh_status() def _copy_host_id(self) -> None: @@ -435,11 +451,16 @@ def _dispatch_target(self, target: ConnectTarget, token: str) -> None: self, _t("rd_quick_connect_btn"), _t("rd_quick_bad_target"), ) - def _take_slot(self, slot: str) -> None: - """Clear ``slot`` for a new session and end this screen's other one.""" + def _take_slot(self, slot: str) -> Optional[functools.partial]: + """Clear ``slot`` for a new session and let go of this screen's other one. + + Both slots are free when this returns; the shutdown of what they held + -- which joins threads -- is returned, to run on a worker. + """ other = SLOT_WS_VIEWER if slot == SLOT_VIEWER else SLOT_VIEWER - registry.release(other, self._owner) - registry.evict(slot, by=self._owner) + closes = [close for close in (registry.detach(other, self._owner, only_own=True), + registry.detach(slot, self._owner)) if close is not None] + return functools.partial(stop_each, *closes) if closes else None def _own_viewer(self): """The viewer this screen opened, or None once it is gone or replaced.""" @@ -464,15 +485,18 @@ def _begin_connect(self, slot: str, build, on_live) -> None: ``on_live`` is a method of this screen or a partial of one; it is held weakly. """ self._cancel_pending_connect() - self._take_slot(slot) + previous = self._take_slot(slot) try: viewer = build() except (OSError, RuntimeError, ValueError, AutoControlException) as error: + if previous is not None: + self._stops.retire(previous) self._on_connect_failed(error) return + # The old session is closed on the connect's worker, before the new one connects. self._connect_task = connect_viewer( self, viewer, on_connected=functools.partial(self._on_viewer_live, slot, WeakCall(on_live)), - on_failed=self._on_connect_failed) + on_failed=self._on_connect_failed, before=previous) self._connect_task.finished.connect(self._on_connect_finished) self._refresh_status() @@ -537,8 +561,12 @@ def _disconnect(self) -> None: # Either transport, and only a session this screen opened. self._cancel_pending_connect() self._uploads.stop() # its socket is about to close; the failure is not news - registry.release(SLOT_VIEWER, self._owner) - registry.release(SLOT_WS_VIEWER, self._owner) + # The slots are free at once; closing the sockets (a join) runs off the GUI thread. + closes = [close for close in (registry.detach(SLOT_VIEWER, self._owner, only_own=True), + registry.detach(SLOT_WS_VIEWER, self._owner, only_own=True)) + if close is not None] + if closes: + self._stops.retire(functools.partial(stop_each, *closes)) self._close_screen_window() self._refresh_status() @@ -630,6 +658,9 @@ def _refresh_status(self) -> None: self._refresh_viewer_status() def _refresh_host_status(self) -> None: + if self._host_op.busy: + self._host_badge.set_state("starting", _t(self._host_pending)) + return status = registry.host_status() if status["running"]: host_id = status.get("host_id") or "" diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index d7bab5442..d4a1a1620 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -2,7 +2,7 @@ import functools import secrets import ssl -from typing import Any, Callable, Optional +from typing import Any, Optional from PySide6.QtCore import QTimer, Signal from PySide6.QtGui import QGuiApplication, QImage @@ -16,6 +16,7 @@ from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.surfaces import Card, set_role +from je_auto_control.gui.remote_desktop._host_ops import release_host, replace_host, stop_host from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui.remote_desktop._helpers import ( _CollapsibleSection, _StatusBadge, _t, @@ -33,31 +34,6 @@ ) -def _replace_host(owner: str, build: Callable[[], Any], - on_displaced: Callable[[str, str], None]) -> Any: - """Worker thread: stop the running host, start the new one and register it for ``owner``. - - In this order because the old host has to let go of its port before the - new one binds it; the stop joins the old host's threads (2 s). - """ - # Whoever started the running host is told it was replaced. Viewers - # are left alone: they belong to other panels or to a script. - registry.evict(SLOT_HOST, by=owner) - host = build() - host.start() - registry.adopt(SLOT_HOST, host, owner, on_displaced) - return host - - -def _stop_host(owner: str) -> bool: - """Worker thread: stop the machine's host, whoever started it.""" - return registry.evict(SLOT_HOST, by=owner) - - -def _release_host(owner: str, _host: Any) -> None: - """A host that came up for a panel that is gone: nobody is left to stop it.""" - registry.release(SLOT_HOST, owner) - class _HostPanel(TranslatableMixin, QWidget): """Start / stop the singleton host and show what is being streamed.""" @@ -344,9 +320,9 @@ def _start(self) -> None: self._starting = {"bind": bind, "transport": transport, "token": token} self._pending_key = "gui_op_starting" self._host_op.run( - functools.partial(_replace_host, self._owner, build, self._view.callback("_on_displaced")), + functools.partial(replace_host, self._owner, build, self._view.callback("_on_displaced")), on_done=self._on_started, on_error=self._on_start_failed, - discard=functools.partial(_release_host, self._owner)) + discard=functools.partial(release_host, self._owner)) self._refresh_status() def _on_started(self, host: Any) -> None: @@ -366,7 +342,7 @@ def _stop(self) -> None: if self._host_op.busy: # a second click while the first is still stopping return self._pending_key = "gui_op_stopping" - self._host_op.run(functools.partial(_stop_host, self._owner), on_done=self._on_stopped, + self._host_op.run(functools.partial(stop_host, self._owner), on_done=self._on_stopped, on_error=self._on_stop_failed) self._refresh_status() diff --git a/je_auto_control/gui/remote_desktop/viewer_panel.py b/je_auto_control/gui/remote_desktop/viewer_panel.py index e1e5250ef..1d6fdec2d 100644 --- a/je_auto_control/gui/remote_desktop/viewer_panel.py +++ b/je_auto_control/gui/remote_desktop/viewer_panel.py @@ -260,7 +260,8 @@ def _connect(self) -> None: if transport in ("WebSocket", "WSS") else RemoteDesktopViewer) self._cancel_pending_connect() - registry.evict(SLOT_VIEWER, by=self._owner) + # The slot is free at once; the old session closes on the connect's worker (a join). + previous = registry.detach(SLOT_VIEWER, self._owner) authority = DeferredAuthorization.capture() clipboard_receiver = ClipboardReceiver(authority, self._view.callback("_on_clipboard_main")) viewer: RemoteDesktopViewer @@ -283,12 +284,14 @@ def _connect(self) -> None: clipboard_receiver.bind(viewer) self._connect_authority = authority except (OSError, RuntimeError, ValueError, AutoControlException) as error: + if previous is not None: + self._stops.retire(previous) QMessageBox.warning(self, _t("rd_viewer_connect"), str(error)) return # The connect itself (TCP, TLS / WebSocket upgrade, auth: up to five # seconds each) held the GUI thread for all of it. self._connect_task = connect_viewer( - self, viewer, on_connected=self._on_connected, on_failed=self._on_connect_failed) + self, viewer, on_connected=self._on_connected, on_failed=self._on_connect_failed, before=previous) self._connect_task.finished.connect(self._on_connect_finished) self._refresh_status() @@ -381,7 +384,9 @@ def _on_displaced(self, _slot: str, _by: str) -> None: def _disconnect(self) -> None: self._clipboard_authority = None self._cancel_pending_connect() - registry.release(SLOT_VIEWER, self._owner) + close = registry.detach(SLOT_VIEWER, self._owner, only_own=True) + if close is not None: + self._stops.retire(close) # free at once; closing the socket joins its thread self._stop_audio_player() self._connected = False self._early_frame = None diff --git a/je_auto_control/utils/remote_desktop/registry.py b/je_auto_control/utils/remote_desktop/registry.py index 941f56c85..6636ddd33 100644 --- a/je_auto_control/utils/remote_desktop/registry.py +++ b/je_auto_control/utils/remote_desktop/registry.py @@ -30,6 +30,7 @@ callback is called with ``(slot, by)`` so it can drop its window and state. The callback runs on the thread that did the replacing. """ +import functools import itertools import ssl import threading @@ -210,6 +211,22 @@ def release(self, slot: str, owner: str, timeout: float = 2.0) -> bool: self._shut(slot, claim, timeout, by=owner) return True + def detach(self, slot: str, by: str, *, only_own: bool = False, + timeout: float = 2.0) -> Optional[Callable[[], None]]: + """Empty ``slot`` now and return the call that stops what it held; ``None`` if it held nothing. + + :meth:`evict` (or, with ``only_own``, :meth:`release`) split in two + for a caller that must not block: the slot is free as soon as this + returns, so a new host or viewer can take it, and the returned call + -- which joins the old one's threads -- runs wherever the caller + chooses, typically a worker. The displaced owner is told when that + call runs, as with ``evict``. + """ + claim = self._take(slot, only_owner=by if only_own else None) + if claim is None: + return None + return functools.partial(self._shut, slot, claim, timeout, by) + def owner_of(self, slot: str) -> Optional[str]: """Return the owner of ``slot``'s occupant, or None when it is empty.""" with self._lock: diff --git a/pyproject.toml b/pyproject.toml index 190f89adc..fb3e08596 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -374,6 +374,7 @@ module = [ "je_auto_control.gui.remote_desktop.view_approvals", "je_auto_control.gui.remote_desktop.view_frames", "je_auto_control.gui.remote_desktop.view_upload", + "je_auto_control.gui.remote_desktop._host_ops", "je_auto_control.gui.rbac_users_panel", "je_auto_control.gui.remote_desktop._connect_task", diff --git a/test/unit_test/headless/test_quick_connect_offthread.py b/test/unit_test/headless/test_quick_connect_offthread.py new file mode 100644 index 000000000..09846e860 --- /dev/null +++ b/test/unit_test/headless/test_quick_connect_offthread.py @@ -0,0 +1,182 @@ +"""Quick Connect starts, stops and disconnects without holding the GUI thread. + +Stopping the host joins its threads and closing a viewer joins its receive +thread, up to 2 s each; Quick Connect did both in the button slot, and taking +a slot for a new connect closed the old session there too. The registry can +now free a slot at once and hand back the blocking shutdown +(:meth:`registry.detach`), which Quick Connect runs on a worker. +""" +import os +import threading +import time + +import pytest + +from je_auto_control.utils.remote_desktop.registry import SLOT_HOST, SLOT_VIEWER, registry + + +class _Blocking: + """A host / viewer whose shutdown waits for ``release`` and records the thread it ran on.""" + + is_running = True + port = 5555 + connected_clients = 0 + host_id = "123456789" + connected = True + + def __init__(self): + self.release, self.entered = threading.Event(), threading.Event() + self.shut_on = [] + + def _shut(self, timeout=2.0): + self.shut_on.append(threading.get_ident()) + self.entered.set() + assert self.release.wait(10.0) + + stop = disconnect = _shut + + +@pytest.fixture(autouse=True) +def empty_slots(): + for slot in (SLOT_HOST, SLOT_VIEWER): + close = registry.detach(slot, "test") + if close is not None: + close() + yield + for slot in (SLOT_HOST, SLOT_VIEWER): + close = registry.detach(slot, "test") + if close is not None: + close() + + +def test_detach_frees_the_slot_at_once_and_returns_the_shutdown(): + told, resource = [], _Blocking() + resource.release.set() + registry.adopt(SLOT_VIEWER, resource, "panel", lambda slot, by: told.append((slot, by))) + close = registry.detach(SLOT_VIEWER, "other") + assert registry.owned(SLOT_VIEWER, "panel") is None # free before anything was closed + assert resource.shut_on == [] and told == [] + close() + assert len(resource.shut_on) == 1 + assert told == [(SLOT_VIEWER, "other")] # the displaced owner is told when it runs + + +def test_detach_only_own_leaves_someone_elses_session_and_an_empty_slot_gives_nothing(): + resource = _Blocking() + registry.adopt(SLOT_VIEWER, resource, "panel") + assert registry.detach(SLOT_VIEWER, "other", only_own=True) is None + assert registry.owned(SLOT_VIEWER, "panel") is resource + resource.release.set() + registry.detach(SLOT_VIEWER, "panel", only_own=True)() + assert registry.detach(SLOT_VIEWER, "panel") is None + + +@pytest.fixture +def screen(monkeypatch, tmp_path): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + try: + from je_auto_control.gui.remote_desktop import connection_screen + except ImportError: + pytest.skip("the remote desktop GUI needs the webrtc extra") + from je_auto_control.utils.remote_desktop.address_book import AddressBook + monkeypatch.setattr(connection_screen, "default_address_book", lambda: AddressBook(tmp_path / "book.json")) + view = connection_screen.QuickConnectScreen() + view._refresh_timer.stop() + yield view + view.deleteLater() + + +def test_stopping_the_host_returns_at_once_and_says_stopping(screen): + from headless._qt_settle import settle_op + from je_auto_control.gui.remote_desktop._helpers import _t + host = _Blocking() + registry.adopt(SLOT_HOST, host, "script") + gui = threading.get_ident() + started = time.monotonic() + screen._stop_hosting() + assert time.monotonic() - started < 0.5 # the 2 s join is not on this thread + assert host.entered.wait(10.0) + assert screen._host_badge.text() == _t("gui_op_stopping") + host.release.set() + assert settle_op(screen._host_op) + assert registry.host is None + assert host.shut_on and host.shut_on[0] != gui + assert screen._host_badge.text() == _t("rd_quick_not_hosting") + + +def test_disconnect_frees_the_session_at_once_and_closes_it_on_a_worker(screen): + from headless._qt_settle import pump_until + viewer = _Blocking() + registry.adopt(SLOT_VIEWER, viewer, screen._owner) + gui = threading.get_ident() + started = time.monotonic() + screen._disconnect() + assert time.monotonic() - started < 0.5 + assert registry.owned(SLOT_VIEWER, screen._owner) is None # free for the next connect already + assert viewer.entered.wait(10.0) + assert viewer.shut_on[0] != gui + viewer.release.set() + assert pump_until(lambda: screen._stops.pending == 0) + + +def test_a_new_connect_closes_the_old_session_on_its_worker_first(monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication, QWidget + QApplication.instance() or QApplication([]) + from je_auto_control.gui.remote_desktop._connect_task import connect_viewer + from headless._qt_settle import pump_until + order, done = [], threading.Event() + + class _Viewer: + def connect(self, timeout): + order.append(("connect", threading.get_ident())) + + def disconnect(self, timeout=2.0): + pass + + owner = QWidget() + try: + def connected(viewer): + done.set() + + handle = connect_viewer(owner, _Viewer(), on_connected=connected, on_failed=lambda error: None, + before=lambda: order.append(("close old", threading.get_ident()))) + assert handle is not None + assert pump_until(done.is_set) + assert [step for step, _thread in order] == ["close old", "connect"] + assert order[0][1] == order[1][1] != threading.get_ident() + finally: + owner.deleteLater() + + +def test_the_viewer_panels_disconnect_closes_on_a_worker_too(monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + try: + from je_auto_control.gui.remote_desktop import viewer_panel + except ImportError: + pytest.skip("the remote desktop GUI needs the webrtc extra") + from headless._qt_settle import pump_until + monkeypatch.setattr(viewer_panel, "is_audio_backend_available", lambda: False) + panel = viewer_panel._ViewerPanel() + viewer = _Blocking() + try: + registry.adopt(SLOT_VIEWER, viewer, panel._owner) + gui = threading.get_ident() + started = time.monotonic() + panel._disconnect() + assert time.monotonic() - started < 0.5 + assert registry.owned(SLOT_VIEWER, panel._owner) is None + assert viewer.entered.wait(10.0) + assert viewer.shut_on[0] != gui + viewer.release.set() + assert pump_until(lambda: panel._stops.pending == 0) + finally: + viewer.release.set() + panel.deleteLater() diff --git a/test/unit_test/headless/test_remote_clipboard_delivery_gui.py b/test/unit_test/headless/test_remote_clipboard_delivery_gui.py index b552f7362..7e7440375 100644 --- a/test/unit_test/headless/test_remote_clipboard_delivery_gui.py +++ b/test/unit_test/headless/test_remote_clipboard_delivery_gui.py @@ -7,7 +7,7 @@ import pytest pytest.importorskip('PySide6.QtWidgets', exc_type=ImportError) -from headless._qt_settle import settle +from headless._qt_settle import pump_until, settle from headless.test_remote_registry_owners_gui import qapp as qapp, _tab from je_auto_control.utils.clipboard import clipboard from je_auto_control.utils.rbac import AuthorizationContext, Role, UserStore, authorization_scope, current_authorization @@ -259,6 +259,9 @@ def test_disconnected_clipboard_callback_does_not_retain_its_own_viewer_until_gc reference = weakref.ref(peer) panel._disconnect() del peer + # The socket closes on a worker (a join); the viewer is held until that has run. + assert pump_until(lambda: panel._stops.pending == 0) + qapp.processEvents() assert reference() is None, 'the clipboard callback retained its own viewer and native panel until arbitrary GC' finally: panel._disconnect() diff --git a/test/unit_test/headless/test_remote_desktop_quick_connect.py b/test/unit_test/headless/test_remote_desktop_quick_connect.py index 6d2a73617..807e0672a 100644 --- a/test/unit_test/headless/test_remote_desktop_quick_connect.py +++ b/test/unit_test/headless/test_remote_desktop_quick_connect.py @@ -13,7 +13,7 @@ from PySide6.QtWidgets import QApplication # noqa: E402 from je_auto_control.utils.remote_desktop.registry import registry # noqa: E402 -from headless._qt_settle import settle # noqa: E402 +from headless._qt_settle import settle, settle_op # noqa: E402 @pytest.fixture(scope="module") @@ -88,11 +88,13 @@ def test_start_hosting_registers_host_and_refreshes_badge(qapp): try: screen._host_token.setText("ttt") # noqa: SLF001 screen._start_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread assert registry.host is not None assert registry.host.is_running # Badge text updated from the idle placeholder to running text. assert "{port}" not in screen._host_badge.text() # noqa: SLF001 screen._stop_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread assert registry.host is None finally: screen.deleteLater() @@ -145,6 +147,7 @@ def test_publish_via_signaling_emits_host_handoff(qapp): try: screen._host_token.setText("ttt") # noqa: SLF001 screen._start_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread captured = [] screen.webrtc_host_handoff_requested.connect( lambda token, host_id: captured.append((token, host_id)), @@ -158,6 +161,7 @@ def test_publish_via_signaling_emits_host_handoff(qapp): assert len(host_id) == 9 assert host_id.isdigit() screen._stop_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread finally: screen.deleteLater() @@ -204,6 +208,7 @@ def fake_show_dialog(self, request): try: screen._host_token.setText("ttt") # noqa: SLF001 screen._start_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread host = registry.host assert host is not None try: @@ -235,6 +240,7 @@ def attempt_connect(): viewer.disconnect(timeout=1.0) finally: screen._stop_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread finally: screen.deleteLater() _ = cs_mod # keep import for namespace stability @@ -264,6 +270,7 @@ def fake_show_dialog(self, request): try: screen._host_token.setText("ttt") # noqa: SLF001 screen._start_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread host = registry.host assert host is not None try: @@ -288,6 +295,7 @@ def attempt(): assert "error" in captured finally: screen._stop_hosting() # noqa: SLF001 + assert settle_op(screen._host_op) # noqa: SLF001 # the start / stop runs off the GUI thread finally: screen.deleteLater() diff --git a/test/unit_test/headless/test_remote_registry_owners_gui.py b/test/unit_test/headless/test_remote_registry_owners_gui.py index 66e656b87..3286dcc57 100644 --- a/test/unit_test/headless/test_remote_registry_owners_gui.py +++ b/test/unit_test/headless/test_remote_registry_owners_gui.py @@ -331,7 +331,9 @@ def _host_tab(): def test_starting_a_host_leaves_every_viewer_alone(): tab, screen = _tab(), _quick("ws") _host_tab() - connection_screen.QuickConnectScreen()._start_hosting() + quick = connection_screen.QuickConnectScreen() + quick._start_hosting() + assert settle_op(quick._host_op) # the start runs off the GUI thread assert tab._own_viewer().connected assert screen._own_viewer().connected @@ -343,6 +345,7 @@ def test_quick_connect_hosting_replaces_the_host_tabs_host_and_tells_it(qapp): assert registry.owner_of(SLOT_HOST) == tab._owner screen = connection_screen.QuickConnectScreen() screen._start_hosting() + assert settle_op(screen._host_op) assert not first.is_running assert registry.owner_of(SLOT_HOST) == screen._owner assert pump_until(lambda: tab._shared is None) # no share text for a host it does not run @@ -357,6 +360,7 @@ def test_stop_stops_the_host_on_show_and_tells_its_owner(): screen = connection_screen.QuickConnectScreen() assert screen._host_id_label.text() != "---" # it shows the host as running screen._stop_hosting() + assert settle_op(screen._host_op) assert not running.is_running assert registry.host is None assert pump_until(lambda: tab._shared is None) From 84a9b65527560799b0424335e7d0058d33f680d2 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 17:28:56 +0800 Subject: [PATCH 100/161] Stop a file transfer already sending when it is cancelled Once begun, a TCP or WebSocket upload streamed to its last byte even after the page closed or the session was dropped. send_file now checks between chunks and, once stopped, sends a cancelled end so the host discards the partial file. --- CHANGELOG.md | 8 + Progress.md | 4 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 24 +-- .../doc/new_features/v223_features_doc.rst | 2 +- .../Zh/doc/new_features/v223_features_doc.rst | 2 +- docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + .../gui/remote_desktop/view_upload.py | 16 +- .../gui/remote_desktop/webrtc_viewer_files.py | 12 +- .../utils/remote_desktop/file_transfer.py | 34 +++- .../utils/remote_desktop/viewer.py | 8 +- .../headless/test_file_transfer_cancel.py | 145 ++++++++++++++++++ .../headless/test_remote_view_retirement.py | 2 +- 16 files changed, 242 insertions(+), 30 deletions(-) create mode 100644 test/unit_test/headless/test_file_transfer_cancel.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c5797c61..6fa116630 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- Remote desktop: `file_transfer.send_file` and `RemoteDesktopViewer.send_file` take a + keyword `cancelled=` callable and otherwise follow the calling thread's cancellation scope. + A transfer stopped mid-file sends a `FILE_END` with status `cancelled` (the receiver discards + the part file) and raises `concurrent.futures.CancelledError`; one stopped before its first + byte sends nothing. GUI: the Viewer tab's upload, Quick Connect's dropped files and the + WebRTC panel's uploads stop at the next chunk when their task is cancelled (the page closes or + the session is dropped). A test double replacing `send_file` must accept `cancelled`. + - Remote desktop: `remote_desktop_registry.detach(slot, by, only_own=False)` frees a slot at once and returns the blocking shutdown of what it held (or `None`), for a caller that must not block. GUI: Quick Connect starts and stops its host off the GUI thread (*Starting…* / diff --git a/Progress.md b/Progress.md index 74c6112c6..bf1f318ee 100644 --- a/Progress.md +++ b/Progress.md @@ -535,8 +535,8 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 -- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移,包含已進入傳輸的取消與同頁 session generation 隔離 - (Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒,U-20261114-32)。分頁的背景工作已全部改走共用 `TaskController` +- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移,包含同頁 session generation 隔離 + (Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒,U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, diff --git a/README.md b/README.md index a43ff1648..d39dae1f1 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ Managed agent tasks and cross-host transfers include experimental features. See [MIT](LICENSE) © JE-Chen. [Third-party licenses](Third_Party_License.md). -Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. Stopping an entered file transfer depends on the backend's cooperative cancellation. +Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. A file transfer already sending stops at its next chunk when the page closes, the session is dropped or the upload is cancelled, and the host discards the partial file (TCP, WebSocket and WebRTC alike). WebRTC host/viewer `stop()` waits up to three seconds for software teardown. `PeerStopPending` retains the same running attempt; explicit retry waits on it. `PeerStopFailed` retains failed resources for explicit retry, and restarting is blocked until cleanup succeeds. Multi-viewer hosts retain failed sessions and their shared source. `FolderSyncEngine.stop_confirmed()` returns `False` while the original worker remains alive. These outcomes do not prove native device release; recovery after page destruction still needs durable ownership and retry integration. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 6e0f0ce4c..6f3fc1b85 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -71,7 +71,7 @@ Wayland NORMAL 输入通过受管理的子进程执行 libei 与 portal 调用 [MIT](../LICENSE) © JE-Chen. [第三方许可](../Third_Party_License.md). -关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。已进入发送阶段的文件传输须依后端的协作式取消停止。 +关闭 Remote Desktop 会释放页面;重新打开会创建新控件,不自动接回共享连接。Registry 的 TCP/WebSocket 连接仍可供脚本使用;页面拥有的 WebRTC 连接与音频在后台停止。待处理批准会拒绝,延迟回调会丢弃。正在发送的文件传输会在页面关闭、连接被放掉或上传取消时于下一个区块停止,主机会丢弃未完成的文件(TCP、WebSocket 与 WebRTC 皆同)。 WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStopPending` 保留同一个尚未完成的操作;显式重试只会继续等待。`PeerStopFailed` 保留清理失败的资源供显式重试,成功前禁止重新启动。Multi-viewer host 保留失败的 session 与共享来源。`FolderSyncEngine.stop_confirmed()` 在原工作线程仍存活时返回 `False`。这些结果不代表原生设备已释放;页面销毁后的恢复仍需持久资源保管与重试整合。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 5e4fa29f0..cebfea9dc 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -71,7 +71,7 @@ Wayland NORMAL 輸入透過受管理的子程序執行 libei 與 portal 呼叫 [MIT](../LICENSE) © JE-Chen. [Third-party licenses](../Third_Party_License.md). -關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸須依後端的合作式取消停止。 +關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已在傳送中的檔案傳輸會在頁面關閉、連線被放掉或上傳取消時於下一個區塊停止,主機會丟棄未完成的檔案(TCP、WebSocket 與 WebRTC 皆同)。 WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStopPending` 保留同一個尚未完成的操作;明確重試只會繼續等待。`PeerStopFailed` 保留清理失敗的資源供明確重試,成功前禁止重新啟動。Multi-viewer host 保留失敗的 session 與共用來源。`FolderSyncEngine.stop_confirmed()` 在原工作執行緒仍存活時回傳 `False`。這些結果不代表原生裝置已釋放;頁面銷毀後的復原仍需持久資源保管與重試整合。 diff --git a/architecture_explore.md b/architecture_explore.md index 4c22b912b..bb6fd9fc8 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,541 | -| 程式碼總行數 | 236,488 | +| 程式碼總行數 | 236,538 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,079 行。 +> 6 個套件、約 32,113 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,753 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,787 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,753 行/77 檔) +#### `utils/remote_desktop/`(16,787 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -832,7 +832,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_media_owners.py` | 249 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | | `webrtc_peer_cleanup.py` | 166 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | | `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | -| `viewer.py` | 743 | TCP 檢視端。 | +| `viewer.py` | 745 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | @@ -842,7 +842,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 323 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | | `ws_protocol.py` | 318 | 最小 RFC 6455 WebSocket 框架與握手。 | -| `file_transfer.py` | 452 | 分塊檔案傳輸。 | +| `file_transfer.py` | 484 | 分塊檔案傳輸。 | | `relay.py` | 316 | NAT 穿透失敗時的 TCP 中繼。 | | `fingerprint.py` | 246 | TOFU 主機指紋驗證。 | | `turn_config.py` | 249 | coturn 設定產生器。 | @@ -1389,7 +1389,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,430 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,446 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1407,14 +1407,14 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,430 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,446 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | | `view_lifetime.py` | 85 | Retirable weak delivery from surviving transports to one Qt view. | | `view_approvals.py` | 64 | Terminal default-deny approval ownership independent of a Qt page. | | `view_frames.py` | 25 | Frame conversion and optional recording without retaining a remote view. | -| `view_upload.py` | 30 | Value-only legacy viewer uploads owned by the shared GUI task controller. | +| `view_upload.py` | 42 | Value-only legacy viewer uploads owned by the shared GUI task controller. | | `folder_sync_controls.py` | 72 | Translate the existing folder toggle into owned start, reconnect handoff and explicit baseline reset. | | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | | `webrtc_panel_state.py` | 165 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | @@ -1547,9 +1547,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 164 | 43,189 | +| `gui/` | 164 | 43,205 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,753 | +| `utils/remote_desktop/` | 77 | 16,787 | | `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1568,7 +1568,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,529** | **235,743** | +| **總計** | **1,529** | **235,793** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 14a5bb9d4..4151eafbf 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -205,7 +205,7 @@ executing may finish. This does not close the remote session itself. Remote Desktop lifetime ----------------------- -Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. An already-entered file transfer is not interrupted by closing the page. +Closing Remote Desktop releases its page. Reopening creates fresh controls without reattaching shared sessions. Registry TCP/WebSocket sessions remain available to scripts; page-owned WebRTC sessions and audio retire in the background. Pending approvals are denied, and late callbacks are discarded. A file transfer already sending stops at its next chunk when the page closes: ``send_file`` takes ``cancelled=`` and otherwise follows the calling thread's cancellation scope, and once stopped sends a ``cancelled`` end so the host discards the part file. Execution details ~~~~~~~~~~~~~~~~~ diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index a62259338..5b63e94d1 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -193,7 +193,7 @@ WebRTC 統計 Remote Desktop 生命週期 ----------------------- -關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已進入傳送階段的檔案傳輸不會因關閉頁面而中斷。 +關閉 Remote Desktop 會釋放頁面;重新開啟會建立新控制項,不自動接回共用連線。Registry 的 TCP/WebSocket 連線仍可供腳本使用;頁面擁有的 WebRTC 連線與音訊在背景停止。待處理核准會拒絕,延遲回呼會丟棄。已在傳送中的檔案傳輸會在頁面關閉時於下一個區塊停止:``send_file`` 接受 ``cancelled=``,未提供時依呼叫執行緒的取消範圍;停止後送出 ``cancelled`` 結尾,主機便丟棄 part 檔。 執行詳情 ~~~~~~~~ diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 9a448c28f..4fe095835 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -542,3 +542,11 @@ - **Docs:** both `new_features_doc.rst` (registry API), both `v223_features_doc.rst` (slow stops), `CHANGELOG.md`. - **Files:** `utils/remote_desktop/registry.py`, `gui/remote_desktop/_host_ops.py` (strict mypy tier, `pyproject.toml`), `gui/remote_desktop/host_panel.py`, `gui/remote_desktop/connection_screen.py`, `gui/remote_desktop/viewer_panel.py`, `gui/remote_desktop/_connect_task.py`, the tests, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › F3 (cancelling a transfer already under way, same-page session generation isolation, backend cancel propagation). + +## U-20261114-33 · 2026-11-14 · A file transfer already sending stops at the next chunk when cancelled · #done #remote-desktop #files + +- **What:** `Progress.md` › F3's *已進入傳輸的取消*. The TCP / WebSocket `file_transfer.send_file` streamed the whole file once it had begun: closing the Remote Desktop page, Disconnect, or cancelling the task that ran it left it sending to the last byte (the docs said so), while the WebRTC sender already took a `cancelled` callable. `send_file` (and `RemoteDesktopViewer.send_file`) now take a keyword `cancelled=` and, without one, follow the calling thread's cancellation scope. The check runs before `FILE_BEGIN` -- nothing is sent then -- and before every chunk; once stopped mid-file it sends `FILE_END` with status `cancelled` (best effort: a channel already closed is logged), so the receiver's existing non-ok path discards the `.part` file, and raises `concurrent.futures.CancelledError`. The Viewer tab's upload task (`view_upload`) passes its controller token and treats the cancellation as the end of the upload; the WebRTC panel's one-file and batch uploads pass theirs to `FileTransferSender`; Quick Connect's dropped-file upload runs as plain `TabTask` work, whose scope `send_file` now follows. +- **Tests:** new `test_file_transfer_cancel.py` (6, against a real `FileReceiver` in a temp inbox: a transfer cancelled after three of ten chunks stops there, ends `cancelled`, and leaves neither file nor part file; one cancelled before it starts sends nothing; the caller's cancellation scope stops it by default; an uncancelled one arrives whole; a closed channel does not hide the cancellation; the Viewer tab's upload task stops its transfer when cancelled; five fail on the old code). `test_remote_view_retirement.py`'s fake viewer accepts `cancelled`. File transfer, remote, Remote Desktop, WebRTC, upload, viewer, folder-sync and Quick Connect tests: 2627 passed, 14 skipped before that fake was updated, which then passed. +- **Docs:** the three READMEs and both `v223_features_doc.rst` (closing Remote Desktop), `CHANGELOG.md`. +- **Files:** `utils/remote_desktop/file_transfer.py`, `utils/remote_desktop/viewer.py`, `gui/remote_desktop/view_upload.py`, `gui/remote_desktop/webrtc_viewer_files.py`, the tests, the docs, `Progress.md`. +- **Open items:** `Progress.md` › F3 (same-page session generation isolation, backend cancel propagation). diff --git a/docs/updates/README.md b/docs/updates/README.md index d0b25275e..2f53777fa 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-33 | 2026-11-14 | A file transfer already sending stops at the next chunk when cancelled | #done #remote-desktop #files | [2026-11-b](2026-11-b.md) | | U-20261114-32 | 2026-11-14 | Quick Connect starts, stops and disconnects off the GUI thread | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-31 | 2026-11-14 | Windows CI keeps a minidump of a crashed python.exe | #done #ci #native-diagnostics | [2026-11-b](2026-11-b.md) | | U-20261114-30 | 2026-11-14 | GUI startup and memory measured against the release, and the theme switch halved | #done #gui #benchmark | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/view_upload.py b/je_auto_control/gui/remote_desktop/view_upload.py index 8aa0dcba4..3a1702804 100644 --- a/je_auto_control/gui/remote_desktop/view_upload.py +++ b/je_auto_control/gui/remote_desktop/view_upload.py @@ -1,5 +1,10 @@ -"""Value-only legacy viewer uploads owned by the shared GUI task controller.""" +"""Value-only legacy viewer uploads owned by the shared GUI task controller. + +Cancelling the task -- the panel closing, or the session being dropped -- +stops the transfer at its next chunk, and the host discards the part file. +""" import functools +from concurrent.futures import CancelledError from typing import TypeVar from PySide6.QtCore import QObject @@ -15,7 +20,10 @@ def _send(viewer: RemoteDesktopViewer, source: str, dest: str, view: ViewLifetime[_Owner], token: CancellationToken) -> None: token.raise_if_cancelled() try: - result = viewer.send_file(source, dest, on_progress=view.callback("_on_file_progress_main")) + result = viewer.send_file(source, dest, on_progress=view.callback("_on_file_progress_main"), + cancelled=functools.partial(_is_cancelled, token)) + except CancelledError: + return # stopped mid-file; the host discarded what it had except (OSError, RuntimeError) as error: token.raise_if_cancelled() view.post("_on_file_complete_main", "", False, str(error), dest) @@ -24,6 +32,10 @@ def _send(viewer: RemoteDesktopViewer, source: str, dest: str, view.post("_on_file_complete_main", result.transfer_id, bool(result.success), result.error or "", dest) +def _is_cancelled(token: CancellationToken) -> bool: + return token.cancelled + + def start_upload(owner: _Owner, viewer: RemoteDesktopViewer, source: str, dest: str, view: ViewLifetime[_Owner]) -> TaskHandle: """Snapshot upload arguments; retiring the view does not disconnect its shared viewer.""" diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py index 179d7702b..bb6fd8285 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_files.py @@ -219,9 +219,13 @@ def _on_file_received_ui(self, path: object) -> None: ) -def _send_one_file(viewer: Any, path: str, _token: CancellationToken) -> None: - """Worker thread: stream one file to the host's inbox.""" - viewer.send_file(path) +def _is_cancelled(token: CancellationToken) -> bool: + return token.cancelled + + +def _send_one_file(viewer: Any, path: str, token: CancellationToken) -> None: + """Worker thread: stream one file to the host's inbox; cancelling the task stops it at the next chunk.""" + viewer.send_file(path, cancelled=functools.partial(_is_cancelled, token)) def _upload_files(viewer: Any, paths: List[str], token: CancellationToken) -> Tuple[int, Optional[str]]: @@ -232,7 +236,7 @@ def _upload_files(viewer: Any, paths: List[str], token: CancellationToken) -> Tu if token.cancelled: break try: - viewer.send_file(path) + viewer.send_file(path, cancelled=functools.partial(_is_cancelled, token)) sent += 1 except (RuntimeError, OSError, ValueError) as error: last_error = str(error) diff --git a/je_auto_control/utils/remote_desktop/file_transfer.py b/je_auto_control/utils/remote_desktop/file_transfer.py index aad7644f1..4b3526ebc 100644 --- a/je_auto_control/utils/remote_desktop/file_transfer.py +++ b/je_auto_control/utils/remote_desktop/file_transfer.py @@ -35,10 +35,12 @@ import threading from collections import OrderedDict import uuid +from concurrent.futures import CancelledError from dataclasses import dataclass from pathlib import Path, PurePosixPath, PureWindowsPath from typing import Any, Callable, Dict, List, Optional, Tuple, Union +from je_auto_control.utils.exception.cancellation import current_cancellation_token from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.protocol import MessageType @@ -408,20 +410,47 @@ class FileSendResult: bytes_sent: int = 0 +def _stop_check(cancelled: Optional[Callable[[], bool]]) -> Callable[[], bool]: + """``cancelled``, or the calling thread's cancellation scope when none is given.""" + if cancelled is not None: + return cancelled + token = current_cancellation_token() + return (lambda: token.is_cancelled) if token is not None else (lambda: False) + + +def _end_cancelled(channel: Any, transfer_id: str) -> None: + """Tell the receiver to discard its part file; a channel already closed has nobody to tell.""" + try: + channel.send_typed(MessageType.FILE_END, + encode_end(transfer_id, status="cancelled", error="cancelled by the sender")) + except (OSError, ConnectionError, RuntimeError) as error: + autocontrol_logger.debug("file transfer %s: cancel notice not sent: %r", transfer_id, error) + + def send_file(channel, source_path: str, dest_path: str, on_progress: Optional[ProgressCallback] = None, chunk_size: int = DEFAULT_CHUNK_SIZE, - transfer_id: Optional[str] = None) -> FileSendResult: + transfer_id: Optional[str] = None, *, + cancelled: Optional[Callable[[], bool]] = None) -> FileSendResult: """Stream ``source_path`` to ``dest_path`` over ``channel``. Synchronous: the caller's thread does the I/O. Wrap in a thread for background uploads. ``on_progress(transfer_id, bytes_done, total)`` fires after every chunk (and once at the start with ``bytes_done=0``). + + The transfer stops at the next chunk once ``cancelled()`` is true -- + by default, once the calling thread's cancellation scope is cancelled: + the receiver is sent a ``cancelled`` end, so it discards the part file, + and :class:`concurrent.futures.CancelledError` is raised. Nothing is sent + when it is cancelled before the first byte. """ + stopped = _stop_check(cancelled) transfer_id = transfer_id or new_transfer_id() source = Path(os.path.expanduser(source_path)) if not source.is_file(): raise FileTransferError(f"source not found: {source}") + if stopped(): + raise CancelledError() total_size = source.stat().st_size channel.send_typed(MessageType.FILE_BEGIN, encode_begin(transfer_id, dest_path, total_size)) @@ -431,6 +460,9 @@ def send_file(channel, source_path: str, dest_path: str, try: with open(source, "rb") as handle: while True: + if stopped(): + _end_cancelled(channel, transfer_id) + raise CancelledError() chunk = handle.read(int(chunk_size)) if not chunk: break diff --git a/je_auto_control/utils/remote_desktop/viewer.py b/je_auto_control/utils/remote_desktop/viewer.py index c83eb6c50..5d96ee639 100644 --- a/je_auto_control/utils/remote_desktop/viewer.py +++ b/je_auto_control/utils/remote_desktop/viewer.py @@ -398,16 +398,18 @@ def _ensure_file_receiver(self) -> FileReceiver: return self._file_receiver def send_file(self, source_path: str, dest_path: str, - on_progress=None): + on_progress=None, *, cancelled=None): """Stream ``source_path`` to ``dest_path`` on the host. Returns the :class:`FileSendResult`. Synchronous: callers wanting - a non-blocking upload should run this in a worker thread. + a non-blocking upload should run this in a worker thread. It stops at + the next chunk once ``cancelled()`` is true, or once the calling + thread's cancellation scope is cancelled (see :func:`send_file`). """ if not self._connected or self._channel is None: raise ConnectionError(_NOT_CONNECTED_MESSAGE) return send_file(self._channel, source_path, dest_path, - on_progress=on_progress) + on_progress=on_progress, cancelled=cancelled) def _handle_file_payload(self, msg_type: MessageType, payload: bytes) -> None: diff --git a/test/unit_test/headless/test_file_transfer_cancel.py b/test/unit_test/headless/test_file_transfer_cancel.py new file mode 100644 index 000000000..2fa918e14 --- /dev/null +++ b/test/unit_test/headless/test_file_transfer_cancel.py @@ -0,0 +1,145 @@ +"""A file transfer already sending stops at the next chunk when it is cancelled, and the host keeps nothing. + +``send_file`` streamed the whole file whatever happened: closing the Remote +Desktop page, disconnecting, or stopping the task that ran it left the upload +going to its last byte. It now checks between chunks and, once stopped, sends a +``cancelled`` end so the receiver discards its part file. +""" +import threading +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.remote_desktop.file_transfer import FileReceiver, decode_end, send_file +from je_auto_control.utils.remote_desktop.protocol import MessageType + +_CHUNK = 1024 + + +class _Wire: + """A channel straight into a real receiver; ``on_chunk(n)`` runs after the n-th chunk.""" + + def __init__(self, receiver, on_chunk=None): + self.receiver, self.on_chunk, self.sent, self.chunks = receiver, on_chunk, [], 0 + + def send_typed(self, kind, payload): + self.sent.append(kind) + if kind is MessageType.FILE_BEGIN: + self.receiver.handle_begin(payload) + elif kind is MessageType.FILE_CHUNK: + self.receiver.handle_chunk(payload) + self.chunks += 1 + if self.on_chunk is not None: + self.on_chunk(self.chunks) + elif kind is MessageType.FILE_END: + self.last_end = decode_end(payload) + self.receiver.handle_end(payload) + + +@pytest.fixture +def transfer(tmp_path): + source = tmp_path / "big.bin" + source.write_bytes(b"x" * (_CHUNK * 10)) + inbox = tmp_path / "inbox" + inbox.mkdir() + outcomes = [] + receiver = FileReceiver(on_complete=lambda tid, ok, error, dest: outcomes.append((ok, error)), base_dir=inbox) + return source, inbox, receiver, outcomes + + +def test_a_transfer_cancelled_mid_file_stops_and_the_receiver_keeps_nothing(transfer): + source, inbox, receiver, outcomes = transfer + stop = threading.Event() + wire = _Wire(receiver, on_chunk=lambda n: stop.set() if n == 3 else None) + with pytest.raises(CancelledError): + send_file(wire, str(source), "big.bin", chunk_size=_CHUNK, cancelled=stop.is_set) + assert wire.chunks == 3 # not the other seven + assert wire.last_end[1] == "cancelled" + assert outcomes == [(False, "cancelled by the sender")] + assert list(inbox.iterdir()) == [] # no file, no part file + + +def test_a_transfer_cancelled_before_it_starts_sends_nothing(transfer): + source, _inbox, receiver, _outcomes = transfer + wire = _Wire(receiver) + with pytest.raises(CancelledError): + send_file(wire, str(source), "big.bin", chunk_size=_CHUNK, cancelled=lambda: True) + assert wire.sent == [] + + +def test_the_callers_cancellation_scope_stops_it_by_default(transfer): + source, inbox, receiver, _outcomes = transfer + token = CancellationToken(task_id=1) + wire = _Wire(receiver, on_chunk=lambda n: token.cancel() if n == 2 else None) + with cancellation_scope(token), pytest.raises(CancelledError): + send_file(wire, str(source), "big.bin", chunk_size=_CHUNK) + assert wire.chunks == 2 + assert list(inbox.iterdir()) == [] + + +def test_an_uncancelled_transfer_arrives_whole(transfer): + source, inbox, receiver, outcomes = transfer + result = send_file(_Wire(receiver), str(source), "big.bin", chunk_size=_CHUNK) + assert result.success and result.bytes_sent == _CHUNK * 10 + assert outcomes == [(True, None)] + assert (inbox / "big.bin").read_bytes() == source.read_bytes() + + +def test_a_closed_channel_does_not_hide_the_cancellation(transfer): + source, _inbox, receiver, _outcomes = transfer + stop = threading.Event() + + class _Closing(_Wire): + def send_typed(self, kind, payload): + if kind is MessageType.FILE_END and stop.is_set(): + raise ConnectionError("the session is gone") + super().send_typed(kind, payload) + + wire = _Closing(receiver, on_chunk=lambda n: stop.set()) + with pytest.raises(CancelledError): + send_file(wire, str(source), "big.bin", chunk_size=_CHUNK, cancelled=stop.is_set) + + +def test_the_viewer_tabs_upload_task_stops_its_transfer_when_cancelled(transfer, monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + import os + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication, QWidget + QApplication.instance() or QApplication([]) + try: + from je_auto_control.gui.remote_desktop import view_upload + from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime + except ImportError: + pytest.skip("the remote desktop GUI needs the webrtc extra") + from headless._qt_settle import pump_until + source, inbox, receiver, _outcomes = transfer + second_chunk, release, done = threading.Event(), threading.Event(), threading.Event() + + def hold(n): + if n == 2: + second_chunk.set() + assert release.wait(10.0) + + wire = _Wire(receiver, on_chunk=hold) + + class _Viewer: + def send_file(self, source_path, dest_path, on_progress=None, *, cancelled=None): + try: + return send_file(wire, source_path, dest_path, chunk_size=_CHUNK, cancelled=cancelled) + finally: + done.set() + + owner = QWidget() + try: + handle = view_upload.start_upload(owner, _Viewer(), str(source), "big.bin", ViewLifetime(owner)) + assert second_chunk.wait(10.0) + handle.cancel() # the panel closed or the session was dropped + release.set() + assert done.wait(10.0) + assert pump_until(lambda: wire.chunks == 2 and getattr(wire, "last_end", None) is not None) + assert wire.last_end[1] == "cancelled" + assert list(inbox.iterdir()) == [] + finally: + release.set() + owner.deleteLater() diff --git a/test/unit_test/headless/test_remote_view_retirement.py b/test/unit_test/headless/test_remote_view_retirement.py index e1fffd1fc..cc946548b 100644 --- a/test/unit_test/headless/test_remote_view_retirement.py +++ b/test/unit_test/headless/test_remote_view_retirement.py @@ -165,7 +165,7 @@ def test_blocked_upload_outlives_view_without_holding_it(qapp): calls = [] class Viewer: - def send_file(self, source, dest, on_progress): + def send_file(self, source, dest, on_progress, cancelled=None): calls.append((source, dest)) entered.set() assert finish.wait(3) From 079efe48e1db0845641e4934036dbc3d6a9d822f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 17:40:07 +0800 Subject: [PATCH 101/161] Keep a replaced viewer session's late events from the next session A session being replaced closes on a worker while the next connects; its last frames painted into the new window and its closing error ran Disconnect, which closed the new session. Each session's callbacks now carry its number, and only the current session's land. --- CHANGELOG.md | 6 ++ Progress.md | 4 +- architecture_explore.md | 16 ++--- docs/updates/2026-11-b.md | 7 ++ docs/updates/README.md | 1 + .../gui/remote_desktop/connection_screen.py | 25 +++++++- .../gui/remote_desktop/view_lifetime.py | 10 +++ .../gui/remote_desktop/viewer_panel.py | 24 ++++++- .../headless/test_quick_connect_offthread.py | 64 +++++++++++++++++++ 9 files changed, 141 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fa116630..450aa0f9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI: Quick Connect and the Viewer tab tag each viewer session's callbacks with a session + number; frames, cursor moves, audio and errors from a session already replaced or closed are + dropped instead of reaching the next session (a late error used to disconnect it). + `ViewLifetime.tagged` / `tagged_error` deliver `method(tag, *arguments)`. `_viewer_callbacks()` + now starts a new session each time it is called. + - Remote desktop: `file_transfer.send_file` and `RemoteDesktopViewer.send_file` take a keyword `cancelled=` callable and otherwise follow the calling thread's cancellation scope. A transfer stopped mid-file sends a `FILE_END` with status `cancelled` (the receiver discards diff --git a/Progress.md b/Progress.md index bf1f318ee..6146ece55 100644 --- a/Progress.md +++ b/Progress.md @@ -535,8 +535,8 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 -- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移,包含同頁 session generation 隔離 - (Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒,U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33)。分頁的背景工作已全部改走共用 `TaskController` +- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移(Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒, + U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33;同頁 session generation 已隔離,U-20261114-34)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, diff --git a/architecture_explore.md b/architecture_explore.md index bb6fd9fc8..74792b355 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,541 | -| 程式碼總行數 | 236,538 | +| 程式碼總行數 | 236,585 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1389,7 +1389,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,446 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,493 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1407,11 +1407,11 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,446 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,493 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `view_lifetime.py` | 85 | Retirable weak delivery from surviving transports to one Qt view. | +| `view_lifetime.py` | 95 | Retirable weak delivery from surviving transports to one Qt view. | | `view_approvals.py` | 64 | Terminal default-deny approval ownership independent of a Qt page. | | `view_frames.py` | 25 | Frame conversion and optional recording without retaining a remote view. | | `view_upload.py` | 42 | Value-only legacy viewer uploads owned by the shared GUI task controller. | @@ -1422,8 +1422,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `webrtc_dialogs.py` | 524 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | -| `connection_screen.py` | 704 | Quick Connect —— AnyDesk 風格單畫面入口。 | -| `viewer_panel.py` | 599 | 「控制另一台機器」子分頁。 | +| `connection_screen.py` | 723 | Quick Connect —— AnyDesk 風格單畫面入口。 | +| `viewer_panel.py` | 617 | 「控制另一台機器」子分頁。 | | `webrtc_known_hosts.py` | 339 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | | `host_panel.py` | 396 | 「分享這台機器」子分頁。 | | `_host_ops.py` | 39 | Start and stop the machine's remote-desktop host on a worker thread. Host 面板與 Quick Connect 共用的 `replace_host`/`stop_host`/`release_host`。 | @@ -1547,7 +1547,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 164 | 43,205 | +| `gui/` | 164 | 43,252 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,787 | | `utils/executor/` | 11 | 10,752 | @@ -1568,7 +1568,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,529** | **235,793** | +| **總計** | **1,529** | **235,840** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 4fe095835..54cab02a7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -550,3 +550,10 @@ - **Docs:** the three READMEs and both `v223_features_doc.rst` (closing Remote Desktop), `CHANGELOG.md`. - **Files:** `utils/remote_desktop/file_transfer.py`, `utils/remote_desktop/viewer.py`, `gui/remote_desktop/view_upload.py`, `gui/remote_desktop/webrtc_viewer_files.py`, the tests, the docs, `Progress.md`. - **Open items:** `Progress.md` › F3 (same-page session generation isolation, backend cancel propagation). + +## U-20261114-34 · 2026-11-14 · A replaced viewer session's late events no longer reach the next one · #done #gui #remote-desktop + +- **What:** `Progress.md` › F3's *同頁 session generation 隔離*, left open by U-20261111-18: the Remote Desktop pages drop late callbacks once the page is released, but not per session. Quick Connect and the Viewer tab built every viewer's `on_frame` / `on_error` / `on_cursor` (and the Viewer tab's `on_audio`) as page callbacks, so a session being replaced -- since U-20261114-32 it closes on a worker while the next one connects -- could still paint its last frames into the new session's window, and its closing error ran `_on_error`, whose Disconnect closed the new session and raised a warning. Each panel now numbers its sessions: `_viewer_callbacks()` (Quick Connect) and every connect (Viewer tab) start a new number, Disconnect starts one too, and the callbacks are built with the new `ViewLifetime.tagged(method, tag)` / `tagged_error(method, tag)`, which deliver `method(tag, ...)`; the `_on_session_*` handlers pass an event on only when its number is current. The WebRTC viewer already ignores answers from a viewer that was stopped or replaced (`self._viewer is viewer`). +- **Tests:** `test_quick_connect_offthread.py` gains three: Quick Connect drops a replaced session's frame, cursor and error and passes the new one's; a disconnected session's error raises no warning; the Viewer tab drops a closed session's error and frame and shows the current one's (the first two fail on the old code). The existing retirement tests still pass through `_viewer_callbacks()`. Remote Desktop, Quick Connect, viewer, WebRTC, clipboard, worker, off-thread and dispose tests: 2587 passed, 12 skipped. +- **Files:** `gui/remote_desktop/view_lifetime.py`, `gui/remote_desktop/connection_screen.py`, `gui/remote_desktop/viewer_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › F3 (backend timeout and cancel propagation, close-failure recovery, session ownership). diff --git a/docs/updates/README.md b/docs/updates/README.md index 2f53777fa..dcc842de5 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-34 | 2026-11-14 | A replaced viewer session's late events no longer reach the next one | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-33 | 2026-11-14 | A file transfer already sending stops at the next chunk when cancelled | #done #remote-desktop #files | [2026-11-b](2026-11-b.md) | | U-20261114-32 | 2026-11-14 | Quick Connect starts, stops and disconnects off the GUI thread | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-31 | 2026-11-14 | Windows CI keeps a minidump of a crashed python.exe | #done #ci #native-diagnostics | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index b9056443c..46c7f692f 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -154,6 +154,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._host_op = SlowOp(self) self._stops = StopQueue(self) self._host_pending = "" + # Which viewer session the window shows: a session being replaced or + # closed keeps closing on a worker, and its late frames, cursor moves + # or errors must not reach the session that followed it. + self._session = 0 self._uploads = TabTask(self) # dropped files going to the host, off-thread self._uploads.error.connect(self._on_upload_failed) self._uploads.finished.connect(self._refresh_status) @@ -475,9 +479,23 @@ def _on_displaced(self, slot: str, _by: str) -> None: self._refresh_status() def _viewer_callbacks(self) -> dict: - return {"on_frame": self._view.callback("_on_frame"), - "on_error": self._view.error_callback("_on_error"), - "on_cursor": self._view.callback("_on_remote_cursor")} + """Callbacks for a new viewer session; they carry its number, and only the current session's land.""" + self._session += 1 + return {"on_frame": self._view.tagged("_on_session_frame", self._session), + "on_error": self._view.tagged_error("_on_session_error", self._session), + "on_cursor": self._view.tagged("_on_session_cursor", self._session)} + + def _on_session_frame(self, session: int, payload: bytes) -> None: + if session == self._session: + self._on_frame(payload) + + def _on_session_cursor(self, session: int, x: int, y: int) -> None: + if session == self._session: + self._on_remote_cursor(x, y) + + def _on_session_error(self, session: int, message: str) -> None: + if session == self._session: # an error from a session already replaced or closed is not news + self._on_error(message) def _begin_connect(self, slot: str, build, on_live) -> None: """Take ``slot``, build the viewer, and connect it off the GUI thread (see ``_connect_task``). @@ -559,6 +577,7 @@ def _handoff_to_webrtc(self, host_id: str, token: str) -> None: def _disconnect(self) -> None: # Either transport, and only a session this screen opened. + self._session += 1 # whatever the closed session still sends is dropped self._cancel_pending_connect() self._uploads.stop() # its socket is about to close; the failure is not news # The slots are free at once; closing the sockets (a join) runs off the GUI thread. diff --git a/je_auto_control/gui/remote_desktop/view_lifetime.py b/je_auto_control/gui/remote_desktop/view_lifetime.py index 662cca03d..7b230804e 100644 --- a/je_auto_control/gui/remote_desktop/view_lifetime.py +++ b/je_auto_control/gui/remote_desktop/view_lifetime.py @@ -60,6 +60,16 @@ def error(exc: Exception) -> None: self.post(method, str(exc)) return error + def tagged(self, method: str, tag: object) -> Callable[..., None]: + """Like :meth:`callback`, delivering ``method(tag, *arguments)``: the tag says which session sent it.""" + return functools.partial(self.post, method, tag) + + def tagged_error(self, method: str, tag: object) -> Callable[[Exception], None]: + """Like :meth:`error_callback`, delivering ``method(tag, message)``.""" + def error(exc: Exception) -> None: + self.post(method, tag, str(exc)) + return error + def post(self, method: str, *arguments: object) -> None: with self._lock: relay = self._relay() diff --git a/je_auto_control/gui/remote_desktop/viewer_panel.py b/je_auto_control/gui/remote_desktop/viewer_panel.py index 1d6fdec2d..b0116919f 100644 --- a/je_auto_control/gui/remote_desktop/viewer_panel.py +++ b/je_auto_control/gui/remote_desktop/viewer_panel.py @@ -63,6 +63,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() self._view = ViewLifetime(self) + self._session = 0 # which connect the window shows; see _on_session_frame self._stops = StopQueue(self) # This panel's name in the registry: it only ever reads, drives and # disconnects the viewer it opened itself. @@ -266,12 +267,16 @@ def _connect(self) -> None: clipboard_receiver = ClipboardReceiver(authority, self._view.callback("_on_clipboard_main")) viewer: RemoteDesktopViewer self._early_frame = None # a frame of the session being replaced + # The replaced session closes on a worker: its late frames, audio and + # error carry its number and are dropped once this one has begun. + self._session += 1 + session = self._session try: viewer = viewer_cls( host=host, port=port, token=token, - on_frame=self._view.callback("_on_frame_main"), - on_error=self._view.error_callback("_on_error_main"), - on_audio=self._view.callback("_on_audio_main"), + on_frame=self._view.tagged("_on_session_frame", session), + on_error=self._view.tagged_error("_on_session_error", session), + on_audio=self._view.tagged("_on_session_audio", session), on_clipboard=clipboard_receiver, expected_host_id=expected_id, ssl_context=ssl_context, @@ -382,6 +387,7 @@ def _on_displaced(self, _slot: str, _by: str) -> None: self._status.setText(_t("rd_viewer_displaced")) def _disconnect(self) -> None: + self._session += 1 # whatever the closed session still sends is dropped self._clipboard_authority = None self._cancel_pending_connect() close = registry.detach(SLOT_VIEWER, self._owner, only_own=True) @@ -447,6 +453,18 @@ def _refresh_status(self) -> None: # --- slot handlers (run on GUI thread) ----------------------------- + def _on_session_frame(self, session: int, payload: bytes) -> None: + if session == self._session: + self._on_frame_main(payload) + + def _on_session_audio(self, session: int, payload: bytes) -> None: + if session == self._session: + self._on_audio_main(payload) + + def _on_session_error(self, session: int, message: str) -> None: + if session == self._session: # an error from a session already replaced or closed is not news + self._on_error_main(message) + def _on_frame_main(self, payload: bytes) -> None: image = QImage.fromData(payload, "JPEG") # type: ignore[arg-type] # reason: the stub says bytes; PySide6 raises ValueError for bytes if image.isNull(): diff --git a/test/unit_test/headless/test_quick_connect_offthread.py b/test/unit_test/headless/test_quick_connect_offthread.py index 09846e860..1767b315b 100644 --- a/test/unit_test/headless/test_quick_connect_offthread.py +++ b/test/unit_test/headless/test_quick_connect_offthread.py @@ -180,3 +180,67 @@ def test_the_viewer_panels_disconnect_closes_on_a_worker_too(monkeypatch): finally: viewer.release.set() panel.deleteLater() + + +def test_a_replaced_sessions_late_events_do_not_reach_the_next_session(screen, monkeypatch): + # The old session closes on a worker while the new one connects; its last + # frames and its error (a closed socket) used to land on the new session, + # and the error's Disconnect closed it. + from headless._qt_settle import pump_until + from je_auto_control.gui.remote_desktop import connection_screen + seen = [] + screen_cls = connection_screen.QuickConnectScreen + monkeypatch.setattr(screen_cls, "_on_frame", lambda self, payload: seen.append(("frame", payload))) + monkeypatch.setattr(screen_cls, "_on_error", lambda self, message: seen.append(("error", message))) + monkeypatch.setattr(screen_cls, "_on_remote_cursor", lambda self, x, y: seen.append(("cursor", x, y))) + old = screen._viewer_callbacks() + new = screen._viewer_callbacks() # a connect replaced the first session + old["on_frame"](b"old frame") + old["on_cursor"](1, 1) + old["on_error"](ConnectionResetError("socket closed")) + new["on_frame"](b"new frame") + new["on_cursor"](2, 2) + assert pump_until(lambda: len(seen) >= 2) + assert seen == [("frame", b"new frame"), ("cursor", 2, 2)] + + +def test_a_disconnected_sessions_error_is_not_reported(screen, monkeypatch): + from headless._qt_settle import pump_until + from je_auto_control.gui.remote_desktop import connection_screen + warnings = [] + monkeypatch.setattr(connection_screen.QMessageBox, "warning", lambda *args: warnings.append(args)) + callbacks = screen._viewer_callbacks() + screen._disconnect() + callbacks["on_error"](ConnectionResetError("socket closed")) + assert pump_until(lambda: bool(warnings), timeout=0.5) is False + + +def test_the_viewer_tab_drops_a_replaced_sessions_events(monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + try: + from je_auto_control.gui.remote_desktop import viewer_panel + except ImportError: + pytest.skip("the remote desktop GUI needs the webrtc extra") + from headless._qt_settle import pump_until + monkeypatch.setattr(viewer_panel, "is_audio_backend_available", lambda: False) + seen = [] + panel_cls = viewer_panel._ViewerPanel + monkeypatch.setattr(panel_cls, "_on_frame_main", lambda self, payload: seen.append(("frame", payload))) + monkeypatch.setattr(panel_cls, "_on_error_main", lambda self, message: seen.append(("error", message))) + panel = panel_cls() + try: + old_session = panel._session + late_error = panel._view.tagged_error("_on_session_error", old_session) + late_frame = panel._view.tagged("_on_session_frame", old_session) + panel._disconnect() # or a new connect: either starts a new session + late_error(ConnectionResetError("socket closed")) + late_frame(b"old frame") + current = panel._view.tagged("_on_session_frame", panel._session) + current(b"new frame") + assert pump_until(lambda: bool(seen)) + assert seen == [("frame", b"new frame")] + finally: + panel.deleteLater() From 8e11e19712241ae1ae5a538ce78f4456636e45a9 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 17:58:25 +0800 Subject: [PATCH 102/161] Stop the WebRTC session the panel captured, and clean up a failed build The host panel dropped offers and disconnected sessions by id, resolved only when the background stop ran, and a dropped offer could stop its session on the GUI thread. It now uses the owned offers and retirements the host already offers. A peer that failed to build also left its token, subscription and a fresh screen source behind. --- CHANGELOG.md | 6 ++ Progress.md | 2 - architecture_explore.md | 20 ++--- docs/updates/2026-11-b.md | 9 +++ docs/updates/README.md | 1 + .../remote_desktop/webrtc_host_connection.py | 43 ++++++++--- .../remote_desktop/webrtc_host_sessions.py | 21 ++++-- .../utils/remote_desktop/multi_viewer.py | 69 ++++++++++++----- .../headless/test_gui_tab_task_controller.py | 7 +- .../headless/test_gui_weak_callbacks.py | 18 +++-- .../test_remote_desktop_multi_viewer.py | 47 ++++++++++++ .../headless/test_webrtc_session_ownership.py | 75 +++++++++++++++++++ .../headless/test_webrtc_slow_stops.py | 6 +- 13 files changed, 267 insertions(+), 57 deletions(-) create mode 100644 test/unit_test/headless/test_webrtc_session_ownership.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 450aa0f9b..1bf4d8e9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- Remote desktop: a WebRTC session whose peer fails to build (`MultiViewerHost.create_owned_session_offer`) + no longer leaves its session token, its relay subscription, or a screen source no other session + uses. GUI: the WebRTC host panel makes owned offers and disconnects through + `session_retirement`, so a dropped offer or a disconnect stops the session it captured -- never + one that reused the id -- and a dropped offer no longer stops its session on the GUI thread. + - GUI: Quick Connect and the Viewer tab tag each viewer session's callbacks with a session number; frames, cursor moves, audio and errors from a session already replaced or closed are dropped instead of reaching the next session (a late error used to disconnect it). diff --git a/Progress.md b/Progress.md index 6146ece55..f1bb40942 100644 --- a/Progress.md +++ b/Progress.md @@ -548,8 +548,6 @@ F 還缺: 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 - **F4** 啟動/記憶體基準對照與功能對等測試已交付(U-20261114-30);仍缺 mixed-DPI 驗收(需要第二台不同縮放的螢幕)。 -- **F3 session 所有權**:GUI 斷線及丟棄 offer 路徑仍須在背景排程前取得原始 session 清理物件; - peer 建構及畫面來源訂閱的部分失敗所有權仍須補齊。 - **F3 Windows 原生釋放驗收**(`BLOCKED`:等 CI 再次發生):`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。CI 的 Windows 工作現在會把 `python.exe` 當掉時的 minidump 存進 `native--` artifact 的 `dumps/`(U-20261114-31);本機 Python 3.14.7 連跑二十次未重現, diff --git a/architecture_explore.md b/architecture_explore.md index 74792b355..76cabbc51 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,541 | -| 程式碼總行數 | 236,585 | +| 程式碼總行數 | 236,648 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,113 行。 +> 6 個套件、約 32,148 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,787 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,822 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,787 行/77 檔) +#### `utils/remote_desktop/`(16,822 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -837,7 +837,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | | `webrtc_transport.py` | 421 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | -| `multi_viewer.py` | 464 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | +| `multi_viewer.py` | 499 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 323 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | @@ -1389,7 +1389,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,493 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,521 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1407,7 +1407,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,493 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,521 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1547,9 +1547,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 164 | 43,252 | +| `gui/` | 164 | 43,280 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,787 | +| `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1568,7 +1568,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,529** | **235,840** | +| **總計** | **1,529** | **235,903** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 54cab02a7..040dbc162 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -557,3 +557,12 @@ - **Tests:** `test_quick_connect_offthread.py` gains three: Quick Connect drops a replaced session's frame, cursor and error and passes the new one's; a disconnected session's error raises no warning; the Viewer tab drops a closed session's error and frame and shows the current one's (the first two fail on the old code). The existing retirement tests still pass through `_viewer_callbacks()`. Remote Desktop, Quick Connect, viewer, WebRTC, clipboard, worker, off-thread and dispose tests: 2587 passed, 12 skipped. - **Files:** `gui/remote_desktop/view_lifetime.py`, `gui/remote_desktop/connection_screen.py`, `gui/remote_desktop/viewer_panel.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › F3 (backend timeout and cancel propagation, close-failure recovery, session ownership). + +## U-20261114-35 · 2026-11-14 · The WebRTC host panel stops the session it captured; a failed peer build leaves nothing · #done #gui #webrtc + +- **What:** `Progress.md` › *F3 session 所有權*, both halves. + - **GUI disconnect and dropped offers.** `MultiViewerHost` already offered `create_owned_session_offer()` (an offer carrying its session's `retirement`) and `session_retirement(session_id)`, which capture the original peer and screen source so a later stop never reaches a session that reused the id; the panel still used `create_session_offer()` and `stop_session(session_id)`, resolved only when the background stop ran. Now the offer task makes owned offers; an offer for a host stopped or replaced meanwhile is retired through its own `retirement` on the panel's `StopQueue`; the task's `discard` (`_drop_offer`) -- which the controller calls on the GUI thread when the panel goes away with the offer undelivered -- hands the retirement to a worker there instead of stopping the session inline, and runs it directly when it is already on a worker. *Disconnect selected* captures `session_retirement(sid)` on the GUI thread before queuing the stop; a session already gone is reported stopped at once. + - **Partial failures building a session.** `create_owned_session_offer` built the peer under the lock after registering the session token and, for the first session, creating the shared screen source; when the screen subscription or `WebRTCDesktopHost(...)` raised, the token stayed registered, the subscription was never stopped, and a source created for that session kept capturing. `_register_session` / `_new_session_peer` now drop the subscription, unregister the token and -- outside the lock, as `_maybe_release_source` requires -- stop the source when no session uses it, then raise the build's own error (a failure releasing the source is logged). The next session builds normally. +- **Tests:** new `test_webrtc_session_ownership.py` (3: dropping an offer on the GUI thread stops it on a worker; on a worker it stops it there; with the real `MultiViewerHost` and fake peers, a dropped stale offer never stops the session that reused its id). `test_remote_desktop_multi_viewer.py` gains two (a peer that fails to build leaves no token, no subscription and no source, and the next one builds; a failed build drops its own subscription and spares the source another session uses; both fail on the old code). The fake hosts in `test_gui_tab_task_controller.py`, `test_gui_weak_callbacks.py` and `test_webrtc_slow_stops.py` follow the owned-offer and retirement calls. WebRTC, remote, Remote Desktop, multi-viewer, host-service, weak-callback, task-controller and slow-stop tests: 2122 passed, 12 skipped. +- **Files:** `utils/remote_desktop/multi_viewer.py`, `gui/remote_desktop/webrtc_host_connection.py`, `gui/remote_desktop/webrtc_host_sessions.py`, the tests, `CHANGELOG.md`, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › F3 (backend timeout and cancel propagation, close-failure recovery). diff --git a/docs/updates/README.md b/docs/updates/README.md index dcc842de5..926b8fc50 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-35 | 2026-11-14 | The WebRTC host panel stops the session it captured; a failed peer build leaves nothing | #done #gui #webrtc | [2026-11-b](2026-11-b.md) | | U-20261114-34 | 2026-11-14 | A replaced viewer session's late events no longer reach the next one | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-33 | 2026-11-14 | A file transfer already sending stops at the next chunk when cancelled | #done #remote-desktop #files | [2026-11-b](2026-11-b.md) | | U-20261114-32 | 2026-11-14 | Quick Connect starts, stops and disconnects off the GUI thread | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py index c2d6ec8a2..846222b5b 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py @@ -9,9 +9,9 @@ import functools import threading -from typing import TYPE_CHECKING, Optional, Tuple +from typing import TYPE_CHECKING, Any, Optional -from PySide6.QtCore import QTimer +from PySide6.QtCore import QCoreApplication, QThread, QTimer from PySide6.QtWidgets import ( QMessageBox, ) @@ -40,19 +40,37 @@ from je_auto_control.utils.remote_desktop.lan_discovery import HostAdvertiser -def _create_offer(host: MultiViewerHostT, _token: CancellationToken) -> Tuple[str, str]: - """Worker thread: mint a session and its offer (ICE gathering, up to 12 s).""" - return host.create_session_offer() +def _create_offer(host: MultiViewerHostT, _token: CancellationToken) -> Any: + """Worker thread: mint a session and its offer (ICE gathering, up to 12 s). + The offer carries its session's ``retirement``, captured as it was made, so + dropping the offer later stops exactly that session. + """ + return host.create_owned_session_offer() -def _drop_offer(host: MultiViewerHostT, outcome: Tuple[str, str]) -> None: - """End the session of an offer nobody will show.""" + +def _retire_quietly(retirement: Any, *_token: object) -> None: + """Worker thread: stop a session nobody will use; one already gone is not an error.""" try: - host.stop_session(outcome[0]) + retirement.stop() except (KeyError, RuntimeError, OSError) as error: autocontrol_logger.debug("dropping an unused offer: %r", error) +def _drop_offer(offer: Any) -> None: + """End the session of an offer nobody will show, without holding the GUI thread. + + The task's ``discard``: on the GUI thread when the panel goes away with the + offer undelivered -- the stop, which waits for the peer to close, then goes + to a worker -- or on the worker that made the offer, which simply runs it. + """ + app = QCoreApplication.instance() + if app is not None and QThread.currentThread() is app.thread(): + task_controller().submit(functools.partial(_retire_quietly, offer.retirement), owner=app) + else: + _retire_quietly(offer.retirement) + + #: One zeroconf registration change at a time: Publish stops the old advertiser and starts the #: next under the same name, and the name is only free once the goodbye packets have gone out. _ADVERTISE_LOCK = threading.Lock() @@ -193,7 +211,7 @@ def _produce_offer(self) -> None: # create_session_offer waits for ICE gathering (up to 12 s), which # used to freeze the window; the backend takes no timeout or cancel. task = task_controller().submit(functools.partial(_create_offer, host), owner=self, - discard=functools.partial(_drop_offer, host)) + discard=_drop_offer) # Weak: the task is this panel's child and must not be what keeps it alive. task.result.connect(weak_slot(self._show_offer, host)) task.error.connect(weak_slot(self._show_offer_error, host)) @@ -202,12 +220,13 @@ def _show_offer_error(self, host: MultiViewerHostT, error: Exception) -> None: if self._multi_host is host: # a host stopped meanwhile fails by design self._show_error(error) - def _show_offer(self, host: MultiViewerHostT, outcome: Tuple[str, str]) -> None: + def _show_offer(self, host: MultiViewerHostT, owned: Any) -> None: """GUI thread: the offer is ready -- unless the host was stopped or replaced meanwhile.""" if self._multi_host is not host: - _drop_offer(host, outcome) + # Its own session, captured with the offer; stopping waits for the peer to close. + self._stops.retire(functools.partial(_retire_quietly, owned.retirement)) return - session_id, offer = outcome + session_id, offer = owned.session_id, owned.sdp self._manual_session_id = session_id self._offer_view.setPlainText(offer) self._status_label.setText(_t("rd_webrtc_offer_ready")) diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py index 3c68ee6c7..7f408d3e8 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py @@ -8,7 +8,7 @@ from je_auto_control.gui.remote_desktop.webrtc_panel_state import _HostPanelPart import functools -from typing import Callable, Mapping, Optional +from typing import Any, Callable, Mapping, Optional from PySide6.QtCore import QPoint, Qt from PySide6.QtWidgets import ( @@ -28,10 +28,10 @@ ) -def _stop_session(host: MultiViewerHostT, sid: str) -> None: - """Worker thread: close one session; one that is already gone is not an error.""" +def _stop_session(retirement: Any) -> None: + """Worker thread: close the session ``retirement`` captured; one that is already gone is not an error.""" try: - host.stop_session(sid) + retirement.stop() except (KeyError, RuntimeError, OSError) as error: autocontrol_logger.warning("disconnect session: %r", error) @@ -229,9 +229,18 @@ def _on_disconnect_selected(self) -> None: if sid in self._stopping_sessions: # a second click on a session already closing return host = self._multi_host + # Captured now, so the stop closes this session even if another takes its id meanwhile. + try: + retirement = host.session_retirement(sid) if host is not None else None + except (KeyError, RuntimeError) as error: # already gone, or the host is shutting down + autocontrol_logger.debug("disconnect session %s: %r", sid, error) + retirement = None + if retirement is None: + self._on_session_stopped(host, sid) + return self._stopping_sessions.add(sid) - # stop_session waits for the peer connection to close (seconds). - self._stops.retire(functools.partial(_stop_session, host, sid), + # Closing waits for the peer connection to close (seconds). + self._stops.retire(functools.partial(_stop_session, retirement), on_done=self._on_session_stopped, args=(host, sid)) def _on_session_stopped(self, host: MultiViewerHostT, sid: str, _outcome: object = None) -> None: diff --git a/je_auto_control/utils/remote_desktop/multi_viewer.py b/je_auto_control/utils/remote_desktop/multi_viewer.py index a31c02c34..7514ac234 100644 --- a/je_auto_control/utils/remote_desktop/multi_viewer.py +++ b/je_auto_control/utils/remote_desktop/multi_viewer.py @@ -156,17 +156,57 @@ def create_session_offer(self) -> Tuple[str, str]: def create_owned_session_offer(self) -> OwnedSessionOffer: """Mint an offer with original-resource ownership for delayed delivery.""" + session_id, host, retirement = self._register_session() + try: + offer = host.create_offer(peer_label=f"viewer-{session_id[:6]}") + except BaseException: + with self._lock: + self._creating.discard(host) + retirement.stop() + raise + with self._lock: + self._creating.discard(host) + retiring = self._retiring.get(session_id) is host + if retiring: + retirement.stop() + raise PeerLifecycleError("session stopped during offer creation") + return OwnedSessionOffer(retirement, offer) + + def _register_session(self) -> Tuple[str, WebRTCDesktopHost, SessionRetirement]: + """Build and register one session's peer, or leave nothing behind and raise. + + A peer that fails to build -- the screen subscription or the peer + itself -- leaves no session token, no relay subscription and, when no + other session uses it, no running screen source. + """ with self._lock: if self._retiring or self._source_stopping or self._source_failed: raise PeerStopPending("finish retiring previous sessions before creating another") if self._source is None: self._source = _ScreenSource(self._config) + source = self._source session_id = secrets.token_hex(8) if session_id in self._sessions: raise PeerLifecycleError("session identity collision") token = object() self._session_tokens[session_id] = token - host = WebRTCDesktopHost( + try: + host = self._new_session_peer(session_id, token, source) + except BaseException as error: # noqa: BLE001 # reason: re-raised below, after the source is released + self._session_tokens.pop(session_id, None) + failure = error + else: + self._sessions[session_id] = host + self._creating.add(host) + return session_id, host, SessionRetirement(session_id, self, host, source) + self._release_unused_source(source) + raise failure + + def _new_session_peer(self, session_id: str, token: object, source: _ScreenSource) -> WebRTCDesktopHost: + """Subscribe to the shared screen and build one session's peer; a failed build drops its subscription.""" + track = source.subscribe() + try: + return WebRTCDesktopHost( token=self._token, config=self._config, trust_list=self._trust_list, @@ -174,28 +214,23 @@ def create_owned_session_offer(self) -> OwnedSessionOffer: input_dispatcher=self._dispatch, ip_whitelist=self._ip_whitelist, on_annotation=self._annotate if self._on_annotation is not None else None, - external_video_track=self._source.subscribe(), + external_video_track=track, on_state_change=self._wrap_state_callback(session_id, token), on_authenticated=self._wrap_auth_callback(session_id, token), on_pending_viewer=self._wrap_pending_callback(session_id, token), ) - self._sessions[session_id] = host - self._creating.add(host) - retirement = SessionRetirement(session_id, self, host, self._source) - try: - offer = host.create_offer(peer_label=f"viewer-{session_id[:6]}") except BaseException: - with self._lock: - self._creating.discard(host) - retirement.stop() + stop = getattr(track, "stop", None) + if callable(stop): + stop() raise - with self._lock: - self._creating.discard(host) - retiring = self._retiring.get(session_id) is host - if retiring: - retirement.stop() - raise PeerLifecycleError("session stopped during offer creation") - return OwnedSessionOffer(retirement, offer) + + def _release_unused_source(self, source: _ScreenSource) -> None: + """After a session failed to build: stop the screen source if no session uses it (it may be new).""" + try: + self._maybe_release_source(source) + except (RuntimeError, OSError) as error: # the build's own error is the one to raise + autocontrol_logger.warning("releasing the screen source after a failed session: %r", error) def session_retirement(self, session_id: str) -> SessionRetirement: """Capture the currently registered generation before queuing cleanup.""" diff --git a/test/unit_test/headless/test_gui_tab_task_controller.py b/test/unit_test/headless/test_gui_tab_task_controller.py index b878ad962..17c6c8401 100644 --- a/test/unit_test/headless/test_gui_tab_task_controller.py +++ b/test/unit_test/headless/test_gui_tab_task_controller.py @@ -7,6 +7,7 @@ was destroyed had nowhere safe to go. """ import functools +import types import os import threading import time @@ -512,9 +513,11 @@ def _wait(self): if self.fail is not None: raise self.fail - def create_session_offer(self): + def create_owned_session_offer(self): self._wait() - return "session-1", "v=0 offer" + retirement = types.SimpleNamespace(session_id="session-1", + stop=functools.partial(self.stop_session, "session-1")) + return types.SimpleNamespace(session_id="session-1", sdp="v=0 offer", retirement=retirement) def process_offer(self, offer_sdp, expected_dtls_fingerprint=None): self._wait() diff --git a/test/unit_test/headless/test_gui_weak_callbacks.py b/test/unit_test/headless/test_gui_weak_callbacks.py index 8e7ca5a45..641bae208 100644 --- a/test/unit_test/headless/test_gui_weak_callbacks.py +++ b/test/unit_test/headless/test_gui_weak_callbacks.py @@ -187,17 +187,20 @@ def start(): assert _freed_while_out(start) +def _owned_offer(): + """An offer as ``create_owned_session_offer`` returns it, whose retirement stops nothing.""" + import types + return types.SimpleNamespace(session_id="session", sdp="offer", retirement=types.SimpleNamespace(stop=lambda: None)) + + def _host_panel_part(gate): pytest.importorskip("aiortc", exc_type=ImportError) from je_auto_control.gui.remote_desktop.webrtc_host_connection import _HostConnectionMixin class _FakeHost: - def create_session_offer(self): + def create_owned_session_offer(self): return gate() - def stop_session(self, _session_id): - """Nothing to stop.""" - class _Part(_HostConnectionMixin): def __init__(self): super().__init__() @@ -212,7 +215,7 @@ def _show_offer(self, host, outcome): def test_an_offer_being_made_does_not_keep_the_host_panel_alive(qapp): def start(): - gate = _Gate(("session", "offer")) + gate = _Gate(_owned_offer()) part = _host_panel_part(gate) part._produce_offer() return part, gate @@ -221,12 +224,13 @@ def start(): def test_an_offer_still_reaches_a_host_panel_that_is_there(qapp): - gate = _Gate(("session", "offer")) + offer = _owned_offer() + gate = _Gate(offer) part = _host_panel_part(gate) part._produce_offer() gate.release.set() assert pump_until(lambda: bool(part.shown)) - assert part.shown == [(part._multi_host, ("session", "offer"))] + assert part.shown == [(part._multi_host, offer)] part.deleteLater() diff --git a/test/unit_test/headless/test_remote_desktop_multi_viewer.py b/test/unit_test/headless/test_remote_desktop_multi_viewer.py index e11fb23bb..9f3870d04 100644 --- a/test/unit_test/headless/test_remote_desktop_multi_viewer.py +++ b/test/unit_test/headless/test_remote_desktop_multi_viewer.py @@ -680,3 +680,50 @@ def create(child, peer_label): assert observed[0].stopped assert host.session_count() == 0 assert host._source is None + + +class _BrokenHost(_FakeHost): + """A peer that cannot be built (an aiortc / codec error at construction).""" + + def __init__(self, **kwargs) -> None: + raise RuntimeError("peer construction failed") + + +class _TrackRelay(_FakeRelay): + """A relay whose subscriptions are real track stand-ins, so a stop can be seen.""" + + def subscribe(self, track): + proxy = Track() + self.subscribed.append(proxy) + return proxy + + +def test_a_peer_that_fails_to_build_leaves_no_token_subscription_or_screen_source(monkeypatch): + monkeypatch.setattr(mv, "MediaRelay", _TrackRelay) + coordinator = _host() + monkeypatch.setattr(mv, "WebRTCDesktopHost", _BrokenHost) + with pytest.raises(RuntimeError, match="peer construction failed"): + coordinator.create_owned_session_offer() + assert coordinator._session_tokens == {} + assert coordinator._source is None # the source made for it is stopped again + assert coordinator.session_count() == 0 + monkeypatch.setattr(mv, "WebRTCDesktopHost", _FakeHost) + offer = coordinator.create_owned_session_offer() # nothing stuck: the next session builds + assert coordinator.session_count() == 1 + offer.retirement.stop() + + +def test_a_failed_build_drops_its_subscription_and_spares_a_source_others_use(monkeypatch): + monkeypatch.setattr(mv, "MediaRelay", _TrackRelay) + coordinator = _host() + first = coordinator.create_owned_session_offer() + source = coordinator._source + monkeypatch.setattr(mv, "WebRTCDesktopHost", _BrokenHost) + with pytest.raises(RuntimeError): + coordinator.create_owned_session_offer() + failed_subscription = source._relay.subscribed[-1] + assert failed_subscription.stopped # its own subscription is dropped + assert coordinator._source is source # the first session still shows the screen + assert not source._track.stopped + assert coordinator.session_count() == 1 + first.retirement.stop() diff --git a/test/unit_test/headless/test_webrtc_session_ownership.py b/test/unit_test/headless/test_webrtc_session_ownership.py new file mode 100644 index 000000000..10df97bcb --- /dev/null +++ b/test/unit_test/headless/test_webrtc_session_ownership.py @@ -0,0 +1,75 @@ +"""The WebRTC host panel stops the session it captured, never a later one, and never on the GUI thread. + +The panel made its offers with ``create_session_offer`` and dropped or +disconnected sessions with ``stop_session(session_id)``, resolved when the +stop ran -- in the background, by then possibly a different session under the +same id. Dropping an offer nobody would show also ran that stop on the GUI +thread when the panel went away. The panel now uses the owned offers and +retirements ``MultiViewerHost`` already offers, captured before anything is +scheduled. +""" +import os +import threading +import types + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +pytest.importorskip("aiortc", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtWidgets import QApplication # noqa: E402 + +from je_auto_control.gui.remote_desktop import webrtc_host_connection # noqa: E402 +from je_auto_control.utils.remote_desktop import multi_viewer as mv # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 +from headless.test_remote_desktop_multi_viewer import _FakeHost, _host, fake_webrtc # noqa: E402,F401 + +_APP = QApplication.instance() or QApplication([]) + + +class _HeldRetirement: + def __init__(self): + self.release, self.entered, self.threads = threading.Event(), threading.Event(), [] + + def stop(self): + self.threads.append(threading.get_ident()) + self.entered.set() + assert self.release.wait(10.0) + + +def test_dropping_an_offer_on_the_gui_thread_stops_it_on_a_worker(): + retirement = _HeldRetirement() + offer = types.SimpleNamespace(session_id="s", sdp="v=0", retirement=retirement) + gui = threading.get_ident() + webrtc_host_connection._drop_offer(offer) # returns without waiting for the peer + assert retirement.entered.wait(10.0) + assert retirement.threads[0] != gui + retirement.release.set() + from je_auto_control.gui.tab_task_controller import task_controller + assert pump_until(lambda: task_controller().active_count() == 0) + + +def test_dropping_an_offer_on_a_worker_stops_it_there(): + retirement = _HeldRetirement() + retirement.release.set() + offer = types.SimpleNamespace(session_id="s", sdp="v=0", retirement=retirement) + worker = threading.Thread(target=webrtc_host_connection._drop_offer, args=(offer,)) + worker.start() + worker.join(10.0) + assert retirement.threads == [worker.ident] + + +def test_a_dropped_offer_never_stops_the_session_that_reused_its_id(monkeypatch): + monkeypatch.setattr(mv.secrets, "token_hex", lambda _: "reused") + coordinator = _host() + stale = coordinator.create_owned_session_offer() # the panel was gone when it arrived + stale.retirement.stop() # ... and the session ended some other way + fresh = coordinator.create_owned_session_offer() # a new session under the same id + fresh_peer = _FakeHost.instances[-1] + worker = threading.Thread(target=webrtc_host_connection._drop_offer, args=(stale,)) + worker.start() + worker.join(10.0) + assert not fresh_peer.stopped + assert coordinator.session_count() == 1 + fresh.retirement.stop() diff --git a/test/unit_test/headless/test_webrtc_slow_stops.py b/test/unit_test/headless/test_webrtc_slow_stops.py index 5af8e8af5..b5aff9753 100644 --- a/test/unit_test/headless/test_webrtc_slow_stops.py +++ b/test/unit_test/headless/test_webrtc_slow_stops.py @@ -3,6 +3,7 @@ Offscreen Qt with fake hosts, viewers, recorders and sync engines whose ``stop`` waits until the test lets it go. Nothing here opens a peer connection. """ +import functools import os import threading import time @@ -101,7 +102,10 @@ def test_a_host_started_while_the_old_one_closes_keeps_its_own_status(): def test_disconnecting_one_session_is_off_the_gui_thread_and_not_repeated(): panel = webrtc_panel._WebRTCHostPanel() gate, counts = _Gate(), [] - panel._multi_host = types.SimpleNamespace(stop_session=gate, session_count=lambda: 0) + # The session is captured on the GUI thread (its retirement); stopping it (the gate) runs on a worker. + panel._multi_host = types.SimpleNamespace( + session_retirement=lambda sid: types.SimpleNamespace(stop=functools.partial(gate, sid)), + session_count=lambda: 0) panel._signals.session_count.disconnect() panel._signals.session_count.connect(counts.append) panel._sessions_table.setRowCount(1) From ac355676829b3cef03b44ca319d007a413d70f9d Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 18:10:47 +0800 Subject: [PATCH 103/161] Keep a failed background stop for a retry from Diagnostics StopQueue and stop_each logged a stop that raised and dropped it, so a session, recorder or host a panel had let go of could stay open with nothing owning it. Failed stops are now kept with their error and the authority they were queued under, and Diagnostics lists and retries them. --- CHANGELOG.md | 8 + Progress.md | 6 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 18 +- .../doc/new_features/v223_features_doc.rst | 11 ++ .../Zh/doc/new_features/v223_features_doc.rst | 6 + docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + je_auto_control/gui/_slow_op.py | 46 ++++- je_auto_control/gui/_stop_custody.py | 187 ++++++++++++++++++ je_auto_control/gui/diagnostics_tab.py | 6 +- je_auto_control/gui/failed_stops_view.py | 116 +++++++++++ .../gui/language_wrapper/english.py | 14 ++ .../gui/language_wrapper/japanese.py | 15 ++ .../language_wrapper/simplified_chinese.py | 14 ++ .../language_wrapper/traditional_chinese.py | 14 ++ .../gui/remote_desktop/_connect_task.py | 10 +- pyproject.toml | 2 + .../headless/test_actions_menu_gui.py | 1 + .../unit_test/headless/test_gui_slow_stops.py | 7 +- test/unit_test/headless/test_stop_custody.py | 152 ++++++++++++++ 23 files changed, 620 insertions(+), 28 deletions(-) create mode 100644 je_auto_control/gui/_stop_custody.py create mode 100644 je_auto_control/gui/failed_stops_view.py create mode 100644 test/unit_test/headless/test_stop_custody.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bf4d8e9c..ff93e9f43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- GUI: a shutdown handed to `StopQueue` that raises is kept by the new + `gui/_stop_custody.py` (`stop_custody()`: `snapshot`, `retry`, `retry_all`, `forget`) with + its error and the caller's authority captured when it was queued, instead of only being + logged. `stop_each` now raises `StopsFailed` (with `failures`) after running every stop when + any failed -- a caller outside `StopQueue` sees that error. The Diagnostics tab lists held + stops and has **Retry failed stops** and **Forget selected failed stop** in the Actions menu + (new `gui/failed_stops_view.py`; new catalogue keys `failed_stops_*`). + - Remote desktop: a WebRTC session whose peer fails to build (`MultiViewerHost.create_owned_session_offer`) no longer leaves its session token, its relay subscription, or a screen source no other session uses. GUI: the WebRTC host panel makes owned offers and disconnects through diff --git a/Progress.md b/Progress.md index f1bb40942..639339314 100644 --- a/Progress.md +++ b/Progress.md @@ -538,9 +538,9 @@ F 還缺: - **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移(Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒, U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33;同頁 session generation 已隔離,U-20261114-34)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 -- **F3 關閉失敗恢復**:`gui/_slow_op.py` 的 StopQueue/stop_each 目前只記錄停止失敗, - 尚未保留失敗資源的明確重試所有權。須接上應用程式生命週期的資源保管、原授權下的 Diagnostics 查詢/重試, - 並遷移一般停止及頁面銷毀後的 discard 路徑,包含 `_drop_offer` 與廣播清理;不能把背景排程等同原生資源已釋放。 +- **F3 關閉失敗恢復**:StopQueue/stop_each 的失敗停止已交給應用程式層的保管者,Diagnostics 可在原授權下查詢/重試 + (U-20261114-36);仍須遷移 SlowOp 的一般停止、頁面銷毀後的 discard 路徑(含 `_drop_offer` 背景停止)與廣播清理, + 讓它們失敗時也交給保管者;不能把背景排程等同原生資源已釋放。 GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 diff --git a/README.md b/README.md index d39dae1f1..917bd76a4 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ Auto Click, Record and Script Executor own their controls and background tasks. Of the three tabs open at start, only Record is built then; Script Builder and Remote Desktop are built the first time they are selected, which roughly halves start-up time and memory. -View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there, and so does every other page that runs work in the background (a model request, a USB listing, a broadcast, a DAG run, a journal read): running, stopping, then completed, cancelled or the error, with progress where the work reports it. A page that has run nothing yet says details are unavailable. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. +View → Execution details (Ctrl+Shift+D) opens a collapsible right pane. Diagnostics publishes its actual progress, stop, result and error state there, and so does every other page that runs work in the background (a model request, a USB listing, a broadcast, a DAG run, a journal read): running, stopping, then completed, cancelled or the error, with progress where the work reports it. A page that has run nothing yet says details are unavailable. A background stop that fails (a session, recorder or host a page let go of) is kept rather than only logged: Diagnostics lists each one with its error, and Actions › Retry failed stops runs them again under the authority they were queued with. Switching or closing a page disconnects its updates. Embedders can supply a TabRegistry to WorkspaceShell; AutoControlGUIWidget(parent) remains supported. Every page opens with a title and a one-line description, groups its controls on cards, and draws check boxes and radio buttons in the theme's accent so they stay visible in the dark theme. Controls shrink with the window instead of forcing it wide: long drop-down entries no longer set a page's width, form labels move above their fields when both do not fit, and long notes wrap. An empty table, list or tree says *Nothing to show yet* until its first row arrives, instead of showing a blank grid. A banner under the page title says when the page's last run failed (the next run clears it) and, when the GUI runs inside an RBAC scope, which of the page's commands the active role cannot run; it has a Dismiss link. The window rearranges itself by width: from 1,200 px the navigation and the execution details sit beside the tabs; below that the details open as a drawer over them; below 800 px the navigation becomes a narrow rail, and its menu button or Ctrl+K opens the feature list as a drawer (Escape or a click beside it closes it). Hiding the navigation for width does not change the saved preference. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 6f3fc1b85..565fbca1d 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -43,7 +43,7 @@ Actions 菜单可停止待完成的搜索;关闭分页会丢弃延迟结果, 启动时打开的三个标签页只先创建 Record;Script Builder 与 Remote Desktop 在第一次被选中时才创建,启动时间与内存约减半。 -View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态,其他在后台执行工作的分页(模型请求、USB 列举、广播、DAG 执行、日志读取)也会:执行中、停止中,然后是完成、已取消或错误,工作有回报进度时一并显示。尚未执行过工作的分页会明确显示没有详情。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 +View → 执行详情(Ctrl+Shift+D)可展开右侧详情。诊断分页会提供实际进度、停止、结果与错误状态,其他在后台执行工作的分页(模型请求、USB 列举、广播、DAG 执行、日志读取)也会:执行中、停止中,然后是完成、已取消或错误,工作有回报进度时一并显示。尚未执行过工作的分页会明确显示没有详情。后台停止失败时(页面放开的连接、录制或主机)会被保留而不只记录日志:诊断分页列出每一个及其错误,Actions › 重试失败的停止 会以排入时的权限再次执行。切换或关闭分页会断开其更新。嵌入程序可将 TabRegistry 传入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 每个分页开头都有标题与一行用途说明,控件按用途分组在卡片上;复选框与单选按钮以主题强调色绘制,深色主题下也看得清楚。控件会随窗口缩小,不再撑宽页面:下拉菜单不再以最长项目决定宽度,表单字段放不下时标签移到字段上方,长说明会自动换行。空的表格、列表或树状清单会显示「暂无内容。」,直到第一笔数据出现,不再只显示空白格线。页面标题下方的横幅会说明该页上次执行失败(下次执行时清除),GUI 在 RBAC 范围内执行时也会说明当前角色无法执行该页的哪些指令;横幅附有关闭链接。窗口会依宽度重新排列:1,200 px 以上,导航与执行详情并排在分页两侧;较窄时详情改为覆盖在分页上的抽屉;800 px 以下导航缩成窄图标栏,按其菜单按钮或 Ctrl+K 以抽屉打开功能列表(Escape 或点击旁边即关闭)。因宽度隐藏导航不会改动已保存的偏好。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index cebfea9dc..fb6430369 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -43,7 +43,7 @@ Actions 選單可停止待完成的搜尋;關閉分頁會丟棄晚到結果, 啟動時開著的三個分頁只先建立 Record;Script Builder 與 Remote Desktop 在第一次被選取時才建立,啟動時間與記憶體約減半。 -View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態,其他在背景執行工作的分頁(模型請求、USB 列舉、廣播、DAG 執行、日誌讀取)也會:執行中、停止中,然後是完成、已取消或錯誤,工作有回報進度時一併顯示。尚未執行過工作的分頁會明確顯示沒有詳情。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 +View → 執行詳情(Ctrl+Shift+D)可展開右側詳情。診斷分頁會提供實際進度、停止、結果與錯誤狀態,其他在背景執行工作的分頁(模型請求、USB 列舉、廣播、DAG 執行、日誌讀取)也會:執行中、停止中,然後是完成、已取消或錯誤,工作有回報進度時一併顯示。尚未執行過工作的分頁會明確顯示沒有詳情。背景停止失敗時(頁面放開的連線、錄影或主機)會被保留而不只記錄日誌:診斷分頁列出每一個及其錯誤,Actions › 重試失敗的停止 會以排入時的權限再次執行。切換或關閉分頁會斷開其更新。嵌入程式可將 TabRegistry 傳入 WorkspaceShell;AutoControlGUIWidget(parent) 仍可使用。 每個分頁開頭都有標題與一行用途說明,控制項依用途分組在卡片上;核取方塊與選項按鈕以主題強調色繪製,深色主題下也看得清楚。控制項會隨視窗縮小,不再撐寬頁面:下拉選單不再以最長項目決定寬度,表單欄位放不下時標籤移到欄位上方,長說明會自動換行。空的表格、清單或樹狀清單會顯示「目前沒有內容。」,直到第一筆資料出現,不再只顯示空白格線。頁面標題下方的橫幅會說明該頁上次執行失敗(下次執行時清除),GUI 在 RBAC 範圍內執行時也會說明目前角色無法執行該頁的哪些指令;橫幅附有關閉連結。視窗會依寬度重新排列:1,200 px 以上,導覽與執行詳情並排在分頁兩側;較窄時詳情改為覆蓋在分頁上的抽屜;800 px 以下導覽縮成窄圖示欄,按其選單鈕或 Ctrl+K 以抽屜開啟功能清單(Escape 或點擊旁邊即關閉)。因寬度隱藏導覽不會改動已儲存的偏好。 diff --git a/architecture_explore.md b/architecture_explore.md index 76cabbc51..3be7b6941 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,541 | -| 程式碼總行數 | 236,648 | +| Python 模組總數(含周邊子專案) | 1,543 | +| 程式碼總行數 | 237,046 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1315,6 +1315,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `workspace.py` | 582 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | | `workspace_details.py` | 116 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 與每個 `TabTask` 都是 publisher;僅訂閱目前頁面,`details_sources()` 通知綁定後才建立的來源。 | | `_task_details.py` | 116 | Execution details a TabTask publishes for the page it runs on. 由子面板往上找出工作區的分頁、第一次執行時建立來源,發布執行中/停止中/完成/已取消/錯誤與回報的進度。 | +| `_stop_custody.py` | 187 | Stops that failed in the background, kept so they can be retried instead of only logged. StopQueue/stop_each 失敗時保留停止、錯誤與排入時的權限;`snapshot` 不執行任何東西,`retry` 以原權限重試。 | +| `failed_stops_view.py` | 116 | Diagnostics' view of background stops that failed: what is held, and a retry from the Actions menu. | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 171 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 130 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | @@ -1339,7 +1341,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 260 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 88 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,544 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,601 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1389,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,521 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,525 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1398,7 +1400,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 277 | 檢視端 USB 裝置瀏覽器。 | | usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | -| diagnostics | `diagnostics_tab.py` | 238 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | +| diagnostics | `diagnostics_tab.py` | 242 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | #### 診斷顯示輔助 @@ -1407,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,521 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,525 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1547,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 164 | 43,280 | +| `gui/` | 166 | 43,678 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | @@ -1568,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,529** | **235,903** | +| **總計** | **1,531** | **236,301** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 4151eafbf..4fbc2b0b4 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -177,6 +177,17 @@ on its own worker before connecting. Callbacks are held weakly: pass a method and ``args=``, not a ``functools.partial`` or a lambda that closes over the tab. +A shutdown handed to a ``StopQueue`` that raises is not only logged: +``je_auto_control.gui._stop_custody.stop_custody()`` keeps it, with its error +and the authority captured when it was queued, for the life of the +application -- the object is out of the panel's hands, but what it held may +still be open. ``stop_each`` still runs every stop and then raises +``StopsFailed`` naming each failed one, so each is kept on its own. The +Diagnostics tab lists them from the custody's snapshot (which runs nothing and +waits on no native lock); **Retry failed stops** runs each again on a worker +under its original authority and releases the ones that succeed, and **Forget +selected failed stop** lets one go. + This is a GUI-internal API (it imports ``PySide6``) and is not re-exported by the package facade; the headless functions a tab calls stay usable without it. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index 5b63e94d1..f5bfc5390 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -163,6 +163,12 @@ GUI 執行緒執行,原本接在阻塞呼叫後面的程式碼就放在這裡。 現在也經 ``registry.detach`` 這樣做,新的連線會先在自己的 worker 上關掉被取代的工作階段再連線。回呼以弱參照持有:請傳方法與 ``args=``,不要傳 ``functools.partial`` 或閉包抓著分頁的 lambda。 +交給 ``StopQueue`` 的關閉若丟出例外,不再只記錄日誌:``je_auto_control.gui._stop_custody.stop_custody()`` +會在應用程式存續期間保留它、它的錯誤以及排入時擷取的權限——物件已不在面板手上,但它持有的資源可能仍未關閉。 +``stop_each`` 仍會執行每個停止,之後丟出列出每個失敗停止的 ``StopsFailed``,讓每一個都分別保留。 +診斷分頁從保管者的快照列出它們(快照不執行任何東西、也不等待原生鎖);\ **重試失敗的停止**\ 會在 worker +上以原權限再次執行每一個並釋放成功的,\ **放棄所選的失敗停止**\ 則放掉一個。 + 這是 GUI 內部 API(會 import ``PySide6``),套件 facade 不會重新匯出;分頁所呼叫的 無頭函式不需要它也能使用。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 040dbc162..777c79ab0 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -566,3 +566,11 @@ - **Tests:** new `test_webrtc_session_ownership.py` (3: dropping an offer on the GUI thread stops it on a worker; on a worker it stops it there; with the real `MultiViewerHost` and fake peers, a dropped stale offer never stops the session that reused its id). `test_remote_desktop_multi_viewer.py` gains two (a peer that fails to build leaves no token, no subscription and no source, and the next one builds; a failed build drops its own subscription and spares the source another session uses; both fail on the old code). The fake hosts in `test_gui_tab_task_controller.py`, `test_gui_weak_callbacks.py` and `test_webrtc_slow_stops.py` follow the owned-offer and retirement calls. WebRTC, remote, Remote Desktop, multi-viewer, host-service, weak-callback, task-controller and slow-stop tests: 2122 passed, 12 skipped. - **Files:** `utils/remote_desktop/multi_viewer.py`, `gui/remote_desktop/webrtc_host_connection.py`, `gui/remote_desktop/webrtc_host_sessions.py`, the tests, `CHANGELOG.md`, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › F3 (backend timeout and cancel propagation, close-failure recovery). + +## U-20261114-36 · 2026-11-14 · A failed background stop is kept for a retry from Diagnostics · #done #gui #lifecycle + +- **What:** the first part of `Progress.md` › *F3 關閉失敗恢復*. `StopQueue` logged a shutdown that raised and dropped it, and `stop_each` logged each failing stop and went on: the session, recorder or host a panel had let go of might still hold its socket or device, and nothing owned it. New Qt-free `gui/_stop_custody.py`: `stop_custody()` keeps each failed stop with its scrubbed error, a label (`describe_stop`, through partials), its attempt count and the caller's `DeferredAuthorization` captured when the stop was queued, for the life of the application (at most 200; the oldest is let go and logged beyond that). `snapshot()` returns plain `FailedStop` records and runs nothing, waiting only on the custody's own lock, so it is safe on the GUI thread; `retry(stop_id)` runs a stop again on the calling worker inside its captured authority, releasing it when it succeeds and recording the new error when it does not; `retry_all()` and `forget()` complete it, and listeners hear every change. `StopQueue.retire` captures the authority and hands a failure to custody through `hold_failed_stop`; `stop_each` still runs every stop but then raises `StopsFailed` naming each failure, which `hold_failed_stop` keeps one by one, so each can be retried alone. Quick Connect's connect-time shutdown of the session it replaces holds its failures too. New `gui/failed_stops_view.py`, embedded in Diagnostics, lists held stops (refreshed through a queued signal from any thread) and adds **Retry failed stops** (a `TabTask` on a worker, not published to the page's execution details) and **Forget selected failed stop** to the Actions menu, with new `failed_stops_*` keys in all four catalogues. +- **Tests:** new `test_stop_custody.py` (9: a held stop's description holds no resource; a failed retry keeps the new error and a successful one releases; a retry runs under the queued authority, not the current one; forget, `retry_all` and the limit; listeners; labels through nested partials; `stop_each` runs every stop and names each failure; a `StopQueue` keeps each failed stop of a `stop_each` shutdown separately; the Diagnostics view lists, retries and forgets). `test_gui_slow_stops.py` expects `StopsFailed` after the remaining stops ran; `test_actions_menu_gui.py` lists the two new Diagnostics entries. Slow-stop, WebRTC, remote, Remote Desktop, Diagnostics, catalogue, Actions-menu, execution-details, page-width and lazy-registry tests: 2422 passed, 17 skipped before those two updates, which then passed. +- **Docs:** the three READMEs and both `v223_features_doc.rst` (slow stops), `CHANGELOG.md`. +- **Files:** `gui/_stop_custody.py`, `gui/failed_stops_view.py` (both in the strict mypy tier, `pyproject.toml`), `gui/_slow_op.py`, `gui/diagnostics_tab.py`, `gui/remote_desktop/_connect_task.py`, the four catalogues, the tests, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (SlowOp stops, discard paths, broadcast cleanup, media owners, the revoked-authority close, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index 926b8fc50..5aea90b49 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-36 | 2026-11-14 | A failed background stop is kept for a retry from Diagnostics | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-35 | 2026-11-14 | The WebRTC host panel stops the session it captured; a failed peer build leaves nothing | #done #gui #webrtc | [2026-11-b](2026-11-b.md) | | U-20261114-34 | 2026-11-14 | A replaced viewer session's late events no longer reach the next one | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261114-33 | 2026-11-14 | A file transfer already sending stops at the next chunk when cancelled | #done #remote-desktop #files | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_slow_op.py b/je_auto_control/gui/_slow_op.py index 370e279a2..b1e7e2e86 100644 --- a/je_auto_control/gui/_slow_op.py +++ b/je_auto_control/gui/_slow_op.py @@ -34,7 +34,7 @@ pass a method and ``args``, never a lambda that closes over the tab. """ import functools -from typing import Any, Callable, Optional, Tuple +from typing import Any, Callable, List, Optional, Tuple from PySide6.QtCore import QObject, Signal @@ -42,7 +42,10 @@ from je_auto_control.gui.tab_task_controller import ( CancellationToken, TaskController, TaskUsageError, _widgets_reachable_from, task_controller, ) +from je_auto_control.gui._stop_custody import stop_custody +from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.rbac.deferred import DeferredAuthorization def _call(work: Callable[[], Any], _token: CancellationToken) -> Any: @@ -55,6 +58,24 @@ def _log_failure(error: object) -> None: autocontrol_logger.warning(f"GUI background operation failed: {error!r}") +class StopsFailed(AutoControlException, RuntimeError): + """Some of :func:`stop_each`'s stops raised; ``failures`` pairs each with its error.""" + + def __init__(self, failures: List[Tuple[Callable[[], Any], BaseException]]) -> None: + super().__init__("; ".join(f"{type(error).__name__}: {error}" for _stop, error in failures)) + self.failures = failures + + +def hold_failed_stop(stop: Callable[[], Any], error: object, + authority: Optional[DeferredAuthorization] = None) -> None: + """Hand a failed stop to the application's custody (each one of a :class:`StopsFailed` separately).""" + if isinstance(error, StopsFailed): + for inner, inner_error in error.failures: + stop_custody().hold(inner, inner_error, authority=authority) + else: + stop_custody().hold(stop, error, authority=authority) + + def _refuse_widgets(work: Callable[[], Any]) -> None: """Raise unless ``work`` is free of widgets (the controller only sees the wrapper around it).""" if _widgets_reachable_from(work): @@ -154,14 +175,16 @@ def retire(self, stop: Callable[[], Any], *, on_done: Callback = None, args: Tuple[Any, ...] = ()) -> None: """Run ``stop()`` off the GUI thread; ``on_done(*args, result)`` follows on the GUI thread. - A shutdown that raises is logged: the object is already out of use - and there is nothing for the panel to undo. + A shutdown that raises is kept by :func:`~je_auto_control.gui._stop_custody.stop_custody`, + with the caller's authority captured now, so it can be retried from + the Diagnostics tab: the object is out of the panel's hands, but its + resource may still be held. """ _refuse_widgets(stop) controller = self._controller if self._controller is not None else task_controller() handle = controller.submit(functools.partial(_call, stop), owner=self) self._pending += 1 - handle.error.connect(_log_failure) + handle.error.connect(functools.partial(hold_failed_stop, stop, authority=DeferredAuthorization.capture())) if on_done is not None: handle.result.connect(weak_slot(on_done, *args)) # a weak call, never the panel handle.finished.connect(self._one_reported) @@ -173,12 +196,19 @@ def _one_reported(self) -> None: def stop_each(*stops: Callable[[], Any]) -> None: - """Worker thread: call every ``stop`` in order; one that fails does not keep the rest from running.""" + """Worker thread: call every ``stop`` in order; one that fails does not keep the rest from running. + + Raises :class:`StopsFailed` afterwards when any did, naming each failed + stop, so a :class:`StopQueue` keeps every one of them for a retry. + """ + failures: List[Tuple[Callable[[], Any], BaseException]] = [] for stop in stops: try: stop() - except Exception as error: # noqa: BLE001 # reason: logged; the remaining shutdowns must still run - autocontrol_logger.warning(f"GUI background shutdown failed: {error!r}") + except Exception as error: # noqa: BLE001 # reason: collected and raised below; the remaining shutdowns must still run + failures.append((stop, error)) + if failures: + raise StopsFailed(failures) -__all__ = ["SlowOp", "StopQueue", "stop_each"] +__all__ = ["SlowOp", "StopQueue", "StopsFailed", "hold_failed_stop", "stop_each"] diff --git a/je_auto_control/gui/_stop_custody.py b/je_auto_control/gui/_stop_custody.py new file mode 100644 index 000000000..9c9fa01bb --- /dev/null +++ b/je_auto_control/gui/_stop_custody.py @@ -0,0 +1,187 @@ +"""Stops that failed in the background, kept so they can be retried instead of only logged. + +A panel lets go of a session, a recorder or a host at once and hands its +``stop`` to a :class:`~je_auto_control.gui._slow_op.StopQueue`. When that stop +raised, the queue used to log it and drop it: the resource might still be +running, and nothing owned it any more. :class:`StopCustody` keeps each failed +stop with the error it raised and the caller's authority captured when the stop +was queued, for the life of the application: + +* :meth:`StopCustody.snapshot` describes what is held -- labels, errors, + attempts -- without running anything or waiting on a native lock, so the + Diagnostics tab can read it on the GUI thread. +* :meth:`StopCustody.retry` runs a held stop again on the calling thread (a + worker), inside the authority it was queued under. A stop that succeeds is + released; one that fails again stays, with its new error. +* :meth:`StopCustody.forget` lets go of one the operator has dealt with. + +Holding a stop is not the same as its resource being released: a record stays +until a retry succeeds or the operator forgets it. This module has no Qt +import; the GUI reads it through the Diagnostics tab. +""" +from __future__ import annotations + +import functools +import itertools +import threading +import time +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional + +from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.logging.secret_scope import scrub_secret_text +from je_auto_control.utils.rbac.deferred import DeferredAuthorization + +#: The most failed stops held at once; the oldest is let go (and logged) beyond it. +MAX_HELD = 200 + + +@dataclass(frozen=True) +class FailedStop: + """What one held stop looks like from outside: no callable, no resource.""" + + stop_id: int + label: str + error: str + failed_at: float + attempts: int + + +@dataclass +class _Held: + stop: Callable[[], Any] + label: str + error: str + failed_at: float + attempts: int + authority: Optional[DeferredAuthorization] + + +def describe_stop(stop: Callable[[], Any]) -> str: + """A short label for ``stop``: the function's name, with its owner's class for a bound method.""" + target: Any = stop + while isinstance(target, functools.partial): + target = target.func + owner = getattr(target, "__self__", None) + name = getattr(target, "__name__", type(target).__name__) + return f"{type(owner).__name__}.{name}" if owner is not None else str(name) + + +class StopCustody: + """Thread-safe holder of failed stops; one per application (:func:`stop_custody`).""" + + def __init__(self, max_held: int = MAX_HELD) -> None: + self._lock = threading.Lock() + self._held: Dict[int, _Held] = {} + self._ids = itertools.count(1) + self._max_held = max_held + self._listeners: List[Callable[[], None]] = [] + + def hold(self, stop: Callable[[], Any], error: object, *, label: str = "", + authority: Optional[DeferredAuthorization] = None) -> int: + """Keep ``stop``, which raised ``error``; return its id. Safe from any thread.""" + record = _Held(stop, label or describe_stop(stop), scrub_secret_text(_text(error)), time.time(), 1, authority) + with self._lock: + stop_id = next(self._ids) + self._held[stop_id] = record + dropped = self._trim() + for old in dropped: + autocontrol_logger.warning(f"failed stop let go (custody full): {old.label}: {old.error}") + autocontrol_logger.warning(f"background stop failed and is held for retry: {record.label}: {record.error}") + self._changed() + return stop_id + + def snapshot(self) -> List[FailedStop]: + """What is held, oldest first; runs no stop and never waits on anything but this lock.""" + with self._lock: + return [FailedStop(stop_id, held.label, held.error, held.failed_at, held.attempts) + for stop_id, held in self._held.items()] + + def retry(self, stop_id: int) -> bool: + """Run a held stop again, under its captured authority; ``True`` when it succeeded (it is then released). + + Blocks for as long as the stop does: call it on a worker. An unknown id is ``False``. + """ + with self._lock: + held = self._held.get(stop_id) + if held is None: + return False + try: + if held.authority is not None: + with held.authority.scope(): + held.stop() + else: + held.stop() + except Exception as error: # noqa: BLE001 # reason: recorded on the held stop, which stays for another retry + with self._lock: + if self._held.get(stop_id) is held: + held.error = scrub_secret_text(_text(error)) + held.attempts += 1 + held.failed_at = time.time() + self._changed() + return False + with self._lock: + if self._held.get(stop_id) is held: + del self._held[stop_id] + self._changed() + return True + + def retry_all(self) -> tuple[int, int]: + """Retry every held stop once, oldest first; return ``(released, still_failing)``.""" + released = failing = 0 + for record in self.snapshot(): + if self.retry(record.stop_id): + released += 1 + else: + failing += 1 + return released, failing + + def forget(self, stop_id: int) -> bool: + """Let go of one held stop without running it; ``True`` when it was held.""" + with self._lock: + found = self._held.pop(stop_id, None) is not None + if found: + self._changed() + return found + + def add_listener(self, listener: Callable[[], None]) -> Callable[[], None]: + """Call ``listener()`` after every change, on the thread that made it; return its removal.""" + with self._lock: + self._listeners.append(listener) + + def remove() -> None: + with self._lock: + if listener in self._listeners: + self._listeners.remove(listener) + return remove + + def _trim(self) -> List[_Held]: + dropped = [] + while len(self._held) > self._max_held: + oldest = next(iter(self._held)) + dropped.append(self._held.pop(oldest)) + return dropped + + def _changed(self) -> None: + with self._lock: + listeners = list(self._listeners) + for listener in listeners: + try: + listener() + except Exception as error: # noqa: BLE001 # reason: a listener must not undo the custody change + autocontrol_logger.warning(f"stop custody listener failed: {error!r}") + + +def _text(error: object) -> str: + return f"{type(error).__name__}: {error}" if isinstance(error, BaseException) else str(error) + + +_CUSTODY = StopCustody() + + +def stop_custody() -> StopCustody: + """The application's custody of failed background stops.""" + return _CUSTODY + + +__all__ = ["FailedStop", "MAX_HELD", "StopCustody", "describe_stop", "stop_custody"] diff --git a/je_auto_control/gui/diagnostics_tab.py b/je_auto_control/gui/diagnostics_tab.py index 225b3eb4d..3efc8ec00 100644 --- a/je_auto_control/gui/diagnostics_tab.py +++ b/je_auto_control/gui/diagnostics_tab.py @@ -13,6 +13,7 @@ from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.diagnostics_capabilities import CapabilityView +from je_auto_control.gui.failed_stops_view import FailedStopsView from je_auto_control.gui.mcp_discovery_view import MCPDiscoveryView from je_auto_control.gui.workspace_details import ExecutionDetails, ExecutionDetailsSource, ExecutionPhase from je_auto_control.gui.task_controller import TaskController, TaskHandle, TaskOutcome @@ -76,6 +77,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._progress_label.setWordWrap(True) self._capability_view = CapabilityView() self._mcp_discovery = MCPDiscoveryView() + self._failed_stops = FailedStopsView() self._table = QTableWidget(0, 4) self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) self._table.horizontalHeader().setSectionResizeMode( @@ -94,6 +96,7 @@ def _build_layout(self) -> None: set_role(self._progress_label, "hint") results = Card().add(self._summary_label).add(self._progress_label).add(self._table, stretch=1) root.addWidget(results, stretch=1) + root.addWidget(Card().add(self._failed_stops)) root.addWidget(Card().add(self._mcp_discovery)) def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: @@ -102,7 +105,7 @@ def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: ("diag_probe", self._probe_capabilities), ("diag_run", self._refresh), ("diag_stop", self._stop), - ] + self._mcp_discovery.menu_actions() + ] + self._failed_stops.menu_actions() + self._mcp_discovery.menu_actions() def retranslate(self) -> None: """Translate idle instructions and headers without starting a diagnostic run.""" @@ -110,6 +113,7 @@ def retranslate(self) -> None: self._apply_table_headers() self._capability_view.retranslate() self._mcp_discovery.retranslate() + self._failed_stops.retranslate() self._render_summary() if self._view.report is not None: self._fill_table(self._view.report) diff --git a/je_auto_control/gui/failed_stops_view.py b/je_auto_control/gui/failed_stops_view.py new file mode 100644 index 000000000..c1ca14f43 --- /dev/null +++ b/je_auto_control/gui/failed_stops_view.py @@ -0,0 +1,116 @@ +"""Diagnostics' view of background stops that failed: what is held, and a retry from the Actions menu. + +The rows come from :func:`~je_auto_control.gui._stop_custody.stop_custody`'s +snapshot, which runs nothing and waits on no native lock, so reading it on the +GUI thread is safe. *Retry failed stops* runs every held stop again on a worker, +each under the authority it was queued with; *Forget selected failed stop* lets +go of one without running it. +""" +from __future__ import annotations + +import datetime +from typing import Callable, Optional + +from PySide6.QtCore import QObject, Qt, Signal +from PySide6.QtWidgets import QAbstractItemView, QLabel, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget + +from je_auto_control.gui._stop_custody import StopCustody, stop_custody +from je_auto_control.gui._tab_task import TabTask +from je_auto_control.gui.adaptive.surfaces import set_role +from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper + +_COLUMNS = ("failed_stops_col_what", "failed_stops_col_error", "failed_stops_col_attempts", "failed_stops_col_at") + + +def _t(key: str) -> str: + return language_wrapper.translate(key, key) + + +class _Relay(QObject): + """Carries the custody's change notice, made on any thread, to the GUI thread.""" + + changed = Signal() + + +class FailedStopsView(QWidget): + """The held failed stops, as a table; its commands go to the owning tab's Actions menu.""" + + def __init__(self, parent: Optional[QWidget] = None, custody: Optional[StopCustody] = None) -> None: + super().__init__(parent) + self._custody = custody if custody is not None else stop_custody() + self._title = QLabel() + set_role(self._title, "sectionTitle") + self._hint = QLabel() + self._hint.setWordWrap(True) + set_role(self._hint, "hint") + self._status = QLabel() + self._status.setWordWrap(True) + self._table = QTableWidget(0, len(_COLUMNS)) + self._table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) + self._table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + for widget in (self._title, self._hint, self._table, self._status): + layout.addWidget(widget) + # Retries run every held stop again: off the GUI thread, one round at a time. + self._retries = TabTask(self, details=False) + self._retries.result.connect(self._show_retried) + self._retries.error.connect(self._show_retry_error) + self._relay = _Relay(self) + self._relay.changed.connect(self.refresh, Qt.ConnectionType.QueuedConnection) + remove = self._custody.add_listener(self._relay.changed.emit) + self.destroyed.connect(lambda *_: remove()) # holds only the removal, never this view + self.retranslate() + + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: + """Retry or forget held stops through the owning tab's Actions menu.""" + return [("failed_stops_retry", self.retry_all), ("failed_stops_forget", self.forget_selected)] + + def retranslate(self) -> None: + """Re-read the texts and headers in the active language.""" + self._title.setText(_t("failed_stops_title")) + self._hint.setText(_t("failed_stops_hint")) + self._table.setHorizontalHeaderLabels([_t(key) for key in _COLUMNS]) + self.refresh() + + def refresh(self) -> None: + """Show what the custody holds now.""" + rows = self._custody.snapshot() + self._table.setRowCount(len(rows)) + for row, held in enumerate(rows): + stamp = datetime.datetime.fromtimestamp(held.failed_at).strftime("%H:%M:%S") + for column, text in enumerate((held.label, held.error, str(held.attempts), stamp)): + item = QTableWidgetItem(text) + item.setData(Qt.ItemDataRole.UserRole, held.stop_id) + self._table.setItem(row, column, item) + + def retry_all(self) -> None: + """Run every held stop again on a worker; a second click while one round runs is refused.""" + if not self._custody.snapshot(): + self._status.setText(_t("failed_stops_nothing")) + return + if self._retries.start(self._custody.retry_all): + self._status.setText(_t("failed_stops_retrying")) + else: + self._status.setText(_t("task_busy")) + + def forget_selected(self) -> None: + """Let go of the selected held stop without running it.""" + item = self._table.item(self._table.currentRow(), 0) if self._table.currentRow() >= 0 else None + stop_id = item.data(Qt.ItemDataRole.UserRole) if item is not None else None + if isinstance(stop_id, int) and self._custody.forget(stop_id): + self._status.setText(_t("failed_stops_forgotten")) + else: + self._status.setText(_t("failed_stops_select_first")) + + def _show_retried(self, outcome: object) -> None: + released, failing = outcome if isinstance(outcome, tuple) else (0, 0) + self._status.setText(_t("failed_stops_result").format(released=released, failing=failing)) + self.refresh() + + def _show_retry_error(self, error: object) -> None: + self._status.setText(f"{type(error).__name__}: {error}") + self.refresh() + + +__all__ = ["FailedStopsView"] diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index 89806ee30..3d397a35e 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -1497,6 +1497,20 @@ "page_banner_refused": "Not permitted: {detail}", "page_banner_permission": "Your role ({role}) cannot run {commands} here. Ask an administrator for access.", "page_banner_dismiss": "Dismiss", + "failed_stops_title": "Background stops that failed", + "failed_stops_hint": ("A panel let go of these, but stopping them raised, so what they held may still be open. " + "Retry runs each stop again under the authority it was queued with."), + "failed_stops_col_what": "What", + "failed_stops_col_error": "Error", + "failed_stops_col_attempts": "Attempts", + "failed_stops_col_at": "Last failed", + "failed_stops_retry": "Retry failed stops", + "failed_stops_forget": "Forget selected failed stop", + "failed_stops_nothing": "No failed stops are held.", + "failed_stops_retrying": "Retrying the failed stops…", + "failed_stops_result": "Released {released}; still failing {failing}.", + "failed_stops_forgotten": "Forgotten.", + "failed_stops_select_first": "Select a failed stop first.", "stop_playback": "Stop playback", "record_playing": "Playing back...", "rd_file_sending": "Sending {name}...", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index 71a349d89..ed937809c 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -1394,6 +1394,21 @@ "page_banner_permission": ("現在のロール({role})ではこのページの {commands} を実行できません。" "管理者にアクセスを依頼してください。"), "page_banner_dismiss": "閉じる", + "failed_stops_title": "失敗したバックグラウンド停止", + "failed_stops_hint": ("パネルはこれらを手放しましたが、停止で例外が発生したため、保持していたも" + "のがまだ開いている可能性があります。" + "再試行は、キューに入れた時点の権限で各停止をもう一度実行します。"), + "failed_stops_col_what": "対象", + "failed_stops_col_error": "エラー", + "failed_stops_col_attempts": "試行回数", + "failed_stops_col_at": "最後の失敗", + "failed_stops_retry": "失敗した停止を再試行", + "failed_stops_forget": "選択した失敗停止を破棄", + "failed_stops_nothing": "保持している失敗停止はありません。", + "failed_stops_retrying": "失敗した停止を再試行しています…", + "failed_stops_result": "解放 {released} 件、失敗のまま {failing} 件。", + "failed_stops_forgotten": "破棄しました。", + "failed_stops_select_first": "先に失敗停止を選択してください。", "stop_playback": "再生を停止", "record_playing": "再生中...", "rd_file_sending": "{name} を送信中...", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index b49456459..9acb58185 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -1357,6 +1357,20 @@ "page_banner_refused": "未获许可:{detail}", "page_banner_permission": "你的角色({role})无法在此执行 {commands}。请向管理员申请权限。", "page_banner_dismiss": "关闭", + "failed_stops_title": "失败的后台停止", + "failed_stops_hint": ("面板已放开这些对象,但停止时发生错误,它们持有的资源可能仍未关闭。" + "重试会以排入时的权限再次执行每个停止。"), + "failed_stops_col_what": "对象", + "failed_stops_col_error": "错误", + "failed_stops_col_attempts": "尝试次数", + "failed_stops_col_at": "最后失败", + "failed_stops_retry": "重试失败的停止", + "failed_stops_forget": "放弃所选的失败停止", + "failed_stops_nothing": "没有保留的失败停止。", + "failed_stops_retrying": "正在重试失败的停止…", + "failed_stops_result": "已释放 {released} 个;仍失败 {failing} 个。", + "failed_stops_forgotten": "已放弃。", + "failed_stops_select_first": "请先选择一个失败停止。", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在发送 {name}...", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index 6d4aabb15..5c4d4e4e3 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -1365,6 +1365,20 @@ "page_banner_refused": "未獲許可:{detail}", "page_banner_permission": "你的角色({role})無法在此執行 {commands}。請向管理員申請權限。", "page_banner_dismiss": "關閉", + "failed_stops_title": "失敗的背景停止", + "failed_stops_hint": ("面板已放開這些物件,但停止時發生錯誤,它們持有的資源可能仍未關閉。" + "重試會以排入時的權限再次執行每個停止。"), + "failed_stops_col_what": "對象", + "failed_stops_col_error": "錯誤", + "failed_stops_col_attempts": "嘗試次數", + "failed_stops_col_at": "最後失敗", + "failed_stops_retry": "重試失敗的停止", + "failed_stops_forget": "放棄所選的失敗停止", + "failed_stops_nothing": "沒有保留的失敗停止。", + "failed_stops_retrying": "正在重試失敗的停止…", + "failed_stops_result": "已釋放 {released} 個;仍失敗 {failing} 個。", + "failed_stops_forgotten": "已放棄。", + "failed_stops_select_first": "請先選擇一個失敗停止。", "stop_playback": "停止回放", "record_playing": "回放中...", "rd_file_sending": "正在傳送 {name}...", diff --git a/je_auto_control/gui/remote_desktop/_connect_task.py b/je_auto_control/gui/remote_desktop/_connect_task.py index 353b8a8f0..ab792a84f 100644 --- a/je_auto_control/gui/remote_desktop/_connect_task.py +++ b/je_auto_control/gui/remote_desktop/_connect_task.py @@ -12,9 +12,11 @@ from PySide6.QtCore import QObject +from je_auto_control.gui._slow_op import hold_failed_stop from je_auto_control.gui._weak_call import weak_slot from je_auto_control.gui.tab_task_controller import CancellationToken, TaskHandle, task_controller from je_auto_control.utils.logging.logging_instance import autocontrol_logger +from je_auto_control.utils.rbac.deferred import DeferredAuthorization #: Seconds the backend gets for each step of the connect. CONNECT_TIMEOUT_S = 5.0 @@ -29,7 +31,7 @@ def _disconnect_quietly(viewer: Any) -> None: def _connect(viewer: Any, timeout_s: float, before: Optional[Callable[[], Any]], - token: CancellationToken) -> Any: + authority: DeferredAuthorization, token: CancellationToken) -> Any: """Worker thread: run ``before`` (always), then connect ``viewer`` and return it.""" if before is not None: # The previous session's shutdown: it lets go of its seat before this @@ -37,7 +39,8 @@ def _connect(viewer: Any, timeout_s: float, before: Optional[Callable[[], Any]], try: before() except (OSError, RuntimeError) as error: - autocontrol_logger.warning("closing the previous remote-desktop session failed: %r", error) + # Kept for a retry from Diagnostics: the old session may still hold its socket. + hold_failed_stop(before, error, authority) # connect() takes a timeout but no cancel signal: a cancelled attempt # runs out its timeout, and the viewer it produced is disconnected by # the task's ``discard``. @@ -61,7 +64,8 @@ def connect_viewer(owner: QObject, viewer: Any, *, one replaces, from ``registry.detach`` -- runs on the same worker first, so it does not hold the GUI thread. """ - handle = task_controller().submit(functools.partial(_connect, viewer, timeout_s, before), + handle = task_controller().submit(functools.partial(_connect, viewer, timeout_s, before, + DeferredAuthorization.capture()), owner=owner, discard=_disconnect_quietly) handle.result.connect(weak_slot(on_connected)) handle.error.connect(weak_slot(on_failed)) diff --git a/pyproject.toml b/pyproject.toml index fb3e08596..0b4be9bdc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -369,6 +369,8 @@ module = [ "je_auto_control.gui.navigation", "je_auto_control.gui.workspace_details", "je_auto_control.gui._task_details", + "je_auto_control.gui._stop_custody", + "je_auto_control.gui.failed_stops_view", "je_auto_control.gui.remote_desktop.webrtc_panel_state", "je_auto_control.gui.remote_desktop.view_lifetime", "je_auto_control.gui.remote_desktop.view_approvals", diff --git a/test/unit_test/headless/test_actions_menu_gui.py b/test/unit_test/headless/test_actions_menu_gui.py index d9c4e63a0..eb724e146 100644 --- a/test/unit_test/headless/test_actions_menu_gui.py +++ b/test/unit_test/headless/test_actions_menu_gui.py @@ -146,6 +146,7 @@ def test_hook_tab_actions_reach_the_menu(report): def test_diagnostic_run_stop_and_passive_inspection_reach_the_window_actions_menu(report): assert report['diagnostic_menu_keys'] == ['diag_probe', 'diag_run', 'diag_stop', + 'failed_stops_retry', 'failed_stops_forget', 'mcp_discovery_search', 'mcp_discovery_schema', 'mcp_disclosure_plan'] diff --git a/test/unit_test/headless/test_gui_slow_stops.py b/test/unit_test/headless/test_gui_slow_stops.py index 5e4df753f..62eb86a09 100644 --- a/test/unit_test/headless/test_gui_slow_stops.py +++ b/test/unit_test/headless/test_gui_slow_stops.py @@ -23,7 +23,7 @@ email_triggers_tab, hotkeys_tab, rest_api_tab, scheduler_tab, triggers_tab, usb_passthrough_panel, webhooks_tab, ) -from je_auto_control.gui._slow_op import SlowOp, StopQueue, stop_each # noqa: E402 +from je_auto_control.gui._slow_op import SlowOp, StopQueue, StopsFailed, stop_each # noqa: E402 from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 from je_auto_control.gui.remote_desktop import host_panel # noqa: E402 from je_auto_control.gui.tab_task_controller import TaskUsageError # noqa: E402 @@ -441,8 +441,11 @@ def test_stop_each_runs_every_stop_even_after_one_failed(): def broken(): raise RuntimeError("already closed") - stop_each(lambda: ran.append(1), broken, lambda: ran.append(2)) + # The rest still run; the failure is reported afterwards so a StopQueue can keep it for a retry. + with pytest.raises(StopsFailed) as raised: + stop_each(lambda: ran.append(1), broken, lambda: ran.append(2)) assert ran == [1, 2] + assert [stop for stop, _error in raised.value.failures] == [broken] def test_a_dropped_owner_is_not_kept_alive_by_its_callbacks(qapp): diff --git a/test/unit_test/headless/test_stop_custody.py b/test/unit_test/headless/test_stop_custody.py new file mode 100644 index 000000000..a0369dabf --- /dev/null +++ b/test/unit_test/headless/test_stop_custody.py @@ -0,0 +1,152 @@ +"""A background stop that fails is kept for a retry, not only logged. + +``StopQueue`` and ``stop_each`` logged a failed stop and dropped it: the +session, recorder or host might still hold its socket or device, and nothing +owned it. The application's stop custody now keeps it with its error and the +authority it was queued under, and the Diagnostics tab lists and retries it. +""" +import os + +import pytest + +from je_auto_control.gui._stop_custody import StopCustody, describe_stop +from je_auto_control.utils.rbac import AuthorizationContext, Role, authorization_scope +from je_auto_control.utils.rbac.authorization import current_authorization +from je_auto_control.utils.rbac.deferred import DeferredAuthorization + + +class _Flaky: + """A stop that fails ``failures`` times, then succeeds; it records the caller each time.""" + + def __init__(self, failures=1, message="socket busy"): + self.failures, self.message, self.callers = failures, message, [] + + def stop(self): + caller = current_authorization() + self.callers.append(None if caller is None else caller.user_id) + if self.failures: + self.failures -= 1 + raise OSError(self.message) + + +def test_a_held_stop_is_described_without_its_resource(): + custody, flaky = StopCustody(), _Flaky() + stop_id = custody.hold(flaky.stop, OSError("socket busy")) + [held] = custody.snapshot() + assert (held.stop_id, held.label, held.error, held.attempts) == (stop_id, "_Flaky.stop", "OSError: socket busy", 1) + assert not hasattr(held, "stop") + + +def test_a_retry_that_succeeds_releases_and_one_that_fails_keeps_the_new_error(): + custody, flaky = StopCustody(), _Flaky(failures=1, message="still busy") + stop_id = custody.hold(flaky.stop, OSError("socket busy")) + assert custody.retry(stop_id) is False + [held] = custody.snapshot() + assert (held.error, held.attempts) == ("OSError: still busy", 2) + assert custody.retry(stop_id) is True + assert custody.snapshot() == [] + assert custody.retry(stop_id) is False # gone: nothing to run + + +def test_a_retry_runs_under_the_authority_it_was_queued_with(): + custody, flaky = StopCustody(), _Flaky(failures=0) + with authorization_scope(AuthorizationContext("operator", Role.OPERATOR)): + authority = DeferredAuthorization.capture() + with authorization_scope(AuthorizationContext("someone-else", Role.ADMIN)): + stop_id = custody.hold(flaky.stop, OSError("busy"), authority=authority) + assert custody.retry(stop_id) + assert flaky.callers == ["operator"] + + +def test_forget_retry_all_and_the_limit(): + custody = StopCustody(max_held=2) + flakies = [_Flaky(failures=0) for _ in range(3)] + ids = [custody.hold(flaky.stop, OSError("busy")) for flaky in flakies] + assert [held.stop_id for held in custody.snapshot()] == ids[1:] # the oldest was let go + assert custody.forget(ids[1]) is True and custody.forget(ids[1]) is False + assert custody.retry_all() == (1, 0) + assert custody.snapshot() == [] + + +def test_listeners_hear_every_change_until_removed(): + custody, heard = StopCustody(), [] + remove = custody.add_listener(lambda: heard.append(len(custody.snapshot()))) + stop_id = custody.hold(_Flaky(failures=0).stop, OSError("busy")) + custody.retry(stop_id) + remove() + custody.hold(_Flaky().stop, OSError("busy")) + assert heard == [1, 0] + + +def test_a_label_names_the_stop_through_a_partial(): + import functools + flaky = _Flaky() + assert describe_stop(functools.partial(functools.partial(flaky.stop))) == "_Flaky.stop" + + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtWidgets import QApplication, QWidget # noqa: E402 + +from je_auto_control.gui import _slow_op # noqa: E402 +from je_auto_control.gui._stop_custody import stop_custody # noqa: E402 +from headless._qt_settle import pump_until # noqa: E402 + +_APP = QApplication.instance() or QApplication([]) + + +@pytest.fixture +def custody(): + held = stop_custody() + for record in held.snapshot(): + held.forget(record.stop_id) + yield held + for record in held.snapshot(): + held.forget(record.stop_id) + + +def test_stop_each_runs_every_stop_and_names_each_failure(): + ran, first, second = [], _Flaky(message="first"), _Flaky(message="second") + with pytest.raises(_slow_op.StopsFailed) as raised: + _slow_op.stop_each(first.stop, lambda: ran.append("ok"), second.stop) + assert ran == ["ok"] + assert [str(error) for _stop, error in raised.value.failures] == ["first", "second"] + + +def test_a_stop_queue_hands_each_failed_stop_to_custody(custody): + owner = QWidget() + try: + queue = _slow_op.StopQueue(owner) + a, b, c = _Flaky(message="a"), _Flaky(message="b"), _Flaky(message="c") + queue.retire(lambda: _slow_op.stop_each(a.stop, b.stop)) # two failures in one shutdown + queue.retire(c.stop) + assert pump_until(lambda: queue.pending == 0) + held = sorted((record.label, record.error) for record in custody.snapshot()) + assert held == [("_Flaky.stop", "OSError: a"), ("_Flaky.stop", "OSError: b"), ("_Flaky.stop", "OSError: c")] + assert custody.retry_all() == (3, 0) # each held on its own, so each can be retried + finally: + owner.deleteLater() + + +def test_the_diagnostics_view_lists_retries_and_forgets_held_stops(custody): + from PySide6.QtCore import Qt + from je_auto_control.gui.failed_stops_view import FailedStopsView + flaky, stuck = _Flaky(failures=1), _Flaky(failures=5, message="device busy") + custody.hold(flaky.stop, OSError("socket busy")) + custody.hold(stuck.stop, OSError("device busy")) + view = FailedStopsView() + try: + assert pump_until(lambda: view._table.rowCount() == 2) + actions = dict(view.menu_actions()) + actions["failed_stops_retry"]() # flaky still fails once; stuck keeps failing + assert pump_until(lambda: not view._retries.running) + actions["failed_stops_retry"]() # flaky is released now + assert pump_until(lambda: not view._retries.running and view._table.rowCount() == 1) + assert view._table.item(0, 0).data(Qt.ItemDataRole.UserRole) == custody.snapshot()[0].stop_id + view._table.setCurrentCell(0, 0) + actions["failed_stops_forget"]() + assert pump_until(lambda: view._table.rowCount() == 0) + assert custody.snapshot() == [] + finally: + view.deleteLater() From adb5641571eaeebdf5df137c06eb14586e0f0083 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 18:19:06 +0800 Subject: [PATCH 104/161] Keep failed SlowOp stops and WebRTC session stops for a retry Stops outside a StopQueue were still only reported or logged. A SlowOp stop now opts into the stop custody as well as telling its panel, and the WebRTC host keeps a dropped offer's or a disconnected session's stop that failed; a start is never kept. --- CHANGELOG.md | 5 +++ Progress.md | 4 +- architecture_explore.md | 10 ++--- .../doc/new_features/v223_features_doc.rst | 7 +++- .../Zh/doc/new_features/v223_features_doc.rst | 5 ++- docs/updates/2026-11-b.md | 8 ++++ docs/updates/README.md | 1 + je_auto_control/gui/_slow_op.py | 9 ++++- je_auto_control/gui/email_triggers_tab.py | 2 +- je_auto_control/gui/hotkeys_tab.py | 2 +- .../gui/remote_desktop/connection_screen.py | 2 +- .../gui/remote_desktop/host_panel.py | 2 +- .../remote_desktop/webrtc_host_connection.py | 12 ++++-- .../remote_desktop/webrtc_host_sessions.py | 7 +++- je_auto_control/gui/rest_api_tab.py | 2 +- je_auto_control/gui/scheduler_tab.py | 2 +- je_auto_control/gui/triggers_tab.py | 2 +- je_auto_control/gui/usb_passthrough_panel.py | 2 +- je_auto_control/gui/webhooks_tab.py | 2 +- test/unit_test/headless/test_stop_custody.py | 40 +++++++++++++++++++ 20 files changed, 101 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff93e9f43..781d36c49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI: `SlowOp.run(..., retain_failure=True)` also hands a failed stop to the stop custody; the + Scheduler, Triggers, Hotkeys, E-mail Triggers, Webhooks, REST API and USB Sharing stops and + both Remote Desktop host stops pass it. The WebRTC host's dropped offers and disconnected + sessions keep a stop that failed instead of logging it; a session already gone is not kept. + - GUI: a shutdown handed to `StopQueue` that raises is kept by the new `gui/_stop_custody.py` (`stop_custody()`: `snapshot`, `retry`, `retry_all`, `forget`) with its error and the caller's authority captured when it was queued, instead of only being diff --git a/Progress.md b/Progress.md index 639339314..5cf887a11 100644 --- a/Progress.md +++ b/Progress.md @@ -539,8 +539,8 @@ F 還缺: U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33;同頁 session generation 已隔離,U-20261114-34)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**:StopQueue/stop_each 的失敗停止已交給應用程式層的保管者,Diagnostics 可在原授權下查詢/重試 - (U-20261114-36);仍須遷移 SlowOp 的一般停止、頁面銷毀後的 discard 路徑(含 `_drop_offer` 背景停止)與廣播清理, - 讓它們失敗時也交給保管者;不能把背景排程等同原生資源已釋放。 + (U-20261114-36);SlowOp 的停止與 WebRTC host 丟棄 offer/中斷工作階段的停止也已交給保管者(U-20261114-37); + 仍須遷移廣播清理;不能把背景排程等同原生資源已釋放。 GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 diff --git a/architecture_explore.md b/architecture_explore.md index 3be7b6941..2c2cbf6d4 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,046 | +| 程式碼總行數 | 237,060 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1391,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,525 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,534 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,525 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,534 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,678 | +| `gui/` | 166 | 43,692 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,301** | +| **總計** | **1,531** | **236,315** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 4fbc2b0b4..305b7c4bb 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -186,7 +186,12 @@ still be open. ``stop_each`` still runs every stop and then raises Diagnostics tab lists them from the custody's snapshot (which runs nothing and waits on no native lock); **Retry failed stops** runs each again on a worker under its original authority and releases the ones that succeed, and **Forget -selected failed stop** lets one go. +selected failed stop** lets one go. A stop run through ``SlowOp`` joins the custody with +``run(..., retain_failure=True)`` -- the Scheduler, Triggers, Hotkeys, E-mail +Triggers, Webhooks, REST API and USB Sharing stops and both Remote Desktop host +stops pass it; a start never does -- and the WebRTC host's dropped offers and +disconnected sessions keep a stop that failed (a session already gone is not a +failure). This is a GUI-internal API (it imports ``PySide6``) and is not re-exported by the package facade; the headless functions a tab calls stay usable without it. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index f5bfc5390..ed3828a06 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -167,7 +167,10 @@ GUI 執行緒執行,原本接在阻塞呼叫後面的程式碼就放在這裡。 會在應用程式存續期間保留它、它的錯誤以及排入時擷取的權限——物件已不在面板手上,但它持有的資源可能仍未關閉。 ``stop_each`` 仍會執行每個停止,之後丟出列出每個失敗停止的 ``StopsFailed``,讓每一個都分別保留。 診斷分頁從保管者的快照列出它們(快照不執行任何東西、也不等待原生鎖);\ **重試失敗的停止**\ 會在 worker -上以原權限再次執行每一個並釋放成功的,\ **放棄所選的失敗停止**\ 則放掉一個。 +上以原權限再次執行每一個並釋放成功的,\ **放棄所選的失敗停止**\ 則放掉一個。經 ``SlowOp`` 執行的停止以 +``run(..., retain_failure=True)`` 加入保管——排程、觸發器、熱鍵、E-mail 觸發器、Webhooks、REST API 與 USB Sharing +的停止以及兩個遠端桌面 host 的停止都會傳入;啟動則從不傳入——WebRTC host 丟棄的 offer 與中斷的工作階段停止失敗時 +也會保留(已經不存在的工作階段不算失敗)。 這是 GUI 內部 API(會 import ``PySide6``),套件 facade 不會重新匯出;分頁所呼叫的 無頭函式不需要它也能使用。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 777c79ab0..c2c6f3057 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -574,3 +574,11 @@ - **Docs:** the three READMEs and both `v223_features_doc.rst` (slow stops), `CHANGELOG.md`. - **Files:** `gui/_stop_custody.py`, `gui/failed_stops_view.py` (both in the strict mypy tier, `pyproject.toml`), `gui/_slow_op.py`, `gui/diagnostics_tab.py`, `gui/remote_desktop/_connect_task.py`, the four catalogues, the tests, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (SlowOp stops, discard paths, broadcast cleanup, media owners, the revoked-authority close, native acceptance). + +## U-20261114-37 · 2026-11-14 · SlowOp stops and the WebRTC host's session stops join the stop custody · #done #gui #lifecycle + +- **What:** the next part of `Progress.md` › *F3 關閉失敗恢復*, after U-20261114-36. Stops that do not go through a `StopQueue` were still only reported or logged. `SlowOp.run` takes `retain_failure=True`: the failure still reaches the panel's `on_error` as before, and it is also kept by the stop custody under the authority captured at the call, so it appears in Diagnostics for a retry. Only stops pass it -- retrying a failed start would start something nobody asked for -- and all nine `SlowOp` stops do: the Scheduler, Triggers, Hotkeys, E-mail Triggers, Webhooks, REST API and USB Sharing tabs and the Remote Desktop host panel's and Quick Connect's host stops. The WebRTC host panel's `_retire_quietly` (dropped offers, through the panel's `StopQueue` or the task's `discard`) and `_stop_session` (*Disconnect selected*) caught and logged every error; a session already gone (`KeyError`) is still only logged, but a stop that failed (`RuntimeError`, `OSError`, which covers the peer lifecycle errors) is kept. +- **Tests:** `test_stop_custody.py` gains three (a `SlowOp` stop with `retain_failure` is kept and still reported to the panel; a start without it is not kept; the WebRTC host keeps a session whose stop failed but not one already gone). Slow-stop, Scheduler, Triggers, Hotkeys, E-mail, Webhooks, REST API, USB, Remote Desktop, WebRTC, custody and Quick Connect tests: 3113 passed, 18 skipped. +- **Docs:** both `v223_features_doc.rst` (slow stops), `CHANGELOG.md`. +- **Files:** `gui/_slow_op.py`, the nine tabs and panels named above, `gui/remote_desktop/webrtc_host_connection.py`, `gui/remote_desktop/webrtc_host_sessions.py`, the test, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (broadcast cleanup, media owners, the revoked-authority close, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index 5aea90b49..87e82d15c 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-37 | 2026-11-14 | SlowOp stops and the WebRTC host's session stops join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-36 | 2026-11-14 | A failed background stop is kept for a retry from Diagnostics | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-35 | 2026-11-14 | The WebRTC host panel stops the session it captured; a failed peer build leaves nothing | #done #gui #webrtc | [2026-11-b](2026-11-b.md) | | U-20261114-34 | 2026-11-14 | A replaced viewer session's late events no longer reach the next one | #done #gui #remote-desktop | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_slow_op.py b/je_auto_control/gui/_slow_op.py index b1e7e2e86..c1a4087f5 100644 --- a/je_auto_control/gui/_slow_op.py +++ b/je_auto_control/gui/_slow_op.py @@ -104,7 +104,7 @@ def busy(self) -> bool: def run(self, work: Callable[[], Any], *, # noqa: PLR0913 # reason: keyword-only options of one call on_done: Callback = None, on_error: Callback = None, args: Tuple[Any, ...] = (), discard: Optional[Callable[[Any], object]] = None, - timeout_s: Optional[float] = None) -> bool: + timeout_s: Optional[float] = None, retain_failure: bool = False) -> bool: """Run ``work()`` off the GUI thread; return ``False`` (and do nothing) while busy. ``on_done(*args, result)`` or ``on_error(*args, exception)`` runs on @@ -112,7 +112,9 @@ def run(self, work: Callable[[], Any], *, # noqa: PLR0913 # reason: keyword-o false. Neither runs when the owner was destroyed meanwhile; the work itself still runs to its end, and what it returned then goes to ``discard`` (stop the server nobody is left to show). An error nobody - handles is logged. + handles is logged. With ``retain_failure`` -- for a stop, never a start + -- a failure is also kept by the stop custody, under the authority + captured now, so it can be retried from the Diagnostics tab. """ if self._busy: return False @@ -125,6 +127,9 @@ def run(self, work: Callable[[], Any], *, # noqa: PLR0913 # reason: keyword-o self._on_error = _WeakCall(on_error, args) handle.result.connect(self._deliver_result) handle.error.connect(self._deliver_error) + if retain_failure: + handle.error.connect(functools.partial(hold_failed_stop, work, + authority=DeferredAuthorization.capture())) handle.finished.connect(self._settle) self.busy_changed.emit(True) return True diff --git a/je_auto_control/gui/email_triggers_tab.py b/je_auto_control/gui/email_triggers_tab.py index 53cf05fe0..ea0634e27 100644 --- a/je_auto_control/gui/email_triggers_tab.py +++ b/je_auto_control/gui/email_triggers_tab.py @@ -164,7 +164,7 @@ def _on_stop(self) -> None: # A Poll Now in flight stops before its next trigger. self._polls.stop() if self._watcher_op.run(default_email_trigger_watcher.stop, on_done=self._on_watcher_stopped, - on_error=self._on_watcher_stopped): + on_error=self._on_watcher_stopped, retain_failure=True): self._refresh() def _on_watcher_stopped(self, _outcome: object = None) -> None: diff --git a/je_auto_control/gui/hotkeys_tab.py b/je_auto_control/gui/hotkeys_tab.py index fd27a32ae..9045a8574 100644 --- a/je_auto_control/gui/hotkeys_tab.py +++ b/je_auto_control/gui/hotkeys_tab.py @@ -150,7 +150,7 @@ def _on_stop(self) -> None: # stop() joins the daemon thread, which used to hold the GUI thread # for up to 2 s; a second Stop while it is out is ignored. if self._engine_op.run(default_hotkey_daemon.stop, on_done=self._on_daemon_stopped, - on_error=self._on_daemon_stopped): + on_error=self._on_daemon_stopped, retain_failure=True): self.sync_with_engine() def _on_daemon_stopped(self, _outcome: object = None) -> None: diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 46c7f692f..5e341cd88 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -397,7 +397,7 @@ def _show_approval_dialog(self, request: _ApprovalRequest) -> None: def _stop_hosting(self) -> None: # Stops the host the badge shows, whoever started it; see _HostPanel._stop. if self._host_op.run(functools.partial(stop_host, self._owner), on_done=self._on_host_changed, - on_error=self._on_host_stop_failed): + on_error=self._on_host_stop_failed, retain_failure=True): self._host_pending = "gui_op_stopping" self._refresh_status() diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index d4a1a1620..308ce9287 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -343,7 +343,7 @@ def _stop(self) -> None: return self._pending_key = "gui_op_stopping" self._host_op.run(functools.partial(stop_host, self._owner), on_done=self._on_stopped, - on_error=self._on_stop_failed) + on_error=self._on_stop_failed, retain_failure=True) self._refresh_status() def _on_stopped(self, _evicted: object = None) -> None: diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py index 846222b5b..6e6ccc7af 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py @@ -23,7 +23,7 @@ from je_auto_control.gui.remote_desktop.webrtc_workers import ( HostPublishLoopWorker, generate_host_id, retire_worker, ) -from je_auto_control.gui._slow_op import stop_each +from je_auto_control.gui._slow_op import hold_failed_stop, stop_each from je_auto_control.gui._weak_call import weak_slot from je_auto_control.gui.tab_task_controller import CancellationToken, task_controller from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -50,11 +50,17 @@ def _create_offer(host: MultiViewerHostT, _token: CancellationToken) -> Any: def _retire_quietly(retirement: Any, *_token: object) -> None: - """Worker thread: stop a session nobody will use; one already gone is not an error.""" + """Worker thread: stop a session nobody will use; one already gone is not an error. + + A stop that fails is kept by the stop custody for a retry from Diagnostics: + the session's peer may still be open. + """ try: retirement.stop() - except (KeyError, RuntimeError, OSError) as error: + except KeyError as error: autocontrol_logger.debug("dropping an unused offer: %r", error) + except (RuntimeError, OSError) as error: + hold_failed_stop(retirement.stop, error) def _drop_offer(offer: Any) -> None: diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py index 7f408d3e8..d9de55488 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_sessions.py @@ -15,6 +15,7 @@ QTableWidgetItem, ) +from je_auto_control.gui._slow_op import hold_failed_stop from je_auto_control.gui.remote_desktop._webrtc_types import MultiViewerHostT from je_auto_control.gui.remote_desktop._helpers import ( _t, @@ -32,8 +33,10 @@ def _stop_session(retirement: Any) -> None: """Worker thread: close the session ``retirement`` captured; one that is already gone is not an error.""" try: retirement.stop() - except (KeyError, RuntimeError, OSError) as error: - autocontrol_logger.warning("disconnect session: %r", error) + except (RuntimeError, OSError) as error: + hold_failed_stop(retirement.stop, error) # its peer may still be open: retry from Diagnostics + except KeyError as error: + autocontrol_logger.debug("disconnect session: already gone: %r", error) class _HostSessionsMixin(_HostPanelPart): diff --git a/je_auto_control/gui/rest_api_tab.py b/je_auto_control/gui/rest_api_tab.py index a37567061..55474ca33 100644 --- a/je_auto_control/gui/rest_api_tab.py +++ b/je_auto_control/gui/rest_api_tab.py @@ -207,7 +207,7 @@ def _on_stop(self) -> None: return self._pending_key = "gui_op_stopping" self._server_op.run(rest_api_registry.stop, on_done=self._on_server_op_done, - on_error=self._on_server_op_done) + on_error=self._on_server_op_done, retain_failure=True) self._refresh_status() def _on_server_op_done(self, _outcome: object = None) -> None: diff --git a/je_auto_control/gui/scheduler_tab.py b/je_auto_control/gui/scheduler_tab.py index c7031febd..4a1ef1c1b 100644 --- a/je_auto_control/gui/scheduler_tab.py +++ b/je_auto_control/gui/scheduler_tab.py @@ -154,7 +154,7 @@ def _on_stop(self) -> None: # stop() joins the engine thread (up to 2 s), which used to hold the # GUI thread; a second Stop while it is out is ignored. if self._engine_op.run(default_scheduler.stop, on_done=self._on_engine_stopped, - on_error=self._on_engine_stopped): + on_error=self._on_engine_stopped, retain_failure=True): self.sync_with_engine() def _on_engine_stopped(self, _outcome: object = None) -> None: diff --git a/je_auto_control/gui/triggers_tab.py b/je_auto_control/gui/triggers_tab.py index 8247417cc..697ff6dc5 100644 --- a/je_auto_control/gui/triggers_tab.py +++ b/je_auto_control/gui/triggers_tab.py @@ -351,7 +351,7 @@ def _on_stop(self) -> None: # stop() joins the engine thread, which used to hold the GUI thread # for up to 2 s; a second Stop while it is out is ignored. if self._engine_op.run(default_trigger_engine.stop, on_done=self._on_engine_stopped, - on_error=self._on_engine_stopped): + on_error=self._on_engine_stopped, retain_failure=True): self.sync_with_engine() def _on_engine_stopped(self, _outcome: object = None) -> None: diff --git a/je_auto_control/gui/usb_passthrough_panel.py b/je_auto_control/gui/usb_passthrough_panel.py index 07d9d1df6..ccc9c94a7 100644 --- a/je_auto_control/gui/usb_passthrough_panel.py +++ b/je_auto_control/gui/usb_passthrough_panel.py @@ -262,7 +262,7 @@ def _disable_sharing(self) -> None: loop, self._share.loopback = self._share.loopback, None self._shared_table.setRowCount(0) self._share_op.run(functools.partial(_close_sharing, loop), on_done=self._on_sharing_closed, - on_error=self._on_sharing_closed) + on_error=self._on_sharing_closed, retain_failure=True) self._refresh_host_badge() def _on_sharing_closed(self, _outcome: object = None) -> None: diff --git a/je_auto_control/gui/webhooks_tab.py b/je_auto_control/gui/webhooks_tab.py index e19b8bf62..880fbbaad 100644 --- a/je_auto_control/gui/webhooks_tab.py +++ b/je_auto_control/gui/webhooks_tab.py @@ -147,7 +147,7 @@ def _on_stop(self) -> None: # stop() shuts the HTTP server down and joins its thread (up to 2 s), # which used to hold the GUI thread; a second Stop is ignored. if self._server_op.run(default_webhook_server.stop, on_done=self._on_server_stopped, - on_error=self._on_server_stopped): + on_error=self._on_server_stopped, retain_failure=True): self._refresh() def _on_server_stopped(self, _outcome: object = None) -> None: diff --git a/test/unit_test/headless/test_stop_custody.py b/test/unit_test/headless/test_stop_custody.py index a0369dabf..95794966a 100644 --- a/test/unit_test/headless/test_stop_custody.py +++ b/test/unit_test/headless/test_stop_custody.py @@ -150,3 +150,43 @@ def test_the_diagnostics_view_lists_retries_and_forgets_held_stops(custody): assert custody.snapshot() == [] finally: view.deleteLater() + + +def test_a_slow_op_stop_that_fails_is_kept_and_still_reported(custody): + owner, reported = QWidget(), [] + try: + op = _slow_op.SlowOp(owner) + flaky = _Flaky(message="port still bound") + assert op.run(flaky.stop, on_error=lambda error: reported.append(str(error)) or True, retain_failure=True) + assert pump_until(lambda: not op.busy and bool(custody.snapshot())) + assert [held.error for held in custody.snapshot()] == ["OSError: port still bound"] + assert reported == ["port still bound"] # the panel is still told + finally: + owner.deleteLater() + + +def test_a_slow_op_start_that_fails_is_not_kept(custody): + owner = QWidget() + try: + op = _slow_op.SlowOp(owner) + assert op.run(_Flaky(message="cannot bind").stop, on_error=lambda error: True) # a start: no retain_failure + assert pump_until(lambda: not op.busy) + assert custody.snapshot() == [] + finally: + owner.deleteLater() + + +def test_the_webrtc_host_keeps_a_session_whose_stop_failed_but_not_one_already_gone(custody): + pytest.importorskip("aiortc", exc_type=ImportError) + import types + from je_auto_control.gui.remote_desktop import webrtc_host_connection, webrtc_host_sessions + + def gone(): + raise KeyError("session-1") + + failing = _Flaky(message="peer close timed out") + webrtc_host_connection._retire_quietly(types.SimpleNamespace(stop=gone)) + webrtc_host_sessions._stop_session(types.SimpleNamespace(stop=gone)) + assert custody.snapshot() == [] + webrtc_host_sessions._stop_session(types.SimpleNamespace(stop=failing.stop)) + assert [held.error for held in custody.snapshot()] == ["OSError: peer close timed out"] From 277d24af0497464e9f872efd84d9b2d92067d86a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 18:29:36 +0800 Subject: [PATCH 105/161] Keep a failed LAN broadcast stop and never call a failed recording saved The advertiser stop logged a pending or uncertain retirement at debug level and dropped the advertiser that still owned the name, and a recording whose finalising raised left Record disabled with no outcome shown. The advertiser now goes to the stop custody, and the recording says it may be incomplete. --- CHANGELOG.md | 6 +++ Progress.md | 6 +-- architecture_explore.md | 12 ++--- docs/updates/2026-11-b.md | 7 +++ docs/updates/README.md | 1 + je_auto_control/gui/_slow_op.py | 7 ++- .../gui/language_wrapper/english.py | 2 + .../gui/language_wrapper/japanese.py | 2 + .../language_wrapper/simplified_chinese.py | 1 + .../language_wrapper/traditional_chinese.py | 1 + .../remote_desktop/webrtc_host_connection.py | 4 +- .../gui/remote_desktop/webrtc_viewer_media.py | 11 +++- .../headless/test_webrtc_slow_stops.py | 51 +++++++++++++++++++ 13 files changed, 99 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 781d36c49..9d292968b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI: `StopQueue.retire` takes `on_error=`. A WebRTC recording whose finalising fails re-enables + Record and says it may be incomplete instead of leaving the button disabled on *Stopping…*; + it is never reported saved. A LAN broadcast (zeroconf advertiser) whose stop fails -- a + `MediaRetirementError` included -- is kept, with that advertiser, by the stop custody instead + of being logged at debug level. New catalogue key `rd_webrtc_recording_unconfirmed`. + - GUI: `SlowOp.run(..., retain_failure=True)` also hands a failed stop to the stop custody; the Scheduler, Triggers, Hotkeys, E-mail Triggers, Webhooks, REST API and USB Sharing stops and both Remote Desktop host stops pass it. The WebRTC host's dropped offers and disconnected diff --git a/Progress.md b/Progress.md index 5cf887a11..6294cfb18 100644 --- a/Progress.md +++ b/Progress.md @@ -540,9 +540,9 @@ F 還缺: (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**:StopQueue/stop_each 的失敗停止已交給應用程式層的保管者,Diagnostics 可在原授權下查詢/重試 (U-20261114-36);SlowOp 的停止與 WebRTC host 丟棄 offer/中斷工作階段的停止也已交給保管者(U-20261114-37); - 仍須遷移廣播清理;不能把背景排程等同原生資源已釋放。 - GUI 廣播/錄影呼叫端仍須保留 `MediaRetirementError.owner` 和取消訊號附帶的清理擁有者; - 不可吞掉未確認結果、清掉失敗子物件或只因 `has_output` 就顯示已儲存。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 + LAN 廣播停止失敗與錄影定稿失敗也已保留原擁有者並如實回報(U-20261114-38);不能把背景排程等同原生資源已釋放。 + 取消訊號附帶的清理擁有者(`interrupted_retirement_owners`)仍未接到 GUI 呼叫端; + 不可吞掉未確認結果或清掉失敗子物件。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; diff --git a/architecture_explore.md b/architecture_explore.md index 2c2cbf6d4..6e995c6d5 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,060 | +| 程式碼總行數 | 237,082 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1341,7 +1341,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `journal_browser.py` | 260 | Run History 與 Self-Healing 共用的唯讀日誌檢視:來源連結/路徑/run/step 篩選、有界快照表與明細,舊結果以 request ID 隔離。 | | `journal_browser_worker.py` | 88 | 背景查閱與逐筆取消;帶入 context 並在開檔前重查 deferred 擁有者,以 queued counts 回報進度。 | | `manual_run_controls.py` | 72 | 手動執行的 history 勾選與獨立 journal 路徑;以共用無頭 scope 包住既有 GUI 執行,不改結果與變數。 | -| `language_wrapper/` | 8,601 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | +| `language_wrapper/` | 8,607 | 四語系字典(英/日/簡中/繁中)+ `multi_language_wrapper` 執行期切換器與監聽註冊表。 | | `selector/` | 216 | 拖曳選取螢幕區域的半透明全螢幕覆蓋層與樣板裁切工具(互動式,但都有對應的程式化 API)。 | > **分頁指令一律走 Actions 選單**:分頁本身只放輸入、表格與結果檢視,指令由視窗層選單暴露。 @@ -1391,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,534 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,545 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,534 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,545 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,692 | +| `gui/` | 166 | 43,714 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,315** | +| **總計** | **1,531** | **236,337** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c2c6f3057..96aaffa23 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -582,3 +582,10 @@ - **Docs:** both `v223_features_doc.rst` (slow stops), `CHANGELOG.md`. - **Files:** `gui/_slow_op.py`, the nine tabs and panels named above, `gui/remote_desktop/webrtc_host_connection.py`, `gui/remote_desktop/webrtc_host_sessions.py`, the test, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (broadcast cleanup, media owners, the revoked-authority close, native acceptance). + +## U-20261114-38 · 2026-11-14 · A failed LAN broadcast stop keeps its advertiser; a failed recording is never reported saved · #done #gui #lifecycle + +- **What:** the broadcast and recording parts of `Progress.md` › *F3 關閉失敗恢復*. The WebRTC host panel's `_stop_advertiser` caught `RuntimeError` / `OSError` and logged them at debug level, so a LAN broadcast whose zeroconf retirement was pending or uncertain (`MediaRetirementError`, which carries the advertiser as its `owner`) was dropped with nothing left owning the name or its socket. It now hands the failure to the stop custody with a retry that stops that same advertiser again under the advertise lock. On the viewer, a recording's stop that raised skipped the queue's done slot: Record stayed disabled on *Stopping…* and the outcome was never reported. `StopQueue.retire` takes `on_error=` (held weakly, like `on_done`); the recording's failure re-enables Record and warns that the file may be incomplete and that its stop is kept in Diagnostics (new key `rd_webrtc_recording_unconfirmed` in all four catalogues) -- never *saved*, which stays reserved for a stop that returned with output. The recorder's stop itself is kept by the custody through the queue (U-20261114-36). +- **Tests:** `test_webrtc_slow_stops.py` gains two (a recording whose finalising fails re-enables Record, warns with the path and error, is not reported saved, and is held; a LAN broadcast whose retirement fails is held and a retry stops the same advertiser; both fail on the old code). Slow-stop, WebRTC, remote, Remote Desktop, custody, recording, LAN, catalogue tests: 3800 passed, 13 skipped. +- **Files:** `gui/_slow_op.py`, `gui/remote_desktop/webrtc_host_connection.py`, `gui/remote_desktop/webrtc_viewer_media.py`, the four catalogues, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (owners attached to an interruption signal, the Host Browser dialog, the revoked-authority close, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index 87e82d15c..2ef8331b2 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-38 | 2026-11-14 | A failed LAN broadcast stop keeps its advertiser; a failed recording is never reported saved | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-37 | 2026-11-14 | SlowOp stops and the WebRTC host's session stops join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-36 | 2026-11-14 | A failed background stop is kept for a retry from Diagnostics | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-35 | 2026-11-14 | The WebRTC host panel stops the session it captured; a failed peer build leaves nothing | #done #gui #webrtc | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_slow_op.py b/je_auto_control/gui/_slow_op.py index c1a4087f5..38908a199 100644 --- a/je_auto_control/gui/_slow_op.py +++ b/je_auto_control/gui/_slow_op.py @@ -177,9 +177,12 @@ def pending(self) -> int: return self._pending def retire(self, stop: Callable[[], Any], *, on_done: Callback = None, - args: Tuple[Any, ...] = ()) -> None: + on_error: Callback = None, args: Tuple[Any, ...] = ()) -> None: """Run ``stop()`` off the GUI thread; ``on_done(*args, result)`` follows on the GUI thread. + ``on_error(*args, exception)`` follows instead when it raised, for a + panel that shows a state until its stop reports (both are held weakly). + A shutdown that raises is kept by :func:`~je_auto_control.gui._stop_custody.stop_custody`, with the caller's authority captured now, so it can be retried from the Diagnostics tab: the object is out of the panel's hands, but its @@ -192,6 +195,8 @@ def retire(self, stop: Callable[[], Any], *, on_done: Callback = None, handle.error.connect(functools.partial(hold_failed_stop, stop, authority=DeferredAuthorization.capture())) if on_done is not None: handle.result.connect(weak_slot(on_done, *args)) # a weak call, never the panel + if on_error is not None: + handle.error.connect(weak_slot(on_error, *args)) handle.finished.connect(self._one_reported) def _one_reported(self) -> None: diff --git a/je_auto_control/gui/language_wrapper/english.py b/je_auto_control/gui/language_wrapper/english.py index 3d397a35e..f005311ae 100644 --- a/je_auto_control/gui/language_wrapper/english.py +++ b/je_auto_control/gui/language_wrapper/english.py @@ -595,6 +595,8 @@ "rd_webrtc_recording_save_as": "Save recording as", "rd_webrtc_recording_saved": "Recording saved: {path}", "rd_webrtc_recording_empty": "Nothing was recorded (no frame arrived): {path} was not created", + "rd_webrtc_recording_unconfirmed": ("The recording {path} may be incomplete: {error}. " + "Its stop is kept in Diagnostics for a retry."), "rd_webrtc_stats_idle": "(no stats yet)", # (B) batch "rd_webrtc_hw_codec_label": "Hardware codec:", diff --git a/je_auto_control/gui/language_wrapper/japanese.py b/je_auto_control/gui/language_wrapper/japanese.py index ed937809c..32cb1e59a 100644 --- a/je_auto_control/gui/language_wrapper/japanese.py +++ b/je_auto_control/gui/language_wrapper/japanese.py @@ -489,6 +489,8 @@ "rd_webrtc_recording_save_as": "録画ファイル保存先", "rd_webrtc_recording_saved": "録画を保存しました: {path}", "rd_webrtc_recording_empty": "録画されたフレームがありません: {path} は作成されませんでした", + "rd_webrtc_recording_unconfirmed": ("録画 {path} は不完全な可能性があります:{error}。" + "停止は診断タブに保持され、再試行できます。"), "rd_webrtc_stats_idle": "(統計データなし)", # (B) batch "rd_webrtc_hw_codec_label": "ハードウェアコーデック:", diff --git a/je_auto_control/gui/language_wrapper/simplified_chinese.py b/je_auto_control/gui/language_wrapper/simplified_chinese.py index 9acb58185..88a844e3d 100644 --- a/je_auto_control/gui/language_wrapper/simplified_chinese.py +++ b/je_auto_control/gui/language_wrapper/simplified_chinese.py @@ -456,6 +456,7 @@ "rd_webrtc_recording_save_as": "录制保存为", "rd_webrtc_recording_saved": "录制已保存: {path}", "rd_webrtc_recording_empty": "没有录到任何画面(未收到帧):未创建 {path}", + "rd_webrtc_recording_unconfirmed": "录像 {path} 可能不完整:{error}。它的停止保留在诊断分页中,可以重试。", "rd_webrtc_stats_idle": "(暂无统计数据)", # (B) batch "rd_webrtc_hw_codec_label": "硬件编码器:", diff --git a/je_auto_control/gui/language_wrapper/traditional_chinese.py b/je_auto_control/gui/language_wrapper/traditional_chinese.py index 5c4d4e4e3..d98bdbc8b 100644 --- a/je_auto_control/gui/language_wrapper/traditional_chinese.py +++ b/je_auto_control/gui/language_wrapper/traditional_chinese.py @@ -463,6 +463,7 @@ "rd_webrtc_recording_save_as": "錄製存檔為", "rd_webrtc_recording_saved": "錄製已儲存:{path}", "rd_webrtc_recording_empty": "沒有錄到任何畫面(未收到影格):未建立 {path}", + "rd_webrtc_recording_unconfirmed": "錄影 {path} 可能不完整:{error}。它的停止保留在診斷分頁中,可以重試。", "rd_webrtc_stats_idle": "(尚無統計資料)", # (B) batch "rd_webrtc_hw_codec_label": "硬體編碼器:", diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py index 6e6ccc7af..34c8f66e0 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py @@ -95,7 +95,9 @@ def _stop_advertiser(advertiser: HostAdvertiser) -> None: try: advertiser.stop() except (RuntimeError, OSError) as error: - autocontrol_logger.debug("lan advertise stop: %r", error) + # Includes MediaRetirementError: zeroconf may still hold the name or its + # socket. Kept, with the advertiser that owns them, for a retry from Diagnostics. + hold_failed_stop(functools.partial(_stop_advertiser, advertiser), error) def _advertise_failed(error: object) -> None: diff --git a/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py b/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py index 15cf4cd90..62669452d 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py +++ b/je_auto_control/gui/remote_desktop/webrtc_viewer_media.py @@ -106,7 +106,8 @@ def _on_toggle_recording(self, checked: bool) -> None: # reports the button says so and takes no click. self._record_btn.setText(_t("gui_op_stopping")) self._record_btn.setEnabled(False) - self._stops.retire(recorder.stop, on_done=self._on_recording_stopped, args=(recorder,)) + self._stops.retire(recorder.stop, on_done=self._on_recording_stopped, + on_error=self._on_recording_stop_failed, args=(recorder,)) def _on_recording_stopped(self, recorder: SessionRecorderT, _outcome: object = None) -> None: """GUI thread: the recording is on disk (or no frame ever arrived).""" @@ -117,6 +118,14 @@ def _on_recording_stopped(self, recorder: SessionRecorderT, _outcome: object = N key = "rd_webrtc_recording_saved" if recorder.has_output else "rd_webrtc_recording_empty" QMessageBox.information(self, "WebRTC", _t(key).format(path=str(recorder.output_path))) + def _on_recording_stop_failed(self, recorder: SessionRecorderT, error: object) -> None: + """GUI thread: finalising failed -- never "saved"; the stop is kept in Diagnostics for a retry.""" + self._record_btn.setEnabled(True) + if self._recorder is None: + self._record_btn.setText(_t("rd_webrtc_start_recording")) + QMessageBox.warning(self, "WebRTC", _t("rd_webrtc_recording_unconfirmed").format( + path=str(recorder.output_path), error=error)) + def _on_stats(self, snapshot: StatsSnapshot) -> None: parts = [] if snapshot.fps is not None: diff --git a/test/unit_test/headless/test_webrtc_slow_stops.py b/test/unit_test/headless/test_webrtc_slow_stops.py index b5aff9753..7a006643c 100644 --- a/test/unit_test/headless/test_webrtc_slow_stops.py +++ b/test/unit_test/headless/test_webrtc_slow_stops.py @@ -191,3 +191,54 @@ def test_stopping_folder_sync_joins_the_watcher_off_the_gui_thread(): assert not _off(panel._sync_btn) assert panel._sync_btn.text() == _t("rd_webrtc_sync_start") assert pump_until(lambda: panel._stops.pending == 0) + + +def _empty_custody(): + from je_auto_control.gui._stop_custody import stop_custody + custody = stop_custody() + for record in custody.snapshot(): + custody.forget(record.stop_id) + return custody + + +def test_a_recording_whose_finalising_fails_is_never_reported_saved(qapp): + # A raising stop skipped the done slot: the button stayed on "Stopping…", + # disabled, and the recording was never reported at all. + custody = _empty_custody() + + def fail(): + raise RuntimeError("muxer did not finish") + + panel = webrtc_panel._WebRTCViewerPanel() + panel._recorder = types.SimpleNamespace(stop=fail, has_output=True, output_path="out.mp4") + try: + panel._on_toggle_recording(False) + assert settle_op(panel._stops) + assert panel._record_btn.isEnabled() + assert panel._record_btn.text() == _t("rd_webrtc_start_recording") + assert qapp.messages == [_t("rd_webrtc_recording_unconfirmed").format( + path="out.mp4", error="muxer did not finish")] + assert [held.error for held in custody.snapshot()] == ["RuntimeError: muxer did not finish"] + finally: + _empty_custody() + + +def test_a_lan_broadcast_whose_retirement_fails_keeps_its_advertiser(): + from je_auto_control.gui.remote_desktop import webrtc_host_connection + custody = _empty_custody() + calls = [] + + class _Advertiser: + def stop(self): + calls.append("stop") + if len(calls) == 1: + raise RuntimeError("media retirement incomplete: unregister") + + try: + webrtc_host_connection._stop_advertiser(_Advertiser()) + [held] = custody.snapshot() + assert "unregister" in held.error + assert custody.retry(held.stop_id) # the same advertiser, stopped again + assert calls == ["stop", "stop"] + finally: + _empty_custody() From feef1f9c287a3bc315d1bb785f7a583425f9eb8b Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 18:37:26 +0800 Subject: [PATCH 106/161] Close the LAN browser off the GUI thread without it holding the dialog The Browse LAN dialog joined zeroconf's thread on the GUI thread, swallowed a failed stop, and handed the browser a bound method that kept the dialog alive. The browser now reports through a weak lease, and its stop runs on an application-owned queue whose failures still reach the stop custody after the dialog is gone. --- CHANGELOG.md | 6 +++ Progress.md | 2 +- architecture_explore.md | 12 +++--- docs/updates/2026-11-b.md | 7 ++++ docs/updates/README.md | 1 + je_auto_control/gui/_slow_op.py | 29 +++++++++++++- .../gui/remote_desktop/webrtc_dialogs.py | 37 ++++++++++-------- .../remote_desktop/webrtc_host_connection.py | 4 +- .../headless/test_gui_listener_cleanup.py | 38 ++++++++++++++++++- 9 files changed, 108 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d292968b..87a083c4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI: the WebRTC *Browse LAN* dialog closes its zeroconf browser on a worker instead of the GUI + thread, through the new application-owned `app_stop_queue()` (in `gui/_slow_op.py`), so a stop + that fails after the dialog closed still reaches the stop custody; the browser reports through + a `ViewLifetime` lease and no longer keeps the dialog alive (`_services_changed` is gone). A + WebRTC offer dropped on the GUI thread is retired through the same queue. + - GUI: `StopQueue.retire` takes `on_error=`. A WebRTC recording whose finalising fails re-enables Record and says it may be incomplete instead of leaving the button disabled on *Stopping…*; it is never reported saved. A LAN broadcast (zeroconf advertiser) whose stop fails -- a diff --git a/Progress.md b/Progress.md index 6294cfb18..96133bfa5 100644 --- a/Progress.md +++ b/Progress.md @@ -542,7 +542,7 @@ F 還缺: (U-20261114-36);SlowOp 的停止與 WebRTC host 丟棄 offer/中斷工作階段的停止也已交給保管者(U-20261114-37); LAN 廣播停止失敗與錄影定稿失敗也已保留原擁有者並如實回報(U-20261114-38);不能把背景排程等同原生資源已釋放。 取消訊號附帶的清理擁有者(`interrupted_retirement_owners`)仍未接到 GUI 呼叫端; - 不可吞掉未確認結果或清掉失敗子物件。`HostBrowser` 對話框的持續所有權與背景清理仍缺整合。 + 不可吞掉未確認結果或清掉失敗子物件。(`HostBrowser` 對話框的所有權與背景清理已整合,U-20261114-39。) 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; diff --git a/architecture_explore.md b/architecture_explore.md index 6e995c6d5..09d0ad003 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,082 | +| 程式碼總行數 | 237,112 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1391,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,545 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,550 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,545 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,550 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1421,7 +1421,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | | `webrtc_panel_state.py` | 165 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | | `webrtc_panel.py` | 422 | WebRTC 子分頁主體。 | -| `webrtc_dialogs.py` | 524 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | +| `webrtc_dialogs.py` | 529 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | | `connection_screen.py` | 723 | Quick Connect —— AnyDesk 風格單畫面入口。 | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,714 | +| `gui/` | 166 | 43,744 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,337** | +| **總計** | **1,531** | **236,367** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 96aaffa23..7791be09a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -589,3 +589,10 @@ - **Tests:** `test_webrtc_slow_stops.py` gains two (a recording whose finalising fails re-enables Record, warns with the path and error, is not reported saved, and is held; a LAN broadcast whose retirement fails is held and a retry stops the same advertiser; both fail on the old code). Slow-stop, WebRTC, remote, Remote Desktop, custody, recording, LAN, catalogue tests: 3800 passed, 13 skipped. - **Files:** `gui/_slow_op.py`, `gui/remote_desktop/webrtc_host_connection.py`, `gui/remote_desktop/webrtc_viewer_media.py`, the four catalogues, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (owners attached to an interruption signal, the Host Browser dialog, the revoked-authority close, native acceptance). + +## U-20261114-39 · 2026-11-14 · The LAN browse dialog closes its browser off the GUI thread and is not kept alive by it · #done #gui #lifecycle + +- **What:** `Progress.md` › *F3 關閉失敗恢復*'s `HostBrowser` dialog ownership. `LanBrowseDialog` (WebRTC viewer › Browse LAN) ran `HostBrowser.stop()` on the GUI thread -- closing zeroconf joins its thread -- and swallowed its failure, and it handed the browser its bound `_update_services`, so zeroconf's thread held the dialog alive and could report to it after it ended. Now the dialog lets go of the browser at once, retires its `ViewLifetime` lease, and hands `browser.stop` to the new application-owned `app_stop_queue()` (`gui/_slow_op.py`): a queue owned by the dialog would die with it, and with it the delivery of a stop that failed after the dialog closed, so the failure would never reach the stop custody. The browser reports through the lease (`ViewLifetime.callback`), which holds the dialog weakly, reaches the GUI thread queued and drops reports once the dialog has ended; `_update_services` stays as a thread-safe entry point. A WebRTC offer dropped on the GUI thread (U-20261114-35) is retired through the same queue instead of a controller task owned by the application. +- **Tests:** `test_gui_listener_cleanup.py`'s ending test waits for the background stop, and gains one: the dialog is freed although its browser outlives it, a late report is dropped, and a stop that fails after the dialog is gone is held by the custody (fails on the old code). `test_r3_gui_thread_marshal.py`'s off-thread report still reaches the table. WebRTC, remote, Remote Desktop, LAN, listener, slow-stop, custody, marshal, session-ownership and dialog tests: 2873 passed, 19 skipped. +- **Files:** `gui/_slow_op.py`, `gui/remote_desktop/webrtc_dialogs.py`, `gui/remote_desktop/webrtc_host_connection.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (owners attached to an interruption signal, the revoked-authority close, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index 2ef8331b2..ec360c9ce 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-39 | 2026-11-14 | The LAN browse dialog closes its browser off the GUI thread and is not kept alive by it | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-38 | 2026-11-14 | A failed LAN broadcast stop keeps its advertiser; a failed recording is never reported saved | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-37 | 2026-11-14 | SlowOp stops and the WebRTC host's session stops join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-36 | 2026-11-14 | A failed background stop is kept for a retry from Diagnostics | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_slow_op.py b/je_auto_control/gui/_slow_op.py index 38908a199..f2bc91d7d 100644 --- a/je_auto_control/gui/_slow_op.py +++ b/je_auto_control/gui/_slow_op.py @@ -36,7 +36,7 @@ import functools from typing import Any, Callable, List, Optional, Tuple -from PySide6.QtCore import QObject, Signal +from PySide6.QtCore import QCoreApplication, QObject, Signal from je_auto_control.gui._weak_call import Callback, WeakCall as _WeakCall, weak_slot from je_auto_control.gui.tab_task_controller import ( @@ -205,6 +205,31 @@ def _one_reported(self) -> None: self.drained.emit() +_APP_STOPS: Optional["StopQueue"] = None + + +def app_stop_queue() -> "StopQueue": + """A :class:`StopQueue` owned by the application, for a window or dialog that is gone before its stop reports. + + A queue owned by a dialog dies with it, and so does the delivery of a + stop that failed after the dialog closed; this one lives as long as the + application, so the failure still reaches the stop custody. GUI thread. + """ + global _APP_STOPS # pylint: disable=global-statement # reason: one queue per application, made on first use + app = QCoreApplication.instance() + queue = _APP_STOPS + try: + alive = queue is not None and queue.parent() is app + except RuntimeError: # its application was destroyed (a test made a new one) + alive = False + if alive and queue is not None: + return queue + if app is None: + raise RuntimeError("app_stop_queue() needs a running QApplication") + _APP_STOPS = StopQueue(app) + return _APP_STOPS + + def stop_each(*stops: Callable[[], Any]) -> None: """Worker thread: call every ``stop`` in order; one that fails does not keep the rest from running. @@ -221,4 +246,4 @@ def stop_each(*stops: Callable[[], Any]) -> None: raise StopsFailed(failures) -__all__ = ["SlowOp", "StopQueue", "StopsFailed", "hold_failed_stop", "stop_each"] +__all__ = ["SlowOp", "StopQueue", "StopsFailed", "app_stop_queue", "hold_failed_stop", "stop_each"] diff --git a/je_auto_control/gui/remote_desktop/webrtc_dialogs.py b/je_auto_control/gui/remote_desktop/webrtc_dialogs.py index ea847a473..162fc3e46 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_dialogs.py +++ b/je_auto_control/gui/remote_desktop/webrtc_dialogs.py @@ -17,6 +17,9 @@ QWidget, ) +from je_auto_control.gui._slow_op import app_stop_queue +from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime + from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.remote_desktop._helpers import ( @@ -397,13 +400,13 @@ class LanBrowseDialog(QDialog): """ chosen = Signal(dict) - # Emitted from the zeroconf thread; a queued connection marshals the - # payload back onto the GUI thread (see _update_services). - _services_changed = Signal(dict) def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) - self._services_changed.connect(self._on_services_changed) + # The zeroconf thread reports through this lease: it holds the dialog + # weakly, reaches the GUI thread queued, and drops reports once the + # dialog has ended -- the browser must not be what keeps it alive. + self._view = ViewLifetime(self) self.setWindowTitle(_t("rd_webrtc_lan_title")) self.setMinimumSize(620, 260) self._services: dict = {} @@ -456,18 +459,16 @@ def _start_browser(self) -> None: if not is_discovery_available(): return try: - self._browser = HostBrowser(on_change=self._update_services) + self._browser = HostBrowser(on_change=self._view.callback("_on_services_changed")) except (RuntimeError, OSError): self._browser = None def _update_services(self, services: dict) -> None: - # Called from the zeroconf browser thread, which has no Qt event loop: - # QTimer.singleShot would create a timer with that thread's affinity and - # never fire. Emit a signal instead — Qt queues it onto the GUI thread. - self._services_changed.emit(dict(services)) + """Any thread: report the hosts seen; the table is redrawn on the GUI thread.""" + self._view.post("_on_services_changed", dict(services)) def _on_services_changed(self, services: dict) -> None: - self._services = services + self._services = dict(services) self._refresh() def _refresh(self) -> None: @@ -495,12 +496,16 @@ def _on_use(self) -> None: return def _stop_browser(self) -> None: - if self._browser is not None: - try: - self._browser.stop() - except (RuntimeError, OSError): - pass # reason: the browser is being discarded either way - self._browser = None + """Let go of the browser now; closing it (which joins zeroconf's thread) runs on a worker. + + It goes to the application's stop queue, not one of the dialog's: the + dialog is normally destroyed right after, and a stop that fails is kept + by the stop custody with the browser that still owns its socket. + """ + browser, self._browser = self._browser, None + self._view.retire() + if browser is not None: + app_stop_queue().retire(browser.stop) def done(self, result: int) -> None: # noqa: D401 # Qt override """Stop browsing however the dialog ends. diff --git a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py index 34c8f66e0..3e7839d58 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_host_connection.py +++ b/je_auto_control/gui/remote_desktop/webrtc_host_connection.py @@ -23,7 +23,7 @@ from je_auto_control.gui.remote_desktop.webrtc_workers import ( HostPublishLoopWorker, generate_host_id, retire_worker, ) -from je_auto_control.gui._slow_op import hold_failed_stop, stop_each +from je_auto_control.gui._slow_op import app_stop_queue, hold_failed_stop, stop_each from je_auto_control.gui._weak_call import weak_slot from je_auto_control.gui.tab_task_controller import CancellationToken, task_controller from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -72,7 +72,7 @@ def _drop_offer(offer: Any) -> None: """ app = QCoreApplication.instance() if app is not None and QThread.currentThread() is app.thread(): - task_controller().submit(functools.partial(_retire_quietly, offer.retirement), owner=app) + app_stop_queue().retire(functools.partial(_retire_quietly, offer.retirement)) else: _retire_quietly(offer.retirement) diff --git a/test/unit_test/headless/test_gui_listener_cleanup.py b/test/unit_test/headless/test_gui_listener_cleanup.py index f4a813233..e3cef8562 100644 --- a/test/unit_test/headless/test_gui_listener_cleanup.py +++ b/test/unit_test/headless/test_gui_listener_cleanup.py @@ -42,8 +42,44 @@ def test_the_lan_browser_stops_however_the_dialog_ends(qapp, monkeypatch, ending dialog = LanBrowseDialog() getattr(dialog, ending)() assert _Browser.instances - assert _Browser.instances[0].stopped dialog.deleteLater() + # Closing joins zeroconf's thread, so it runs on a worker -- even once the dialog is gone. + from headless._qt_settle import pump_until + assert pump_until(lambda: _Browser.instances[0].stopped) + + +def test_the_lan_browser_neither_keeps_the_dialog_alive_nor_loses_a_failed_stop(qapp, monkeypatch): + import gc + import weakref + from headless._qt_settle import pump_until + from je_auto_control.gui._stop_custody import stop_custody + from je_auto_control.utils.remote_desktop import lan_discovery + from je_auto_control.gui.remote_desktop.webrtc_dialogs import LanBrowseDialog + + class _Stuck(_Browser): + def stop(self): + raise RuntimeError("media retirement incomplete: zeroconf close") + + custody = stop_custody() + for record in custody.snapshot(): + custody.forget(record.stop_id) + monkeypatch.setattr(lan_discovery, "HostBrowser", _Stuck) + monkeypatch.setattr(lan_discovery, "is_discovery_available", lambda: True) + _Browser.instances.clear() + dialog = LanBrowseDialog() + reference = weakref.ref(dialog) + browser = _Browser.instances[0] + dialog.reject() + dialog.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete.value) + del dialog + gc.collect() + assert reference() is None # the browser's callback did not hold it + browser.on_change({"late": {"host_id": "late"}}) # a report after the dialog is gone: dropped + assert pump_until(lambda: bool(custody.snapshot())) + assert "zeroconf close" in custody.snapshot()[0].error + for record in custody.snapshot(): + custody.forget(record.stop_id) def test_a_destroyed_presence_tab_leaves_the_registry(qapp, monkeypatch): From 5fb02b001d48d2ae1980cba9cd22ee9c0676b8f3 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 18:42:54 +0800 Subject: [PATCH 107/161] Keep the cleanup owners an interruption leaves behind A cancellation that cuts a media cleanup short carries the original owners still holding resources, but the GUI kept only the outer stop. Each attached owner is now kept by the stop custody with its own stop. --- CHANGELOG.md | 4 +++ Progress.md | 3 +- architecture_explore.md | 6 ++-- docs/updates/2026-11-b.md | 7 +++++ docs/updates/README.md | 1 + je_auto_control/gui/_slow_op.py | 18 +++++++++--- test/unit_test/headless/test_stop_custody.py | 31 ++++++++++++++++++++ 7 files changed, 61 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87a083c4f..13969a902 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- GUI: `hold_failed_stop` also keeps each original owner an interruption signal carries + (`interrupted_retirement_owners`) -- a cancellation that cut a media cleanup short -- with its + own `stop`, so its resources have a keeper; one that is the stop already kept is not doubled. + - GUI: the WebRTC *Browse LAN* dialog closes its zeroconf browser on a worker instead of the GUI thread, through the new application-owned `app_stop_queue()` (in `gui/_slow_op.py`), so a stop that fails after the dialog closed still reaches the stop custody; the browser reports through diff --git a/Progress.md b/Progress.md index 96133bfa5..78b065bfb 100644 --- a/Progress.md +++ b/Progress.md @@ -541,8 +541,7 @@ F 還缺: - **F3 關閉失敗恢復**:StopQueue/stop_each 的失敗停止已交給應用程式層的保管者,Diagnostics 可在原授權下查詢/重試 (U-20261114-36);SlowOp 的停止與 WebRTC host 丟棄 offer/中斷工作階段的停止也已交給保管者(U-20261114-37); LAN 廣播停止失敗與錄影定稿失敗也已保留原擁有者並如實回報(U-20261114-38);不能把背景排程等同原生資源已釋放。 - 取消訊號附帶的清理擁有者(`interrupted_retirement_owners`)仍未接到 GUI 呼叫端; - 不可吞掉未確認結果或清掉失敗子物件。(`HostBrowser` 對話框的所有權與背景清理已整合,U-20261114-39。) + 取消訊號附帶的清理擁有者也已交給保管者(U-20261114-40);不可吞掉未確認結果或清掉失敗子物件。(`HostBrowser` 對話框的所有權與背景清理已整合,U-20261114-39。) 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; diff --git a/architecture_explore.md b/architecture_explore.md index 09d0ad003..fd2a36818 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,112 | +| 程式碼總行數 | 237,122 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,744 | +| `gui/` | 166 | 43,754 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,367** | +| **總計** | **1,531** | **236,377** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 7791be09a..3954832ae 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -596,3 +596,10 @@ - **Tests:** `test_gui_listener_cleanup.py`'s ending test waits for the background stop, and gains one: the dialog is freed although its browser outlives it, a late report is dropped, and a stop that fails after the dialog is gone is held by the custody (fails on the old code). `test_r3_gui_thread_marshal.py`'s off-thread report still reaches the table. WebRTC, remote, Remote Desktop, LAN, listener, slow-stop, custody, marshal, session-ownership and dialog tests: 2873 passed, 19 skipped. - **Files:** `gui/_slow_op.py`, `gui/remote_desktop/webrtc_dialogs.py`, `gui/remote_desktop/webrtc_host_connection.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (owners attached to an interruption signal, the revoked-authority close, native acceptance). + +## U-20261114-40 · 2026-11-14 · An interruption's attached cleanup owners join the stop custody · #done #gui #lifecycle + +- **What:** `Progress.md` › *F3 關閉失敗恢復*'s owners attached to a cancellation signal. When an interruption (an `OperationCancelledError` or another run interruption) cuts a media cleanup short, the audio and LAN-discovery owners attach themselves to the signal (`preserve_interrupted_owner`) so the caller can still reach the resources they hold; the GUI only ever kept the outer stop that raised it. `hold_failed_stop` -- used by `StopQueue`, `SlowOp(retain_failure=True)`, the WebRTC host's session stops and the advertiser -- now also keeps every owner `interrupted_retirement_owners(error)` returns, with that owner's own `stop` and the same captured authority, skipping an owner whose `stop` is the one already kept. Interruption signals are ordinary exceptions, so they reach a task's error delivery like any other failure. +- **Tests:** `test_stop_custody.py` gains one (an interruption with an attached owner keeps both the outer stop and the owner's stop, a retry stops the owner, and the owner's own stop is not kept twice; fails on the old code). Slow-stop, custody, WebRTC, remote, LAN, listener, media-retirement and audio tests: 2379 passed, 18 skipped. +- **Files:** `gui/_slow_op.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (the revoked-authority close, media state read from the custody's snapshot, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index ec360c9ce..b35553325 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-40 | 2026-11-14 | An interruption's attached cleanup owners join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-39 | 2026-11-14 | The LAN browse dialog closes its browser off the GUI thread and is not kept alive by it | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-38 | 2026-11-14 | A failed LAN broadcast stop keeps its advertiser; a failed recording is never reported saved | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-37 | 2026-11-14 | SlowOp stops and the WebRTC host's session stops join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_slow_op.py b/je_auto_control/gui/_slow_op.py index f2bc91d7d..16fc83b7e 100644 --- a/je_auto_control/gui/_slow_op.py +++ b/je_auto_control/gui/_slow_op.py @@ -46,6 +46,7 @@ from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.rbac.deferred import DeferredAuthorization +from je_auto_control.utils.remote_desktop.media_retirement import interrupted_retirement_owners def _call(work: Callable[[], Any], _token: CancellationToken) -> Any: @@ -68,12 +69,21 @@ def __init__(self, failures: List[Tuple[Callable[[], Any], BaseException]]) -> N def hold_failed_stop(stop: Callable[[], Any], error: object, authority: Optional[DeferredAuthorization] = None) -> None: - """Hand a failed stop to the application's custody (each one of a :class:`StopsFailed` separately).""" + """Hand a failed stop to the application's custody (each one of a :class:`StopsFailed` separately). + + An interruption that cut a media cleanup short carries the original owners + it left holding resources (``interrupted_retirement_owners``); each is kept + as well, with its own ``stop``, unless it is the stop already being kept. + """ if isinstance(error, StopsFailed): for inner, inner_error in error.failures: - stop_custody().hold(inner, inner_error, authority=authority) - else: - stop_custody().hold(stop, error, authority=authority) + hold_failed_stop(inner, inner_error, authority) + return + stop_custody().hold(stop, error, authority=authority) + if isinstance(error, BaseException): + for owner in interrupted_retirement_owners(error): + if getattr(stop, "__self__", None) is not owner: + stop_custody().hold(owner.stop, error, authority=authority) def _refuse_widgets(work: Callable[[], Any]) -> None: diff --git a/test/unit_test/headless/test_stop_custody.py b/test/unit_test/headless/test_stop_custody.py index 95794966a..7ebed83ff 100644 --- a/test/unit_test/headless/test_stop_custody.py +++ b/test/unit_test/headless/test_stop_custody.py @@ -190,3 +190,34 @@ def gone(): assert custody.snapshot() == [] webrtc_host_sessions._stop_session(types.SimpleNamespace(stop=failing.stop)) assert [held.error for held in custody.snapshot()] == ["OSError: peer close timed out"] + + +def test_an_interruption_keeps_the_owners_it_left_holding_resources(custody): + # A cancellation that cut a media cleanup short carries the original owner; + # only the outer stop used to be seen, and the owner's resources had no keeper. + from je_auto_control.utils.exception.control_signals import OperationCancelledError + from je_auto_control.utils.remote_desktop.media_retirement import preserve_interrupted_owner + + class _Owner: + stopped = 0 + + @property + def retirement_status(self): + return None + + def stop(self): + _Owner.stopped += 1 + + owner = _Owner() + try: + preserve_interrupted_owner(owner, OperationCancelledError("cancelled during unregister")) + except OperationCancelledError as signal: + interrupted = signal + outer = _Flaky(failures=0) + _slow_op.hold_failed_stop(outer.stop, interrupted) + labels = sorted(held.label for held in custody.snapshot()) + assert labels == ["_Flaky.stop", "_Owner.stop"] + assert custody.retry_all() == (2, 0) + assert _Owner.stopped == 1 + _slow_op.hold_failed_stop(owner.stop, interrupted) # the owner's own stop is not kept twice + assert [held.label for held in custody.snapshot()] == ["_Owner.stop"] From 2206314eff609593bccf3f5bdafb8e4f297c1070 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 18:46:23 +0800 Subject: [PATCH 108/161] Show a held media stop's retirement state from its own snapshot Reading a media owner's live retirement status can wait on the lock its native cleanup holds. The custody now keeps the status the error captured when it was raised, and Diagnostics shows that instead. --- CHANGELOG.md | 5 ++++ Progress.md | 13 ++++------ architecture_explore.md | 10 ++++---- docs/updates/2026-11-b.md | 7 +++++ docs/updates/README.md | 1 + je_auto_control/gui/_stop_custody.py | 26 +++++++++++++++++-- je_auto_control/gui/failed_stops_view.py | 3 ++- test/unit_test/headless/test_stop_custody.py | 27 ++++++++++++++++++++ 8 files changed, 76 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13969a902..210018177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- GUI: a held failed stop whose error is a `MediaRetirementError` records the owner's retirement + state from the snapshot the error carries (`FailedStop.detail`: admission, resources, + finalization, failed steps); the custody never asks the owner, whose live status may wait on + its native cleanup's lock. Diagnostics shows it beside the error. + - GUI: `hold_failed_stop` also keeps each original owner an interruption signal carries (`interrupted_retirement_owners`) -- a cancellation that cut a media cleanup short -- with its own `stop`, so its resources have a keeper; one that is the stop already kept is not doubled. diff --git a/Progress.md b/Progress.md index 78b065bfb..682c8fc9d 100644 --- a/Progress.md +++ b/Progress.md @@ -538,14 +538,11 @@ F 還缺: - **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移(Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒, U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33;同頁 session generation 已隔離,U-20261114-34)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 -- **F3 關閉失敗恢復**:StopQueue/stop_each 的失敗停止已交給應用程式層的保管者,Diagnostics 可在原授權下查詢/重試 - (U-20261114-36);SlowOp 的停止與 WebRTC host 丟棄 offer/中斷工作階段的停止也已交給保管者(U-20261114-37); - LAN 廣播停止失敗與錄影定稿失敗也已保留原擁有者並如實回報(U-20261114-38);不能把背景排程等同原生資源已釋放。 - 取消訊號附帶的清理擁有者也已交給保管者(U-20261114-40);不可吞掉未確認結果或清掉失敗子物件。(`HostBrowser` 對話框的所有權與背景清理已整合,U-20261114-39。) - 仍缺授權撤銷後可安全執行、只封閉本機准入且不等待原生鎖的獨立操作;不能用完整 stop 代替。 - 媒體狀態查詢可能等候原生清理所持的鎖,Diagnostics 須讀取保管者快照,不能在 GUI 執行緒同步查詢。 - 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止; - 強制中斷、行程結束及原生資源回收尚未驗收。媒體清理缺口已用假資源重現,未執行原生/裝置/網路驗收。 +- **F3 關閉失敗恢復**(失敗停止的保管與 Diagnostics 原授權重試、媒體狀態快照,以及 LAN 廣播、錄影、 + `HostBrowser` 對話框與取消訊號附帶擁有者的移交已交付,U-20261114-36~41):仍缺授權撤銷後可安全執行、 + 只封閉本機准入且不等待原生鎖的獨立操作——audio 與 LAN discovery 目前在各自的 stop 內關閉准入,不能用完整 stop 代替。 + 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止;強制中斷、行程結束及原生資源回收尚未驗收。 + 媒體清理缺口只用假資源重現,未執行原生/裝置/網路驗收;不能把背景排程等同原生資源已釋放。 - **F4** 啟動/記憶體基準對照與功能對等測試已交付(U-20261114-30);仍缺 mixed-DPI 驗收(需要第二台不同縮放的螢幕)。 - **F3 Windows 原生釋放驗收**(`BLOCKED`:等 CI 再次發生):`test/unit_test/headless/test_remote_desktop_host_id.py` 的 freed-thread-state abort 尚缺 Windows 原生堆疊與獨立根因確認。CI 的 Windows 工作現在會把 `python.exe` 當掉時的 minidump 存進 diff --git a/architecture_explore.md b/architecture_explore.md index fd2a36818..899731e12 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,122 | +| 程式碼總行數 | 237,145 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1315,8 +1315,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `workspace.py` | 582 | Registry-owned tab workspace with scrollable pages and passive execution details. `WorkspaceShell(registry, parent)` 保留分頁身分、弱關閉觀測、show/hide/close API 與右側詳情;每頁放入時加頁首並跑 `fit_to_width`;`set_details_overlay` 讓詳情在窄視窗改為右側抽屜。 | | `workspace_details.py` | 116 | Immutable execution snapshots and a passive, scrollable workspace detail view. Diagnostics 與每個 `TabTask` 都是 publisher;僅訂閱目前頁面,`details_sources()` 通知綁定後才建立的來源。 | | `_task_details.py` | 116 | Execution details a TabTask publishes for the page it runs on. 由子面板往上找出工作區的分頁、第一次執行時建立來源,發布執行中/停止中/完成/已取消/錯誤與回報的進度。 | -| `_stop_custody.py` | 187 | Stops that failed in the background, kept so they can be retried instead of only logged. StopQueue/stop_each 失敗時保留停止、錯誤與排入時的權限;`snapshot` 不執行任何東西,`retry` 以原權限重試。 | -| `failed_stops_view.py` | 116 | Diagnostics' view of background stops that failed: what is held, and a retry from the Actions menu. | +| `_stop_custody.py` | 209 | Stops that failed in the background, kept so they can be retried instead of only logged. StopQueue/stop_each 失敗時保留停止、錯誤與排入時的權限;`snapshot` 不執行任何東西,`retry` 以原權限重試。 | +| `failed_stops_view.py` | 117 | Diagnostics' view of background stops that failed: what is held, and a retry from the Actions menu. | | `workspace_settings.py` | 36 | 驗證與載入主題、字級、導覽面板顯示與寬度;QSettings 使用當次帳號家目錄的 `gui.ini`,測試可注入獨立檔案。 | | `agent_transfer_view.py` | 171 | Explicit transfer requests and consent preparation with revision-bound background observations. | | `config_sync_worker.py` | 130 | Run explicit workspace requests with immutable inputs, live authority and cooperative cancellation. | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,754 | +| `gui/` | 166 | 43,777 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,822 | | `utils/executor/` | 11 | 10,752 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,377** | +| **總計** | **1,531** | **236,400** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 3954832ae..d7ad4ea2d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -603,3 +603,10 @@ - **Tests:** `test_stop_custody.py` gains one (an interruption with an attached owner keeps both the outer stop and the owner's stop, a retry stops the owner, and the owner's own stop is not kept twice; fails on the old code). Slow-stop, custody, WebRTC, remote, LAN, listener, media-retirement and audio tests: 2379 passed, 18 skipped. - **Files:** `gui/_slow_op.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (the revoked-authority close, media state read from the custody's snapshot, native acceptance). + +## U-20261114-41 · 2026-11-14 · Diagnostics shows a held media stop's retirement state from its snapshot · #done #gui #lifecycle + +- **What:** `Progress.md` › *F3 關閉失敗恢復*'s requirement that Diagnostics read the custodian's snapshot of media state rather than query it on the GUI thread: an owner's live `retirement_status` may wait on the lock its native cleanup holds. A `MediaRetirementError` already carries the `RetirementStatus` taken when the owner raised it; the stop custody now records it with the held stop (`FailedStop.detail`: admission open or closed, resources and finalization completion, failed steps), refreshes it when a retry fails with a new one, and never asks the owner. The Diagnostics list shows it beside the error. The custody module stays Qt-free. The `Progress.md` entry is rewritten to what is still open. +- **Tests:** `test_stop_custody.py` gains one (the detail comes from the error's snapshot while a live read of the owner would fail, and the stop can still be retried). Custody tests: 14 passed. +- **Files:** `gui/_stop_custody.py`, `gui/failed_stops_view.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (the revoked-authority admission close, senders stuck in an uninterruptible backend call, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index b35553325..3aec3f578 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-41 | 2026-11-14 | Diagnostics shows a held media stop's retirement state from its snapshot | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-40 | 2026-11-14 | An interruption's attached cleanup owners join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-39 | 2026-11-14 | The LAN browse dialog closes its browser off the GUI thread and is not kept alive by it | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-38 | 2026-11-14 | A failed LAN broadcast stop keeps its advertiser; a failed recording is never reported saved | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_stop_custody.py b/je_auto_control/gui/_stop_custody.py index 9c9fa01bb..f277d2a1d 100644 --- a/je_auto_control/gui/_stop_custody.py +++ b/je_auto_control/gui/_stop_custody.py @@ -31,6 +31,7 @@ from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.logging.secret_scope import scrub_secret_text from je_auto_control.utils.rbac.deferred import DeferredAuthorization +from je_auto_control.utils.remote_desktop.media_retirement import RetirementStatus #: The most failed stops held at once; the oldest is let go (and logged) beyond it. MAX_HELD = 200 @@ -45,6 +46,8 @@ class FailedStop: error: str failed_at: float attempts: int + #: For a media owner: its retirement state as it was when the stop failed, never read live. + detail: str = "" @dataclass @@ -55,6 +58,7 @@ class _Held: failed_at: float attempts: int authority: Optional[DeferredAuthorization] + detail: str = "" def describe_stop(stop: Callable[[], Any]) -> str: @@ -80,7 +84,8 @@ def __init__(self, max_held: int = MAX_HELD) -> None: def hold(self, stop: Callable[[], Any], error: object, *, label: str = "", authority: Optional[DeferredAuthorization] = None) -> int: """Keep ``stop``, which raised ``error``; return its id. Safe from any thread.""" - record = _Held(stop, label or describe_stop(stop), scrub_secret_text(_text(error)), time.time(), 1, authority) + record = _Held(stop, label or describe_stop(stop), scrub_secret_text(_text(error)), time.time(), 1, authority, + _media_detail(error)) with self._lock: stop_id = next(self._ids) self._held[stop_id] = record @@ -94,7 +99,7 @@ def hold(self, stop: Callable[[], Any], error: object, *, label: str = "", def snapshot(self) -> List[FailedStop]: """What is held, oldest first; runs no stop and never waits on anything but this lock.""" with self._lock: - return [FailedStop(stop_id, held.label, held.error, held.failed_at, held.attempts) + return [FailedStop(stop_id, held.label, held.error, held.failed_at, held.attempts, held.detail) for stop_id, held in self._held.items()] def retry(self, stop_id: int) -> bool: @@ -116,6 +121,7 @@ def retry(self, stop_id: int) -> bool: with self._lock: if self._held.get(stop_id) is held: held.error = scrub_secret_text(_text(error)) + held.detail = _media_detail(error) held.attempts += 1 held.failed_at = time.time() self._changed() @@ -172,6 +178,22 @@ def _changed(self) -> None: autocontrol_logger.warning(f"stop custody listener failed: {error!r}") +def _media_detail(error: object) -> str: + """A media owner's retirement state from the snapshot its error carries -- never by asking the owner. + + Reading ``retirement_status`` live may wait on the lock the owner's native + cleanup holds; ``MediaRetirementError.status`` was taken when it was raised. + """ + status = getattr(error, "status", None) + if not isinstance(status, RetirementStatus): + return "" + parts = [f"admission {'closed' if status.admission_closed else 'open'}", + f"resources {status.resources.value}", f"finalization {status.finalization.value}"] + if status.failed_steps: + parts.append("failed: " + ", ".join(status.failed_steps)) + return "; ".join(parts) + + def _text(error: object) -> str: return f"{type(error).__name__}: {error}" if isinstance(error, BaseException) else str(error) diff --git a/je_auto_control/gui/failed_stops_view.py b/je_auto_control/gui/failed_stops_view.py index c1ca14f43..87218beea 100644 --- a/je_auto_control/gui/failed_stops_view.py +++ b/je_auto_control/gui/failed_stops_view.py @@ -79,7 +79,8 @@ def refresh(self) -> None: self._table.setRowCount(len(rows)) for row, held in enumerate(rows): stamp = datetime.datetime.fromtimestamp(held.failed_at).strftime("%H:%M:%S") - for column, text in enumerate((held.label, held.error, str(held.attempts), stamp)): + error = f"{held.error} ({held.detail})" if held.detail else held.error + for column, text in enumerate((held.label, error, str(held.attempts), stamp)): item = QTableWidgetItem(text) item.setData(Qt.ItemDataRole.UserRole, held.stop_id) self._table.setItem(row, column, item) diff --git a/test/unit_test/headless/test_stop_custody.py b/test/unit_test/headless/test_stop_custody.py index 7ebed83ff..93c99560e 100644 --- a/test/unit_test/headless/test_stop_custody.py +++ b/test/unit_test/headless/test_stop_custody.py @@ -221,3 +221,30 @@ def stop(self): assert _Owner.stopped == 1 _slow_op.hold_failed_stop(owner.stop, interrupted) # the owner's own stop is not kept twice assert [held.label for held in custody.snapshot()] == ["_Owner.stop"] + + +def test_a_media_owners_state_comes_from_its_errors_snapshot_never_a_live_query(): + from je_auto_control.utils.remote_desktop.media_retirement import ( + Completion, MediaRetirementError, RetirementStatus, + ) + + class _Advertiser: + live = True + + @property + def retirement_status(self): + if not _Advertiser.live: # a live read would wait on the native cleanup's lock + raise AssertionError("the custody queried the owner") + return RetirementStatus(True, Completion.UNCERTAIN, Completion.PENDING, failed_steps=("unregister",)) + + def stop(self): + pass + + owner = _Advertiser() + error = MediaRetirementError(owner) # the snapshot is taken here, as the owner raises it + _Advertiser.live = False + custody = StopCustody() + custody.hold(owner.stop, error) + [held] = custody.snapshot() + assert held.detail == "admission closed; resources uncertain; finalization pending; failed: unregister" + assert custody.retry(held.stop_id) From 6f0b6980ad6f8662ab4d09c35c29b3289108d73b Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 19:09:02 +0800 Subject: [PATCH 109/161] Add close_admission() so media owners stop taking anything new at once A full stop waits on native work under the owner's lock, and a caller whose authority was revoked may never run it; until then the owner kept admitting audio, reports, sessions and input. close_admission() only stops admission, with no native call or cleanup lock, and StopQueue calls it on every owner before queuing the stop. --- CHANGELOG.md | 8 ++ Progress.md | 4 +- architecture_explore.md | 22 ++-- .../doc/new_features/media_retirement_doc.rst | 19 ++- .../doc/new_features/media_retirement_doc.rst | 13 +- docs/updates/2026-11-b.md | 12 ++ docs/updates/README.md | 1 + je_auto_control/gui/_slow_op.py | 41 ++++++- je_auto_control/utils/remote_desktop/audio.py | 6 + .../utils/remote_desktop/audio_retirement.py | 11 ++ .../utils/remote_desktop/lan_discovery.py | 9 ++ .../utils/remote_desktop/multi_viewer.py | 22 +++- .../headless/test_close_admission.py | 112 ++++++++++++++++++ 13 files changed, 258 insertions(+), 22 deletions(-) create mode 100644 test/unit_test/headless/test_close_admission.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 210018177..43e4e923a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- Remote desktop: `close_admission()` on `AudioCapture` / `AudioPlayer` (and `AudioLease`), + `HostBrowser` and `MultiViewerHost` stops taking anything new at once -- audio blocks and + writes, discovery reports, new sessions, answers and viewer input -- without the owner's + native-cleanup lock or a native call; `stop()` still closes what was admitted. After it, + `MultiViewerHost.create_owned_session_offer` and `accept_session_answer` raise + `PeerStopPending`. GUI: `StopQueue.retire` closes admission on every owner a stop refers to + before queuing it (`close_admission_of` in `gui/_slow_op.py`). + - GUI: a held failed stop whose error is a `MediaRetirementError` records the owner's retirement state from the snapshot the error carries (`FailedStop.detail`: admission, resources, finalization, failed steps); the custody never asks the owner, whose live status may wait on diff --git a/Progress.md b/Progress.md index 682c8fc9d..46f42e5a1 100644 --- a/Progress.md +++ b/Progress.md @@ -539,8 +539,8 @@ F 還缺: U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33;同頁 session generation 已隔離,U-20261114-34)。分頁的背景工作已全部改走共用 `TaskController` (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**(失敗停止的保管與 Diagnostics 原授權重試、媒體狀態快照,以及 LAN 廣播、錄影、 - `HostBrowser` 對話框與取消訊號附帶擁有者的移交已交付,U-20261114-36~41):仍缺授權撤銷後可安全執行、 - 只封閉本機准入且不等待原生鎖的獨立操作——audio 與 LAN discovery 目前在各自的 stop 內關閉准入,不能用完整 stop 代替。 + `HostBrowser` 對話框、取消訊號附帶擁有者的移交,以及授權撤銷後也能用、不等原生鎖的 `close_admission()` + 已交付,U-20261114-36~42):仍缺原生驗收。 傳送器已進入無法中斷的後端呼叫時仍可能持續待停止;強制中斷、行程結束及原生資源回收尚未驗收。 媒體清理缺口只用假資源重現,未執行原生/裝置/網路驗收;不能把背景排程等同原生資源已釋放。 - **F4** 啟動/記憶體基準對照與功能對等測試已交付(U-20261114-30);仍缺 mixed-DPI 驗收(需要第二台不同縮放的螢幕)。 diff --git a/architecture_explore.md b/architecture_explore.md index 899731e12..6021f8ae3 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,145 | +| 程式碼總行數 | 237,230 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,148 行。 +> 6 個套件、約 32,194 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,822 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,868 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,822 行/77 檔) +#### `utils/remote_desktop/`(16,868 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -837,7 +837,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | | `webrtc_transport.py` | 421 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | -| `multi_viewer.py` | 499 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | +| `multi_viewer.py` | 519 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 323 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | @@ -849,8 +849,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence.py` | 238 | 多檢視者的執行緒安全在場註冊表。 | | `jpeg_recorder_encrypted.py` | 239 | AES-GCM 加密版 session 錄影。 | | `address_book.py` | 229 | 檢視端的主機通訊錄。 | -| `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 250 / 296 / 195 | 音訊擷取播放、音訊軌、麥克風上行。 | -| `audio_retirement.py` | 121 | 保留單一音訊串流世代、准入中的操作與無法確認的清理結果。 | +| `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 256 / 296 / 195 | 音訊擷取播放、音訊軌、麥克風上行。 | +| `audio_retirement.py` | 132 | 保留單一音訊串流世代、准入中的操作與無法確認的清理結果。 | | `media_retirement.py` | 89 | 區分媒體資源釋放與最終化狀態,傳遞失敗或取消時仍需保留的擁有者。 | | `webrtc_file_commit.py` | 355 | Confirm native file publication with bounded authenticated probes and transfer/hash/size receipt matching. | | `webrtc_file_callbacks.py` | 38 | Notify native file path and frozen receipt listeners while preserving original interruption objects. | @@ -859,7 +859,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_file_tasks.py` | 147 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | | `webrtc_files.py` | 416 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | -| `lan_discovery.py` | 378 | mDNS/Zeroconf 區網探索。 | +| `lan_discovery.py` | 387 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 257 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | @@ -1549,9 +1549,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,777 | +| `gui/` | 166 | 43,816 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,822 | +| `utils/remote_desktop/` | 77 | 16,868 | | `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,400** | +| **總計** | **1,531** | **236,485** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/media_retirement_doc.rst b/docs/source/Eng/doc/new_features/media_retirement_doc.rst index 2b0a5ba97..b602dbacc 100644 --- a/docs/source/Eng/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Eng/doc/new_features/media_retirement_doc.rst @@ -17,7 +17,16 @@ MultiViewerHost's ``create_owned_session_offer()`` returns the SDP and original session retirement receipt. Capture an existing session with ``session_retirement(id)`` before queuing cleanup. Receipt retries cannot stop a replacement peer or screen source even when its session ID is reused. The legacy tuple-returning API remains. -GUI disconnect and discarded offers still need to adopt this ownership. +The WebRTC host panel's disconnect and its discarded offers use both. + +``close_admission()`` is separate from ``stop()``: audio capture and playback, +``HostBrowser`` and ``MultiViewerHost`` stop taking anything new at once (audio +blocks and writes, discovery reports, new sessions, answers and viewer input) +without the lock a native cleanup holds and without a native call, so it is safe +from any thread and for a caller whose authority was revoked; the full ``stop()`` +still closes what was admitted. ``HostAdvertiser`` admits nothing, so it has none. +The GUI's ``StopQueue`` closes admission on every owner a stop refers to before +it queues the stop. Peer hosts and viewers adopt failed-constructor cleanup owners and expose cached, immutable ``media_failures``. Failed children cannot be overwritten. Live disable @@ -25,6 +34,8 @@ observes original task completion, and peer close proceeds alongside unrelated media cleanup. A busy microphone-start slot reports pending without blocking the bridge loop on its lock. Deferred detach and renegotiation bind their original peer. -This producer unit does not complete application caretaker, GUI saved-result -reporting, GUI discard paths, or HostBrowser dialog ownership. Native acceptance -remains pending; validation uses injected resources only. +In the GUI, a stop that fails is kept by the application's stop custody with its +owner and the status its ``MediaRetirementError`` captured, and can be retried +from Diagnostics; a recording whose finalising fails is never reported saved; and +the LAN browse dialog hands its browser's stop to an application-owned queue. +Native acceptance remains pending; validation uses injected resources only. diff --git a/docs/source/Zh/doc/new_features/media_retirement_doc.rst b/docs/source/Zh/doc/new_features/media_retirement_doc.rst index 98a2fd97b..20433f4fa 100644 --- a/docs/source/Zh/doc/new_features/media_retirement_doc.rst +++ b/docs/source/Zh/doc/new_features/media_retirement_doc.rst @@ -16,12 +16,19 @@ Zeroconf close 可重試;建構取得資源失敗仍維持不確定。單次 MultiViewerHost 的 ``create_owned_session_offer()`` 回傳 SDP 與原始 session 清理物件。 排入背景工作前,可用 ``session_retirement(id)`` 取得既有連線的清理物件; 即使 ID 重用,重試也不會停止新的連線或畫面來源。既有 tuple API 保持相容。 -GUI 斷線與丟棄 offer 路徑仍須接入此所有權。 +WebRTC host 面板的斷線與丟棄 offer 路徑都已使用這兩者。 + +``close_admission()`` 與 ``stop()`` 分開:音訊擷取與播放、``HostBrowser`` 與 ``MultiViewerHost`` +會立即停止接收任何新東西(音訊區塊與寫入、探索回報、新的連線、answer 與 viewer 輸入), +不取用原生清理所持的鎖、也不做原生呼叫,因此可從任何執行緒、在呼叫端權限已撤銷時使用; +完整的 ``stop()`` 仍負責關閉已接收的部分。``HostAdvertiser`` 不接收任何東西,所以沒有這個操作。 +GUI 的 ``StopQueue`` 在排入停止前,會先對該停止涉及的每個 owner 關閉准入。 Host/viewer peer 會接收建構失敗的清理 owner,並透過 ``media_failures`` 提供快取的 不可變結果。失敗的子資源不能被覆寫;即時停用會觀測原 task 的實際完成,其他媒體與 peer 關閉仍可獨立進行。麥克風啟動佔用中的 slot 會回報待完成,不會卡住 bridge loop 等待鎖。延後執行的 detach 與重新協商均綁定原 peer。 -此 producer 單元尚未完成應用程式 caretaker、GUI 儲存成功提示、GUI 丟棄路徑, -以及 HostBrowser 對話框所有權整合。原生驗收仍待完成;本單元使用注入的資源驗證。 +GUI 中停止失敗時,會由應用程式的停止保管者保留 owner 及其 ``MediaRetirementError`` 擷取的狀態, +可從診斷分頁重試;錄影定稿失敗時不會顯示已儲存;LAN 瀏覽對話框把瀏覽器的停止交給應用程式擁有的佇列。 +原生驗收仍待完成;本單元使用注入的資源驗證。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d7ad4ea2d..d9ff874bb 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -610,3 +610,15 @@ - **Tests:** `test_stop_custody.py` gains one (the detail comes from the error's snapshot while a live read of the owner would fail, and the stop can still be retried). Custody tests: 14 passed. - **Files:** `gui/_stop_custody.py`, `gui/failed_stops_view.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (the revoked-authority admission close, senders stuck in an uninterruptible backend call, native acceptance). + +## U-20261114-42 · 2026-11-14 · close_admission(): media owners stop taking anything new at once · #done #remote-desktop #lifecycle + +- **What:** `Progress.md` › *F3 關閉失敗恢復*'s independent close, which the maintainer chose (2026-11-14) to add as `close_admission()`. A full `stop()` waits on native work under the owner's lock -- PortAudio's close, zeroconf's thread, a peer connection -- and a caller whose authority was revoked may not get to run it; until it ran, the owner kept admitting. Now: + - `AudioLease.close_admission()` refuses further `enter()` under the lease's short lock and marks the lease retiring; `AudioCapture` / `AudioPlayer.close_admission()` reach the lease without the owner's lock, so they return while a stop or start holds it around a native call. The stream itself is still closed by `stop()`. + - `HostBrowser.close_admission()` retires the listener (no further reports) and marks it stopping under its short state lock; `stop()` still cancels the browser and closes zeroconf. `HostAdvertiser` admits nothing and has no such method. + - `MultiViewerHost.close_admission()` sets a flag under its short lock: new sessions and answers raise `PeerStopPending`, and viewer input is dropped before the dispatcher; `stop_all()` still closes the peers. + - `StopQueue.retire` calls `close_admission_of(stop)` on the GUI thread before queuing the stop: it finds every owner the stop refers to -- a bound method's owner, through `functools.partial` and the stops given to `stop_each` -- and closes admission on each; a failure there is logged and the full stop is still queued. +- **Tests:** new `test_close_admission.py` (5: an audio lease admits nothing once closed and still retires; an audio player closes admission while its lock is held, refuses `play`, and leaves the stream to `stop()`; a LAN browser stops reporting at once and still stops; a multi-viewer host takes no new session, answer or input once closed and `stop_all` still stops the admitted peer; a `StopQueue` closes admission on every owner of a `stop_each` shutdown on the GUI thread before either stop runs on a worker). Audio, LAN, browser-retirement, multi-viewer, media, WebRTC, remote, slow-stop, custody, admission and listener tests: 2959 passed, 22 skipped. +- **Docs:** both `media_retirement_doc.rst` (also corrected: the GUI disconnect, discard paths, caretaker, saved-result reporting and the LAN dialog are done), `CHANGELOG.md`. +- **Files:** `utils/remote_desktop/audio_retirement.py`, `utils/remote_desktop/audio.py`, `utils/remote_desktop/lan_discovery.py`, `utils/remote_desktop/multi_viewer.py`, `gui/_slow_op.py`, the test, the docs, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › *F3 關閉失敗恢復* (native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index 3aec3f578..f5b365392 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-42 | 2026-11-14 | close_admission(): media owners stop taking anything new at once | #done #remote-desktop #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-41 | 2026-11-14 | Diagnostics shows a held media stop's retirement state from its snapshot | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-40 | 2026-11-14 | An interruption's attached cleanup owners join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-39 | 2026-11-14 | The LAN browse dialog closes its browser off the GUI thread and is not kept alive by it | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_slow_op.py b/je_auto_control/gui/_slow_op.py index 16fc83b7e..fdf6eb064 100644 --- a/je_auto_control/gui/_slow_op.py +++ b/je_auto_control/gui/_slow_op.py @@ -86,6 +86,42 @@ def hold_failed_stop(stop: Callable[[], Any], error: object, stop_custody().hold(owner.stop, error, authority=authority) +def _admission_owners(stop: object, depth: int = 0) -> List[object]: + """The objects ``stop`` would stop that can close admission: bound methods' owners, through partials.""" + if depth > 4: + return [] + found: List[object] = [] + owner = getattr(stop, "__self__", None) + if owner is not None and callable(getattr(owner, "close_admission", None)): + found.append(owner) + if isinstance(stop, functools.partial): + for inner in (stop.func, *stop.args, *stop.keywords.values()): + if callable(getattr(inner, "close_admission", None)) and not callable(inner): + found.append(inner) # an owner passed as an argument + elif callable(inner): + found.extend(_admission_owners(inner, depth + 1)) + return found + + +def close_admission_of(stop: Callable[[], Any]) -> int: + """Close admission, now, on every owner ``stop`` would stop; return how many were closed. + + ``close_admission()`` takes only short locks and makes no native call, so + this runs on the GUI thread before the full stop is queued: a session, + stream or browser a panel let go of admits nothing more from that moment, + even while its full stop waits on a native lock -- or is refused because + the caller's authority was revoked. + """ + closed = 0 + for owner in _admission_owners(stop): + try: + owner.close_admission() # type: ignore[attr-defined] # reason: checked callable by _admission_owners + closed += 1 + except Exception as error: # noqa: BLE001 # reason: logged; the full stop is still queued + autocontrol_logger.warning(f"closing admission failed for {type(owner).__name__}: {error!r}") + return closed + + def _refuse_widgets(work: Callable[[], Any]) -> None: """Raise unless ``work`` is free of widgets (the controller only sees the wrapper around it).""" if _widgets_reachable_from(work): @@ -199,6 +235,7 @@ def retire(self, stop: Callable[[], Any], *, on_done: Callback = None, resource may still be held. """ _refuse_widgets(stop) + close_admission_of(stop) # at once: nothing new is admitted while the stop is queued controller = self._controller if self._controller is not None else task_controller() handle = controller.submit(functools.partial(_call, stop), owner=self) self._pending += 1 @@ -256,4 +293,6 @@ def stop_each(*stops: Callable[[], Any]) -> None: raise StopsFailed(failures) -__all__ = ["SlowOp", "StopQueue", "StopsFailed", "app_stop_queue", "hold_failed_stop", "stop_each"] +__all__ = [ + "SlowOp", "StopQueue", "StopsFailed", "app_stop_queue", "close_admission_of", "hold_failed_stop", "stop_each", +] diff --git a/je_auto_control/utils/remote_desktop/audio.py b/je_auto_control/utils/remote_desktop/audio.py index 37346c2ee..2456bfcb0 100644 --- a/je_auto_control/utils/remote_desktop/audio.py +++ b/je_auto_control/utils/remote_desktop/audio.py @@ -105,6 +105,12 @@ def _start_stream(self, lease: AudioLease, factory: Callable[[], AudioStream]) - raise_caused_run_interruption(error) raise AudioBackendError("audio device failed to start") from error + def close_admission(self) -> None: + """Stop admitting audio at once, without the owner's lock or a native call; :meth:`stop` still retires.""" + lease = self._lease + if lease is not None: + lease.close_admission() + def stop(self) -> None: """Close admission and report any unconfirmed retirement.""" with self._lock: diff --git a/je_auto_control/utils/remote_desktop/audio_retirement.py b/je_auto_control/utils/remote_desktop/audio_retirement.py index b35dfb8ca..6017c6ef6 100644 --- a/je_auto_control/utils/remote_desktop/audio_retirement.py +++ b/je_auto_control/utils/remote_desktop/audio_retirement.py @@ -42,6 +42,17 @@ def activate(self) -> None: with self._lock: self._admitting = True + def close_admission(self) -> None: + """Admit no further block or write, now; the stream itself is closed by :meth:`retire`. + + Takes only this lease's short lock and makes no native call, so it is + safe from any thread -- including while a retire holds the owner's lock + around a native close, and for a caller whose authority was revoked. + """ + with self._lock: + self._admitting = False + self._retiring = True + @property def running(self) -> bool: with self._lock: diff --git a/je_auto_control/utils/remote_desktop/lan_discovery.py b/je_auto_control/utils/remote_desktop/lan_discovery.py index e131397b8..045fad3d5 100644 --- a/je_auto_control/utils/remote_desktop/lan_discovery.py +++ b/je_auto_control/utils/remote_desktop/lan_discovery.py @@ -283,6 +283,15 @@ def retirement_status(self) -> RetirementStatus: return RetirementStatus(self._stopping, resources, finalized, retryable, tuple(sorted(self._failures))) + def close_admission(self) -> None: + """Report no further hosts, at once; :meth:`stop` still cancels the browser and closes zeroconf. + + Takes only short state locks and makes no native call. + """ + self._listener.retire() + with self._state_lock: + self._stopping = True + def stop(self) -> None: """Close publication, attempt cancellation once and observe original resource completion.""" self._listener.retire() diff --git a/je_auto_control/utils/remote_desktop/multi_viewer.py b/je_auto_control/utils/remote_desktop/multi_viewer.py index 7514ac234..73c5b0254 100644 --- a/je_auto_control/utils/remote_desktop/multi_viewer.py +++ b/je_auto_control/utils/remote_desktop/multi_viewer.py @@ -119,7 +119,7 @@ def __init__(self, *, token: str, else SessionPermissions.from_read_only(read_only) ) # The sessions relay one shared track, so they map input by its origin. - self._dispatch = input_dispatcher or dispatcher_at(self._capture_origin) + self._deliver_input = input_dispatcher or dispatcher_at(self._capture_origin) self._ip_whitelist = list(ip_whitelist) if ip_whitelist else [] self._on_annotation = on_annotation self._on_session_state = on_session_state @@ -134,6 +134,7 @@ def __init__(self, *, token: str, self._source_failed = False self._source: Optional[_ScreenSource] = None self._lock = threading.Lock() + self._admission_closed = False def _capture_origin(self) -> Tuple[int, int]: source = self._source @@ -147,6 +148,21 @@ def _annotate(self, data: dict) -> None: if self._on_annotation is not None: self._on_annotation({**data, "screen_origin": self._capture_origin()}) + def _dispatch(self, action: Mapping[str, Any]) -> Any: + """Hand a viewer's input on, unless admission was closed.""" + if self._admission_closed: + return None + return self._deliver_input(action) + + def close_admission(self) -> None: + """Accept no new session, answer or viewer input, at once; :meth:`stop_all` still closes the peers. + + Takes only this host's short lock and makes no native call, so it is + safe from any thread and for a caller whose authority was revoked. + """ + with self._lock: + self._admission_closed = True + # --- session lifecycle -------------------------------------------------- def create_session_offer(self) -> Tuple[str, str]: @@ -180,6 +196,8 @@ def _register_session(self) -> Tuple[str, WebRTCDesktopHost, SessionRetirement]: other session uses it, no running screen source. """ with self._lock: + if self._admission_closed: + raise PeerStopPending("admission is closed: the host is stopping") if self._retiring or self._source_stopping or self._source_failed: raise PeerStopPending("finish retiring previous sessions before creating another") if self._source is None: @@ -242,6 +260,8 @@ def session_retirement(self, session_id: str) -> SessionRetirement: return SessionRetirement(session_id, self, host, source) def accept_session_answer(self, session_id: str, answer_sdp: str) -> None: + if self._admission_closed: + raise PeerStopPending("admission is closed: the host is stopping") host = self._require_session(session_id) host.accept_answer(answer_sdp) diff --git a/test/unit_test/headless/test_close_admission.py b/test/unit_test/headless/test_close_admission.py new file mode 100644 index 000000000..a89d6cc99 --- /dev/null +++ b/test/unit_test/headless/test_close_admission.py @@ -0,0 +1,112 @@ +"""Closing admission is separate from a full stop: immediate, lock-light, and safe when authority is gone. + +A full ``stop()`` waits on native work -- PortAudio's close, zeroconf's thread, +a peer connection -- under the owner's lock, and a caller whose authority was +revoked may not get to run it at all. ``close_admission()`` only stops the +owner taking anything new (audio blocks and writes, discovery reports, viewer +sessions, answers and input), takes no lock a native cleanup holds, and leaves +the full stop to run later. A ``StopQueue`` calls it on the GUI thread before +it queues the stop. +""" +import threading + +import pytest + +from je_auto_control.utils.remote_desktop.audio import AudioPlayer +from je_auto_control.utils.remote_desktop.audio_retirement import AudioLease +from je_auto_control.utils.remote_desktop.webrtc_retirement import PeerStopPending +from headless.test_remote_desktop_audio import fake_sd # noqa: F401 # reason: shared fake sounddevice fixture +from headless.test_browser_retirement import backend # noqa: F401 # reason: shared fake zeroconf fixture +from headless.test_remote_desktop_multi_viewer import _FakeHost, _host, fake_webrtc # noqa: F401 + + +def test_an_audio_lease_admits_nothing_once_closed_and_still_retires(): + lease = AudioLease() + lease.activate() + assert lease.enter() + lease.leave() + lease.close_admission() + assert lease.enter() is False + assert lease.status.admission_closed + lease.retire() # no stream: the full retire still completes + assert lease.status.complete + + +def test_an_audio_player_closes_admission_while_its_lock_is_held(fake_sd): # noqa: F811 + player = AudioPlayer() + player.start() + stream = fake_sd.last_output + with player._lock: # a stop or start busy in a native call + done = threading.Event() + worker = threading.Thread(target=lambda: (player.close_admission(), done.set())) + worker.start() + assert done.wait(2.0), "close_admission waited for the owner's lock" + worker.join(2.0) + with pytest.raises(RuntimeError, match="not running"): + player.play(b"\x00\x00") + assert not stream.closed # the stream is the full stop's job + player.stop() + assert stream.closed + + +def test_a_lan_browser_stops_reporting_at_once_and_still_stops(backend): # noqa: F811 + from je_auto_control.utils.remote_desktop import lan_discovery as discovery + published = [] + browser = discovery.HostBrowser(published.append) + browser.close_admission() + browser._listener.add_service(None, "kind", "late-host") + assert published == [] + assert browser.retirement_status.admission_closed + browser.stop() + assert "cancel" in backend.calls and "close" in backend.calls + + +def test_a_multi_viewer_host_takes_no_new_session_answer_or_input_once_closed(): + delivered = [] + host = _host(input_dispatcher=delivered.append) + existing = host.create_owned_session_offer() + host._dispatch({"type": "click"}) + host.close_admission() + host._dispatch({"type": "click"}) + assert delivered == [{"type": "click"}] # only the input before the close + with pytest.raises(PeerStopPending): + host.create_owned_session_offer() + with pytest.raises(PeerStopPending): + host.accept_session_answer(existing.session_id, "answer") + host.stop_all() # the full stop still closes what was admitted + assert _FakeHost.instances[0].stopped + + +def test_a_stop_queue_closes_admission_before_the_stop_runs(): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + import functools + import os + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication, QWidget + QApplication.instance() or QApplication([]) + from je_auto_control.gui import _slow_op + from headless._qt_settle import pump_until + events, release = [], threading.Event() + + class _Owner: + def close_admission(self): + events.append(("close_admission", threading.get_ident())) + + def stop(self): + assert release.wait(10.0) + events.append(("stop", threading.get_ident())) + + owner, nested = _Owner(), _Owner() + widget = QWidget() + try: + queue = _slow_op.StopQueue(widget) + queue.retire(functools.partial(_slow_op.stop_each, owner.stop, nested.stop)) + gui = threading.get_ident() + assert events == [("close_admission", gui), ("close_admission", gui)] # both, before anything ran + release.set() + assert pump_until(lambda: queue.pending == 0) + assert [name for name, _thread in events[2:]] == ["stop", "stop"] + assert all(thread != gui for _name, thread in events[2:]) + finally: + release.set() + widget.deleteLater() From 7e1e32d0b3555551da746453f479e6ea6daa73a8 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 19:20:13 +0800 Subject: [PATCH 110/161] Stop network calls and signaling waits with their task A GUI task's Stop or deadline cancelled its scope, but the HTTP helper and the signaling long-polls never looked at it, and stopping the WebRTC host left its publish loop waiting up to ten minutes for an answer. perform_call now checks the scope around each request, and the waits check their stop between polls. --- CHANGELOG.md | 8 ++ Progress.md | 3 - architecture_explore.md | 28 ++--- .../doc/new_features/v223_features_doc.rst | 7 +- .../Zh/doc/new_features/v223_features_doc.rst | 5 +- docs/updates/2026-11-b.md | 10 ++ docs/updates/README.md | 1 + .../gui/remote_desktop/webrtc_workers.py | 16 ++- .../utils/http_client/http_client.py | 9 +- .../utils/remote_desktop/signaling_client.py | 68 ++++++++--- .../headless/test_network_cancellation.py | 114 ++++++++++++++++++ 11 files changed, 229 insertions(+), 40 deletions(-) create mode 100644 test/unit_test/headless/test_network_cancellation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 43e4e923a..096dacb75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- `http_client.perform_call` observes a bound cancellation scope: once it is cancelled the request + is not sent, and a reply that arrives after the cancellation raises `CancelledError` instead of + being returned; unscoped calls are unchanged. `signaling_client.wait_for_answer` / + `wait_for_offer` take `cancelled=` (default: the caller's scope) and raise `CancelledError` + within about 0.1 s. GUI: the WebRTC signaling workers and the host's publish loop pass their + interruption, so stopping the host ends a wait of up to ten minutes and drops the session it + had published. + - Remote desktop: `close_admission()` on `AudioCapture` / `AudioPlayer` (and `AudioLease`), `HostBrowser` and `MultiViewerHost` stops taking anything new at once -- audio blocks and writes, discovery reports, new sessions, answers and viewer input -- without the owner's diff --git a/Progress.md b/Progress.md index 46f42e5a1..32f7ba261 100644 --- a/Progress.md +++ b/Progress.md @@ -535,9 +535,6 @@ F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: 設計系統、視窗斷點(U-20261114-02)與 51 個分頁的版面重排(U-20261114-04)已交付,`WIDE_PAGES` 已清空。仍缺: - 已在本機真實桌面(Windows 11、單一螢幕 1920×1080、150% 縮放)審閱(U-20261114-05);混合 DPI/多螢幕與 Linux/macOS 字型仍只有 offscreen 截圖。 -- **F3** 還缺 backend timeout/cancel 傳遞與關閉生命週期遷移(Quick Connect 與 Viewer 分頁的啟停/中斷連線已移出 GUI 執行緒, - U-20261114-32;傳送中的檔案傳輸會在下一個區塊停止,U-20261114-33;同頁 session generation 已隔離,U-20261114-34)。分頁的背景工作已全部改走共用 `TaskController` - (`TabTask`,U-20261114-13~26),GUI 內除兩個 controller 本身外已無 `start_worker` 呼叫。 - **F3 關閉失敗恢復**(失敗停止的保管與 Diagnostics 原授權重試、媒體狀態快照,以及 LAN 廣播、錄影、 `HostBrowser` 對話框、取消訊號附帶擁有者的移交,以及授權撤銷後也能用、不等原生鎖的 `close_admission()` 已交付,U-20261114-36~42):仍缺原生驗收。 diff --git a/architecture_explore.md b/architecture_explore.md index 6021f8ae3..ca8d0d909 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,230 | +| 程式碼總行數 | 237,281 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,194 行。 +> 6 個套件、約 32,224 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,868 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,898 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,571 行。 +> 24 個套件、約 7,578 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -572,7 +572,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/email_send/` | 118 | SMTP 寄信(email 觸發器的發送端搭檔) | | `utils/events/` | 106 | 對外 CloudEvents 發送(執行生命週期事件) | | `utils/http_cassette/` | 200 | 錄製/重播 HTTP 互動,做離線決定性 API 測試 | -| `utils/http_client/` | 265 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | +| `utils/http_client/` | 272 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | | `utils/http_conditional/` | 148 | 條件式 HTTP 請求與快取驗證器 | | `utils/http_content/` | 158 | HTTP 內容協商與回應解壓縮 | | `utils/http_problem/` | 122 | RFC 9457 problem+json 解析 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,868 行/77 檔) +#### `utils/remote_desktop/`(16,898 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -866,7 +866,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | | `adaptive_bitrate.py` | 148 | 依統計調整主機擷取 FPS。 | -| `signaling_client.py` | 164 | 純標準庫的訊令用戶端。 | +| `signaling_client.py` | 194 | 純標準庫的訊令用戶端。 | | `trust_list.py` | 139 | 自動接受的檢視端信任清單。 | | `webrtc_inspector.py` | 138 | 行程級的 `StatsSnapshot` 滾動視窗。 | | `input_dispatch.py` | 161 | 在主機端套用輸入訊息。 | @@ -1391,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,550 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,564 | 見下。 | | presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,550 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,564 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1430,7 +1430,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `host_panel.py` | 396 | 「分享這台機器」子分頁。 | | `_host_ops.py` | 39 | Start and stop the machine's remote-desktop host on a worker thread. Host 面板與 Quick Connect 共用的 `replace_host`/`stop_host`/`release_host`。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | -| `webrtc_workers.py` | 237 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | +| `webrtc_workers.py` | 251 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | | `tab.py` | 180 | 外層容器分頁。 | | `_helpers.py` | 326 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | | `remote_screen_window.py` | 140 | 檢視端的彈出視窗。 | @@ -1549,9 +1549,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,816 | +| `gui/` | 166 | 43,830 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,868 | +| `utils/remote_desktop/` | 77 | 16,898 | | `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,222 | -| **總計** | **1,531** | **236,485** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,229 | +| **總計** | **1,531** | **236,536** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v223_features_doc.rst b/docs/source/Eng/doc/new_features/v223_features_doc.rst index 305b7c4bb..9969dd579 100644 --- a/docs/source/Eng/doc/new_features/v223_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v223_features_doc.rst @@ -149,7 +149,12 @@ What it adds to a plain worker: ``CancellationToken``: it polls ``raise_if_cancelled()`` / ``wait()``, hands ``remaining()`` to a backend that takes a timeout, and registers how to let go of what it holds with ``on_cancel()``. ``handle.cancel()`` runs those at - once, on the cancelling thread. + once, on the cancelling thread. Work started through ``TabTask`` runs in a + cancellation scope that a Stop or a deadline cancels, and the network + helpers follow it: ``http_client.perform_call`` sends nothing once it is + cancelled and does not hand on a reply that arrived afterwards, and the + signaling waits (``wait_for_answer`` / ``wait_for_offer``, which also take + ``cancelled=``) end within about 0.1 s. * **Typed outcomes.** ``result`` carries the return value, ``error`` the exception, ``progress`` whatever ``token.report_progress()`` was given. A timeout is reported as ``TaskTimeout``, a cancellation as ``TaskCancelled``. diff --git a/docs/source/Zh/doc/new_features/v223_features_doc.rst b/docs/source/Zh/doc/new_features/v223_features_doc.rst index ed3828a06..4fb8c1e4f 100644 --- a/docs/source/Zh/doc/new_features/v223_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v223_features_doc.rst @@ -141,7 +141,10 @@ GUI 設定檔): * **取消會傳到後端。** 工作會收到 ``CancellationToken``:以 ``raise_if_cancelled()`` / ``wait()`` 輪詢、把 ``remaining()`` 交給接受逾時的 後端,並用 ``on_cancel()`` 登記如何釋放手上的資源。``handle.cancel()`` 會在 - 呼叫取消的執行緒上立刻執行那些釋放動作。 + 呼叫取消的執行緒上立刻執行那些釋放動作。經 ``TabTask`` 啟動的工作在取消範圍內執行, + 按下停止或超過期限都會取消它,網路輔助函式也會遵守:``http_client.perform_call`` 取消後不會送出, + 取消後才到的回應也不會交出去;信令等待(``wait_for_answer``/``wait_for_offer``,也接受 ``cancelled=``\ ) + 會在約 0.1 秒內結束。 * **有型別的結果。** ``result`` 帶回傳值、``error`` 帶例外、``progress`` 帶 ``token.report_progress()`` 傳入的內容。逾時回報為 ``TaskTimeout``,取消回報為 ``TaskCancelled``。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d9ff874bb..6860ef374 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -622,3 +622,13 @@ - **Docs:** both `media_retirement_doc.rst` (also corrected: the GUI disconnect, discard paths, caretaker, saved-result reporting and the LAN dialog are done), `CHANGELOG.md`. - **Files:** `utils/remote_desktop/audio_retirement.py`, `utils/remote_desktop/audio.py`, `utils/remote_desktop/lan_discovery.py`, `utils/remote_desktop/multi_viewer.py`, `gui/_slow_op.py`, the test, the docs, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › *F3 關閉失敗恢復* (native acceptance). + +## U-20261114-43 · 2026-11-14 · Network calls and signaling waits stop with their task · #done #remote-desktop #network + +- **What:** `Progress.md` › F3's backend timeout and cancel propagation, scoped by the maintainer (2026-11-14) to the network-bound backends the GUI runs; with it the F3 entry is closed (its lifecycle migration was U-20261114-13 to -34). A GUI task's Stop or deadline cancels the cancellation scope its work runs in, but the network helpers did not look at it: + - `http_client.perform_call` -- the single outbound path of the REST, signaling, USB-browser, config-sync and admin clients -- now checks the scope before sending (nothing is sent once cancelled) and after the reply (a reply that arrived after the cancellation raises `CancelledError` rather than being acted on). A request already out still runs to its own timeout. Unscoped callers see no change. + - `signaling_client.wait_for_answer` / `wait_for_offer` share one poll loop that checks `cancelled()` -- a new keyword, defaulting to the caller's scope -- before every poll and while sleeping between polls in 0.1 s slices, and raises `CancelledError`. The WebRTC host's publish loop waited up to 600 s for an answer and looked at its interruption only between sessions, so stopping the host left the thread waiting it out; it, and the host and viewer signaling workers, now pass `isInterruptionRequested`, and the publish loop stops the session it had published when interrupted. `retire_worker`'s docstring says what an interruption now reaches. +- **Tests:** new `test_network_cancellation.py` (7: a cancelled scope sends nothing; a reply after the cancellation is not handed on; an unscoped call is unchanged; a signaling wait ends soon after its `cancelled` turns true and after its scope is cancelled; an uncancelled wait still times out; stopping the publish loop ends its ten-minute wait within the second and drops the session). HTTP, signaling, WebRTC, remote, config-sync, outbound, daemon-thread, admin, USB, REST, webhook, network, peer-control and egress tests: 2835 passed, 42 skipped. +- **Docs:** both `v223_features_doc.rst` (background work in a tab), `CHANGELOG.md`. +- **Files:** `utils/http_client/http_client.py`, `utils/remote_desktop/signaling_client.py`, `gui/remote_desktop/webrtc_workers.py`, the test, the docs, `Progress.md`. +- **Open items:** none for the F3 entry; `Progress.md` keeps *F3 關閉失敗恢復* (native acceptance) and the native, hardware and CI-blocked items. diff --git a/docs/updates/README.md b/docs/updates/README.md index f5b365392..5bcc56f33 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-43 | 2026-11-14 | Network calls and signaling waits stop with their task | #done #remote-desktop #network | [2026-11-b](2026-11-b.md) | | U-20261114-42 | 2026-11-14 | close_admission(): media owners stop taking anything new at once | #done #remote-desktop #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-41 | 2026-11-14 | Diagnostics shows a held media stop's retirement state from its snapshot | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-40 | 2026-11-14 | An interruption's attached cleanup owners join the stop custody | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/webrtc_workers.py b/je_auto_control/gui/remote_desktop/webrtc_workers.py index 25590346d..ebc87c040 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_workers.py +++ b/je_auto_control/gui/remote_desktop/webrtc_workers.py @@ -9,6 +9,7 @@ """ from __future__ import annotations +from concurrent.futures import CancelledError import secrets from typing import Optional, Set @@ -50,7 +51,10 @@ def run(self) -> None: answer = signaling_client.wait_for_answer( self._server_url, self._host_id, secret=self._secret, timeout_s=self._timeout_s, + cancelled=self.isInterruptionRequested, ) + except CancelledError: + return # stopped: nobody is waiting for the answer except signaling_client.SignalingError as error: autocontrol_logger.warning("host signaling: %r", error) self.failed.emit(str(error)) @@ -77,7 +81,10 @@ def run(self) -> None: offer = signaling_client.wait_for_offer( self._server_url, self._host_id, secret=self._secret, timeout_s=self._timeout_s, + cancelled=self.isInterruptionRequested, ) + except CancelledError: + return # stopped: nobody is waiting for the offer except signaling_client.SignalingError as error: autocontrol_logger.warning("viewer signaling: %r", error) self.failed.emit(str(error)) @@ -156,13 +163,19 @@ def _publish_one_session(self) -> bool: secret=self._secret, ) self.offer_published.emit(session_id) + # Stopping the host interrupts the thread: the wait (up to ten + # minutes) used to run out first, and only then saw the stop. answer = signaling_client.wait_for_answer( self._server_url, self._host_id, secret=self._secret, timeout_s=self._wait_timeout_s, + cancelled=self.isInterruptionRequested, ) self._multi_host.accept_session_answer(session_id, answer) self.session_connected.emit(session_id) return True + except CancelledError: + self._safe_stop_session_if(session_id) # stopped while waiting: nobody will answer it + return False except signaling_client.SignalingError as error: return self._handle_signaling_error(session_id, error) except (ValueError, RuntimeError, OSError) as error: @@ -212,7 +225,8 @@ def retire_worker(worker: Optional[DaemonThread]) -> None: """Stop ``worker`` without destroying it while its thread still runs. A stopped worker is usually blocked in a signaling long-poll (up to ten - minutes), which ``requestInterruption`` cannot cut short. Dropping the last + minutes); ``requestInterruption`` now ends that wait within about 0.1 s, + but a request already out still runs to its timeout. Dropping the last reference to it there aborted the whole process with "QThread: Destroyed while thread is still running", from the Stop button, a second Publish or Connect click, or an auto-reconnect. The worker is kept here, cut off from diff --git a/je_auto_control/utils/http_client/http_client.py b/je_auto_control/utils/http_client/http_client.py index 0aec7b9df..a5a2fabca 100644 --- a/je_auto_control/utils/http_client/http_client.py +++ b/je_auto_control/utils/http_client/http_client.py @@ -14,6 +14,7 @@ import urllib.parse import urllib.request +from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.http_headers import CREDENTIAL_HEADERS from typing import Any, Dict, Mapping, Optional @@ -256,4 +257,10 @@ def perform_call(call: Mapping[str, Any]) -> Dict[str, Any]: """ from je_auto_control.utils.egress.egress_policy import get_egress_policy get_egress_policy().check(call["url"]) # allow-all unless an operator locked it down - return urllib_transport(call) + # Inside a cancelled scope (a GUI task stopped or past its deadline) the + # request is not sent, and a reply that arrives after the cancellation is + # not handed on; the request itself cannot be interrupted once it is out. + cancellation_checkpoint() + response = urllib_transport(call) + cancellation_checkpoint() + return response diff --git a/je_auto_control/utils/remote_desktop/signaling_client.py b/je_auto_control/utils/remote_desktop/signaling_client.py index 3380cf76c..c3769f4a9 100644 --- a/je_auto_control/utils/remote_desktop/signaling_client.py +++ b/je_auto_control/utils/remote_desktop/signaling_client.py @@ -13,8 +13,10 @@ import json import time import urllib.parse -from typing import Optional +from concurrent.futures import CancelledError +from typing import Callable, Optional +from je_auto_control.utils.exception.cancellation import current_cancellation_token from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -116,32 +118,60 @@ def fetch_answer(server_url: str, host_id: str, *, secret=secret, timeout=timeout)) +#: How often a wait looks at ``cancelled()`` while it sleeps between polls. +_STOP_CHECK_S = 0.1 + + +def _stop_check(cancelled: Optional[Callable[[], bool]]) -> Callable[[], bool]: + """``cancelled``, or the calling thread's cancellation scope when none is given.""" + if cancelled is not None: + return cancelled + token = current_cancellation_token() + return (lambda: token.is_cancelled) if token is not None else (lambda: False) + + +def _wait_for(fetch: Callable[[], Optional[str]], what: str, host_id: str, timeout_s: float, + poll_interval_s: float, cancelled: Optional[Callable[[], bool]]) -> str: + """Poll ``fetch`` until it answers, ``timeout_s`` passes, or the wait is cancelled.""" + stopped = _stop_check(cancelled) + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + if stopped(): + raise CancelledError() + value = fetch() + if value is not None: + return value + pause_until = min(deadline, time.monotonic() + poll_interval_s) + while time.monotonic() < pause_until: + if stopped(): + raise CancelledError() + time.sleep(min(_STOP_CHECK_S, max(0.0, pause_until - time.monotonic()))) + raise SignalingError(f"no {what} for host_id={host_id} within {timeout_s}s") + + def wait_for_answer(server_url: str, host_id: str, *, secret: Optional[str] = None, timeout_s: float = 60.0, - poll_interval_s: float = _POLL_INTERVAL_S) -> str: - """Host: block until viewer posts an answer or ``timeout_s`` elapses.""" - deadline = time.monotonic() + timeout_s - while time.monotonic() < deadline: - answer = fetch_answer(server_url, host_id, secret=secret) - if answer is not None: - return answer - time.sleep(poll_interval_s) - raise SignalingError(f"no answer for host_id={host_id} within {timeout_s}s") + poll_interval_s: float = _POLL_INTERVAL_S, + cancelled: Optional[Callable[[], bool]] = None) -> str: + """Host: block until viewer posts an answer or ``timeout_s`` elapses. + + Raises :class:`concurrent.futures.CancelledError` within about 0.1 s once + ``cancelled()`` is true -- by default, once the caller's cancellation + scope is cancelled. + """ + return _wait_for(lambda: fetch_answer(server_url, host_id, secret=secret), "answer", host_id, + timeout_s, poll_interval_s, cancelled) def wait_for_offer(server_url: str, host_id: str, *, secret: Optional[str] = None, timeout_s: float = 60.0, - poll_interval_s: float = _POLL_INTERVAL_S) -> str: - """Viewer: block until host posts an offer or ``timeout_s`` elapses.""" - deadline = time.monotonic() + timeout_s - while time.monotonic() < deadline: - offer = fetch_offer(server_url, host_id, secret=secret) - if offer is not None: - return offer - time.sleep(poll_interval_s) - raise SignalingError(f"no offer for host_id={host_id} within {timeout_s}s") + poll_interval_s: float = _POLL_INTERVAL_S, + cancelled: Optional[Callable[[], bool]] = None) -> str: + """Viewer: block until host posts an offer or ``timeout_s`` elapses; cancellable as :func:`wait_for_answer`.""" + return _wait_for(lambda: fetch_offer(server_url, host_id, secret=secret), "offer", host_id, + timeout_s, poll_interval_s, cancelled) def delete_session(server_url: str, host_id: str, *, diff --git a/test/unit_test/headless/test_network_cancellation.py b/test/unit_test/headless/test_network_cancellation.py new file mode 100644 index 000000000..a94247ed4 --- /dev/null +++ b/test/unit_test/headless/test_network_cancellation.py @@ -0,0 +1,114 @@ +"""Network calls the GUI runs stop when their task is stopped or runs out of time. + +``perform_call`` -- the one path the REST, signaling, USB and admin clients use +-- now sends nothing inside a cancelled scope and does not hand on a reply that +arrived after the cancellation. The signaling long-polls (the host waits up to +ten minutes for an answer) look at their stop between polls instead of only +after the whole wait: stopping the WebRTC host used to leave the publish loop +waiting it out. +""" +import threading +import time +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.http_client import http_client +from je_auto_control.utils.remote_desktop import signaling_client + + +def _reply(): + return {"status": 200, "text": "{}", "json": {}, "headers": {}} + + +def test_a_cancelled_scope_sends_nothing(monkeypatch): + sent = [] + monkeypatch.setattr(http_client, "urllib_transport", lambda call: sent.append(call) or _reply()) + token = CancellationToken(task_id=1) + token.cancel() + with cancellation_scope(token), pytest.raises(CancelledError): + http_client.perform_call(http_client.build_call("http://127.0.0.1:9/x", "GET")) # NOSONAR python:S5332 + assert sent == [] + + +def test_a_reply_after_the_cancellation_is_not_handed_on(monkeypatch): + token = CancellationToken(task_id=2) + + def slow_transport(call): + token.cancel() # Stop pressed while the request was out + return _reply() + + monkeypatch.setattr(http_client, "urllib_transport", slow_transport) + with cancellation_scope(token), pytest.raises(CancelledError): + http_client.perform_call(http_client.build_call("http://127.0.0.1:9/x", "GET")) # NOSONAR python:S5332 + + +def test_an_unscoped_call_is_unchanged(monkeypatch): + monkeypatch.setattr(http_client, "urllib_transport", lambda call: _reply()) + assert http_client.perform_call(http_client.build_call("http://127.0.0.1:9/x", "GET"))["status"] == 200 # NOSONAR + + +def test_a_signaling_wait_ends_soon_after_it_is_cancelled(monkeypatch): + monkeypatch.setattr(signaling_client, "fetch_answer", lambda *a, **k: None) + stop = threading.Event() + threading.Timer(0.2, stop.set).start() + started = time.monotonic() + with pytest.raises(CancelledError): + signaling_client.wait_for_answer("http://127.0.0.1:9", "h", timeout_s=600.0, # NOSONAR python:S5332 + poll_interval_s=5.0, cancelled=stop.is_set) + assert time.monotonic() - started < 1.5 + + +def test_a_signaling_wait_follows_the_callers_scope(monkeypatch): + monkeypatch.setattr(signaling_client, "fetch_offer", lambda *a, **k: None) + token = CancellationToken(task_id=3) + threading.Timer(0.2, token.cancel).start() + started = time.monotonic() + with cancellation_scope(token), pytest.raises(CancelledError): + signaling_client.wait_for_offer("http://127.0.0.1:9", "h", timeout_s=600.0, # NOSONAR python:S5332 + poll_interval_s=5.0) + assert time.monotonic() - started < 1.5 + + +def test_an_uncancelled_wait_still_times_out(monkeypatch): + monkeypatch.setattr(signaling_client, "fetch_answer", lambda *a, **k: None) + with pytest.raises(signaling_client.SignalingError): + signaling_client.wait_for_answer("http://127.0.0.1:9", "h", timeout_s=0.3, # NOSONAR python:S5332 + poll_interval_s=0.1) + + +def test_stopping_the_publish_loop_ends_its_long_wait_and_drops_the_session(monkeypatch): + pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + import os + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + from PySide6.QtWidgets import QApplication + QApplication.instance() or QApplication([]) + try: + from je_auto_control.gui.remote_desktop.webrtc_workers import HostPublishLoopWorker + except ImportError: + pytest.skip("the WebRTC GUI needs the webrtc extra") + from headless._qt_settle import pump_until + monkeypatch.setattr(signaling_client, "push_offer", lambda *a, **k: None) + monkeypatch.setattr(signaling_client, "fetch_answer", lambda *a, **k: None) + stopped, waiting = [], threading.Event() + + class _Host: + def create_session_offer(self): + waiting.set() + return "session-1", "v=0" + + def stop_session(self, session_id): + stopped.append(session_id) + + worker = HostPublishLoopWorker(multi_host=_Host(), server_url="http://127.0.0.1:9", # NOSONAR python:S5332 + host_id="h", secret=None, wait_timeout_s=600.0) + worker.start() + try: + assert waiting.wait(5.0) + time.sleep(0.2) # now inside the ten-minute wait + worker.requestInterruption() + assert pump_until(lambda: not worker.isRunning(), timeout=3.0) + assert stopped == ["session-1"] + finally: + worker.requestInterruption() From 553096aa9f8ed14bffd05841a4d40f3baa17105f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 20:06:11 +0800 Subject: [PATCH 111/161] Stop tabs keeping themselves alive, the cause of the exit crash A Qt connection holds its slot from C++, out of the collector's sight. The Script Builder connected a lambda over self to each of its 714 Add-step actions, so every tab built lived until exit, where Qt's teardown released the closure inside a destructor and deleted the tab a second time. Those slots, and the similar ones in four other tabs, are now methods or weak references. --- CHANGELOG.md | 8 +++ Progress.md | 20 +++--- architecture_explore.md | 16 ++--- docs/updates/2026-11-b.md | 8 +++ docs/updates/README.md | 1 + je_auto_control/gui/live_hud_tab.py | 19 ++++- je_auto_control/gui/presence_tab.py | 15 ++-- .../gui/script_builder/builder_tab.py | 24 +++++-- .../gui/script_builder/one_time_dialog.py | 9 ++- .../gui/script_builder/step_form_view.py | 9 ++- je_auto_control/gui/triggers_tab.py | 21 +++++- je_auto_control/gui/window_tab.py | 19 ++++- .../headless/test_gui_tab_not_kept_alive.py | 70 +++++++++++++++++++ 13 files changed, 200 insertions(+), 39 deletions(-) create mode 100644 test/unit_test/headless/test_gui_tab_not_kept_alive.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 096dacb75..17347a8b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- GUI: no tab keeps itself alive any more. Lambdas over `self` connected to Qt signals -- one per + Script Builder Add-step action (714), the Triggers tab's two Browse buttons, the step form's + Browse and the one-time-values dialog's Copy -- and closures connected to `destroyed` that + reached the tab (Live HUD's log filter, Presence's registry listener) held every tab built + until exit, where Qt's teardown deleted it a second time: the exit crash under PySide6 6.12. + They are now methods of the widget, weak references, or (Window Manager) a child timer; + `WindowManagerTab` gains `dispose()`. + - `http_client.perform_call` observes a bound cancellation scope: once it is cancelled the request is not sent, and a reply that arrives after the cancellation raises `CancelledError` instead of being returned; unscoped calls are unchanged. `signaling_client.wait_for_answer` / diff --git a/Progress.md b/Progress.md index 32f7ba261..cedbf4411 100644 --- a/Progress.md +++ b/Progress.md @@ -208,17 +208,15 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD --- -## PySide6 6.12:headless 測試跑完後直譯器結束時崩潰(全平台) - -`TODO` — 維護者 2026-11-14 決定全面固定回 PySide6 6.11.2(U-20261114-03;dependabot 忽略 6.12.0),待之後的 6.12.x 或找出 closure 後再升級並重驗。先在容器看到(U-20261114-01:`docker.yml` 4 次 3 次 SIGSEGV);到 `1d372dba`(PR #552,2026-11-14)已是**每一格**:全部測試通過後,Ubuntu 3.14 exit 255(glibc `malloc_consolidate` abort)、macOS 3.11 `Fatal Python error: Aborted`、Windows 3.11/3.14 access violation、3.13 `Aborted`,Windows 3.12 在 `test_gui_offthread_sites.py` 中段 abort。本機 Windows 3.14 的完整套件沒有重現。 -- Ubuntu 的 gdb 堆疊(dev run 43484575781):`destroyQCoreApplication` → `visitAllPyObjects` → 某個 QObject 的 `~QObject` 釋放接在它訊號上的 Python 函式 → `func_dealloc` → closure cell → 一個 widget 的 wrapper 歸零 → `~QWidget` → `~QScrollBar` → `free()` 重複釋放;前一行是 `shared QObject was deleted directly`。即 closure 握有最後一個參考的 widget,在結束時被 shiboken 與 Qt 各刪一次。是哪個 closure 還不知道。 -- 試過把分頁關閉鈕的 lambda(握住頁面)換成 bound method,或改用 Qt 內建關閉鈕:`test_gui_lazy_registry.py` 的探針在 `os._exit` 10/10 崩潰(HEAD 13/13 正常),已還原;這條路徑本身就是「把 Python 建的 widget 放進分頁列在結束時崩潰」那一項。 -- 兩次在測試全部跑完後的直譯器結束:`Py_FinalizeEx` → `PySide::runCleanupFunctions` → `destroyQCoreApplication` - → `BindingManager::visitAllPyObjects` → `QObject::~QObject`,前一行是 Qt 的 `shared QObject was deleted directly`。 -- 一次在測試中段(約 46%)主執行緒的 `Shiboken::BindingManager::runDeletionInMainThread()` → QtWidgets。 -- 不是 Python 3.12 或容器映像特有(每個平台與版本都有);還不知道是哪個測試留下了被兩邊刪除的物件。 - 上游查無相同回報。`docker.yml` 現在以 gdb 跑、`-X faulthandler`、`-v`,下次中段崩潰會有測試名稱。 -- 升級回 6.12 前要做的:在 PR 上跑完整矩陣(含 `docker.yml`)確認結束時不再崩潰;或先找出握住 widget 的 closure(上面的分頁關閉鈕實驗顯示改動它會改變崩潰點,不是單純移除)。 +## PySide6 6.12:升級回 6.12 前須在 CI 全矩陣重驗 + +`DECIDE` — 結束時崩潰的 closure 已找到並修正(U-20261114-44):Qt 連線從 C++ 端持有 slot, +`ScriptBuilderTab` 每個 Add-step 動作一個捕捉 `self` 的 lambda(714 個)、Triggers 的兩個瀏覽 lambda, +以及 Live HUD 與 Presence 連到 `destroyed` 的 closure,讓分頁一直活到結束,Qt 拆除時在 C++ 解構子裡放掉最後一個參考、 +把分頁刪第二次。本機 PySide6 6.12.0 的 GUI 子集(742 個測試)修正前每次結束都 access violation,修正後兩次都正常結束; +`test_gui_tab_not_kept_alive.py` 守住每個分頁都能被回收且直譯器正常結束。 +維護者 2026-11-14 固定在 PySide6 6.11.2(U-20261114-03;dependabot 忽略 6.12.0)。是否升級回 6.12: +須在 PR 上以 6.12 跑完整矩陣(含 `docker.yml`)確認每一格結束時都不再崩潰;其他平台與完整套件尚未以 6.12 重驗。 --- diff --git a/architecture_explore.md b/architecture_explore.md index ca8d0d909..971c3ffe9 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,281 | +| 程式碼總行數 | 237,357 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1356,7 +1356,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | screenshot | `_screenshot_tab.py` | 180 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 158 | 樣板裁切、定位、定位全部、定位並點擊。 | | record | `_record_tab.py` | 166 | 錄製/停止/回放/存檔/載入。 | -| script_builder | `script_builder/` | 6,928 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | +| script_builder | `script_builder/` | 6,956 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | | flow_editor | `flow_editor/` | 496 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | | script | `_script_tab.py` | 183 | 載入/執行單檔或整個目錄、內建編輯器執行。 | | recording_editor | `recording_editor_tab.py` | 255 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | @@ -1366,13 +1366,13 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 952 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | -| live_hud | `live_hud_tab.py` | 140 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | +| live_hud | `live_hud_tab.py` | 155 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | | llm_planner | `llm_planner_tab.py` | 196 | 自然語言描述 → 預覽 → 執行。 | | computer_use | `computer_use_tab.py` | 164 | 從 GUI 啟動 Anthropic 閉環 agent。 | | agent_tasks | `agent_tasks_tab.py` | 618 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | | scheduler | `scheduler_tab.py` | 174 | 註冊間隔式 action JSON 執行。 | | hotkeys | `hotkeys_tab.py` | 166 | 將全域熱鍵綁到 action 檔。 | -| triggers | `triggers_tab.py` | 384 | 影像/視窗/像素/檔案事件監看。 | +| triggers | `triggers_tab.py` | 401 | 影像/視窗/像素/檔案事件監看。 | | webhooks | `webhooks_tab.py` | 222 | 將 HTTP 請求綁到 action 腳本。 | | email_triggers | `email_triggers_tab.py` | 254 | 將 IMAP 信箱綁到 action 腳本。 | | test_suite | `test_suite_tab.py` | 200 | 執行 QA 套件規格並管理易碎隔離區。 | @@ -1385,14 +1385,14 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | media_checks | `media_checks_tab.py` | 129 | 音訊活動與影片動態斷言。 | | run_history | `run_history_tab.py` + `run_history_timeline.py` + `journal_browser.py` + `journal_browser_worker.py` | 836 | 瀏覽已記錄的執行、時間軸、截圖與非擁有式日誌連結;內嵌背景快照查閱。 | | profiler | `profiler_tab.py` | 141 | 視覺化逐動作耗時熱點。 | -| window_manager | `window_tab.py` | 139 | 列出、聚焦、關閉視窗。 | +| window_manager | `window_tab.py` | 152 | 列出、聚焦、關閉視窗。 | | plugins | `plugins_tab.py` | 85 | 從使用者目錄載入額外 `AC_` 指令。 | | webrunner | `webrunner_tab.py` | 203 | 從 GUI 驅動 `je_web_runner`。 | | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | | remote_desktop | `remote_desktop/`(40 檔) | 8,564 | 見下。 | -| presence | `presence_tab.py` | 168 | 多檢視者在場名單。 | +| presence | `presence_tab.py` | 171 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | @@ -1549,7 +1549,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,830 | +| `gui/` | 166 | 43,906 | | `utils/mcp_server/` | 63 | 22,228 | | `utils/remote_desktop/` | 77 | 16,898 | | `utils/executor/` | 11 | 10,752 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,229 | -| **總計** | **1,531** | **236,536** | +| **總計** | **1,531** | **236,612** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 6860ef374..5e07ee8d7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -632,3 +632,11 @@ - **Docs:** both `v223_features_doc.rst` (background work in a tab), `CHANGELOG.md`. - **Files:** `utils/http_client/http_client.py`, `utils/remote_desktop/signaling_client.py`, `gui/remote_desktop/webrtc_workers.py`, the test, the docs, `Progress.md`. - **Open items:** none for the F3 entry; `Progress.md` keeps *F3 關閉失敗恢復* (native acceptance) and the native, hardware and CI-blocked items. + +## U-20261114-44 · 2026-11-14 · The PySide6 6.12 exit crash: tabs no longer keep themselves alive · #done #gui #pyside6 + +- **What:** the cause `Progress.md` › *PySide6 6.12* was looking for -- the Ubuntu gdb stack showed `destroyQCoreApplication` → `~QObject` releasing a Python function connected to its signal → closure cell → a widget's wrapper dropping to zero → `~QWidget` → double free, without knowing which closure. Reproduced on this machine (PySide6 6.12.0, Windows 11, Python 3.14.7): the 742-test GUI subset passed and the interpreter then took an access violation, every time. Bisected by file to 13, reduced to `test_gui_script_runs.py` (4/5 alone), to `test_builder_run_and_stop`, and to a probe that builds and drops `ScriptBuilderTab` 20 times (6/6 crash). The dropped tabs survived `gc.collect()`, held by closure cells: `ScriptBuilderTab._add_button` connected `lambda _checked=False, cmd=spec.command: self._add_step_from_command(cmd)` to each of 714 Add-step actions. A Qt connection holds its slot from C++, which Python's collector cannot see, so every tab built lived until exit, where Qt's teardown released the closure inside a C++ destructor and the tab was deleted twice. A probe over every registered tab found the same pattern elsewhere: Triggers' two Browse lambdas, Live HUD's `destroyed` closure reaching the log tail whose filter was the tab's bound method, Presence's `destroyed` closure and registry listener holding its bound method, and Window Manager's `QTimer.singleShot(0, self, ...)` keeping the wrapper after deletion. +- **Fix:** the actions carry their command in `setData` and connect one method (`_on_add_action`, reading `sender()`); Up / Down, the step form's Browse and the one-time-values dialog's Copy become methods reading the button's property; Live HUD filters through a `WeakMethod` (`_WeakFilter`); Presence registers a `weak_slot` listener and removes that same object on `destroyed` and in `dispose`; Window Manager uses a child single-shot timer (and gains `dispose()`). After it the GUI subset exits cleanly (two of two), `test_gui_script_runs.py` five of five, and the 20-tab probe six of six. The PySide6 6.11.2 pin stays: `Progress.md` now records the upgrade as a maintainer decision that needs the full CI matrix on 6.12. +- **Tests:** new `test_gui_tab_not_kept_alive.py` (in a child interpreter: every registered tab, dropped and disposed-and-deleted, is collected; 20 dropped Script Builder tabs and a natural exit return 0; it names all five tabs on the old code). Builder, script, HUD, presence, triggers, window, listener, one-time, step-form and GUI tests: 2734 passed, 87 skipped before Window Manager's `dispose()`, whose dispose and lifecycle guards then passed. +- **Files:** `gui/script_builder/builder_tab.py`, `gui/script_builder/step_form_view.py`, `gui/script_builder/one_time_dialog.py`, `gui/triggers_tab.py`, `gui/live_hud_tab.py`, `gui/presence_tab.py`, `gui/window_tab.py`, the test, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › *PySide6 6.12* (`DECIDE`: upgrade after a full-matrix run on 6.12). diff --git a/docs/updates/README.md b/docs/updates/README.md index 5bcc56f33..6080281c5 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261114-44 | 2026-11-14 | The PySide6 6.12 exit crash: tabs no longer keep themselves alive | #done #gui #pyside6 | [2026-11-b](2026-11-b.md) | | U-20261114-43 | 2026-11-14 | Network calls and signaling waits stop with their task | #done #remote-desktop #network | [2026-11-b](2026-11-b.md) | | U-20261114-42 | 2026-11-14 | close_admission(): media owners stop taking anything new at once | #done #remote-desktop #lifecycle | [2026-11-b](2026-11-b.md) | | U-20261114-41 | 2026-11-14 | Diagnostics shows a held media stop's retirement state from its snapshot | #done #gui #lifecycle | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/live_hud_tab.py b/je_auto_control/gui/live_hud_tab.py index f33faea67..a9293d157 100644 --- a/je_auto_control/gui/live_hud_tab.py +++ b/je_auto_control/gui/live_hud_tab.py @@ -1,8 +1,9 @@ """Live HUD: mouse position, pixel colour under cursor and log tail.""" -from typing import Optional +from typing import Callable, Optional import logging import threading +import weakref from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( @@ -23,6 +24,17 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) +class _WeakFilter: + """A logging filter that calls a method without keeping its object alive; a record passes once it is gone.""" + + def __init__(self, method: Callable[[logging.LogRecord], bool]) -> None: + self._method = weakref.WeakMethod(method) + + def __call__(self, record: logging.LogRecord) -> bool: + method = self._method() + return True if method is None else method(record) + + class LiveHUDTab(TranslatableMixin, QWidget): """Poll watchers and render a readable HUD.""" @@ -36,7 +48,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: # at 4 ticks a second they were every line in the pane. self._sampling = False self._gui_thread = threading.get_ident() - self._log_tail.addFilter(self._not_own_sampling) + # Held weakly: the tail outlives the tab on the global logger, and the closure + # connected to ``destroyed`` below reaches the tail, so a strong filter kept the + # tab alive until Qt's teardown released it -- and deleted it a second time. + self._log_tail.addFilter(_WeakFilter(self._not_own_sampling)) self._pos_suffix = " --" self._color_suffix = " --" self._pos_label = QLabel() diff --git a/je_auto_control/gui/presence_tab.py b/je_auto_control/gui/presence_tab.py index f50708c70..c58e0fda1 100644 --- a/je_auto_control/gui/presence_tab.py +++ b/je_auto_control/gui/presence_tab.py @@ -16,6 +16,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._weak_call import weak_slot from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -50,11 +51,13 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._registry_changed.connect(self.refresh) # Listener fires on every change; the timer is a belt-and-braces # refresh in case a listener exception drops us off. - self._registry.add_listener(self._on_registry_event) - # The registry outlives the tab; left registered, it kept calling a - # deleted widget after every change. - registry, listener = self._registry, self._on_registry_event - self.destroyed.connect(lambda *_args: registry.remove_listener(listener)) + # The registry outlives the tab, so it holds the tab's listener weakly: a bound + # method there (and in the closure connected to ``destroyed``) kept the tab alive + # until Qt's teardown released it and deleted it a second time. + self._registry_listener = weak_slot(self._on_registry_event) + self._registry.add_listener(self._registry_listener) + # Left registered, it kept calling a deleted widget after every change. + self.destroyed.connect(functools.partial(self._registry.remove_listener, self._registry_listener)) self._timer = QTimer(self) self._timer.setInterval(5000) self._timer.timeout.connect(self.refresh) @@ -66,7 +69,7 @@ def dispose(self) -> None: Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. """ - release_resources(self, functools.partial(self._registry.remove_listener, self._on_registry_event)) + release_resources(self, functools.partial(self._registry.remove_listener, self._registry_listener)) def retranslate(self) -> None: TranslatableMixin.retranslate(self) diff --git a/je_auto_control/gui/script_builder/builder_tab.py b/je_auto_control/gui/script_builder/builder_tab.py index 00c44fd9d..5653c6670 100644 --- a/je_auto_control/gui/script_builder/builder_tab.py +++ b/je_auto_control/gui/script_builder/builder_tab.py @@ -139,8 +139,8 @@ def _build_toolbar(self) -> FlowLayout: edit_buttons: List[QWidget] = [self._add_button()] for key, handler in ( ("sb_delete", self._on_delete), - ("sb_up", lambda: self._tree.move_selected(-1)), - ("sb_down", lambda: self._tree.move_selected(1)), + ("sb_up", self._move_up), + ("sb_down", self._move_down), ): btn = self._tr(QPushButton(), key) btn.clicked.connect(handler) @@ -170,14 +170,28 @@ def _add_button(self) -> QToolButton: submenu = menu.addMenu(category) for spec in specs_in_category(category): action = QAction(spec.label, submenu) - action.triggered.connect( - lambda _checked=False, cmd=spec.command: self._add_step_from_command(cmd) - ) + # The command rides on the action and the slot is a method of this tab: a + # lambda over ``self`` per action kept every tab alive until exit, where + # Qt's teardown dropped the last reference and deleted it a second time. + action.setData(spec.command) + action.triggered.connect(self._on_add_action) submenu.addAction(action) button.setMenu(menu) self._add_btn = button return button + def _move_up(self) -> None: + self._tree.move_selected(-1) + + def _move_down(self) -> None: + self._tree.move_selected(1) + + def _on_add_action(self) -> None: + action = self.sender() + command = action.data() if isinstance(action, QAction) else None + if isinstance(command, str): + self._add_step_from_command(command) + def _wire_signals(self) -> None: self._tree.selected_step_changed.connect(self._form.load_step) self._form.step_changed.connect(self._tree.refresh_current_label) diff --git a/je_auto_control/gui/script_builder/one_time_dialog.py b/je_auto_control/gui/script_builder/one_time_dialog.py index 4a7de206f..ef1b211d6 100644 --- a/je_auto_control/gui/script_builder/one_time_dialog.py +++ b/je_auto_control/gui/script_builder/one_time_dialog.py @@ -106,12 +106,19 @@ def _add_row(self, grid: QGridLayout, row: int, value: OneTimeValue) -> None: field = QLineEdit(value.value) field.setReadOnly(True) copy = QPushButton(_t("sb_one_time_copy")) - copy.clicked.connect(lambda _checked=False, index=row: self.copy_value(index)) + copy.setProperty("row_index", row) + copy.clicked.connect(self._on_copy_clicked) # a method, not a lambda over self grid.addWidget(QLabel(value_label(value)), row, 0) grid.addWidget(field, row, 1) grid.addWidget(copy, row, 2) self._fields.append(field) + def _on_copy_clicked(self) -> None: + button = self.sender() + index = button.property("row_index") if button is not None else None + if isinstance(index, int): + self.copy_value(index) + def labels(self) -> List[str]: """The label of each value still held, in the order shown.""" return [value_label(value) for value in self._values] diff --git a/je_auto_control/gui/script_builder/step_form_view.py b/je_auto_control/gui/script_builder/step_form_view.py index c2ebf7e0e..a14eb1257 100644 --- a/je_auto_control/gui/script_builder/step_form_view.py +++ b/je_auto_control/gui/script_builder/step_form_view.py @@ -146,13 +146,20 @@ def _build_file(self, spec: FieldSpec) -> QWidget: line.setPlaceholderText(spec.placeholder) browse = QPushButton("...") browse.setMaximumWidth(30) - browse.clicked.connect(lambda: self._browse_file(line)) + browse.setProperty("line_edit", line) + browse.clicked.connect(self._on_browse_clicked) # a method, not a lambda over self line.textChanged.connect(self._commit_field) row.addWidget(line) row.addWidget(browse) container.setProperty("line_edit", line) return container + def _on_browse_clicked(self) -> None: + button = self.sender() + line = button.property("line_edit") if button is not None else None + if isinstance(line, QLineEdit): + self._browse_file(line) + def _build_rgb(self, spec: FieldSpec) -> QWidget: editor = QLineEdit() editor.setPlaceholderText(spec.placeholder or "R,G,B") diff --git a/je_auto_control/gui/triggers_tab.py b/je_auto_control/gui/triggers_tab.py index 697ff6dc5..f7cffc907 100644 --- a/je_auto_control/gui/triggers_tab.py +++ b/je_auto_control/gui/triggers_tab.py @@ -194,7 +194,8 @@ def _build_image_form(self) -> dict: path_input = QLineEdit() threshold_input = QLineEdit("0.8") browse = self._tr(QPushButton(), "browse") - browse.clicked.connect(lambda: self._browse_image(path_input)) + browse.setProperty("line_edit", path_input) + browse.clicked.connect(self._on_browse_image) # a method: a lambda over self kept the tab alive threshold = QWidget() threshold.setProperty("role", "bare") threshold.setLayout(flow_of(field_pair(self._tr(QLabel(), "tr_threshold_label"), threshold_input))) @@ -225,10 +226,26 @@ def _build_pixel_form(self) -> dict: def _build_file_form(self) -> dict: path_input = QLineEdit() browse = self._tr(QPushButton(), "browse") - browse.clicked.connect(lambda: self._browse_watch(path_input)) + browse.setProperty("line_edit", path_input) + browse.clicked.connect(self._on_browse_watch) self._add_page(self._field_row("tr_watch_label", path_input, browse)) return {"path": path_input} + def _browse_target(self) -> Optional[QLineEdit]: + button = self.sender() + line = button.property("line_edit") if button is not None else None + return line if isinstance(line, QLineEdit) else None + + def _on_browse_image(self) -> None: + line = self._browse_target() + if line is not None: + self._browse_image(line) + + def _on_browse_watch(self) -> None: + line = self._browse_target() + if line is not None: + self._browse_watch(line) + def _browse_script(self) -> None: path, _ = QFileDialog.getOpenFileName( self, _t("tr_dialog_select_script"), "", "JSON (*.json)", diff --git a/je_auto_control/gui/window_tab.py b/je_auto_control/gui/window_tab.py index 787404954..612315ee0 100644 --- a/je_auto_control/gui/window_tab.py +++ b/je_auto_control/gui/window_tab.py @@ -7,6 +7,7 @@ QTableWidgetItem, QVBoxLayout, QWidget, ) +from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin from je_auto_control.gui.adaptive.surfaces import Card, set_role from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( @@ -32,6 +33,12 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._filter = QLineEdit() self._apply_filter_placeholder() self._filter.textChanged.connect(self._apply_filter) + # A child timer, deleted with the tab: ``QTimer.singleShot(0, self, ...)`` kept + # the bound method -- and the tab's wrapper -- after the tab was deleted first. + self._filter_timer = QTimer(self) + self._filter_timer.setSingleShot(True) + self._filter_timer.setInterval(0) + self._filter_timer.timeout.connect(self._apply_filter) self._status_count: Optional[int] = None self._status_error: Optional[str] = None self._status = QLabel("") @@ -69,6 +76,13 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) + def dispose(self) -> None: + """Release what the tab holds beyond its widgets: its pending filter timer. + + Called by ``close_tab(key, release=True)`` before the widget is deleted; safe to call twice. + """ + release_resources(self) + def menu_actions(self) -> list: """Expose tab commands to the window-level Actions menu.""" return [ @@ -93,9 +107,8 @@ def refresh(self) -> None: self._table.setItem(row, 1, QTableWidgetItem(title)) self._status_count = len(windows) self._apply_status() - # With the tab as context: cancelled if the tab is deleted first, where - # it read the deleted filter box. - QTimer.singleShot(0, self, self._apply_filter) + # A child of the tab, so it never fires on a deleted filter box. + self._filter_timer.start() def _apply_filter(self) -> None: needle = self._filter.text().strip().lower() diff --git a/test/unit_test/headless/test_gui_tab_not_kept_alive.py b/test/unit_test/headless/test_gui_tab_not_kept_alive.py new file mode 100644 index 000000000..63ceb76c3 --- /dev/null +++ b/test/unit_test/headless/test_gui_tab_not_kept_alive.py @@ -0,0 +1,70 @@ +"""No tab keeps itself alive, and dropped tabs do not crash the interpreter at exit. + +A Qt connection holds its slot from C++, where Python's collector cannot see +it. A ``lambda`` over ``self`` connected to a child's signal -- the Script +Builder had one per Add-step action, 714 of them -- therefore kept every tab +built alive until exit, where Qt's teardown released the closure, dropped the +tab's last reference inside a C++ destructor and deleted the tab a second time: +the access violation / ``malloc_consolidate`` abort every CI square showed after +all tests passed under PySide6 6.12. The probe runs in a child interpreter so +the exit itself is part of the check. +""" +import os +import subprocess # nosec B404 # reason: runs this interpreter on a literal probe +import sys + +import pytest + +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +_PROBE = r""" +import gc, importlib, os, weakref +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +os.environ["AUTOCONTROL_GUI_SETTINGS"] = "off" +from PySide6.QtWidgets import QApplication +app = QApplication.instance() or QApplication([]) +from je_auto_control.gui.tab_registry import TAB_SPECS + +def build(spec, delete): + widget = getattr(importlib.import_module(spec.module), spec.class_name)() + ref = weakref.ref(widget) + if delete: + getattr(widget, "dispose", lambda: None)() + widget.deleteLater() + return ref + +kept = [] +for delete in (False, True): + for spec in TAB_SPECS: + if not spec.module: + continue + try: + ref = build(spec, delete) + except ImportError: + continue # an optional extra this environment lacks + for _ in range(3): + app.sendPostedEvents(None, 52) + app.processEvents() + gc.collect() + if ref() is not None: + kept.append(f"{spec.key} ({'deleted' if delete else 'dropped'})") +print("KEPT:", kept, flush=True) + +import je_auto_control.gui.script_builder.builder_tab as builder_tab +def drop(): + builder_tab.ScriptBuilderTab() +for _ in range(20): + drop() +print("EXITING", flush=True) +""" + + +def test_no_tab_keeps_itself_alive_and_the_interpreter_exits_cleanly(): + env = dict(os.environ, QT_QPA_PLATFORM="offscreen") + # argv is this interpreter plus a literal probe. No shell. + done = subprocess.run([sys.executable, "-c", _PROBE], capture_output=True, text=True, # nosec B603 # reason: literal argv + check=False, timeout=300, env=env) + kept = [line for line in done.stdout.splitlines() if line.startswith("KEPT:")] + assert kept == ["KEPT: []"], done.stdout + done.stderr + assert "EXITING" in done.stdout + assert done.returncode == 0, f"the interpreter crashed at exit (rc {done.returncode}):\n{done.stderr[-2000:]}" From cb50d255031285a84ec99afafca205ef3ccc347d Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sat, 14 Nov 2026 21:24:09 +0800 Subject: [PATCH 112/161] Trial PySide6 6.12.0 again now that the exit crash is fixed The pin to 6.11.2 waited on finding what crashed the test process at interpreter exit under 6.12. That was tabs kept alive by slots holding themselves, fixed on dev; this branch runs the full matrix on 6.12.0 before the pin moves. --- .github/dependabot.yml | 5 ----- .github/workflows/dev.yml | 2 +- .github/workflows/quality.yml | 4 ++-- CHANGELOG.md | 4 ++++ dev.toml | 2 +- dev_requirements.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 8 files changed, 11 insertions(+), 12 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c105727cc..c40004304 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,8 +14,3 @@ updates: - "/.github/requirements" schedule: interval: "daily" - ignore: - # 6.12.0 crashes the test process at interpreter exit on every platform - # (Progress.md, "PySide6 6.12"); a later 6.12 release may be proposed. - - dependency-name: "pyside6" - versions: ["6.12.0"] diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index 6f16eb888..a0fc90ef6 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -79,7 +79,7 @@ jobs: shell: bash # The same line as quality.yml (test_dev_release.py compares them). # Quoted: `--only-binary :all:` puts a colon-space inside the scalar. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.11.2 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" # No path argument: the paths come from `testpaths` in pyproject.toml, # and an argument would drop the flow_control tests. Linux runs under a diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 07e89e307..9461a63a3 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -149,7 +149,7 @@ jobs: shell: bash # Quoted: `--only-binary :all:` puts a colon-space inside the # scalar, which YAML reads as a mapping and refuses. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.11.2 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" - name: Verify native diagnostics runner (Linux) if: runner.os == 'Linux' @@ -294,7 +294,7 @@ jobs: python-version: "3.12" cache: "pip" - run: pip install -e ".[gui,webrtc]" # NOSONAR githubactions:S8541,githubactions:S8544 # reason: installs the checked-out project itself, there is no upstream version to lock and the build must run - - run: "pip install --only-binary :all: mypy==2.4.0 PySide6==6.11.2 aiortc==1.15.0 av==17.1.0 aioice==0.10.2 pyee==14.0.0 pylibsrtp==1.0.0" + - run: "pip install --only-binary :all: mypy==2.4.0 PySide6==6.12.0 aiortc==1.15.0 av==17.1.0 aioice==0.10.2 pyee==14.0.0 pylibsrtp==1.0.0" - name: The ordinary contract does not change when the extras are installed run: python test/verify/typing_contract_verify.py - name: The package against the real PySide6 / aiortc / av types diff --git a/CHANGELOG.md b/CHANGELOG.md index 17347a8b0..acd34034d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- The `gui` extra pins PySide6 6.12.0 again (it was held at 6.11.2 because the test process + crashed at interpreter exit under 6.12; the cause, tabs kept alive by slots holding + themselves, was fixed in U-20261114-44). Dependabot no longer ignores 6.12.0. + - GUI: no tab keeps itself alive any more. Lambdas over `self` connected to Qt signals -- one per Script Builder Add-step action (714), the Triggers tab's two Browse buttons, the step form's Browse and the one-time-values dialog's Copy -- and closures connected to `destroyed` that diff --git a/dev.toml b/dev.toml index c286f70cf..2a6375fc2 100644 --- a/dev.toml +++ b/dev.toml @@ -85,7 +85,7 @@ find = { namespaces = false } ] [project.optional-dependencies] -gui = ["PySide6==6.11.2"] +gui = ["PySide6==6.12.0"] webrtc = ["aiortc>=1.14.0", "av>=14.0.0"] signaling = ["fastapi>=0.115", "starlette>=1.0.1", "uvicorn>=0.32"] discovery = ["zeroconf>=0.149.16"] diff --git a/dev_requirements.txt b/dev_requirements.txt index 697da8fca..0520862cb 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -4,7 +4,7 @@ build twine sphinx sphinx-rtd-theme -PySide6==6.11.2 +PySide6==6.12.0 mss==10.2.0 defusedxml==0.7.1 diff --git a/pyproject.toml b/pyproject.toml index 0b4be9bdc..268bfc955 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -110,7 +110,7 @@ find = { namespaces = false } ] [project.optional-dependencies] -gui = ["PySide6==6.11.2"] +gui = ["PySide6==6.12.0"] webrtc = ["aiortc>=1.14.0", "av>=14.0.0"] signaling = ["fastapi>=0.115", "starlette>=1.0.1", "uvicorn>=0.32"] discovery = ["zeroconf>=0.149.16"] diff --git a/requirements.txt b/requirements.txt index 8ae22da1b..b51e3948b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,4 @@ je_auto_control>=1.0.4 # replaced that entry. A direct requirement does. pillow>=12.3.0 mss==10.2.0 -PySide6==6.11.2 +PySide6==6.12.0 From f351b2771cf54e21094a9457a0d3b53da6759ecd Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 03:38:01 +0800 Subject: [PATCH 113/161] Record the PySide6 6.12.0 CI trial in Progress.md --- Progress.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Progress.md b/Progress.md index cedbf4411..e76ed1470 100644 --- a/Progress.md +++ b/Progress.md @@ -217,6 +217,8 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD `test_gui_tab_not_kept_alive.py` 守住每個分頁都能被回收且直譯器正常結束。 維護者 2026-11-14 固定在 PySide6 6.11.2(U-20261114-03;dependabot 忽略 6.12.0)。是否升級回 6.12: 須在 PR 上以 6.12 跑完整矩陣(含 `docker.yml`)確認每一格結束時都不再崩潰;其他平台與完整套件尚未以 6.12 重驗。 + 試驗分支 `trial/pyside6-6.12`(2026-11-15,維護者決定):草稿 PR #554 進 dev(`dev.yml`,並手動觸發 `quality.yml`)、 + 只跑 CI 的草稿 PR #555 進 main(`docker.yml`、`stable.yml`,看完結果即關閉)。全部格子都正常結束才合併 #554。 --- From a9ee174f70bf5d0e59781cb5bf36d896b046de29 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 04:41:12 +0800 Subject: [PATCH 114/161] Record the PySide6 6.12.0 trial: clean from 3.12 up, 3.11 still aborts --- Progress.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Progress.md b/Progress.md index e76ed1470..193bc956a 100644 --- a/Progress.md +++ b/Progress.md @@ -219,6 +219,12 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 須在 PR 上以 6.12 跑完整矩陣(含 `docker.yml`)確認每一格結束時都不再崩潰;其他平台與完整套件尚未以 6.12 重驗。 試驗分支 `trial/pyside6-6.12`(2026-11-15,維護者決定):草稿 PR #554 進 dev(`dev.yml`,並手動觸發 `quality.yml`)、 只跑 CI 的草稿 PR #555 進 main(`docker.yml`、`stable.yml`,看完結果即關閉)。全部格子都正常結束才合併 #554。 + `quality.yml`(run 43599637920)結果:所有 3.12/3.13/3.14 格子(Windows、Ubuntu、macOS)通過,結束時不再崩潰; + 兩個 3.11 格子仍失敗——Ubuntu 3.11 的 `test_gui_page_widths.py` 探針子程序在建構 `flakiness_tab` 時 + `Fatal Python error: none_dealloc`(None 的參考計數被多減一次;3.12 起 None 是 immortal,所以只有 3.11 會死), + Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_and_a_disconnect_is_not` 中段 abort。 + 本機 Windows 3.11.9 + 6.12.0 單獨重跑這兩個檔案(含 webrtc)各 3~5 次都通過,逐一建構所有分頁、Qt 訊息處理器與常用 API + 也量不到 None 參考計數漂移;尚未找到減少 None 的呼叫。可選:維持 6.11.2;或只對 Python ≥ 3.12 改用 6.12(3.11 留在 6.11.2)。 --- From 0da361e6e4cda8746b5f0a4f7b017885fbd7b9b7 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 08:43:10 +0800 Subject: [PATCH 115/161] Keep Python 3.11 on PySide6 6.11.2 in the 6.12.0 trial Every 3.12 to 3.14 square passed and exited cleanly on 6.12.0, but both 3.11 squares still abort: a None refcount underflow that is harmless where None is immortal. The pin now takes 6.12.0 only from 3.12 on. --- .github/workflows/dev.yml | 2 +- .github/workflows/quality.yml | 2 +- CHANGELOG.md | 8 +++++--- dev.toml | 2 +- dev_requirements.txt | 3 ++- pyproject.toml | 2 +- requirements.txt | 3 ++- 7 files changed, 13 insertions(+), 9 deletions(-) diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index a0fc90ef6..e455015ac 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -79,7 +79,7 @@ jobs: shell: bash # The same line as quality.yml (test_dev_release.py compares them). # Quoted: `--only-binary :all:` puts a colon-space inside the scalar. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 'PySide6==6.12.0; python_version >= \"3.12\"' 'PySide6==6.11.2; python_version < \"3.12\"' radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" # No path argument: the paths come from `testpaths` in pyproject.toml, # and an argument would drop the flow_control tests. Linux runs under a diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 9461a63a3..e719ca294 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -149,7 +149,7 @@ jobs: shell: bash # Quoted: `--only-binary :all:` puts a colon-space inside the # scalar, which YAML reads as a mapping and refuses. - run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 PySide6==6.12.0 radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" + run: "pip install --only-binary :all: ruff==0.16.0 bandit==1.9.4 pytest==9.1.1 pytest-timeout==2.4.0 pytest-rerunfailures==16.7 coverage==7.15.4 'PySide6==6.12.0; python_version >= \"3.12\"' 'PySide6==6.11.2; python_version < \"3.12\"' radon==6.0.1 fastapi==0.143.0 starlette==1.7.0 uvicorn==0.54.0 httpx==0.28.1" - name: Verify native diagnostics runner (Linux) if: runner.os == 'Linux' diff --git a/CHANGELOG.md b/CHANGELOG.md index acd34034d..2f369c933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,11 @@ ## [Unreleased] -- The `gui` extra pins PySide6 6.12.0 again (it was held at 6.11.2 because the test process - crashed at interpreter exit under 6.12; the cause, tabs kept alive by slots holding - themselves, was fixed in U-20261114-44). Dependabot no longer ignores 6.12.0. +- The `gui` extra pins PySide6 6.12.0 again on Python 3.12 and later (it was held at 6.11.2 + because the test process crashed at interpreter exit under 6.12; the cause, tabs kept alive + by slots holding themselves, was fixed in U-20261114-44). Python 3.11 keeps 6.11.2: under + 6.12.0 its CI squares still abort (a `None` refcount underflow, harmless where `None` is + immortal). Dependabot no longer ignores 6.12.0. - GUI: no tab keeps itself alive any more. Lambdas over `self` connected to Qt signals -- one per Script Builder Add-step action (714), the Triggers tab's two Browse buttons, the step form's diff --git a/dev.toml b/dev.toml index 2a6375fc2..9a9a1b279 100644 --- a/dev.toml +++ b/dev.toml @@ -85,7 +85,7 @@ find = { namespaces = false } ] [project.optional-dependencies] -gui = ["PySide6==6.12.0"] +gui = ["PySide6==6.12.0; python_version >= '3.12'", "PySide6==6.11.2; python_version < '3.12'"] webrtc = ["aiortc>=1.14.0", "av>=14.0.0"] signaling = ["fastapi>=0.115", "starlette>=1.0.1", "uvicorn>=0.32"] discovery = ["zeroconf>=0.149.16"] diff --git a/dev_requirements.txt b/dev_requirements.txt index 0520862cb..a3d2bb53c 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -4,7 +4,8 @@ build twine sphinx sphinx-rtd-theme -PySide6==6.12.0 +PySide6==6.12.0; python_version >= '3.12' +PySide6==6.11.2; python_version < '3.12' mss==10.2.0 defusedxml==0.7.1 diff --git a/pyproject.toml b/pyproject.toml index 268bfc955..e2e5e24e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -110,7 +110,7 @@ find = { namespaces = false } ] [project.optional-dependencies] -gui = ["PySide6==6.12.0"] +gui = ["PySide6==6.12.0; python_version >= '3.12'", "PySide6==6.11.2; python_version < '3.12'"] webrtc = ["aiortc>=1.14.0", "av>=14.0.0"] signaling = ["fastapi>=0.115", "starlette>=1.0.1", "uvicorn>=0.32"] discovery = ["zeroconf>=0.149.16"] diff --git a/requirements.txt b/requirements.txt index b51e3948b..d7261959f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,5 @@ je_auto_control>=1.0.4 # replaced that entry. A direct requirement does. pillow>=12.3.0 mss==10.2.0 -PySide6==6.12.0 +PySide6==6.12.0; python_version >= '3.12' +PySide6==6.11.2; python_version < '3.12' From 57b7f62ab5cf4ace36490f6d9e7e576c5893af2b Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 09:56:00 +0800 Subject: [PATCH 116/161] Use raw strings for the Windows paths in the CI diagnostics test The two assertions on the crash-dump step spelled LocalDumps\python.exe and autocontrol-native\dumps with a single backslash, which Python 3.11 reports as invalid escape sequences. --- test/unit_test/headless/test_ci_native_diagnostics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unit_test/headless/test_ci_native_diagnostics.py b/test/unit_test/headless/test_ci_native_diagnostics.py index b1e9f4d88..02f0f4307 100644 --- a/test/unit_test/headless/test_ci_native_diagnostics.py +++ b/test/unit_test/headless/test_ci_native_diagnostics.py @@ -123,5 +123,5 @@ def test_ci_workflows_keep_native_diagnostics_after_failure(name): dumps = next(step for step in steps if step.get('name') == 'Keep native crash dumps (Windows)') assert dumps['if'] == "runner.os == 'Windows'" assert steps.index(dumps) < steps.index(runner) - assert 'LocalDumps\python.exe' in dumps['run'] and 'DumpFolder' in dumps['run'] - assert "autocontrol-native\dumps" in dumps['run'] and upload['with']['path'].endswith('autocontrol-native') + assert r'LocalDumps\python.exe' in dumps['run'] and 'DumpFolder' in dumps['run'] + assert r"autocontrol-native\dumps" in dumps['run'] and upload['with']['path'].endswith('autocontrol-native') From 1d0b0f50c373a9e2ac22cdb1d97e84338043898c Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 10:54:07 +0800 Subject: [PATCH 117/161] Record the PySide6 6.12.0 pin on 3.12+ and the 3.11 follow-up The trial ran clean on every 3.12+ square, so the decision is settled; what remains is unifying the pin once a 6.12.x runs clean on 3.11. --- Progress.md | 26 +++++++++----------------- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Progress.md b/Progress.md index 193bc956a..2898019cb 100644 --- a/Progress.md +++ b/Progress.md @@ -208,23 +208,15 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD --- -## PySide6 6.12:升級回 6.12 前須在 CI 全矩陣重驗 - -`DECIDE` — 結束時崩潰的 closure 已找到並修正(U-20261114-44):Qt 連線從 C++ 端持有 slot, -`ScriptBuilderTab` 每個 Add-step 動作一個捕捉 `self` 的 lambda(714 個)、Triggers 的兩個瀏覽 lambda, -以及 Live HUD 與 Presence 連到 `destroyed` 的 closure,讓分頁一直活到結束,Qt 拆除時在 C++ 解構子裡放掉最後一個參考、 -把分頁刪第二次。本機 PySide6 6.12.0 的 GUI 子集(742 個測試)修正前每次結束都 access violation,修正後兩次都正常結束; -`test_gui_tab_not_kept_alive.py` 守住每個分頁都能被回收且直譯器正常結束。 -維護者 2026-11-14 固定在 PySide6 6.11.2(U-20261114-03;dependabot 忽略 6.12.0)。是否升級回 6.12: -須在 PR 上以 6.12 跑完整矩陣(含 `docker.yml`)確認每一格結束時都不再崩潰;其他平台與完整套件尚未以 6.12 重驗。 - 試驗分支 `trial/pyside6-6.12`(2026-11-15,維護者決定):草稿 PR #554 進 dev(`dev.yml`,並手動觸發 `quality.yml`)、 - 只跑 CI 的草稿 PR #555 進 main(`docker.yml`、`stable.yml`,看完結果即關閉)。全部格子都正常結束才合併 #554。 - `quality.yml`(run 43599637920)結果:所有 3.12/3.13/3.14 格子(Windows、Ubuntu、macOS)通過,結束時不再崩潰; - 兩個 3.11 格子仍失敗——Ubuntu 3.11 的 `test_gui_page_widths.py` 探針子程序在建構 `flakiness_tab` 時 - `Fatal Python error: none_dealloc`(None 的參考計數被多減一次;3.12 起 None 是 immortal,所以只有 3.11 會死), - Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_and_a_disconnect_is_not` 中段 abort。 - 本機 Windows 3.11.9 + 6.12.0 單獨重跑這兩個檔案(含 webrtc)各 3~5 次都通過,逐一建構所有分頁、Qt 訊息處理器與常用 API - 也量不到 None 參考計數漂移;尚未找到減少 None 的呼叫。可選:維持 6.11.2;或只對 Python ≥ 3.12 改用 6.12(3.11 留在 6.11.2)。 +## PySide6 6.12:Python 3.11 仍固定在 6.11.2 + +`TODO` — `gui` extra 自 U-20261115-01 起依直譯器分開固定:Python ≥ 3.12 用 PySide6 6.12.0,3.11 留在 6.11.2 +(`pyproject.toml`、`dev.toml`、`requirements.txt`、`dev_requirements.txt`、`dev.yml` 與 `quality.yml` 的安裝行都帶環境標記)。 +原因:6.12.0 在 CI 的 3.11 格子會 abort——Ubuntu 3.11 的 `test_gui_page_widths.py` 探針子程序建構 `flakiness_tab` 時 +`Fatal Python error: none_dealloc`(None 的參考計數被多減一次;3.12 起 None 是 immortal,所以只有 3.11 會死), +Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_and_a_disconnect_is_not` 中段 abort(run 43599637920)。 +本機 Windows 3.11.9 + 6.12.0 重跑這兩個檔案各 3~5 次都通過,尚未找到減少 None 的呼叫。 +待辦:之後的 6.12.x(或 3.11 支援結束)時,在 3.11 格子以新版重跑完整矩陣;都正常結束就把兩行標記合回單一固定版本。 --- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 5e07ee8d7..41fc36fba 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -640,3 +640,10 @@ - **Tests:** new `test_gui_tab_not_kept_alive.py` (in a child interpreter: every registered tab, dropped and disposed-and-deleted, is collected; 20 dropped Script Builder tabs and a natural exit return 0; it names all five tabs on the old code). Builder, script, HUD, presence, triggers, window, listener, one-time, step-form and GUI tests: 2734 passed, 87 skipped before Window Manager's `dispose()`, whose dispose and lifecycle guards then passed. - **Files:** `gui/script_builder/builder_tab.py`, `gui/script_builder/step_form_view.py`, `gui/script_builder/one_time_dialog.py`, `gui/triggers_tab.py`, `gui/live_hud_tab.py`, `gui/presence_tab.py`, `gui/window_tab.py`, the test, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › *PySide6 6.12* (`DECIDE`: upgrade after a full-matrix run on 6.12). + +## U-20261115-01 · 2026-11-15 · PySide6 6.12.0 on Python 3.12+, 6.11.2 kept on 3.11 · #done #gui #pyside6 #dependencies + +- **What:** the `DECIDE` item `Progress.md` › *PySide6 6.12* left after U-20261114-44: whether to move back to 6.12 once a full CI matrix ran clean on it. The maintainer chose a trial branch: `trial/pyside6-6.12`, draft PR #554 into `dev` (`dev.yml`, plus `quality.yml`) and a CI-only draft PR #555 into `main` (`docker.yml`, `stable.yml`). On 6.12.0 everywhere (run 43599637920) every 3.12 / 3.13 / 3.14 square on Windows, Ubuntu and macOS passed and exited cleanly, so the exit crash is gone; both 3.11 squares still aborted (Ubuntu: `Fatal Python error: none_dealloc` in the `test_gui_page_widths.py` probe child while building `flakiness_tab`, a None refcount underflow that only kills 3.11 because None is immortal from 3.12; Windows: an abort inside `test_gui_offthread_sites.py`), neither reproducible locally on Windows 3.11.9. The maintainer chose 6.12.0 on 3.12+ only. +- **Change:** the `gui` extra in `pyproject.toml` and `dev.toml` is `PySide6==6.12.0; python_version >= '3.12'` plus `PySide6==6.11.2; python_version < '3.12'`; `requirements.txt`, `dev_requirements.txt` and the install lines of `dev.yml` and `quality.yml` carry the same markers (the 3.12 `typing-extras` job installs 6.12.0); the dependabot ignore for 6.12.0 is removed; `CHANGELOG.md` records the pin. With the markers, run 43659573836 and the PR checks passed on every square; the one failure, Windows 3.11 on 6.11.2 (`test_agent_presence_windows.py`, "physical presence request deadline exhausted" on a 59-minute runner), was a timing flake that passes locally five of five and passed on rerun. Merged as #554 (`e65857df`); #555 closed. +- **Files:** `pyproject.toml`, `dev.toml`, `requirements.txt`, `dev_requirements.txt`, `.github/workflows/dev.yml`, `.github/workflows/quality.yml`, `.github/dependabot.yml`, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › *PySide6 6.12:Python 3.11 仍固定在 6.11.2* (`TODO`: unify the pin once a later 6.12.x runs clean on 3.11). diff --git a/docs/updates/README.md b/docs/updates/README.md index 6080281c5..3245ea854 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-01 | 2026-11-15 | PySide6 6.12.0 on Python 3.12+, 6.11.2 kept on 3.11 | #done #gui #pyside6 #dependencies | [2026-11-b](2026-11-b.md) | | U-20261114-44 | 2026-11-14 | The PySide6 6.12 exit crash: tabs no longer keep themselves alive | #done #gui #pyside6 | [2026-11-b](2026-11-b.md) | | U-20261114-43 | 2026-11-14 | Network calls and signaling waits stop with their task | #done #remote-desktop #network | [2026-11-b](2026-11-b.md) | | U-20261114-42 | 2026-11-14 | close_admission(): media owners stop taking anything new at once | #done #remote-desktop #lifecycle | [2026-11-b](2026-11-b.md) | From 13cfe8c267d96406e969cf8b5aa1eec0c736e10c Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 10:55:32 +0800 Subject: [PATCH 118/161] Lock dnspython 2.9.2 for its memory and CPU use advisory Dependabot alert 177 flags dnspython below 2.9.2 in uv.lock. The relock also records the gui extra's split PySide6 pin, which the lock still showed as a single 6.12.0. --- CHANGELOG.md | 4 ++ docs/updates/2026-11-b.md | 8 +++ docs/updates/README.md | 1 + pyproject.toml | 5 +- uv.lock | 114 ++++++++++++++++++++++++++++++++++---- 5 files changed, 118 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f369c933..34f15f139 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- `uv.lock` resolves dnspython 2.9.2 (the `[tool.uv]` floor is now `>=2.9.2`), which fixes the + excessive memory and CPU use advisory in earlier releases; the wheel metadata is unchanged. The + lock also records the `gui` extra's split PySide6 pin (6.12.0 on 3.12+, 6.11.2 on 3.11). + - The `gui` extra pins PySide6 6.12.0 again on Python 3.12 and later (it was held at 6.11.2 because the test process crashed at interpreter exit under 6.12; the cause, tabs kept alive by slots holding themselves, was fixed in U-20261114-44). Python 3.11 keeps 6.11.2: under diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 41fc36fba..92602b0b7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -647,3 +647,11 @@ - **Change:** the `gui` extra in `pyproject.toml` and `dev.toml` is `PySide6==6.12.0; python_version >= '3.12'` plus `PySide6==6.11.2; python_version < '3.12'`; `requirements.txt`, `dev_requirements.txt` and the install lines of `dev.yml` and `quality.yml` carry the same markers (the 3.12 `typing-extras` job installs 6.12.0); the dependabot ignore for 6.12.0 is removed; `CHANGELOG.md` records the pin. With the markers, run 43659573836 and the PR checks passed on every square; the one failure, Windows 3.11 on 6.11.2 (`test_agent_presence_windows.py`, "physical presence request deadline exhausted" on a 59-minute runner), was a timing flake that passes locally five of five and passed on rerun. Merged as #554 (`e65857df`); #555 closed. - **Files:** `pyproject.toml`, `dev.toml`, `requirements.txt`, `dev_requirements.txt`, `.github/workflows/dev.yml`, `.github/workflows/quality.yml`, `.github/dependabot.yml`, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › *PySide6 6.12:Python 3.11 仍固定在 6.11.2* (`TODO`: unify the pin once a later 6.12.x runs clean on 3.11). + +## U-20261115-02 · 2026-11-15 · dnspython 2.9.2 in uv.lock for Dependabot alert 177 · #release #security #dependencies + +- **What:** Dependabot alert 177 (high, opened 2026-11-14): "dnspython has excessive memory and CPU use", affecting `< 2.9.2`, raised against `uv.lock`, which resolved the transitive dnspython at 2.9.0. +- **Change:** the lock-only floor in `pyproject.toml` `[tool.uv] constraint-dependencies` goes from `dnspython>=2.9.0` to `>=2.9.2`, and `uv lock --upgrade-package dnspython` (uv 0.12.23) moved only dnspython to 2.9.2. The same relock brought `uv.lock` in line with the `gui` extra of U-20261115-01: it still recorded a single PySide6 6.12.0, and now holds 6.12.0 for Python 3.12+ and 6.11.2 (with its addons, essentials and shiboken6) for 3.11. The wheel metadata does not change. `CHANGELOG.md` records it. +- **Tests:** `test_crypto_fifty_install_contract.py` (reads `uv.lock`) and `test_dev_toml_parity.py`: 15 passed. +- **Files:** `pyproject.toml`, `uv.lock`, `CHANGELOG.md`. +- **Open items:** none. The alert closes when this reaches `main` (PR #552). diff --git a/docs/updates/README.md b/docs/updates/README.md index 3245ea854..a219d2d4d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-02 | 2026-11-15 | dnspython 2.9.2 in uv.lock for Dependabot alert 177 | #release #security #dependencies | [2026-11-b](2026-11-b.md) | | U-20261115-01 | 2026-11-15 | PySide6 6.12.0 on Python 3.12+, 6.11.2 kept on 3.11 | #done #gui #pyside6 #dependencies | [2026-11-b](2026-11-b.md) | | U-20261114-44 | 2026-11-14 | The PySide6 6.12 exit crash: tabs no longer keep themselves alive | #done #gui #pyside6 | [2026-11-b](2026-11-b.md) | | U-20261114-43 | 2026-11-14 | Network calls and signaling waits stop with their task | #done #remote-desktop #network | [2026-11-b](2026-11-b.md) | diff --git a/pyproject.toml b/pyproject.toml index e2e5e24e5..7255b4211 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -126,9 +126,10 @@ locale = ["babel>=2.12"] audio = ["pycaw>=20240210"] # Lock-only security floor for a transitive dependency (uv.lock; the wheel -# metadata is unchanged). dnspython 2.9.0 fixes the advisory in 2.8.0. +# metadata is unchanged). dnspython 2.9.0 fixes the advisory in 2.8.0, and 2.9.2 +# the excessive memory and CPU use in earlier releases. [tool.uv] -constraint-dependencies = ["dnspython>=2.9.0"] +constraint-dependencies = ["dnspython>=2.9.2"] # CLAUDE.md's 120-character line limit. Without this table CI's `ruff check` # ran the default rule set, which has no E501, so the documented limit was diff --git a/uv.lock b/uv.lock index d25cefd26..2a658ef14 100644 --- a/uv.lock +++ b/uv.lock @@ -1,9 +1,13 @@ version = 1 revision = 5 requires-python = ">=3.11" +resolution-markers = [ + "python_full_version >= '3.12'", + "python_full_version < '3.12'", +] [manifest] -constraints = [{ name = "dnspython", specifier = ">=2.9.0" }] +constraints = [{ name = "dnspython", specifier = ">=2.9.2" }] [[package]] name = "aioice" @@ -321,11 +325,11 @@ wheels = [ [[package]] name = "dnspython" -version = "2.9.0" +version = "2.9.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ef/4a/50822184bd67cc6493f0fb6a880749158fcd31ab3fa07409acfd91f9fc85/dnspython-2.9.0.tar.gz", hash = "sha256:b44dc6b18f07a8b1c56676a19fbfdb5209415b046a9cece286baafa87ff3f7f1", size = 423560, upload-time = "2026-10-09T00:07:24.352Z" } +sdist = { url = "https://files.pythonhosted.org/packages/76/49/900383b471c645a3c397f47b3211d1fcecb3a540c98f683494cdf86b33de/dnspython-2.9.2.tar.gz", hash = "sha256:8d4d39a513e649d634004ce4d39ade2352efcea472a0247535a5c2d18a9d7ba9", size = 455484, upload-time = "2026-11-03T23:56:53.601Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/10/02/cdcc9b7c051786a103c3b09e1003a82fa0c66bcb91ffbdabcfbf7b4163b9/dnspython-2.9.0-py3-none-any.whl", hash = "sha256:9a4aedb833c3c1b49214d04d44d3032ab7a9135f7c1d29a549b4ff78fd82fda9", size = 354822, upload-time = "2026-10-09T00:07:22.622Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0c/5346358b3a20275d256978c35203ddc2c8617f78c1b23795b79ba22ced6d/dnspython-2.9.2-py3-none-any.whl", hash = "sha256:af15f7d385a6ae2fb35a796fde2138004c8c42c7389090e2addc83e3b3340fd8", size = 360455, upload-time = "2026-11-03T23:56:52.088Z" }, ] [[package]] @@ -437,7 +441,8 @@ fuzzy = [ { name = "rapidfuzz" }, ] gui = [ - { name = "pyside6" }, + { name = "pyside6", version = "6.11.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "pyside6", version = "6.12.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, ] locale = [ { name = "babel" }, @@ -481,7 +486,8 @@ requires-dist = [ { name = "pyobjc", marker = "sys_platform == 'darwin'", specifier = "==12.2.2" }, { name = "pyobjc-core", marker = "sys_platform == 'darwin'", specifier = "==12.2.2" }, { name = "pypdf", marker = "extra == 'pdf'", specifier = ">=6.21.4" }, - { name = "pyside6", marker = "extra == 'gui'", specifier = "==6.12.0" }, + { name = "pyside6", marker = "python_full_version >= '3.12' and extra == 'gui'", specifier = "==6.12.0" }, + { name = "pyside6", marker = "python_full_version < '3.12' and extra == 'gui'", specifier = "==6.11.2" }, { name = "python-docx", marker = "extra == 'office'", specifier = ">=1.1" }, { name = "python-pptx", marker = "extra == 'office'", specifier = ">=0.6" }, { name = "python-xlib", marker = "platform_system == 'FreeBSD' or platform_system == 'NetBSD' or platform_system == 'OpenBSD' or sys_platform == 'linux'", specifier = "==0.33" }, @@ -4038,13 +4044,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3f/4b/77e8ad4ac42c9d93600f40541a50e9feb3a61d2bbee2d76f659346072051/pypdf-6.21.4-py3-none-any.whl", hash = "sha256:33e4fb41ca352810eb4e9838aa0d82d6888a5f8bf682f43e99cce5faa666255c", size = 410430, upload-time = "2026-10-28T17:00:53.146Z" }, ] +[[package]] +name = "pyside6" +version = "6.11.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.12'", +] +dependencies = [ + { name = "pyside6-addons", version = "6.11.2", source = { registry = "https://pypi.org/simple" } }, + { name = "pyside6-essentials", version = "6.11.2", source = { registry = "https://pypi.org/simple" } }, + { name = "shiboken6", version = "6.11.2", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/b5/99ff75f604d69eda1c5d1fe85cc43fb697d95eabc30ba86af099c2ddcd96/pyside6-6.11.2-cp310-abi3-macosx_13_0_universal2.whl", hash = "sha256:13a3c79816879d9743672a669f1988f74459a78f89a97a2624fae4fe059ffa3a", size = 571875, upload-time = "2026-08-18T06:37:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/b2/fe/968844def58150a41568b505edca0d68df6901b20ea4222ccb0c069cc703/pyside6-6.11.2-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:dc6d03990489a5085842770718392ef5de36352d8f608d9a9fe03e60af4d7b66", size = 572120, upload-time = "2026-08-18T06:37:30.298Z" }, + { url = "https://files.pythonhosted.org/packages/5e/5c/f4ecc6defaec645e5ac3ca2f99e3da286a28d1c647c2d10b584e0392b94c/pyside6-6.11.2-cp310-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:57fe867a6c93821a085d74e8a26f863fc2363516848181c466032595b33b1729", size = 572121, upload-time = "2026-08-18T06:37:32.383Z" }, + { url = "https://files.pythonhosted.org/packages/94/fe/4aea9d30300fff4cda9bb729c1363b9e1095a8544e0d6b57065465e16599/pyside6-6.11.2-cp310-abi3-win_amd64.whl", hash = "sha256:3201d67e3c10be2eaedd3910ff0f02351eca7e88c95a291cde5e7f2f55ef207f", size = 578382, upload-time = "2026-08-18T06:37:34.385Z" }, + { url = "https://files.pythonhosted.org/packages/26/b0/8e2fb01e9ee15ad29fe10d0dd2d37f503e4aa3714c9fbb07aca380618de7/pyside6-6.11.2-cp310-abi3-win_arm64.whl", hash = "sha256:0444ac71d0791a19bded35f6d9a94515941f23a6eb7098ca45a1b64a338be697", size = 561768, upload-time = "2026-08-18T06:37:36.437Z" }, +] + [[package]] name = "pyside6" version = "6.12.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.12'", +] dependencies = [ - { name = "pyside6-addons" }, - { name = "pyside6-essentials" }, + { name = "pyside6-addons", version = "6.12.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyside6-essentials", version = "6.12.0", source = { registry = "https://pypi.org/simple" } }, { name = "pyside6-pdf" }, { name = "pyside6-webengine" }, ] @@ -4056,12 +4085,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5f/2e/3ebafaf7f4ccea6f6ea9d017f7fc7d9484b79e6b31d1cb92f5f5262055f0/pyside6-6.12.0-cp310-abi3-win_arm64.whl", hash = "sha256:22e2ec6407f32b61955a28f91ab55676e60017210285c28f0c381bfeed389414", size = 562743, upload-time = "2026-10-08T09:11:21.552Z" }, ] +[[package]] +name = "pyside6-addons" +version = "6.11.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.12'", +] +dependencies = [ + { name = "pyside6-essentials", version = "6.11.2", source = { registry = "https://pypi.org/simple" } }, + { name = "shiboken6", version = "6.11.2", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/91/339fe9f7c94163815004ccd6b5c58b926b2dfb4e51c3b5563d412eab151f/pyside6_addons-6.11.2-cp310-abi3-macosx_13_0_universal2.whl", hash = "sha256:354c574a839f7d0751960ba03f33bec87c95e0f2796dca3287f54d03abe97dac", size = 332047075, upload-time = "2026-08-18T06:35:33.037Z" }, + { url = "https://files.pythonhosted.org/packages/28/cd/ce470e20f68901f4dfa5f742d6a3a58ba865684a232e4b87d5a1a2179cc0/pyside6_addons-6.11.2-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:a8b00956925fbdeffc7052cf933506391289f35ac4f3f71a0a167ec195cd47b4", size = 175062576, upload-time = "2026-08-18T06:35:45.583Z" }, + { url = "https://files.pythonhosted.org/packages/11/bd/f725a8984703612c72cd17d0871d047132bacaccc13fc0d288a5e8a37dad/pyside6_addons-6.11.2-cp310-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:a2ca3c73e5f060d4aca49451abd9fba68dd0e1c66ff40cea3a1fe0415def579a", size = 170827254, upload-time = "2026-08-18T06:35:56.675Z" }, + { url = "https://files.pythonhosted.org/packages/fb/c1/08bf6594101b42fc88834009f1dac59a983c5b6805c62c5081f077d09b4a/pyside6_addons-6.11.2-cp310-abi3-win_amd64.whl", hash = "sha256:f449ea4431da20e7b86752cca8d166f93434516fe417f981c27e5f8e1b554407", size = 168208836, upload-time = "2026-08-18T06:36:07.295Z" }, + { url = "https://files.pythonhosted.org/packages/26/60/e4b7f09343e9f29e565f488fb44c4f1fe260db481ba2c08ad8a1a7d48216/pyside6_addons-6.11.2-cp310-abi3-win_arm64.whl", hash = "sha256:d5606af369484b862b4d5741cfc179e19d2b8819c3e04d210b8188e0c9f85988", size = 35807245, upload-time = "2026-08-18T06:36:12.485Z" }, +] + [[package]] name = "pyside6-addons" version = "6.12.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.12'", +] dependencies = [ - { name = "pyside6-essentials" }, + { name = "pyside6-essentials", version = "6.12.0", source = { registry = "https://pypi.org/simple" } }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c3/16/c401d6455dbf49df37a8b142883e12d446abf51919c3e0ef5d9570e29160/pyside6_addons-6.12.0-cp310-abi3-macosx_14_0_universal2.whl", hash = "sha256:1d9bcd294ce1c9829194c7d13b01f771a2254b86cb3462cc3399321d2797fdac", size = 90545550, upload-time = "2026-10-08T09:08:14.778Z" }, @@ -4071,12 +4122,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ea/73/860ab764368cd59b1a09cb891a9a4519425395ad1f6c47d83fde908fe603/pyside6_addons-6.12.0-cp310-abi3-win_arm64.whl", hash = "sha256:3c079cbaad2ad28bc5bfa92fd6bac4ba28d622b825825e3b4220f0682599b2db", size = 35940682, upload-time = "2026-10-08T09:08:35.424Z" }, ] +[[package]] +name = "pyside6-essentials" +version = "6.11.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.12'", +] +dependencies = [ + { name = "shiboken6", version = "6.11.2", source = { registry = "https://pypi.org/simple" } }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/16/0b7ecf89ebada82ed0430be33809ff325761ece83104f8635b1bd101fcd0/pyside6_essentials-6.11.2-cp310-abi3-macosx_13_0_universal2.whl", hash = "sha256:77795c145202e65a78d88f7cd409d186e3ba23d159bdb3ba2dcd159ae5e5f0d9", size = 110800753, upload-time = "2026-08-18T06:36:33.674Z" }, + { url = "https://files.pythonhosted.org/packages/0e/1a/84a84bbc75835ee88abdcb66eb875b8e1a21834af9b833bc1893f2c1bfaf/pyside6_essentials-6.11.2-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:aaf9f25f0f324874085fa5b26a610318db8a8e243cf85bb3e5400595191c7778", size = 80108947, upload-time = "2026-08-18T06:36:40.637Z" }, + { url = "https://files.pythonhosted.org/packages/60/4c/d92b08a2151d095b9a3725fa0e71b215ec686d40bbd5d8b702d21a9b5eaa/pyside6_essentials-6.11.2-cp310-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:d3ec6e1885c46e57f16364f38ea8040ffc5dc0b18341058f608fede3ba930567", size = 79575497, upload-time = "2026-08-18T06:36:46.97Z" }, + { url = "https://files.pythonhosted.org/packages/dc/09/d2662684aee4d3f027ff9b1e965f22301bc28ffc5b7f167658508e4475dc/pyside6_essentials-6.11.2-cp310-abi3-win_amd64.whl", hash = "sha256:c8a29def77032773a30879f7f24415b5395ad08592d147c170824ef4c735dfc1", size = 76913043, upload-time = "2026-08-18T06:36:54.038Z" }, + { url = "https://files.pythonhosted.org/packages/cd/87/4dd2a6468cea600da1fcf9c7f02bc248eeaa98cdc75658e48e669d95326a/pyside6_essentials-6.11.2-cp310-abi3-win_arm64.whl", hash = "sha256:fadd75c5c20800d64dd0a586ea8cb337c5e630aa2246df0e5105738afa46e02c", size = 58125520, upload-time = "2026-08-18T06:36:59.073Z" }, +] + [[package]] name = "pyside6-essentials" version = "6.12.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.12'", +] dependencies = [ - { name = "shiboken6" }, + { name = "shiboken6", version = "6.12.0", source = { registry = "https://pypi.org/simple" } }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/e1/90/d528f8dd3f9f20712bc719e10c698d27c998e1dd76ed3f33b6fb606d0972/pyside6_essentials-6.12.0-cp310-abi3-macosx_14_0_universal2.whl", hash = "sha256:0867b709a724db28b161227c7d6ecb5ed10cc09226a53542417ac6dee1308239", size = 116002775, upload-time = "2026-10-08T09:09:54.453Z" }, @@ -4091,7 +4163,7 @@ name = "pyside6-pdf" version = "6.12.0.140" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyside6-essentials" }, + { name = "pyside6-essentials", version = "6.12.0", source = { registry = "https://pypi.org/simple" } }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/58/33/23949c3b48af4b96b618e0502b7313ac52a782615db8dceae5bc2c516831/pyside6_pdf-6.12.0.140-cp310-abi3-macosx_14_0_universal2.whl", hash = "sha256:74287989dd24a82ac1604e27a2d4530a0ab71ff03cdf878c16fdbcf5144373fb", size = 8644803, upload-time = "2026-10-08T09:07:36.716Z" }, @@ -4106,7 +4178,7 @@ name = "pyside6-webengine" version = "6.12.0.140" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyside6-addons" }, + { name = "pyside6-addons", version = "6.12.0", source = { registry = "https://pypi.org/simple" } }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/08/37/3b50067bdcba5c22e20a8d7a029c919850c6d94f8398175b330c3b8765ad/pyside6_webengine-6.12.0.140-cp310-abi3-macosx_14_0_universal2.whl", hash = "sha256:9a1de2da360d1817c08e9400a2a2fc5234beb3022a22123e15355169e183074e", size = 249778242, upload-time = "2026-10-08T09:06:03.602Z" }, @@ -4259,10 +4331,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/46/5f/4c174edad94f82de888ac00a5ddd8d07b35609b6c94f0bdf4d74af57703e/s3transfer-0.19.0-py3-none-any.whl", hash = "sha256:777cc2415536f1debadb5c2ef7779275d0fc0fe0e042411cdd6caebeb2685262", size = 90101, upload-time = "2026-06-16T19:44:50.439Z" }, ] +[[package]] +name = "shiboken6" +version = "6.11.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.12'", +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/44/11bf71c36e71936ab4e923e5dd23599dab527c4488b01860b0f689ce9947/shiboken6-6.11.2-cp310-abi3-macosx_13_0_universal2.whl", hash = "sha256:53659683b1f7a08e9f87eff9b1065f1ceb7110cd7a4bc09fdf5efe43d286604d", size = 476674, upload-time = "2026-08-18T06:37:11.526Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9a/f41bea4316d0c1bec4800842dcb4bd8fd3e29d6a79c496bc32e1aec42583/shiboken6-6.11.2-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:7a7a0a72a9ed26c9bf77d42246b1c736486befb8f31aa2fb29957ea4cdd1c1c2", size = 272435, upload-time = "2026-08-18T06:37:13.397Z" }, + { url = "https://files.pythonhosted.org/packages/56/05/79ed0697515d4fc7435459e4ed4c4a3b5621a55b7c91d0f3f2cc3d617aa0/shiboken6-6.11.2-cp310-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:4bbbd6fa4d7cff5ec5e12bc4c10e1d845fa30c89457ecb13cc64f7bddb77f6f9", size = 270668, upload-time = "2026-08-18T06:37:15.025Z" }, + { url = "https://files.pythonhosted.org/packages/ce/6b/fee1b4814317e4664e318644c9c007676c65a71e5b2b9d3ac4121a94dc0a/shiboken6-6.11.2-cp310-abi3-win_amd64.whl", hash = "sha256:6ab0eba1c904455df621f9a6df3ca2bb896bab8670572d2bc4e37804ae91f19a", size = 1226578, upload-time = "2026-08-18T06:37:18.002Z" }, + { url = "https://files.pythonhosted.org/packages/4d/b5/80c4e5aafeb8ac777cf5a1becfe87ac7197c35051df00b5f7819787e09d5/shiboken6-6.11.2-cp310-abi3-win_arm64.whl", hash = "sha256:97c49432488df958f0308736f3d15b6915d8826fc380af17bb4b9ec5c4a5e81b", size = 1784669, upload-time = "2026-08-18T06:37:21.046Z" }, +] + [[package]] name = "shiboken6" version = "6.12.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.12'", +] wheels = [ { url = "https://files.pythonhosted.org/packages/b5/45/11536fba5f50a57671eb14441c6098096f3e57074e54c9d7d66039a5831e/shiboken6-6.12.0-cp310-abi3-macosx_14_0_universal2.whl", hash = "sha256:47105e05baf57d35453e07d240bbe59cb4b8d9565377ea5134ff9fb37d4f5c02", size = 479653, upload-time = "2026-10-08T09:10:41.506Z" }, { url = "https://files.pythonhosted.org/packages/49/c2/a04fa003b4360e99d8e3fc2829abacf37396ace63ea1cd616402209ec7c6/shiboken6-6.12.0-cp310-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:3bde565bb0890044b5c7f63808adddede5abc241e9395a2bfed61919884d6240", size = 279268, upload-time = "2026-10-08T09:10:42.982Z" }, From a9f1429f3ce8f2618789f164b659e33846211811 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 11:06:51 +0800 Subject: [PATCH 119/161] Record an RBAC decision for every AC_* command 817 commands had no entry in COMMAND_CAPABILITIES and relied on the submitting surface without anyone having decided that was right. Each was reviewed against the admin-only state the table protects; none needed raising, and a test now fails on a command in neither table. The review also found ac_journal_read's drive_input override sitting above the DATA_TOOLS spread, where it was silently overwritten. --- CHANGELOG.md | 7 + Progress.md | 2 +- architecture.md | 6 + architecture_explore.md | 22 +- docs/updates/2026-11-b.md | 10 + docs/updates/README.md | 1 + je_auto_control/utils/rbac/command_review.py | 252 ++++++++++++++++++ je_auto_control/utils/rbac/policy.py | 6 +- .../utils/remote_desktop/presence.py | 10 +- pyproject.toml | 1 + .../headless/test_rbac_command_review.py | 73 +++++ 11 files changed, 372 insertions(+), 18 deletions(-) create mode 100644 je_auto_control/utils/rbac/command_review.py create mode 100644 test/unit_test/headless/test_rbac_command_review.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 34f15f139..3cba6162f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +- RBAC: every `AC_*` command now has a recorded decision. The 817 commands not in + `COMMAND_CAPABILITIES` were reviewed as reaching nothing admin-only and are listed in + `utils/rbac/command_review.py` (33 of them with the reason); a new command in neither table + fails CI. Nothing changes at run time for them. `ac_journal_read` now needs `drive_input` + like `AC_journal_read`: its override sat above the `DATA_TOOLS` spread and was overwritten + (operators hold both capabilities, so no role gains or loses access). + - `uv.lock` resolves dnspython 2.9.2 (the `[tool.uv]` floor is now `>=2.9.2`), which fixes the excessive memory and CPU use advisory in earlier releases; the wheel metadata is unchanged. The lock also records the `gui` extra's split PySide6 pin (6.12.0 on 3.12+, 6.11.2 on 3.11). diff --git a/Progress.md b/Progress.md index 2898019cb..73f562bbc 100644 --- a/Progress.md +++ b/Progress.md @@ -135,7 +135,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - `ac_list_plugins` 的外掛 factory,以及 `ac_web_list_commands`/`ac_web_current_url` 的實際相依版本初始化契約尚待審查;目前不列入唯讀目錄,完整目錄仍要求 `read_data`。本機 sibling 原始碼不代表部署版本驗收。 - `ac_diagnose` 的預設 audit-log 初始化可能建立固定目錄及 SQLite schema;全域零寫入診斷與外部 SDK 初始化副作用仍未驗證。 - - 尚需完整審查未列入 `COMMAND_CAPABILITIES` 的 executor 指令;未列指令目前仍依賴提交入口授權,不能把已核對的指令視為完整分類。若改為執行時預設拒絕,須同時處理預檢中的動作清單與一般資料串列,避免誤拒正常資料。 + - executor 指令已全部分類(U-20261115-03:`utils/rbac/command_review.py`,新指令未分類時 CI 失敗;執行時仍不預設拒絕,維護者 2026-11-15 決定)。審查留下兩個設計問題(`DECIDE`):`AC_approval_approve`/`ac_approval_approve` 的 approver 是呼叫者給的字串而不是 RBAC 使用者,同一個 operator 換個名字就能核准自己的請求(目前主機上沒有東西依核准結果放行);presence 角色只是提示,沒有主機呼叫 `PresenceRegistry.can_control()`——哪天主機依角色擋輸入,presence 指令要升到 `manage_hosts`。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, diff --git a/architecture.md b/architecture.md index 56046197b..8556c0734 100644 --- a/architecture.md +++ b/architecture.md @@ -691,6 +691,12 @@ TCP client authentication marks rejection terminal before writing AUTH_FAIL. Adm reaping therefore releases its client slot before an immediate retry can arrive, while the separate handshake semaphore bounds outstanding cleanup and authentication threads. +Executor commands follow one rule: submitting an action list needs drive_input, and +the executor checks `COMMAND_CAPABILITIES` for every action, nested blocks and +parallel branches included. Every other `AC_*` command is reviewed in +`utils/rbac/command_review.py` as reaching nothing admin-only, and a test fails on a +command in neither table. + MCP capability policy uses an explicit reviewed screen/caller-data catalogue in `utils/rbac/tool_classification.py`; unknown read-only hints require read_data. Canonical aliases and stronger overrides share base and argument requirements at diff --git a/architecture_explore.md b/architecture_explore.md index 971c3ffe9..4ba67dfb5 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,543 | -| 程式碼總行數 | 237,357 | +| Python 模組總數(含周邊子專案) | 1,544 | +| 程式碼總行數 | 237,613 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,224 行。 +> 6 個套件、約 32,226 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,898 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,900 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,478 行。 +> 13 個套件、約 4,732 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -674,7 +674,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/governance/` | 243 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | -| `utils/rbac/` | 1,731 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data | +| `utils/rbac/` | 1,985 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data;command_review.py 記錄 `COMMAND_CAPABILITIES` 以外每個 `AC_*` 指令的審查(只需提交入口的 drive_input),新指令未分類時 CI 失敗 | | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,898 行/77 檔) +#### `utils/remote_desktop/`(16,900 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -846,7 +846,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `relay.py` | 316 | NAT 穿透失敗時的 TCP 中繼。 | | `fingerprint.py` | 246 | TOFU 主機指紋驗證。 | | `turn_config.py` | 249 | coturn 設定產生器。 | -| `presence.py` | 238 | 多檢視者的執行緒安全在場註冊表。 | +| `presence.py` | 240 | 多檢視者的執行緒安全在場註冊表。 | | `jpeg_recorder_encrypted.py` | 239 | AES-GCM 加密版 session 錄影。 | | `address_book.py` | 229 | 檢視端的主機通訊錄。 | | `audio.py` / `webrtc_audio.py` / `webrtc_mic.py` | 256 / 296 / 195 | 音訊擷取播放、音訊軌、麥克風上行。 | @@ -1551,7 +1551,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 166 | 43,906 | | `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,898 | +| `utils/remote_desktop/` | 77 | 16,900 | | `utils/executor/` | 11 | 10,752 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,006 | 103,229 | -| **總計** | **1,531** | **236,612** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,483 | +| **總計** | **1,532** | **236,868** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 92602b0b7..c0ec3edce 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -655,3 +655,13 @@ - **Tests:** `test_crypto_fifty_install_contract.py` (reads `uv.lock`) and `test_dev_toml_parity.py`: 15 passed. - **Files:** `pyproject.toml`, `uv.lock`, `CHANGELOG.md`. - **Open items:** none. The alert closes when this reaches `main` (PR #552). + +## U-20261115-03 · 2026-11-15 · Every AC_* command has an RBAC decision · #done #rbac #security + +- **What:** `Progress.md` › *這一輪修正留下的後續* › RBAC asked for a complete review of the executor commands missing from `COMMAND_CAPABILITIES`: 817 of 911. The maintainer chose to classify them and keep unlisted commands allowed at run time. The boundary that matters: submitting an action list needs `drive_input`, and the operator role holds `read_screen`, `read_data` and `drive_input`, so a command needs a table entry only when it reaches admin-only state (signing key, users, host administration, the servers the host runs, USB and egress policy, vault administration, the audit log, plug-in loading). +- **Review:** every name screened by keyword; every adapter's source scanned for the modules holding that state (signing, secrets, egress, USB ACL and passthrough, plug-ins, server registries, the admin console, the user store, the audit log); each candidate read. None needed raising. Reasons kept in `OPERATOR_NOTES` for 33: the signing-key pair (refuses an existing file and a verify-only endpoint; signing needs `sign_actions`), action-file encryption, approvals (nothing on the host consults the gate), secret leases (no value; redeeming is Python-only), secret, webhook and remote-host status (no tokens in the replies), the WebRTC host's offer and answer (the viewer still authenticates with the host's token), USB loopback and remote open (match their `drive_input` routes), egress check, plug-in listing, presence (advisory), ChatOps dispatch and `AC_parallel`. Probed under an operator context: a privileged command inside `AC_parallel`, `AC_loop`, `AC_retry`, `AC_try`, `AC_if_var`, `AC_while_var`, `AC_for_each`, a macro, `AC_run_stoppable`, `AC_execute_action`, `AC_execute_files` and ChatOps `/run` is refused by the executor's own check. +- **Found:** `TOOL_CAPABILITIES` set `"ac_journal_read": _DRIVE` above the `DATA_TOOLS` spread (2613101eb), which overwrote it with `read_data`; the override now sits with the others below the spread, so the tool agrees with `AC_journal_read`. No role holds one of the two without the other. `presence.py`'s docstring said the registry gates input dispatch; nothing calls `can_control()`, and it now says so. Two design questions go to `Progress.md`: the approver is a caller-supplied name, and presence roles are advisory. +- **Change:** new `utils/rbac/command_review.py` (`OPERATOR_COMMANDS`, 784 names; `OPERATOR_NOTES`, 33; strict mypy tier); `policy.py` points at it. `test_rbac_command_review.py`: every known command in exactly one table, no stale names, a listed command needs what its `ac_*` twin needs, no reviewed command has an admin-only twin, and the nested-block refusals (with an admin control reaching the patched `list_users`). +- **Tests:** the new file (5) and the RBAC, journal, read-only catalogue and presence tests: 702 passed. +- **Files:** `utils/rbac/command_review.py`, `utils/rbac/policy.py`, `utils/remote_desktop/presence.py`, `pyproject.toml`, the test, `architecture.md`, `architecture_explore.md`, `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › RBAC (`DECIDE`: approver identity; presence roles). diff --git a/docs/updates/README.md b/docs/updates/README.md index a219d2d4d..890cad394 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-03 | 2026-11-15 | Every AC_* command has an RBAC decision | #done #rbac #security | [2026-11-b](2026-11-b.md) | | U-20261115-02 | 2026-11-15 | dnspython 2.9.2 in uv.lock for Dependabot alert 177 | #release #security #dependencies | [2026-11-b](2026-11-b.md) | | U-20261115-01 | 2026-11-15 | PySide6 6.12.0 on Python 3.12+, 6.11.2 kept on 3.11 | #done #gui #pyside6 #dependencies | [2026-11-b](2026-11-b.md) | | U-20261114-44 | 2026-11-14 | The PySide6 6.12 exit crash: tabs no longer keep themselves alive | #done #gui #pyside6 | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/rbac/command_review.py b/je_auto_control/utils/rbac/command_review.py new file mode 100644 index 000000000..b26e81653 --- /dev/null +++ b/je_auto_control/utils/rbac/command_review.py @@ -0,0 +1,252 @@ +"""The ``AC_*`` commands reviewed as needing only what the submitting surface checks. + +Submitting an action list already needs ``drive_input`` (``POST /execute``, +``ac_execute_actions``, an action file run by a caller holding it), and the +executor checks :data:`~je_auto_control.utils.rbac.policy.COMMAND_CAPABILITIES` +on every action it runs, nested blocks and parallel branches included. Every +other command is listed here, reviewed against the one boundary that matters to +an action list: the operator role holds ``read_screen``, ``read_data`` and +``drive_input``, so a command belongs in the policy table only when it reaches +what only an admin may touch -- the signing key, users, host administration, +the servers the host runs, its USB and egress policy, the secrets vault's +administration, the audit log, or plug-in loading. + +The review (U-20261115-03) screened every name, and every adapter's source for +the modules that hold that state, and read each candidate: +:data:`OPERATOR_NOTES` records why each one stays at operator. Membership +changes nothing at run time -- an unlisted command was already allowed -- but +``test_rbac_command_review.py`` fails on a command in neither table, so a new +command gets the same decision instead of inheriting the default unseen. +""" +from typing import Dict, FrozenSet + +#: Reviewed candidates that stay at operator, with the reason. +OPERATOR_NOTES: Dict[str, str] = { + "AC_approval_approve": ( + "maker-checker for scripts: nothing on the host consults the gate, and the approver is a caller-supplied " + "name, not the RBAC user" + ), + "AC_approval_reject": "as AC_approval_approve", + "AC_approval_request": "maker-checker for scripts: nothing on the host consults the gate", + "AC_approval_status": "reads a request's state", + "AC_approve_artifact": "promotes a test baseline: workflow data, not host policy", + "AC_chatops_dispatch": ( + "/run executes the script in the caller's thread, so the executor's own check refuses a privileged " + "command inside it" + ), + "AC_create_signing_keypair": ( + "writes a new pair only: it refuses an existing file and a verify-only endpoint, and signing with the " + "pair needs sign_actions" + ), + "AC_decrypt_action_file": ( + "reveals a file's content, which read_data covers and an operator holds; an operator can already run the " + "file it protects" + ), + "AC_egress_check": "reads the egress policy; setting or resetting it needs manage_hosts", + "AC_encrypt_action_file": ( + "Fernet with a caller passphrase or the per-user key; the content is the caller's own file" + ), + "AC_lease_active": "lists leases without values", + "AC_lease_secret": "a lease token carries no value; redeeming one is Python-only", + "AC_lease_valid": "as AC_lease_secret", + "AC_list_plugins": "lists entry points; loading them needs manage_hosts", + "AC_parallel": ( + "branches keep the caller's authorization: the executor refuses a privileged command inside a branch" + ), + "AC_presence_clear": "as AC_presence_register", + "AC_presence_register": ( + "advisory: no host consults PresenceRegistry.can_control(); raise the presence commands to manage_hosts " + "if one starts gating input on it" + ), + "AC_presence_set_role": "as AC_presence_register", + "AC_presence_unregister": "as AC_presence_register", + "AC_repair_approve": "accepts a locator-repair suggestion: workflow data, not host policy", + "AC_revoke_lease": "as AC_lease_secret", + "AC_secret_list": "names only; vault administration (init, set, remove, lock, unlock) needs manage_hosts", + "AC_secret_status": "path and lock state only, as AC_secret_list", + "AC_usb_acl_list": "the stored ACL, read_data as ac_usb_acl_list and GET /usb/acl", + "AC_usb_loopback_open": ( + "matches POST /usb/loopback/open (drive_input); the ACL and the passthrough switch need manage_hosts" + ), + "AC_usb_remote_open": "matches POST /usb/remote/open, as AC_usb_loopback_open", + "AC_verify_action_file": "checks a signature against a public key; it grants nothing", + "AC_webhook_list": "rows carry has_token, never the token; add, remove, start and stop need manage_hosts", + "AC_webhook_status": "running state and bound address only, as AC_webhook_list", + "AC_webrtc_accept_answer": "as AC_webrtc_create_offer", + "AC_webrtc_create_offer": ( + "signals a host that AC_start_webrtc_host (manage_hosts) started; the viewer still authenticates with " + "that host's token" + ), + "AC_webrtc_host_status": "running, authenticated and connection state only", + "AC_ws_host_status": "state and owner only, no token (AC_remote_host_status's reply)", +} + +#: Every other command: it drives input, observes the screen, or reads or +#: writes what the operator's own capabilities already reach. +OPERATOR_COMMANDS: FrozenSet[str] = frozenset({ + "AC_a11y_click", "AC_a11y_dump", "AC_a11y_find", "AC_a11y_find_all", "AC_a11y_focused", "AC_a11y_list", + "AC_a11y_record_events", "AC_a11y_record_start", "AC_a11y_record_stop", "AC_ab_best_strategy", "AC_ab_clear", + "AC_ab_locate", "AC_ab_report", "AC_ab_significance", "AC_act_in_view", "AC_act_with_mode", + "AC_adaptive_timeout", "AC_agent_card", "AC_agent_dag", "AC_agent_dag_inspect", "AC_agent_runtime_readiness", + "AC_agent_runtime_status", "AC_agent_skill", "AC_agent_skill_list", "AC_agent_target_list", + "AC_agent_task_act", "AC_agent_task_cancel", "AC_agent_task_draft", "AC_agent_task_finish", + "AC_agent_task_get", "AC_agent_task_list", "AC_agent_task_lookup", "AC_agent_task_observe", + "AC_agent_task_pause", "AC_agent_task_prune", "AC_agent_task_receipts", "AC_agent_task_reconcile", + "AC_agent_task_recovery", "AC_agent_task_resume", "AC_agent_task_stop_all", "AC_agent_task_submit", + "AC_agent_transfer", "AC_agent_trigger", "AC_agent_trigger_list", "AC_allow_sleep", "AC_anchor_click", + "AC_anchor_locate", "AC_anchor_locate_all", "AC_android_alert_accept", "AC_android_alert_dismiss", + "AC_android_app_state", "AC_android_click_element", "AC_android_device_info", "AC_android_drag", + "AC_android_dump_hierarchy", "AC_android_find_by_description", "AC_android_find_element", + "AC_android_find_image", "AC_android_find_text", "AC_android_get_clipboard", "AC_android_install_app", + "AC_android_key", "AC_android_launch_app", "AC_android_list_devices", "AC_android_long_press", + "AC_android_pinch", "AC_android_pull_file", "AC_android_push_file", "AC_android_screen_info", + "AC_android_screenshot", "AC_android_self_heal", "AC_android_set_clipboard", "AC_android_shell", + "AC_android_start_recording", "AC_android_stop_app", "AC_android_stop_recording", "AC_android_swipe", + "AC_android_tap", "AC_android_text", "AC_android_type_text", "AC_android_wait_for_app", + "AC_annotate_screenshot", "AC_apply_json_patch", "AC_apply_unified", "AC_apply_vex", "AC_arrange_cascade", + "AC_arrange_grid", "AC_assert_all", "AC_assert_any", "AC_assert_audio", "AC_assert_clipboard", "AC_assert_db", + "AC_assert_duration", "AC_assert_eventually", "AC_assert_file", "AC_assert_http", "AC_assert_image", + "AC_assert_pdf_text", "AC_assert_pixel", "AC_assert_process", "AC_assert_session_active", "AC_assert_text", + "AC_assert_var", "AC_assert_video_changes", "AC_assert_visual", "AC_assert_vlm", "AC_assert_window", + "AC_assign_stable_ids", "AC_associate_fields", "AC_audit_accessibility", "AC_audit_contrast", + "AC_audit_focus_order", "AC_auto_threshold", "AC_baggage_format", "AC_baggage_parse", "AC_best_candidate", + "AC_bidi_check", "AC_bidi_strip", "AC_break", "AC_bring_to_front", "AC_browser_check", "AC_browser_click", + "AC_browser_download", "AC_browser_fill", "AC_browser_link", "AC_browser_navigate", "AC_browser_read", + "AC_browser_select", "AC_browser_upload", "AC_browser_wait", "AC_build_critic_record", "AC_build_multipart", + "AC_build_provenance", "AC_build_timeline", "AC_bulkhead_run", "AC_burn_alerts", "AC_call_macro", + "AC_canonical_log", "AC_canonicalize_url", "AC_capture_window", "AC_cas_get", "AC_cas_put", "AC_cascade_rects", + "AC_categorical_drift", "AC_cell_by_header", "AC_cell_changes", "AC_cell_for_point", "AC_change_volume", + "AC_changed_regions", "AC_check_accepted_values", "AC_check_catalog", "AC_check_compatibility", + "AC_check_foreign_key", "AC_check_key_is_press", "AC_check_licenses", "AC_check_overflow", + "AC_check_postcondition", "AC_check_row_count", "AC_check_unique_key", "AC_checkpoint_clear", + "AC_checkpoint_status", "AC_checksum_digit", "AC_checksum_validate", "AC_ci_annotations", "AC_circuit_call", + "AC_classify_effect", "AC_classify_formats", "AC_classify_icon", "AC_classify_lines", + "AC_classify_lock_transitions", "AC_classify_widget", "AC_click_mouse", "AC_click_text", "AC_client_point", + "AC_clip_history_capture", "AC_clip_history_list", "AC_clip_history_search", "AC_clip_history_start", + "AC_clip_history_stop", "AC_clipboard_formats", "AC_clipboard_get", "AC_clipboard_get_image", + "AC_clipboard_set", "AC_clipboard_set_image", "AC_close_window", "AC_cofailure_pairs", "AC_collapse_control", + "AC_collation_compare", "AC_collation_sort", "AC_colors_collide", "AC_column_gutters", + "AC_compare_field_value", "AC_compliance_report", "AC_computer_use", "AC_confusable_compare", + "AC_confusable_scan", "AC_consensus_element", "AC_consensus_point", "AC_continue", "AC_control_expand_state", + "AC_control_get_state", "AC_control_get_value", "AC_control_invoke", "AC_control_range", + "AC_control_set_value", "AC_control_text_attributes", "AC_control_toggle", "AC_cookie_header", + "AC_costs_clear", "AC_costs_list", "AC_costs_record", "AC_costs_summary", "AC_create_project", + "AC_critical_steps", "AC_cua_command", "AC_debug_trace", "AC_decision_table", "AC_decode_body", + "AC_decode_conversion_mode", "AC_dedup_check", "AC_dedupe_images", "AC_define_macro", "AC_delta_observation", + "AC_describe_screen", "AC_describe_stats", "AC_detect_anomalies", "AC_detect_borderless_table", + "AC_detect_drift", "AC_detect_lists", "AC_detect_pii", "AC_detect_scale", "AC_diff_formats", "AC_diff_json", + "AC_diff_rows", "AC_diff_runs", "AC_dominant_hue_regions", "AC_dominant_pair", "AC_drag_path", "AC_drop_files", + "AC_edge_match", "AC_edge_match_all", "AC_effect_near_point", "AC_element_click", "AC_element_find", + "AC_element_list", "AC_element_remove", "AC_element_save", "AC_email_trigger_add", "AC_email_trigger_list", + "AC_email_trigger_poll_once", "AC_email_trigger_remove", "AC_email_trigger_start", "AC_email_trigger_stop", + "AC_emit_event", "AC_ensure_field_value", "AC_enumerate_monitors", "AC_evaluate_flag", "AC_evaluate_slo", + "AC_evaluate_trajectory", "AC_ewma", "AC_execute_action", "AC_execute_files", "AC_execute_process", + "AC_expand_control", "AC_expect_poll", "AC_explain_config", "AC_export_sarif", "AC_extract_fields", + "AC_failure_clusters", "AC_failure_hook_clear", "AC_failure_hook_fire", "AC_failure_hook_list", + "AC_failure_signature", "AC_feature_match", "AC_file_association", "AC_find_color_region", + "AC_find_control_text", "AC_find_grid", "AC_find_lines", "AC_find_rectangles", "AC_find_separators", + "AC_find_shapes", "AC_find_text_lines", "AC_find_text_regex", "AC_find_text_regions", "AC_flag_enabled", + "AC_flaky_report", "AC_flow_order", "AC_focus_control", "AC_focus_window", "AC_for_each", "AC_for_each_row", + "AC_foreground_window", "AC_foreground_window_pid", "AC_format_currency", "AC_format_date", + "AC_format_decimal", "AC_format_list", "AC_format_message", "AC_fuse_elements", "AC_fuzzy_best_match", + "AC_fuzzy_dedupe", "AC_fuzzy_ratio", "AC_gamepad_click", "AC_gamepad_dpad", "AC_gamepad_left_stick", + "AC_gamepad_left_trigger", "AC_gamepad_press", "AC_gamepad_release", "AC_gamepad_reset", + "AC_gamepad_right_stick", "AC_gamepad_right_trigger", "AC_generate_code", "AC_generate_data", + "AC_generate_html", "AC_generate_html_report", "AC_generate_json", "AC_generate_json_report", + "AC_generate_sbom", "AC_generate_sop", "AC_generate_xml", "AC_generate_xml_report", "AC_get_asset", + "AC_get_client_rect", "AC_get_clipboard_csv", "AC_get_clipboard_files", "AC_get_clipboard_html", + "AC_get_clipboard_rtf", "AC_get_control_text", "AC_get_element_properties", "AC_get_keyboard_keys_table", + "AC_get_mouse_position", "AC_get_mouse_table", "AC_get_selected_text", "AC_get_selection", "AC_get_var", + "AC_get_visible_text", "AC_get_volume", "AC_gettext_ngettext", "AC_gettext_translate", "AC_grade_contrast", + "AC_grid_cell", "AC_grid_cells", "AC_grid_rects", "AC_group_failures", "AC_group_paragraphs", "AC_guard_text", + "AC_handle_file_dialog", "AC_has_motion", "AC_heal_stats", "AC_histogram_changed", "AC_history_clear", + "AC_history_list", "AC_hold_key", "AC_hotkey", "AC_http_replay", "AC_http_request", "AC_http_to_var", + "AC_human_move", "AC_human_type", "AC_humanize_role", "AC_idempotency_begin", "AC_idempotency_complete", + "AC_idempotency_release", "AC_idle_point", "AC_idle_seconds", "AC_if_image_found", "AC_if_pixel", "AC_if_var", + "AC_image_hash", "AC_image_histogram", "AC_image_quality", "AC_ime_state", "AC_inc_var", "AC_infer_schema", + "AC_input_reachable", "AC_input_sequence", "AC_inspector_reset", "AC_ios_alert_accept", "AC_ios_alert_dismiss", + "AC_ios_app_state", "AC_ios_click_element", "AC_ios_device_info", "AC_ios_drag", "AC_ios_dump_source", + "AC_ios_find_by_description", "AC_ios_find_element", "AC_ios_find_image", "AC_ios_find_text", + "AC_ios_get_clipboard", "AC_ios_install_app", "AC_ios_launch_app", "AC_ios_long_press", "AC_ios_pinch", + "AC_ios_press_key", "AC_ios_pull_file", "AC_ios_push_file", "AC_ios_screen_info", "AC_ios_screenshot", + "AC_ios_self_heal", "AC_ios_set_clipboard", "AC_ios_start_recording", "AC_ios_stop_app", + "AC_ios_stop_recording", "AC_ios_swipe", "AC_ios_tap", "AC_ios_type", "AC_ios_wait_for_app", "AC_is_composing", + "AC_is_idle", "AC_json_extract", "AC_json_query", "AC_jwt_decode", "AC_jwt_encode", "AC_keep_awake_on", + "AC_label_color", "AC_legacy_default_action", "AC_legacy_info", "AC_list_assets", "AC_list_executions", + "AC_list_views", "AC_list_windows", "AC_llm_plan", "AC_llm_run", "AC_load_data", "AC_load_dotenv", + "AC_localize_changes", "AC_locate_all_image", "AC_locate_and_click", "AC_locate_chain", + "AC_locate_image_center", "AC_locate_text", "AC_lock_session", "AC_loop", "AC_loop_guard_observe", + "AC_loop_guard_reset", "AC_make_json_patch", "AC_mark_click", "AC_mark_screen", "AC_mask_rows", + "AC_match_auto", "AC_match_color", "AC_match_color_all", "AC_match_elements", "AC_match_ensemble", + "AC_match_json", "AC_match_labels_to_widgets", "AC_match_masked", "AC_match_masked_all", + "AC_match_persistence", "AC_match_rotated", "AC_match_rotated_all", "AC_match_subpixel", "AC_match_template", + "AC_match_template_all", "AC_match_theme", "AC_match_with_trust", "AC_mcp_manifest", "AC_memory_forget", + "AC_memory_recall", "AC_memory_recent", "AC_memory_remember", "AC_memory_stats", "AC_merge_patch", + "AC_merge_results", "AC_mine_actions", "AC_minimize_window", "AC_minimize_windows_for_pid", + "AC_monitor_at_point", "AC_most_salient", "AC_mouse_left", "AC_mouse_middle", "AC_mouse_right", + "AC_mouse_scroll", "AC_move_along_path", "AC_move_element", "AC_move_mouse_relative", "AC_move_to_trash", + "AC_move_window", "AC_near_duplicates", "AC_next_url", "AC_normalize_ext", "AC_normalize_text", + "AC_normalize_url", "AC_notify", "AC_notify_webhook", "AC_now_to_var", "AC_observation_index", + "AC_observe_add", "AC_observe_list", "AC_observe_poll", "AC_observe_remove", "AC_observe_start", + "AC_observe_stop", "AC_ocr_languages", "AC_ocr_read_structure", "AC_ocr_status", "AC_ocr_to_var", + "AC_open_path", "AC_otp_to_var", "AC_outbox_enqueue", "AC_outbox_pending", "AC_outline", + "AC_parse_cache_control", "AC_parse_decimal", "AC_parse_dotenv", "AC_parse_link_header", "AC_parse_multipart", + "AC_parse_number", "AC_parse_problem", "AC_parse_quality_values", "AC_parse_set_cookie", "AC_parse_sse", + "AC_pdf_to_var", "AC_pending_artifacts", "AC_percentiles", "AC_perceptual_diff", "AC_place_labels", + "AC_plan_file_drop", "AC_plan_keep_awake", "AC_plan_lock_session", "AC_plan_open", "AC_plan_repair", + "AC_plan_retry_delays", "AC_point_for_cell", "AC_populate_table", "AC_post_click_to_window", + "AC_post_key_to_window", "AC_preprocess_image", "AC_presence_list", "AC_presence_update_cursor", + "AC_press_keyboard_key", "AC_press_mouse", "AC_profile_rows", "AC_profiler_disable", "AC_profiler_enable", + "AC_profiler_hot_spots", "AC_profiler_reset", "AC_profiler_stats", "AC_propose_elements", "AC_pseudo_localize", + "AC_quality_gate", "AC_quarantine_add", "AC_quarantine_auto", "AC_quarantine_clear", "AC_quarantine_list", + "AC_quarantine_remove", "AC_queue_add", "AC_queue_complete", "AC_queue_fail", "AC_queue_next", + "AC_queue_stats", "AC_random_to_var", "AC_rank_changes", "AC_rank_tests", "AC_rate_limit", "AC_read_barcodes", + "AC_read_document", "AC_read_file_to_var", "AC_read_presentation", "AC_read_qr", "AC_read_table", + "AC_read_text_in_region", "AC_read_workbook", "AC_readability_report", "AC_reading_order", "AC_realize_item", + "AC_record", "AC_redact_config", "AC_redact_pii", "AC_redact_screenshot", "AC_redact_secret_text", + "AC_region_color_stats", "AC_region_contrast", "AC_region_stability", "AC_release_keyboard_key", + "AC_release_mouse", "AC_remote_connect", "AC_remote_disconnect", "AC_remote_send_input", "AC_repair_pending", + "AC_repair_record", "AC_repair_resolved", "AC_replay_timeline", "AC_replay_trace", "AC_resize_element", + "AC_resolve_config", "AC_resolve_pointer", "AC_resolve_ref", "AC_resolve_refs", "AC_restore_window_layout", + "AC_retry", "AC_retry_after", "AC_retry_delay", "AC_rrule_next", "AC_rrule_occurrences", "AC_run_agent", + "AC_run_chaos", "AC_run_dag", "AC_run_device_matrix", "AC_run_resumable", "AC_run_saga", + "AC_run_state_machine", "AC_run_stoppable", "AC_run_suite", "AC_s3_delete", "AC_s3_download", "AC_s3_list", + "AC_s3_upload", "AC_salient_regions", "AC_save_window_layout", "AC_scale_sweep", "AC_scan_secrets", + "AC_scan_vulns", "AC_score_candidates", "AC_score_step", "AC_screen_changed", "AC_screen_diff", + "AC_screen_size", "AC_screen_snapshot", "AC_screenshot", "AC_scroll_control_into_view", "AC_scroll_to_find", + "AC_search_documents", "AC_seed_everything", "AC_segment_hsv", "AC_select_control_item", + "AC_select_control_text", "AC_select_tests", "AC_self_heal_click", "AC_self_heal_locate", + "AC_self_heal_log_clear", "AC_self_heal_log_list", "AC_send_email", "AC_send_to_back", "AC_sequence_observe", + "AC_serialize_observation", "AC_set_asset", "AC_set_clipboard_csv", "AC_set_clipboard_files", + "AC_set_clipboard_html", "AC_set_clipboard_rtf", "AC_set_control_range", "AC_set_field_text", + "AC_set_mouse_position", "AC_set_mute", "AC_set_record_enable", "AC_set_topmost", "AC_set_var", "AC_set_view", + "AC_set_volume", "AC_set_window_state", "AC_settle_point", "AC_shard_suite", "AC_shell_command", + "AC_shell_to_var", "AC_simhash", "AC_simulate_cvd", "AC_skill_list", "AC_skill_remove", "AC_skill_run", + "AC_skill_save", "AC_skill_search", "AC_sleep", "AC_slugify", "AC_sma", "AC_snap_window", "AC_soft_assert", + "AC_spans_to_otlp", "AC_sql_to_var", "AC_ssim_changed_regions", "AC_ssim_compare", "AC_start_webrtc_viewer", + "AC_stop_execution", "AC_stop_record", "AC_stop_record_timeline", "AC_stop_webrtc_viewer", + "AC_store_validators", "AC_tab_order", "AC_table_cell", "AC_table_headers", "AC_tag_kinds", "AC_take_golden", + "AC_text_similarity", "AC_three_way_merge", "AC_tile_rect", "AC_timeout_stats", "AC_to_model", + "AC_to_physical", "AC_toggle_mute", "AC_trace_export", "AC_trace_extract", "AC_trace_inject", + "AC_trace_record", "AC_trace_reset", "AC_trace_summary", "AC_transform_var", "AC_try", "AC_ts_downsample", + "AC_ts_rate", "AC_tween_drag", "AC_type_keyboard", "AC_type_unicode", "AC_type_unicode_keys", + "AC_type_unicode_text", "AC_unified_diff", "AC_urls_equal", "AC_usb_watch_start", "AC_usb_watch_stop", + "AC_validate_action", "AC_validate_config", "AC_validate_json", "AC_validate_rows", "AC_verify_artifact", + "AC_verify_field_value", "AC_verify_provenance", "AC_vlm_click", "AC_vlm_locate", "AC_voice_clear", + "AC_voice_dispatch", "AC_voice_list", "AC_voice_register", "AC_vote_centers", "AC_wait_actionable", + "AC_wait_clipboard_change", "AC_wait_color", "AC_wait_for_composition_commit", "AC_wait_for_file", + "AC_wait_for_focus_change", "AC_wait_for_port", "AC_wait_for_process", "AC_wait_for_unlock", "AC_wait_image", + "AC_wait_image_gone", "AC_wait_pixel", "AC_wait_pixel_changes", "AC_wait_region_idle", "AC_wait_screen_stable", + "AC_wait_text", "AC_wait_text_gone", "AC_wait_until_app_idle", "AC_wait_window", "AC_wait_window_closed", + "AC_wait_window_title", "AC_walk_tree", "AC_watchdog_add", "AC_watchdog_list", "AC_watchdog_start", + "AC_watchdog_stop", "AC_wcag_audit", "AC_web_available", "AC_web_current_url", "AC_web_list_commands", + "AC_web_open", "AC_web_quit", "AC_web_run", "AC_web_run_actions", "AC_web_screenshot", + "AC_webrtc_process_offer", "AC_webrtc_send_input", "AC_webrtc_viewer_status", "AC_while_image", "AC_while_var", + "AC_window_interaction_state", "AC_window_pid", "AC_window_rect", "AC_windows_for_pid", "AC_with_modifiers", + "AC_workflow_control", "AC_workflow_download", "AC_workflow_manifest", "AC_workflow_open", "AC_workflow_wait", + "AC_write", "AC_write_document", "AC_write_presentation", "AC_write_secret", "AC_write_step_video", + "AC_write_workbook", "AC_ws_connect", "AC_ws_disconnect", "AC_ws_send_input", "AC_ws_viewer_status", + "AC_xy_cut", +}) + +__all__ = ["OPERATOR_COMMANDS", "OPERATOR_NOTES"] diff --git a/je_auto_control/utils/rbac/policy.py b/je_auto_control/utils/rbac/policy.py index 98fa0b65a..f83d58063 100644 --- a/je_auto_control/utils/rbac/policy.py +++ b/je_auto_control/utils/rbac/policy.py @@ -95,7 +95,8 @@ route for route, needed in REST_ROUTE_CAPABILITIES.items() if needed == _DATA) #: Explicit command requirements, including audited host-data reads. Unlisted -#: commands still rely on the capability of the surface submitting the action list. +#: commands still rely on the capability of the surface submitting the action list; +#: every one of them is reviewed in :mod:`je_auto_control.utils.rbac.command_review`. COMMAND_CAPABILITIES: Dict[str, str] = { "AC_agent_target": _HOSTS, "AC_agent_target_recover": _HOSTS, @@ -262,7 +263,6 @@ "ac_agent_task_recovery": _DRIVE, "ac_agent_trigger_list": _DRIVE, "ac_journal_capture": _DRIVE, - "ac_journal_read": _DRIVE, "ac_remote_host_start": _HOSTS, "ac_remote_host_stop": _HOSTS, "ac_usb_acl_add": _HOSTS, @@ -291,6 +291,8 @@ "ac_clip_history_list": _DRIVE, "ac_clip_history_search": _DRIVE, "ac_assert_clipboard": _DRIVE, + # AC_journal_read's requirement; above the DATA_TOOLS spread it was overwritten + "ac_journal_read": _DRIVE, "ac_read_action_file": _DRIVE, "ac_load_dotenv": _DRIVE, "ac_sql_query": _DRIVE, diff --git a/je_auto_control/utils/remote_desktop/presence.py b/je_auto_control/utils/remote_desktop/presence.py index db6a56a89..d0b1569b7 100644 --- a/je_auto_control/utils/remote_desktop/presence.py +++ b/je_auto_control/utils/remote_desktop/presence.py @@ -2,10 +2,12 @@ Tracks one ``ViewerPresence`` row per connected viewer: identity, role (``controller`` / ``observer``), and most-recent cursor position. -Plugged into :class:`MultiViewerHost` it lets the host fan out the -roster to every viewer so each one can render the other cursors as -ghost overlays, and gates input dispatch by role so observers cannot -move the mouse / type. +Plugged into a host it would let it fan out the roster to every viewer +so each one can render the other cursors as ghost overlays, and +:meth:`PresenceRegistry.can_control` answers whether a viewer's role +allows input. No host consults it yet: :class:`MultiViewerHost` does not +gate input on presence, so the roles are advisory (see +``utils/rbac/command_review.py``). Pure stdlib + dataclasses — no aiortc / Qt deps — so the module is unit-testable on any platform and can be re-used by the REST API and diff --git a/pyproject.toml b/pyproject.toml index 7255b4211..9e5725d4a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -450,6 +450,7 @@ module = [ "je_auto_control.utils.rbac.admin", "je_auto_control.utils.rbac.authorization", "je_auto_control.utils.rbac.cli", + "je_auto_control.utils.rbac.command_review", "je_auto_control.utils.rbac.deferred", "je_auto_control.utils.rbac.policy", "je_auto_control.utils.script_vars.execution", diff --git a/test/unit_test/headless/test_rbac_command_review.py b/test/unit_test/headless/test_rbac_command_review.py new file mode 100644 index 000000000..35f33f2da --- /dev/null +++ b/test/unit_test/headless/test_rbac_command_review.py @@ -0,0 +1,73 @@ +"""Every ``AC_*`` command has an RBAC decision, and an executor command agrees with its MCP twin.""" +from je_auto_control.utils.executor.action_executor import Executor +from je_auto_control.utils.mcp_server.tools import build_default_tool_registry +from je_auto_control.utils.rbac.authorization import AuthorizationContext, authorization_scope +from je_auto_control.utils.rbac.command_review import OPERATOR_COMMANDS, OPERATOR_NOTES +from je_auto_control.utils.rbac.policy import COMMAND_CAPABILITIES, capability_for_tool +from je_auto_control.utils.rbac.users import Capability + +_ADMIN_ONLY = {Capability.MANAGE_HOSTS, Capability.MANAGE_USERS, Capability.READ_AUDIT, + Capability.SIGN_ACTIONS} + + +def _known() -> set: + # A fresh executor: the shared one also holds what other tests registered. + return Executor().known_commands() + + +def _tool_capabilities() -> dict: + return {tool.name: capability_for_tool(tool.name, bool(tool.annotations.read_only)) + for tool in build_default_tool_registry(read_only=False)} + + +def test_every_command_has_exactly_one_decision(): + listed, operator, noted = set(COMMAND_CAPABILITIES), set(OPERATOR_COMMANDS), set(OPERATOR_NOTES) + assert not listed & operator and not listed & noted and not operator & noted + undecided = sorted(_known() - listed - operator - noted) + assert not undecided, ( + f"{undecided}: decide each one -- COMMAND_CAPABILITIES in utils/rbac/policy.py when it reaches " + "admin-only state, otherwise OPERATOR_COMMANDS in utils/rbac/command_review.py") + + +def test_the_review_names_only_commands_that_exist(): + assert not (set(OPERATOR_COMMANDS) | set(OPERATOR_NOTES)) - _known() + assert all(reason.strip() for reason in OPERATOR_NOTES.values()) + + +def test_a_listed_command_needs_what_its_mcp_twin_needs(): + tools = _tool_capabilities() + differ = {name: (needed, tools[f"ac_{name[3:]}"]) for name, needed in COMMAND_CAPABILITIES.items() + if f"ac_{name[3:]}" in tools and tools[f"ac_{name[3:]}"] != needed} + assert not differ + + +def test_no_operator_command_has_an_admin_only_mcp_twin(): + tools = _tool_capabilities() + raised = {name: tools[f"ac_{name[3:]}"] for name in set(OPERATOR_COMMANDS) | set(OPERATOR_NOTES) + if tools.get(f"ac_{name[3:]}") in _ADMIN_ONLY} + assert not raised, f"{raised}: the action-list path would skip what the tool requires" + + +def test_a_privileged_command_inside_blocks_and_branches_is_still_refused(monkeypatch): + calls = [] + # Patched where AC_user_list's adapter looks it up at call time, so a parallel branch's + # fresh executor (stock commands only) reaches the recorder too. + monkeypatch.setattr("je_auto_control.utils.rbac.admin.list_users", + lambda *_a, **_k: calls.append("ran") or []) + nested = ["AC_user_list"] + lists = { + "parallel": [["AC_parallel", {"branches": [[nested]]}]], + "loop": [["AC_loop", {"times": 1, "body": [nested]}]], + "try": [["AC_try", {"body": [nested]}]], + "macro": [["AC_define_macro", {"name": "m", "body": [nested]}], ["AC_call_macro", {"name": "m"}]], + "run_stoppable": [["AC_run_stoppable", {"body": [nested]}]], + "execute_action": [["AC_execute_action", {"action_list": [nested]}]], + } + operator = AuthorizationContext(user_id="op", role="operator") + for label, actions in lists.items(): + with authorization_scope(operator): + Executor().execute_action(actions, raise_on_error=False) + assert calls == [], label + with authorization_scope(AuthorizationContext(user_id="root", role="admin")): + Executor().execute_action(lists["parallel"], raise_on_error=False) + assert calls == ["ran"], "the recorder is reached when the role allows it" From 8d1fa056f6b11e20a50b8c753547806b3db776b2 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 11:22:38 +0800 Subject: [PATCH 120/161] Bind the approval gate's maker and checker to the RBAC user The approver was whatever name the caller passed, so under RBAC one operator could file a request and approve it as somebody else, which defeats segregation of duties. Outside RBAC the names work as before. --- CHANGELOG.md | 5 ++ Progress.md | 1 - architecture_explore.md | 10 ++-- .../Eng/doc/new_features/v32_features_doc.rst | 6 ++ .../Zh/doc/new_features/v32_features_doc.rst | 4 ++ docs/updates/2026-11-b.md | 26 +++++--- docs/updates/README.md | 1 + .../utils/governance/governance.py | 20 +++++++ je_auto_control/utils/rbac/command_review.py | 6 +- .../test_governance_approval_identity.py | 59 +++++++++++++++++++ 10 files changed, 120 insertions(+), 18 deletions(-) create mode 100644 test/unit_test/headless/test_governance_approval_identity.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cba6162f..9d1a6a31d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- Approval gate: with RBAC on, the maker and the checker are the authenticated user. A + `requester` or `approver` naming anyone else raises `AuthorizationError` (an empty one means + that user), so one operator can no longer file a request and approve it under a second name. + Without RBAC the supplied names are used as before. + - RBAC: every `AC_*` command now has a recorded decision. The 817 commands not in `COMMAND_CAPABILITIES` were reviewed as reaching nothing admin-only and are listed in `utils/rbac/command_review.py` (33 of them with the reason); a new command in neither table diff --git a/Progress.md b/Progress.md index 73f562bbc..becaff441 100644 --- a/Progress.md +++ b/Progress.md @@ -135,7 +135,6 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - `ac_list_plugins` 的外掛 factory,以及 `ac_web_list_commands`/`ac_web_current_url` 的實際相依版本初始化契約尚待審查;目前不列入唯讀目錄,完整目錄仍要求 `read_data`。本機 sibling 原始碼不代表部署版本驗收。 - `ac_diagnose` 的預設 audit-log 初始化可能建立固定目錄及 SQLite schema;全域零寫入診斷與外部 SDK 初始化副作用仍未驗證。 - - executor 指令已全部分類(U-20261115-03:`utils/rbac/command_review.py`,新指令未分類時 CI 失敗;執行時仍不預設拒絕,維護者 2026-11-15 決定)。審查留下兩個設計問題(`DECIDE`):`AC_approval_approve`/`ac_approval_approve` 的 approver 是呼叫者給的字串而不是 RBAC 使用者,同一個 operator 換個名字就能核准自己的請求(目前主機上沒有東西依核准結果放行);presence 角色只是提示,沒有主機呼叫 `PresenceRegistry.can_control()`——哪天主機依角色擋輸入,presence 指令要升到 `manage_hosts`。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, diff --git a/architecture_explore.md b/architecture_explore.md index 4ba67dfb5..402e6f2e5 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,544 | -| 程式碼總行數 | 237,613 | +| 程式碼總行數 | 237,633 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -665,13 +665,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,732 行。 +> 13 個套件、約 4,752 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/config_redaction/` | 86 | 設定結構與 log 字串的機密遮蔽 | | `utils/egress/` | 169 | 無頭 HTTP 用戶端的網路外連允許清單守衛 | -| `utils/governance/` | 243 | 治理:maker-checker 核准閘門與即時憑證租約 | +| `utils/governance/` | 263 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | | `utils/rbac/` | 1,985 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data;command_review.py 記錄 `COMMAND_CAPABILITIES` 以外每個 `AC_*` 指令的審查(只需提交入口的 drive_input),新指令未分類時 CI 失敗 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,483 | -| **總計** | **1,532** | **236,868** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,503 | +| **總計** | **1,532** | **236,888** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/new_features/v32_features_doc.rst b/docs/source/Eng/doc/new_features/v32_features_doc.rst index 5d7dc84e8..229e0398a 100644 --- a/docs/source/Eng/doc/new_features/v32_features_doc.rst +++ b/docs/source/Eng/doc/new_features/v32_features_doc.rst @@ -36,6 +36,12 @@ requester, compared after trimming, NFKC normalisation and case folding (so ``get(token)`` returns the full record, and ``pending()`` lists every request still awaiting a decision. +With RBAC on (``JE_AUTOCONTROL_RBAC_USERS``), the maker and the checker are the +authenticated user, not the name passed in: a ``requester`` or ``approver`` naming +anyone else raises ``AuthorizationError``, and an empty one means that user. One +operator therefore cannot file a request and approve it under a second name. +Without RBAC the supplied names are used as above. + Executor commands ----------------- diff --git a/docs/source/Zh/doc/new_features/v32_features_doc.rst b/docs/source/Zh/doc/new_features/v32_features_doc.rst index 459873bc5..4d04fb6da 100644 --- a/docs/source/Zh/doc/new_features/v32_features_doc.rst +++ b/docs/source/Zh/doc/new_features/v32_features_doc.rst @@ -33,6 +33,10 @@ Maker-Checker 審批閘門 ``status(token)`` 回傳 ``pending`` / ``approved`` / ``rejected``(未知 token 為 ``None``),``get(token)`` 回傳完整紀錄,``pending()`` 則列出所有仍待決議的請求。 +開啟 RBAC(``JE_AUTOCONTROL_RBAC_USERS``)時,maker 與 checker 是已驗證的使用者,而不是傳入的名字: +``requester`` 或 ``approver`` 寫成別人會丟出 ``AuthorizationError``,留空則代表該使用者。 +因此同一個 operator 無法提出請求後再換個名字核准。沒開 RBAC 時照上面的方式使用傳入的名字。 + 執行器指令 ---------- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c0ec3edce..27062d1c9 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -133,7 +133,7 @@ - **What:** Closes the `BLOCKED` `Progress.md` item "minimatch 11 在 VS Code 擴充套件" and corrects U-20261101-17. GHSA-g3hv-75wg-m249 was revised on 2026-11-04: its only vulnerable range is now `>= 7.0.0, < 11.0.1` (patched 11.0.1). `autocontrol-lsp/vscode/package-lock.json` locks `minimatch` 5.1.9, which that range does not include, so the lock needs no override and no wait for `vscode-languageclient`. - **Evidence:** `gh api advisories/GHSA-g3hv-75wg-m249` (updated 2026-11-04T16:50:04Z, not withdrawn). The repository's Dependabot alerts list no `minimatch` alert in any state and 0 open alerts. npm: `vscode-languageclient` 11.0.0 (2026-10-22) requires `minimatch ^10.2.6`, inside the range, so upgrading the client to its latest release would move the extension *into* the advisory; the lock stays on 9.0.1. - **Files:** `Progress.md`, this entry, the index row, the pointer added to U-20261101-17. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-03 · 2026-11-12 · MCP tool calls are stoppable runs; a cancel stops them · #done #mcp #executor @@ -157,7 +157,7 @@ - **What:** `dev` CI run 43064397517 (commit `edc6205d`) failed the same 4 tests on all four `pytest-headless` squares: `test_webrtc_host_channels.py::test_a_mic_that_fails_to_close_is_still_forgotten`, `test_webrtc_viewer_control.py::test_a_microphone_that_fails_to_close_is_still_forgotten`, and both parameters of `test_webrtc_media_types.py::test_recording_releases_container_when_video_stream_cannot_be_created`. They predate U-20261111-26/-32: a mic whose close fails is now retained with its failure and the error propagates (`WebRTCMediaOwners.stop_field`), and a recorder whose setup or write failed reports `MediaRetirementError` with `UNCERTAIN` finalization from `stop()` (`docs/media_retirement_contract.md`). The newer tests (`test_webrtc_media_consumers.py`, `test_media_retirement.py`) already assert that contract. - **Fix:** the four tests now assert it too: the close error propagates, the original mic owner stays in place, `media_failures` is non-empty; the recorder's `stop()` raises `MediaRetirementError`, the container is still closed exactly once, and finalization is `UNCERTAIN`. No library code changed. - **Evidence:** the three files: 140 passed locally (they failed 4 before). -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-06 · 2026-11-12 · Split the tools/call path out of the MCP server module · #done #mcp #quality @@ -165,7 +165,7 @@ - **Seam kept:** four test modules replace `server._capture_error_screenshot`. The mixin resolves that name on `server` when a tool fails, so the patch still applies; `server.py` keeps importing it (`# noqa: F401` with the reason), and a new test (`test_mcp_call_run.py::test_failure_screenshot_is_still_looked_up_on_the_server_module`) fails if the lookup ever binds early. - **Evidence:** MCP, run-control, RBAC, surface, cross-project, facade and budget test files: 1,704 passed, 1 failed (the `test_sync_workspace_surfaces.py` long-path case that fails on the unchanged tree too, see U-20261112-03). Ruff and Radon clean; typing contract on win32/linux/darwin: 0 modules with errors. - **Files:** `utils/mcp_server/{server.py,_tool_calls.py (new)}`, `test_mcp_call_run.py`, `architecture_explore.md` (re-measured with `--fix`), `Progress.md`. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-07 · 2026-11-12 · Build only the first start-up tab; the others when first selected · #done #gui #performance @@ -181,7 +181,7 @@ - **What:** `dev` CI run 43077567957 (U-20261112-03) failed `test_typing_modernization_contract.py::test_every_module_is_strict_or_predates_the_tier` on top of the four WebRTC tests of U-20261112-05: the new `utils/mcp_server/_call_run.py`, and later `_tool_calls.py` (U-20261112-06), were not in the strict `[[tool.mypy.overrides]]` block. U-20261112-03 and -06 ran the typing contract but not that test. Both modules are now listed and pass strict mypy on win32, linux and darwin. - **Also found:** `test/verify/typing_contract_verify.py --extras` on Windows (PySide6 6.11.2, aiortc 1.15.0) reported `gui.navigation` and `utils.remote_desktop.webrtc_host` as failing on the pre-session commit `edc6205d` as well. The Windows stubs type `QTreeWidgetItem.child()` as optional, and `WebRTCMediaOwners.create(...)` returned `Media | None` even with `optional=False`, which raises instead of returning `None`. `navigation.py` iterates through a `_features(group)` helper that skips missing children; `create` has an overload returning `Media` for `optional=False`; `webrtc_host.py` passes a local track to `addTrack`. CI's `typing-extras` job runs on Ubuntu, whose stubs did not flag the first. No behaviour change. - **Evidence:** the strict-tier and `dev.toml` parity tests: 23 passed; extras-config mypy for the three modules on win32 and linux, and normal-config on win32 and darwin: no issues; navigation / WebRTC / media test files: 1,169 passed, 1 skipped. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-09 · 2026-11-12 · The result hook follows AC_parallel branches · #done #executor #gui @@ -196,26 +196,26 @@ - **What:** The `Progress.md` › 雜項 bullet "能力探測" said the Windows locked-workstation / session 0 / low-integrity / capture-failure branches and three macOS preflight calls had run only against fakes, and that it was unknown whether pyobjc's `Quartz` has `CGPreflightListenEventAccess`. Those branches lived in `wrapper/capability_probes.py` (c134d367f), which no longer exists on `dev`: it went away in the 1.1.0 merge (`538a23096`), and `wrapper/capabilities.py::probe_capabilities` now reports `unverified` for Windows and macOS input and capture without calling any OS API. No code makes those calls, so the bullet is removed. - **For whoever brings a macOS probe back:** `pyobjc-framework-Quartz==12.2.2` (the version `pyobjc==12.2.2` in `pyproject.toml` resolves to) declares `CGPreflightListenEventAccess`, `CGPreflightPostEventAccess` and `CGPreflightScreenCaptureAccess`, each with signature `B` (no arguments, returns bool), together with the matching `CGRequest…Access`, in `Quartz/CoreGraphics/_metadata.py`. Read from the downloaded wheel, not run; the functions exist only on macOS 10.15 and later. - **Not covered here:** Windows session and integrity checks elsewhere (`session_guard`, `input_reach`, `agent_runtime/presence_*_windows.py`) stay under the deferred native acceptance items in `Progress.md`. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-11 · 2026-11-12 · Refuse asset paths Windows cannot create before staging · #done #config-sync #windows - **What:** Closes the `TODO` added to `Progress.md` › 雜項 earlier today (commit `7158d9a5`). On Windows with `LongPathsEnabled=0` (this machine), `test_sync_workspace_surfaces.py`'s 64 + 64-character record name staged a 265-character path under `cache/.incoming-*` and failed with `FileNotFoundError`, reported only as "asset transfer could not publish a complete generation". `utils/config_sync/assets.py` now checks first: `_path_limit()` reads `HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled` (259 when it is not 1 or cannot be read; no limit off Windows), and `_require_paths_fit` measures every published path (`generation-/files/`, longer than the staging one) and raises `ConfigSyncError` naming the length, the limit and both remedies before the cache root is created. Of the two options the item named, this is the explicit refusal; `\?\` paths were not adopted, because every reader of the returned paths would have to use them too. - **Test:** `test_sync_assets.py` +2 (refused before anything is created under a patched limit; no limit means no check). The long case of `test_workspace_command_mcp_builder_capture_review_and_materialize` now skips with the measured lengths on a host that cannot hold its path, instead of failing; CI's shorter temp root still runs it. Sync asset / workspace suites: 55 passed, 7 skipped. - **Files:** `utils/config_sync/assets.py`, the two tests, the three `docs/guides/*/usage.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-12 · 2026-11-12 · Move the finished on_enter note out of Progress · #docs #executor - **What:** `Progress.md` › 雜項 still carried "a state machine's single-action `on_enter` was always rejected and never ran (fixed, U-20261009-24); a machine that relied on it not running now runs it". That is a finished fix with a compatibility effect, not open work, and `CHANGELOG.md` already records it under 1.0.0 (variable-scope entry) and 1.1.0. The bullet is removed; no code changed. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-13 · 2026-11-12 · Bring the shared .venv to the pinned pillow and PySide6 · #done #tooling - **What:** Closes the `Progress.md` › 雜項 line left by U-20261112-01; the maintainer approved the upgrade on 2026-11-12. Compared first with `pip install --dry-run`: pillow 12.3.0 → 13.0.0 (`pyproject.toml` pins `==13.0.0`), PySide6 / PySide6_Addons / PySide6_Essentials / shiboken6 6.11.2 → 6.12.0 (the `[gui]` pin), plus two packages PySide6 6.12 now requires, `PySide6_Pdf` and `PySide6_WebEngine` 6.12.0.140. Nothing else changed; `pip check` reports no conflict for these packages. - **Evidence:** GUI, imaging, theme, navigation, remote-desktop and WebRTC test files on the upgraded env: 3,099 passed, 15 skipped, 1 failed (`test_a11y_window_audit.py::test_restoring_duplicate_titles_moves_each_window_once`, the order-dependent `KeyError` that fails the same way on the pre-session tree, U-20261112-07). - **Note:** CI still installs `PySide6==6.11.2` for the `pytest-headless` and `typing-extras` jobs, so the shared env is now newer than CI there; the typing-extras exempt list was measured against 6.11.2. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261112-14 · 2026-11-12 · Reading the iOS pasteboard needs an explicit allowance · #done #mobile #ios @@ -249,7 +249,7 @@ - **SonarCloud (gate: new reliability rating 3 > 1):** three python:S7497 findings in code from 2026-11-11. `webrtc_host_media.py` (`_retire_live_video`) and `webrtc_peer_cleanup.py` (`_cancel_task`) cancelled a child task and then caught every `CancelledError` from awaiting it, which also swallowed the cleaning task's own cancellation if it arrived during the wait. Both now re-raise when the running task itself is being cancelled (`asyncio.current_task().cancelling() > 0`, Python ≥ 3.11), and still absorb the child's. `asyncio.wait` was tried first but the tests' fake tasks are not futures. `webrtc_file_tasks.py` (`_observe_sender`) already keeps the first cancellation and re-raises it once the worker has exited, so it is marked `# NOSONAR python:S7497` with that reason. - **Tests:** `test_webrtc_cancel_propagation.py` (new, 2): a cancelled child is awaited and absorbed; the cleaner cancelled mid-wait ends cancelled (fails on the previous code). WebRTC / media / remote-desktop files: 1,218 passed, 18 skipped. `test_docker_artifacts.py`: 28 passed. Typing on win32 / linux / darwin clean. - **Files:** `docker/Dockerfile`, `utils/remote_desktop/{webrtc_host_media.py,webrtc_peer_cleanup.py,webrtc_file_tasks.py}`, the new test, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. -- **Open items:** none. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). ## U-20261113-04 · 2026-11-13 · `post_key_to_window` takes any printable character · #done #windows #x11 @@ -665,3 +665,11 @@ - **Tests:** the new file (5) and the RBAC, journal, read-only catalogue and presence tests: 702 passed. - **Files:** `utils/rbac/command_review.py`, `utils/rbac/policy.py`, `utils/remote_desktop/presence.py`, `pyproject.toml`, the test, `architecture.md`, `architecture_explore.md`, `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › RBAC (`DECIDE`: approver identity; presence roles). + +## U-20261115-04 · 2026-11-15 · The approval gate binds maker and checker to the RBAC user · #done #rbac #governance + +- **What:** the two `DECIDE` questions U-20261115-03 left in `Progress.md` › RBAC. The approver of `AC_approval_approve` / `ac_approval_approve` was a caller-supplied name, so one operator could file a request and approve it as someone else; the maintainer chose to bind it to the RBAC user. Presence roles stay advisory (maintainer's choice); the note to raise the presence commands if a host ever gates input on them stays in `command_review.py` and `Progress.md`. +- **Change:** `ApprovalGate.request` and `approve` / `reject` take the principal from `current_authorization()` inside an RBAC scope: a supplied name that is not that user (compared as `_principal` compares, trimmed, NFKC, case-folded) raises `AuthorizationError`, an empty one means that user. Outside RBAC nothing changes. The executor commands and MCP tools call the gate, so both are covered. The approval rows in `OPERATOR_NOTES`, both v32 feature docs and `CHANGELOG.md` say so. +- **Tests:** new `test_governance_approval_identity.py` (self-approval under another name refused, an empty name is the user, another user approves, a request under another name refused, the non-RBAC path unchanged, the executor commands end to end) with the governance, command-review, MCP safety, resilience, redaction and shared-JSON tests: 126 passed. +- **Files:** `utils/governance/governance.py`, `utils/rbac/command_review.py`, the test, `docs/source/{Eng,Zh}/doc/new_features/v32_features_doc.rst`, `CHANGELOG.md`, `Progress.md`. +- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). diff --git a/docs/updates/README.md b/docs/updates/README.md index 890cad394..5cb5344ff 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-04 | 2026-11-15 | The approval gate binds maker and checker to the RBAC user | #done #rbac #governance | [2026-11-b](2026-11-b.md) | | U-20261115-03 | 2026-11-15 | Every AC_* command has an RBAC decision | #done #rbac #security | [2026-11-b](2026-11-b.md) | | U-20261115-02 | 2026-11-15 | dnspython 2.9.2 in uv.lock for Dependabot alert 177 | #release #security #dependencies | [2026-11-b](2026-11-b.md) | | U-20261115-01 | 2026-11-15 | PySide6 6.12.0 on Python 3.12+, 6.11.2 kept on 3.11 | #done #gui #pyside6 #dependencies | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/governance/governance.py b/je_auto_control/utils/governance/governance.py index 3ae5eb7a3..8e10faaec 100644 --- a/je_auto_control/utils/governance/governance.py +++ b/je_auto_control/utils/governance/governance.py @@ -7,6 +7,11 @@ ``is_approved`` is true. State is an optional JSON file so the maker and checker can run as separate processes (CI dispatcher and a human approver). +Inside an RBAC scope the maker and the checker are the authenticated user, not +whatever name the caller supplies: one operator could otherwise file a request +and approve it under another name. A supplied name that is not that user is +refused; an empty one means that user. + Pure standard library; imports no ``PySide6``. Tokens use :mod:`secrets`. """ import functools @@ -27,6 +32,19 @@ def _principal(user: object) -> str: """Compare user ids as one person: "Alice" approving "alice" is self-approval.""" return unicodedata.normalize("NFKC", str(user or "")).strip().casefold() + +def _acting(supplied: str, role: str) -> str: + """``supplied`` outside RBAC; inside it, the authenticated user, which ``supplied`` must name.""" + from je_auto_control.utils.rbac.authorization import AuthorizationError, current_authorization + context = current_authorization() + if context is None: + return supplied + if _principal(supplied) and _principal(supplied) != _principal(context.user_id): + raise AuthorizationError( + f"{role} {supplied!r} is not the authenticated user {context.user_id!r}") + return context.user_id + + class ApprovalGate: """A maker-checker approval registry backed by an optional JSON file. @@ -41,6 +59,7 @@ def __init__(self, db_path: Optional[str] = None) -> None: def request(self, action: str, requester: str = "") -> str: """File an approval request for ``action``; return its token.""" + requester = _acting(requester, "requester") token = secrets.token_hex(8) record = { "token": token, "action": action, "requester": requester, @@ -50,6 +69,7 @@ def request(self, action: str, requester: str = "") -> str: return token def _decide(self, token: str, approver: str, status: str) -> bool: + approver = _acting(approver, "approver") checker = _principal(approver) def decide(items: Dict[str, Dict[str, object]]) -> bool: diff --git a/je_auto_control/utils/rbac/command_review.py b/je_auto_control/utils/rbac/command_review.py index b26e81653..3b0406b61 100644 --- a/je_auto_control/utils/rbac/command_review.py +++ b/je_auto_control/utils/rbac/command_review.py @@ -23,11 +23,11 @@ #: Reviewed candidates that stay at operator, with the reason. OPERATOR_NOTES: Dict[str, str] = { "AC_approval_approve": ( - "maker-checker for scripts: nothing on the host consults the gate, and the approver is a caller-supplied " - "name, not the RBAC user" + "maker-checker for scripts: nothing on the host consults the gate, and under RBAC the approver is the " + "authenticated user (ApprovalGate refuses another name)" ), "AC_approval_reject": "as AC_approval_approve", - "AC_approval_request": "maker-checker for scripts: nothing on the host consults the gate", + "AC_approval_request": "maker-checker for scripts; under RBAC the requester is the authenticated user", "AC_approval_status": "reads a request's state", "AC_approve_artifact": "promotes a test baseline: workflow data, not host policy", "AC_chatops_dispatch": ( diff --git a/test/unit_test/headless/test_governance_approval_identity.py b/test/unit_test/headless/test_governance_approval_identity.py new file mode 100644 index 000000000..fd20aa124 --- /dev/null +++ b/test/unit_test/headless/test_governance_approval_identity.py @@ -0,0 +1,59 @@ +"""Inside an RBAC scope the approval gate's maker and checker are the authenticated user.""" +import pytest + +from je_auto_control.utils.executor.action_executor import Executor +from je_auto_control.utils.governance.governance import ApprovalGate +from je_auto_control.utils.rbac.authorization import ( + AuthorizationContext, AuthorizationError, authorization_scope, +) + +_ALICE = AuthorizationContext(user_id="alice", role="operator") +_BOB = AuthorizationContext(user_id="bob", role="operator") + + +def test_one_user_cannot_approve_their_own_request_under_another_name(): + gate = ApprovalGate() + with authorization_scope(_ALICE): + token = gate.request("deploy", "alice") + with pytest.raises(AuthorizationError, match="approver 'mallory'"): + gate.approve(token, "mallory") + assert gate.approve(token, "") is False # an empty name is alice: still self-approval + assert gate.status(token) == "pending" + + +def test_another_authenticated_user_approves(): + gate = ApprovalGate() + with authorization_scope(_ALICE): + token = gate.request("deploy") + assert gate.get(token)["requester"] == "alice" + with authorization_scope(_BOB): + assert gate.approve(token, "Bob") is True # the same person, as _principal compares + assert gate.get(token)["approver"] == "bob" and gate.is_approved(token) + + +def test_a_request_filed_under_another_name_is_refused(): + with authorization_scope(_ALICE), pytest.raises(AuthorizationError, match="requester 'bob'"): + ApprovalGate().request("deploy", "bob") + + +def test_outside_rbac_the_supplied_names_are_used_as_before(): + gate = ApprovalGate() + token = gate.request("deploy", "alice") + assert gate.approve(token, "alice") is False + assert gate.approve(token, "bob") is True + + +def test_the_executor_commands_bind_the_same_way(tmp_path): + db = str(tmp_path / "approvals.json") + executor = Executor() + with authorization_scope(_ALICE): + token = executor.execute_action( + [["AC_approval_request", {"action": "deploy", "requester": "alice", "db": db}]]) + token = next(iter(token.values()))["token"] + refused = executor.execute_action( + [["AC_approval_approve", {"token": token, "approver": "mallory", "db": db}]], + raise_on_error=False) + assert "AuthorizationError" in str(refused) + with authorization_scope(_BOB): + executor.execute_action([["AC_approval_approve", {"token": token, "approver": "bob", "db": db}]]) + assert ApprovalGate(db).is_approved(token) From a324fd1b3270839babda7a51dc2fa4b93ad2f747 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 11:22:51 +0800 Subject: [PATCH 121/161] Say which Progress.md RBAC line U-20261115-04 removed --- docs/updates/2026-11-b.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 27062d1c9..2443dfb2b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -133,7 +133,7 @@ - **What:** Closes the `BLOCKED` `Progress.md` item "minimatch 11 在 VS Code 擴充套件" and corrects U-20261101-17. GHSA-g3hv-75wg-m249 was revised on 2026-11-04: its only vulnerable range is now `>= 7.0.0, < 11.0.1` (patched 11.0.1). `autocontrol-lsp/vscode/package-lock.json` locks `minimatch` 5.1.9, which that range does not include, so the lock needs no override and no wait for `vscode-languageclient`. - **Evidence:** `gh api advisories/GHSA-g3hv-75wg-m249` (updated 2026-11-04T16:50:04Z, not withdrawn). The repository's Dependabot alerts list no `minimatch` alert in any state and 0 open alerts. npm: `vscode-languageclient` 11.0.0 (2026-10-22) requires `minimatch ^10.2.6`, inside the range, so upgrading the client to its latest release would move the extension *into* the advisory; the lock stays on 9.0.1. - **Files:** `Progress.md`, this entry, the index row, the pointer added to U-20261101-17. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-03 · 2026-11-12 · MCP tool calls are stoppable runs; a cancel stops them · #done #mcp #executor @@ -157,7 +157,7 @@ - **What:** `dev` CI run 43064397517 (commit `edc6205d`) failed the same 4 tests on all four `pytest-headless` squares: `test_webrtc_host_channels.py::test_a_mic_that_fails_to_close_is_still_forgotten`, `test_webrtc_viewer_control.py::test_a_microphone_that_fails_to_close_is_still_forgotten`, and both parameters of `test_webrtc_media_types.py::test_recording_releases_container_when_video_stream_cannot_be_created`. They predate U-20261111-26/-32: a mic whose close fails is now retained with its failure and the error propagates (`WebRTCMediaOwners.stop_field`), and a recorder whose setup or write failed reports `MediaRetirementError` with `UNCERTAIN` finalization from `stop()` (`docs/media_retirement_contract.md`). The newer tests (`test_webrtc_media_consumers.py`, `test_media_retirement.py`) already assert that contract. - **Fix:** the four tests now assert it too: the close error propagates, the original mic owner stays in place, `media_failures` is non-empty; the recorder's `stop()` raises `MediaRetirementError`, the container is still closed exactly once, and finalization is `UNCERTAIN`. No library code changed. - **Evidence:** the three files: 140 passed locally (they failed 4 before). -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-06 · 2026-11-12 · Split the tools/call path out of the MCP server module · #done #mcp #quality @@ -165,7 +165,7 @@ - **Seam kept:** four test modules replace `server._capture_error_screenshot`. The mixin resolves that name on `server` when a tool fails, so the patch still applies; `server.py` keeps importing it (`# noqa: F401` with the reason), and a new test (`test_mcp_call_run.py::test_failure_screenshot_is_still_looked_up_on_the_server_module`) fails if the lookup ever binds early. - **Evidence:** MCP, run-control, RBAC, surface, cross-project, facade and budget test files: 1,704 passed, 1 failed (the `test_sync_workspace_surfaces.py` long-path case that fails on the unchanged tree too, see U-20261112-03). Ruff and Radon clean; typing contract on win32/linux/darwin: 0 modules with errors. - **Files:** `utils/mcp_server/{server.py,_tool_calls.py (new)}`, `test_mcp_call_run.py`, `architecture_explore.md` (re-measured with `--fix`), `Progress.md`. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-07 · 2026-11-12 · Build only the first start-up tab; the others when first selected · #done #gui #performance @@ -181,7 +181,7 @@ - **What:** `dev` CI run 43077567957 (U-20261112-03) failed `test_typing_modernization_contract.py::test_every_module_is_strict_or_predates_the_tier` on top of the four WebRTC tests of U-20261112-05: the new `utils/mcp_server/_call_run.py`, and later `_tool_calls.py` (U-20261112-06), were not in the strict `[[tool.mypy.overrides]]` block. U-20261112-03 and -06 ran the typing contract but not that test. Both modules are now listed and pass strict mypy on win32, linux and darwin. - **Also found:** `test/verify/typing_contract_verify.py --extras` on Windows (PySide6 6.11.2, aiortc 1.15.0) reported `gui.navigation` and `utils.remote_desktop.webrtc_host` as failing on the pre-session commit `edc6205d` as well. The Windows stubs type `QTreeWidgetItem.child()` as optional, and `WebRTCMediaOwners.create(...)` returned `Media | None` even with `optional=False`, which raises instead of returning `None`. `navigation.py` iterates through a `_features(group)` helper that skips missing children; `create` has an overload returning `Media` for `optional=False`; `webrtc_host.py` passes a local track to `addTrack`. CI's `typing-extras` job runs on Ubuntu, whose stubs did not flag the first. No behaviour change. - **Evidence:** the strict-tier and `dev.toml` parity tests: 23 passed; extras-config mypy for the three modules on win32 and linux, and normal-config on win32 and darwin: no issues; navigation / WebRTC / media test files: 1,169 passed, 1 skipped. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-09 · 2026-11-12 · The result hook follows AC_parallel branches · #done #executor #gui @@ -196,26 +196,26 @@ - **What:** The `Progress.md` › 雜項 bullet "能力探測" said the Windows locked-workstation / session 0 / low-integrity / capture-failure branches and three macOS preflight calls had run only against fakes, and that it was unknown whether pyobjc's `Quartz` has `CGPreflightListenEventAccess`. Those branches lived in `wrapper/capability_probes.py` (c134d367f), which no longer exists on `dev`: it went away in the 1.1.0 merge (`538a23096`), and `wrapper/capabilities.py::probe_capabilities` now reports `unverified` for Windows and macOS input and capture without calling any OS API. No code makes those calls, so the bullet is removed. - **For whoever brings a macOS probe back:** `pyobjc-framework-Quartz==12.2.2` (the version `pyobjc==12.2.2` in `pyproject.toml` resolves to) declares `CGPreflightListenEventAccess`, `CGPreflightPostEventAccess` and `CGPreflightScreenCaptureAccess`, each with signature `B` (no arguments, returns bool), together with the matching `CGRequest…Access`, in `Quartz/CoreGraphics/_metadata.py`. Read from the downloaded wheel, not run; the functions exist only on macOS 10.15 and later. - **Not covered here:** Windows session and integrity checks elsewhere (`session_guard`, `input_reach`, `agent_runtime/presence_*_windows.py`) stay under the deferred native acceptance items in `Progress.md`. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-11 · 2026-11-12 · Refuse asset paths Windows cannot create before staging · #done #config-sync #windows - **What:** Closes the `TODO` added to `Progress.md` › 雜項 earlier today (commit `7158d9a5`). On Windows with `LongPathsEnabled=0` (this machine), `test_sync_workspace_surfaces.py`'s 64 + 64-character record name staged a 265-character path under `cache/.incoming-*` and failed with `FileNotFoundError`, reported only as "asset transfer could not publish a complete generation". `utils/config_sync/assets.py` now checks first: `_path_limit()` reads `HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled` (259 when it is not 1 or cannot be read; no limit off Windows), and `_require_paths_fit` measures every published path (`generation-/files/`, longer than the staging one) and raises `ConfigSyncError` naming the length, the limit and both remedies before the cache root is created. Of the two options the item named, this is the explicit refusal; `\?\` paths were not adopted, because every reader of the returned paths would have to use them too. - **Test:** `test_sync_assets.py` +2 (refused before anything is created under a patched limit; no limit means no check). The long case of `test_workspace_command_mcp_builder_capture_review_and_materialize` now skips with the measured lengths on a host that cannot hold its path, instead of failing; CI's shorter temp root still runs it. Sync asset / workspace suites: 55 passed, 7 skipped. - **Files:** `utils/config_sync/assets.py`, the two tests, the three `docs/guides/*/usage.md`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-12 · 2026-11-12 · Move the finished on_enter note out of Progress · #docs #executor - **What:** `Progress.md` › 雜項 still carried "a state machine's single-action `on_enter` was always rejected and never ran (fixed, U-20261009-24); a machine that relied on it not running now runs it". That is a finished fix with a compatibility effect, not open work, and `CHANGELOG.md` already records it under 1.0.0 (variable-scope entry) and 1.1.0. The bullet is removed; no code changed. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-13 · 2026-11-12 · Bring the shared .venv to the pinned pillow and PySide6 · #done #tooling - **What:** Closes the `Progress.md` › 雜項 line left by U-20261112-01; the maintainer approved the upgrade on 2026-11-12. Compared first with `pip install --dry-run`: pillow 12.3.0 → 13.0.0 (`pyproject.toml` pins `==13.0.0`), PySide6 / PySide6_Addons / PySide6_Essentials / shiboken6 6.11.2 → 6.12.0 (the `[gui]` pin), plus two packages PySide6 6.12 now requires, `PySide6_Pdf` and `PySide6_WebEngine` 6.12.0.140. Nothing else changed; `pip check` reports no conflict for these packages. - **Evidence:** GUI, imaging, theme, navigation, remote-desktop and WebRTC test files on the upgraded env: 3,099 passed, 15 skipped, 1 failed (`test_a11y_window_audit.py::test_restoring_duplicate_titles_moves_each_window_once`, the order-dependent `KeyError` that fails the same way on the pre-session tree, U-20261112-07). - **Note:** CI still installs `PySide6==6.11.2` for the `pytest-headless` and `typing-extras` jobs, so the shared env is now newer than CI there; the typing-extras exempt list was measured against 6.11.2. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261112-14 · 2026-11-12 · Reading the iOS pasteboard needs an explicit allowance · #done #mobile #ios @@ -249,7 +249,7 @@ - **SonarCloud (gate: new reliability rating 3 > 1):** three python:S7497 findings in code from 2026-11-11. `webrtc_host_media.py` (`_retire_live_video`) and `webrtc_peer_cleanup.py` (`_cancel_task`) cancelled a child task and then caught every `CancelledError` from awaiting it, which also swallowed the cleaning task's own cancellation if it arrived during the wait. Both now re-raise when the running task itself is being cancelled (`asyncio.current_task().cancelling() > 0`, Python ≥ 3.11), and still absorb the child's. `asyncio.wait` was tried first but the tests' fake tasks are not futures. `webrtc_file_tasks.py` (`_observe_sender`) already keeps the first cancellation and re-raises it once the worker has exited, so it is marked `# NOSONAR python:S7497` with that reason. - **Tests:** `test_webrtc_cancel_propagation.py` (new, 2): a cancelled child is awaited and absorbed; the cleaner cancelled mid-wait ends cancelled (fails on the previous code). WebRTC / media / remote-desktop files: 1,218 passed, 18 skipped. `test_docker_artifacts.py`: 28 passed. Typing on win32 / linux / darwin clean. - **Files:** `docker/Dockerfile`, `utils/remote_desktop/{webrtc_host_media.py,webrtc_peer_cleanup.py,webrtc_file_tasks.py}`, the new test, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. ## U-20261113-04 · 2026-11-13 · `post_key_to_window` takes any printable character · #done #windows #x11 @@ -672,4 +672,4 @@ - **Change:** `ApprovalGate.request` and `approve` / `reject` take the principal from `current_authorization()` inside an RBAC scope: a supplied name that is not that user (compared as `_principal` compares, trimmed, NFKC, case-folded) raises `AuthorizationError`, an empty one means that user. Outside RBAC nothing changes. The executor commands and MCP tools call the gate, so both are covered. The approval rows in `OPERATOR_NOTES`, both v32 feature docs and `CHANGELOG.md` say so. - **Tests:** new `test_governance_approval_identity.py` (self-approval under another name refused, an empty name is the user, another user approves, a request under another name refused, the non-RBAC path unchanged, the executor commands end to end) with the governance, command-review, MCP safety, resilience, redaction and shared-JSON tests: 126 passed. - **Files:** `utils/governance/governance.py`, `utils/rbac/command_review.py`, the test, `docs/source/{Eng,Zh}/doc/new_features/v32_features_doc.rst`, `CHANGELOG.md`, `Progress.md`. -- **Open items:** none (the RBAC bullet in `Progress.md` is removed: nothing in it is open any more). +- **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. From fc8e0843a92f6b3494813698c99a4057cc5acf8a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 11:30:38 +0800 Subject: [PATCH 122/161] Hold 896 older modules to the strict typing tier They already passed disallow_untyped_defs and disallow_any_generics on all three target platforms, real Qt and aiortc types included, but the shrink-only lists left them free to regress. --- Progress.md | 2 +- docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + .../accessibility/backends/null_backend.py | 2 +- .../utils/critical_exit/critical_exit.py | 2 +- .../utils/vision/backends/null_backend.py | 2 +- pyproject.toml | 902 ++++++++++++++++-- test/verify/typing_not_yet_strict.txt | 193 ---- test/verify/typing_strict_baseline.txt | 703 -------------- 9 files changed, 851 insertions(+), 964 deletions(-) diff --git a/Progress.md b/Progress.md index becaff441..503172688 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;仍缺嚴格型別深化、完整範例/文件及最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的 896 個舊模組(U-20261115-05,共 1,039 個)。仍缺:`test/verify/typing_strict_baseline.txt` 344 個與 `typing_not_yet_strict.txt` 141 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台合計約 2,500 個錯誤,集中在 478 個檔案;其中 6 個只差模組層級的 `X = Any` 別名),以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 2443dfb2b..f6fd0ffce 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -673,3 +673,11 @@ - **Tests:** new `test_governance_approval_identity.py` (self-approval under another name refused, an empty name is the user, another user approves, a request under another name refused, the non-RBAC path unchanged, the executor commands end to end) with the governance, command-review, MCP safety, resilience, redaction and shared-JSON tests: 126 passed. - **Files:** `utils/governance/governance.py`, `utils/rbac/command_review.py`, the test, `docs/source/{Eng,Zh}/doc/new_features/v32_features_doc.rst`, `CHANGELOG.md`, `Progress.md`. - **Open items:** none; the executor-review line under `Progress.md` › RBAC is removed, and the other RBAC sub-items stay open. + +## U-20261115-05 · 2026-11-15 · 896 older modules join the strict typing tier · #done #typing + +- **What:** part of `Progress.md` › *跨平台與 GUI 全面改版* › H, "嚴格型別深化". The strict tier (`disallow_untyped_defs`, `disallow_any_generics`) held 143 modules; 1,047 sat in `typing_strict_baseline.txt` and 334 in `typing_not_yet_strict.txt`, both shrink-only. Measured with mypy 2.4.0 and both flags on package-wide for `--platform win32`, `linux` and `darwin`: 2,552 / 2,538 / 2,540 errors in 478 / 476 / 478 files, so 709 baseline and 193 not-yet-strict modules already passed on all three targets. +- **Change:** 896 of them move into the strict block of `pyproject.toml` (a package that is strict all the way down is named as `pkg` and `pkg.*`, so a file added to it is covered; 901 patterns, 1,039 modules) and leave both lists (1,047 → 344 entries, 334 → 141). Six stay out because they bind a module-level name to `Any`, which the contract allows only in the SDK adapter: `wrapper.backend_contract`, `grid_locator`, `grounding_consensus`, `match_ensemble`, `match_stability`, `scale_detect`. Three needed only `-> None` on `__init__`: `critical_exit`, the vision and accessibility null backends. +- **Tests:** `test/verify/typing_contract_verify.py` (three platforms) and `--extras` (real PySide6 6.12.0 / aiortc 1.15.0 / av types, the versions CI pins): 0 modules failing in either. `test_typing_modernization_contract.py`: 14 passed. +- **Files:** `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `test/verify/typing_not_yet_strict.txt`, the three constructors, `Progress.md`. +- **Open items:** `Progress.md` › H (the 485 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index 5cb5344ff..cff0053c0 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-05 | 2026-11-15 | 896 older modules join the strict typing tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-04 | 2026-11-15 | The approval gate binds maker and checker to the RBAC user | #done #rbac #governance | [2026-11-b](2026-11-b.md) | | U-20261115-03 | 2026-11-15 | Every AC_* command has an RBAC decision | #done #rbac #security | [2026-11-b](2026-11-b.md) | | U-20261115-02 | 2026-11-15 | dnspython 2.9.2 in uv.lock for Dependabot alert 177 | #release #security #dependencies | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/accessibility/backends/null_backend.py b/je_auto_control/utils/accessibility/backends/null_backend.py index 2b7ecc7a8..55bc8e17a 100644 --- a/je_auto_control/utils/accessibility/backends/null_backend.py +++ b/je_auto_control/utils/accessibility/backends/null_backend.py @@ -15,7 +15,7 @@ class NullAccessibilityBackend(AccessibilityBackend): name = "null" available = False - def __init__(self, reason: str = "no accessibility backend available"): + def __init__(self, reason: str = "no accessibility backend available") -> None: self._reason = reason def list_elements(self, app_name: Optional[str] = None, diff --git a/je_auto_control/utils/critical_exit/critical_exit.py b/je_auto_control/utils/critical_exit/critical_exit.py index 076e5682c..a978553d4 100644 --- a/je_auto_control/utils/critical_exit/critical_exit.py +++ b/je_auto_control/utils/critical_exit/critical_exit.py @@ -43,7 +43,7 @@ class CriticalExit(Thread): - 預設為 F7 鍵 """ - def __init__(self, default_daemon: bool = True): + def __init__(self, default_daemon: bool = True) -> None: """ 初始化 CriticalExit Initialize CriticalExit diff --git a/je_auto_control/utils/vision/backends/null_backend.py b/je_auto_control/utils/vision/backends/null_backend.py index 7ea8db695..4851d2114 100644 --- a/je_auto_control/utils/vision/backends/null_backend.py +++ b/je_auto_control/utils/vision/backends/null_backend.py @@ -12,7 +12,7 @@ class NullVLMBackend(VLMBackend): name = "null" available = False - def __init__(self, reason: str = "no VLM backend available"): + def __init__(self, reason: str = "no VLM backend available") -> None: self._reason = reason def locate(self, image_bytes: bytes, description: str, diff --git a/pyproject.toml b/pyproject.toml index 9e5725d4a..6a61e6988 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -355,132 +355,906 @@ ignore_missing_imports = true # as a whole is named with `.*` as well, so a file added to it is covered the # day it is written. Nothing here loosens a setting from `[tool.mypy]`. module = [ - "je_auto_control.utils.remote_desktop.webrtc_retirement", - "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", - "je_auto_control.utils.remote_desktop.media_retirement", - "je_auto_control.utils.remote_desktop.webrtc_media_owners", - "je_auto_control.utils.remote_desktop.audio_retirement", + "je_auto_control.__main__", + "je_auto_control._export_bindings", + "je_auto_control._lazy_exports", + "je_auto_control.android", "je_auto_control.android.apps", + "je_auto_control.android.find", "je_auto_control.android.input", "je_auto_control.android.screen", "je_auto_control.android.session", + "je_auto_control.api", + "je_auto_control.api.*", + "je_auto_control.gui", + "je_auto_control.gui._arrow_icons", + "je_auto_control.gui._daemon_thread", + "je_auto_control.gui._dispose", + "je_auto_control.gui._i18n_helpers", + "je_auto_control.gui._image_detect_tab", + "je_auto_control.gui._qt_typed", + "je_auto_control.gui._report_tab", + "je_auto_control.gui._screen_geometry", + "je_auto_control.gui._screenshot_tab", + "je_auto_control.gui._slow_op", + "je_auto_control.gui._stop_custody", "je_auto_control.gui._tab_close_icon", + "je_auto_control.gui._tab_task", + "je_auto_control.gui._task_details", + "je_auto_control.gui._validators", + "je_auto_control.gui._weak_call", + "je_auto_control.gui._worker_thread", + "je_auto_control.gui.adaptive", + "je_auto_control.gui.adaptive.*", + "je_auto_control.gui.adaptive_window", "je_auto_control.gui.config_sync_tab", + "je_auto_control.gui.config_sync_worker", + "je_auto_control.gui.diagnostics_capabilities", + "je_auto_control.gui.diagnostics_tab", + "je_auto_control.gui.failed_stops_view", + "je_auto_control.gui.healing_evaluation_panel", + "je_auto_control.gui.healing_evaluation_worker", + "je_auto_control.gui.journal_browser", + "je_auto_control.gui.journal_browser_worker", + "je_auto_control.gui.journal_candidate_dialog", + "je_auto_control.gui.journal_candidate_panel", + "je_auto_control.gui.journal_candidate_worker", + "je_auto_control.gui.language_wrapper", + "je_auto_control.gui.language_wrapper.english", + "je_auto_control.gui.language_wrapper.japanese", + "je_auto_control.gui.language_wrapper.simplified_chinese", + "je_auto_control.gui.language_wrapper.traditional_chinese", + "je_auto_control.gui.manual_run_controls", + "je_auto_control.gui.mcp_discovery_view", "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", - "je_auto_control.gui.workspace_details", - "je_auto_control.gui._task_details", - "je_auto_control.gui._stop_custody", - "je_auto_control.gui.failed_stops_view", - "je_auto_control.gui.remote_desktop.webrtc_panel_state", - "je_auto_control.gui.remote_desktop.view_lifetime", - "je_auto_control.gui.remote_desktop.view_approvals", - "je_auto_control.gui.remote_desktop.view_frames", - "je_auto_control.gui.remote_desktop.view_upload", - "je_auto_control.gui.remote_desktop._host_ops", - "je_auto_control.gui.rbac_users_panel", + "je_auto_control.gui.remote_desktop", "je_auto_control.gui.remote_desktop._connect_task", + "je_auto_control.gui.remote_desktop._host_ops", "je_auto_control.gui.remote_desktop._webrtc_types", + "je_auto_control.gui.remote_desktop.advanced_group", + "je_auto_control.gui.remote_desktop.connection_recent", + "je_auto_control.gui.remote_desktop.folder_sync_controls", + "je_auto_control.gui.remote_desktop.folder_sync_io", + "je_auto_control.gui.remote_desktop.tab", + "je_auto_control.gui.remote_desktop.trusted_group", + "je_auto_control.gui.remote_desktop.view_approvals", + "je_auto_control.gui.remote_desktop.view_frames", + "je_auto_control.gui.remote_desktop.view_lifetime", + "je_auto_control.gui.remote_desktop.view_upload", "je_auto_control.gui.remote_desktop.webrtc_host_connection", "je_auto_control.gui.remote_desktop.webrtc_host_media", "je_auto_control.gui.remote_desktop.webrtc_host_sessions", "je_auto_control.gui.remote_desktop.webrtc_host_trust", "je_auto_control.gui.remote_desktop.webrtc_host_ui", "je_auto_control.gui.remote_desktop.webrtc_panel_common", + "je_auto_control.gui.remote_desktop.webrtc_panel_state", "je_auto_control.gui.remote_desktop.webrtc_viewer_address_book", "je_auto_control.gui.remote_desktop.webrtc_viewer_connection", "je_auto_control.gui.remote_desktop.webrtc_viewer_files", "je_auto_control.gui.remote_desktop.webrtc_viewer_media", "je_auto_control.gui.remote_desktop.webrtc_viewer_ui", + "je_auto_control.gui.remote_desktop_tab", + "je_auto_control.gui.script_builder.command_schema", "je_auto_control.gui.script_builder.one_time_dialog", + "je_auto_control.gui.script_builder.step_form_view", + "je_auto_control.gui.script_builder.step_list_view", + "je_auto_control.gui.selector", + "je_auto_control.gui.selector.region_selector", + "je_auto_control.gui.selector.template_cropper", "je_auto_control.gui.tab_registry", + "je_auto_control.gui.tab_task_controller", "je_auto_control.gui.task_controller", + "je_auto_control.gui.template_candidate_worker", "je_auto_control.gui.theme", + "je_auto_control.gui.workspace", + "je_auto_control.gui.workspace_details", + "je_auto_control.gui.workspace_settings", + "je_auto_control.ios", "je_auto_control.ios.apps", + "je_auto_control.ios.find", + "je_auto_control.ios.input", + "je_auto_control.ios.screen", "je_auto_control.ios.session", + "je_auto_control.linux_wayland", + "je_auto_control.linux_wayland._dbus_client", + "je_auto_control.linux_wayland._detect", + "je_auto_control.linux_wayland._input_state", + "je_auto_control.linux_wayland._layout", + "je_auto_control.linux_wayland._ydotool_cli", + "je_auto_control.linux_wayland.capture", "je_auto_control.linux_wayland.ei_default", "je_auto_control.linux_wayland.ei_protocol", "je_auto_control.linux_wayland.ei_transport", "je_auto_control.linux_wayland.ei_worker", "je_auto_control.linux_wayland.global_shortcuts", "je_auto_control.linux_wayland.input_events", + "je_auto_control.linux_wayland.keymap", + "je_auto_control.linux_wayland.oeffis", + "je_auto_control.linux_wayland.portal", + "je_auto_control.linux_wayland.record", + "je_auto_control.linux_wayland.screen", + "je_auto_control.linux_with_x11", + "je_auto_control.linux_with_x11.core", + "je_auto_control.linux_with_x11.core.*", + "je_auto_control.linux_with_x11.keyboard", + "je_auto_control.linux_with_x11.keyboard.*", + "je_auto_control.linux_with_x11.listener", + "je_auto_control.linux_with_x11.mouse", + "je_auto_control.linux_with_x11.mouse.*", + "je_auto_control.linux_with_x11.record", + "je_auto_control.linux_with_x11.screen", + "je_auto_control.linux_with_x11.screen.*", + "je_auto_control.linux_with_x11.uinput", + "je_auto_control.linux_with_x11.uinput.keyboard", + "je_auto_control.linux_with_x11.uinput.mouse", + "je_auto_control.osx", + "je_auto_control.osx.core", + "je_auto_control.osx.core.*", + "je_auto_control.osx.keyboard", + "je_auto_control.osx.keyboard.*", + "je_auto_control.osx.listener", + "je_auto_control.osx.mouse", + "je_auto_control.osx.pid", + "je_auto_control.osx.pid.*", + "je_auto_control.osx.record", + "je_auto_control.osx.record.*", + "je_auto_control.osx.screen", + "je_auto_control.osx.screen.*", + "je_auto_control.utils", + "je_auto_control.utils.a11y_audit", + "je_auto_control.utils.a11y_audit.*", + "je_auto_control.utils.a2a", + "je_auto_control.utils.a2a.*", + "je_auto_control.utils.ab_locator", + "je_auto_control.utils.ab_locator.store", + "je_auto_control.utils.accessibility", + "je_auto_control.utils.accessibility.backends", + "je_auto_control.utils.accessibility.backends.base", + "je_auto_control.utils.accessibility.backends.linux_backend", + "je_auto_control.utils.accessibility.backends.null_backend", + "je_auto_control.utils.accessibility.backends.windows_automation", + "je_auto_control.utils.accessibility.backends.windows_events", + "je_auto_control.utils.accessibility.recorder", + "je_auto_control.utils.accessibility.tree", + "je_auto_control.utils.acme_v2", + "je_auto_control.utils.acme_v2.jws", + "je_auto_control.utils.act_in_view", + "je_auto_control.utils.act_modes", + "je_auto_control.utils.act_modes.*", + "je_auto_control.utils.action_effect", + "je_auto_control.utils.action_grounding", + "je_auto_control.utils.action_grounding.*", "je_auto_control.utils.action_journal", "je_auto_control.utils.action_journal.*", - "je_auto_control.utils.action_journal.events", - "je_auto_control.utils.action_journal.store", + "je_auto_control.utils.action_lint", + "je_auto_control.utils.action_lint.__main__", + "je_auto_control.utils.action_lint.schema", + "je_auto_control.utils.action_signing", + "je_auto_control.utils.action_signing._key_file", "je_auto_control.utils.action_signing._private_file", "je_auto_control.utils.action_signing.asymmetric", "je_auto_control.utils.action_signing.config", - "je_auto_control.utils.agent.backends._computer_actions", - "je_auto_control.utils.agent.backends._computer_beta_path", - "je_auto_control.utils.agent.backends._computer_messages", - "je_auto_control.utils.agent.backends._computer_toolset_path", + "je_auto_control.utils.action_signing.signer", + "je_auto_control.utils.actionability", + "je_auto_control.utils.adaptive_timeout", + "je_auto_control.utils.adaptive_timeout.*", + "je_auto_control.utils.admin", + "je_auto_control.utils.agent", + "je_auto_control.utils.agent.backends", + "je_auto_control.utils.agent.backends.*", + "je_auto_control.utils.agent.computer_use", + "je_auto_control.utils.agent_memory", + "je_auto_control.utils.agent_memory.*", + "je_auto_control.utils.agent_replay", + "je_auto_control.utils.agent_replay.*", + "je_auto_control.utils.agent_runtime", + "je_auto_control.utils.agent_runtime.__main__", + "je_auto_control.utils.agent_runtime.activity", + "je_auto_control.utils.agent_runtime.android_action_result", + "je_auto_control.utils.agent_runtime.android_geometry", + "je_auto_control.utils.agent_runtime.android_session", + "je_auto_control.utils.agent_runtime.android_transport", + "je_auto_control.utils.agent_runtime.browser_environment", + "je_auto_control.utils.agent_runtime.browser_validation", + "je_auto_control.utils.agent_runtime.budget_clock", + "je_auto_control.utils.agent_runtime.client", + "je_auto_control.utils.agent_runtime.context", + "je_auto_control.utils.agent_runtime.control_admission", + "je_auto_control.utils.agent_runtime.delegation", + "je_auto_control.utils.agent_runtime.document_launch", + "je_auto_control.utils.agent_runtime.evidence_cache", + "je_auto_control.utils.agent_runtime.helper_environment", + "je_auto_control.utils.agent_runtime.images", + "je_auto_control.utils.agent_runtime.jobs", + "je_auto_control.utils.agent_runtime.models", + "je_auto_control.utils.agent_runtime.native_job", + "je_auto_control.utils.agent_runtime.ollama", + "je_auto_control.utils.agent_runtime.owner_service_nested", + "je_auto_control.utils.agent_runtime.owner_service_wire", + "je_auto_control.utils.agent_runtime.ownership", + "je_auto_control.utils.agent_runtime.parent_watch", + "je_auto_control.utils.agent_runtime.path_identity", + "je_auto_control.utils.agent_runtime.policy", + "je_auto_control.utils.agent_runtime.presence_endpoint_linux", + "je_auto_control.utils.agent_runtime.presence_native_types", + "je_auto_control.utils.agent_runtime.presence_peer_linux", + "je_auto_control.utils.agent_runtime.presence_pipe_linux", + "je_auto_control.utils.agent_runtime.presence_pipe_windows", + "je_auto_control.utils.agent_runtime.presence_platform", + "je_auto_control.utils.agent_runtime.presence_quartz", + "je_auto_control.utils.agent_runtime.presence_security_windows", + "je_auto_control.utils.agent_runtime.presence_win32", + "je_auto_control.utils.agent_runtime.presence_x11", + "je_auto_control.utils.agent_runtime.readiness", + "je_auto_control.utils.agent_runtime.resume_gate", + "je_auto_control.utils.agent_runtime.retention", + "je_auto_control.utils.agent_runtime.runtime_lock", + "je_auto_control.utils.agent_runtime.service", + "je_auto_control.utils.agent_runtime.target_continuity", + "je_auto_control.utils.agent_runtime.target_factory", + "je_auto_control.utils.agent_runtime.transfer_cache", + "je_auto_control.utils.agent_runtime.transfer_files", + "je_auto_control.utils.agent_runtime.transfer_import_jobs", + "je_auto_control.utils.agent_runtime.transfer_operations", + "je_auto_control.utils.agent_runtime.transfer_records", + "je_auto_control.utils.agent_runtime.window_pixels", + "je_auto_control.utils.agent_runtime.wire_data", + "je_auto_control.utils.agent_runtime.workflow_files", + "je_auto_control.utils.agent_trace", + "je_auto_control.utils.agent_trace.*", + "je_auto_control.utils.anchor_locator", + "je_auto_control.utils.anchor_locator.*", + "je_auto_control.utils.annotate", + "je_auto_control.utils.annotate.*", + "je_auto_control.utils.anomaly", + "je_auto_control.utils.anomaly.*", + "je_auto_control.utils.app_idle", + "je_auto_control.utils.app_idle.*", + "je_auto_control.utils.approval", + "je_auto_control.utils.artifact_store", + "je_auto_control.utils.assertion", + "je_auto_control.utils.assertion.*", + "je_auto_control.utils.assets", + "je_auto_control.utils.assets.*", + "je_auto_control.utils.ax_events", + "je_auto_control.utils.ax_events.*", + "je_auto_control.utils.ax_props", + "je_auto_control.utils.ax_props.*", + "je_auto_control.utils.ax_text", + "je_auto_control.utils.ax_tree_walk", + "je_auto_control.utils.ax_tree_walk.*", + "je_auto_control.utils.baggage", + "je_auto_control.utils.baggage.*", + "je_auto_control.utils.barcode", + "je_auto_control.utils.bidi_check", + "je_auto_control.utils.bidi_check.*", + "je_auto_control.utils.bulkhead", + "je_auto_control.utils.callback", + "je_auto_control.utils.cancellable_process", + "je_auto_control.utils.canonical_log", + "je_auto_control.utils.canonical_log.*", + "je_auto_control.utils.change_localize", + "je_auto_control.utils.chaos", + "je_auto_control.utils.chaos.*", + "je_auto_control.utils.chatops", + "je_auto_control.utils.chatops.handlers", + "je_auto_control.utils.chatops.router", + "je_auto_control.utils.checkpoint", + "je_auto_control.utils.checkpoint.*", + "je_auto_control.utils.checksum", + "je_auto_control.utils.checksum.*", + "je_auto_control.utils.ci_annotations", + "je_auto_control.utils.ci_annotations.*", + "je_auto_control.utils.cli_output", + "je_auto_control.utils.clipboard", + "je_auto_control.utils.clipboard.win32_clipboard_api", + "je_auto_control.utils.clipboard_files", + "je_auto_control.utils.clipboard_files.*", + "je_auto_control.utils.clipboard_formats", + "je_auto_control.utils.clipboard_history", + "je_auto_control.utils.clipboard_history.*", + "je_auto_control.utils.clipboard_rich_formats", + "je_auto_control.utils.clipboard_rich_formats.*", + "je_auto_control.utils.codegen", + "je_auto_control.utils.codegen.candidate_archive", + "je_auto_control.utils.codegen.candidate_models", + "je_auto_control.utils.codegen.candidate_validation", + "je_auto_control.utils.codegen.journal_cli", + "je_auto_control.utils.codegen.journal_commands", "je_auto_control.utils.codegen.journal_import", + "je_auto_control.utils.codegen.journal_selection", + "je_auto_control.utils.codegen.journal_source", + "je_auto_control.utils.codegen.journal_steps", "je_auto_control.utils.codegen.robot_check", - "je_auto_control.utils.config_sync.adapters", - "je_auto_control.utils.config_sync.assets", - "je_auto_control.utils.config_sync.client", - "je_auto_control.utils.config_sync.outbox", - "je_auto_control.utils.config_sync.store", - "je_auto_control.utils.config_sync.versions", + "je_auto_control.utils.color_match", + "je_auto_control.utils.color_region", + "je_auto_control.utils.color_stats", + "je_auto_control.utils.color_stats.*", + "je_auto_control.utils.column_layout", + "je_auto_control.utils.column_layout.*", + "je_auto_control.utils.compliance", + "je_auto_control.utils.config_bundle", + "je_auto_control.utils.config_redaction", + "je_auto_control.utils.config_redaction.*", + "je_auto_control.utils.config_schema", + "je_auto_control.utils.config_schema.*", + "je_auto_control.utils.config_sync", + "je_auto_control.utils.config_sync.*", + "je_auto_control.utils.confusables", + "je_auto_control.utils.confusables.*", + "je_auto_control.utils.contrast_map", + "je_auto_control.utils.control_patterns", + "je_auto_control.utils.cookie_jar", + "je_auto_control.utils.cookie_jar.*", + "je_auto_control.utils.coordinate_space", + "je_auto_control.utils.coordinate_space.*", + "je_auto_control.utils.cost_telemetry.store", + "je_auto_control.utils.critic_features", + "je_auto_control.utils.critic_features.*", + "je_auto_control.utils.critical_exit", + "je_auto_control.utils.critical_exit.*", + "je_auto_control.utils.cua_action", + "je_auto_control.utils.cv2_utils", + "je_auto_control.utils.cv2_utils.frame_clock", + "je_auto_control.utils.cv2_utils.image_file", + "je_auto_control.utils.cv2_utils.locator_frame", + "je_auto_control.utils.cv2_utils.optional", + "je_auto_control.utils.cv2_utils.region_capture", + "je_auto_control.utils.cv2_utils.screen_grabber", + "je_auto_control.utils.cv2_utils.screenshot", + "je_auto_control.utils.cv2_utils.template_detection", + "je_auto_control.utils.cvd_simulate", + "je_auto_control.utils.cvd_simulate.*", + "je_auto_control.utils.dag", + "je_auto_control.utils.dag.graph", + "je_auto_control.utils.dag.task_contract", + "je_auto_control.utils.data_drift", + "je_auto_control.utils.data_drift.*", + "je_auto_control.utils.data_profile", + "je_auto_control.utils.data_profile.*", + "je_auto_control.utils.data_quality", + "je_auto_control.utils.data_source", + "je_auto_control.utils.data_source.*", + "je_auto_control.utils.dataset_diff", + "je_auto_control.utils.dataset_diff.*", + "je_auto_control.utils.dbus_client", + "je_auto_control.utils.dbus_client.cancellable_io", + "je_auto_control.utils.decision_table", + "je_auto_control.utils.decision_table.*", + "je_auto_control.utils.dedup_window", + "je_auto_control.utils.dedup_window.*", + "je_auto_control.utils.deterministic", + "je_auto_control.utils.device_matrix", + "je_auto_control.utils.device_matrix.*", + "je_auto_control.utils.diagnostics", + "je_auto_control.utils.diagnostics.capability_commands", + "je_auto_control.utils.diagnostics.diagnostics", + "je_auto_control.utils.dotenv", + "je_auto_control.utils.dotenv.*", + "je_auto_control.utils.edge_lines", + "je_auto_control.utils.edge_match", + "je_auto_control.utils.egress", + "je_auto_control.utils.egress.*", + "je_auto_control.utils.element_diff", + "je_auto_control.utils.element_parse", + "je_auto_control.utils.element_parse.*", + "je_auto_control.utils.element_proposal", + "je_auto_control.utils.element_proposal.*", + "je_auto_control.utils.element_repository", + "je_auto_control.utils.element_repository.*", + "je_auto_control.utils.element_scoring", + "je_auto_control.utils.element_scoring.*", + "je_auto_control.utils.email_send", + "je_auto_control.utils.email_send.*", + "je_auto_control.utils.ensure_state", + "je_auto_control.utils.ensure_state.*", + "je_auto_control.utils.events", + "je_auto_control.utils.events.*", + "je_auto_control.utils.exception", + "je_auto_control.utils.exception.*", + "je_auto_control.utils.executor", + "je_auto_control.utils.executor.action_redaction", + "je_auto_control.utils.executor.flags", + "je_auto_control.utils.executor.result_hook", + "je_auto_control.utils.executor.run_control", + "je_auto_control.utils.expect_poll", + "je_auto_control.utils.expect_poll.*", + "je_auto_control.utils.failure_bundle", + "je_auto_control.utils.failure_hooks", + "je_auto_control.utils.failure_hooks.manager", + "je_auto_control.utils.failure_hooks.report", + "je_auto_control.utils.failure_signature", + "je_auto_control.utils.failure_signature.*", + "je_auto_control.utils.feature_flags", + "je_auto_control.utils.feature_match", + "je_auto_control.utils.field_entry", + "je_auto_control.utils.field_entry.*", + "je_auto_control.utils.file_assoc", + "je_auto_control.utils.file_assoc.*", + "je_auto_control.utils.file_dialog", + "je_auto_control.utils.file_dialog.*", + "je_auto_control.utils.file_drop", + "je_auto_control.utils.file_drop.*", + "je_auto_control.utils.file_process", + "je_auto_control.utils.file_process.*", + "je_auto_control.utils.flake_cluster", + "je_auto_control.utils.flake_cluster.*", + "je_auto_control.utils.flakiness", + "je_auto_control.utils.flakiness.*", + "je_auto_control.utils.flow_debugger", + "je_auto_control.utils.flow_debugger.*", + "je_auto_control.utils.focus_order", + "je_auto_control.utils.focus_order.*", + "je_auto_control.utils.form_fields", + "je_auto_control.utils.fuzzy", + "je_auto_control.utils.gamepad", + "je_auto_control.utils.generate_report", + "je_auto_control.utils.generate_report.generate_json_report", + "je_auto_control.utils.generate_report.generate_xml_report", "je_auto_control.utils.generate_report.report_path", - "je_auto_control.utils.rbac.tool_classification", - "je_auto_control.utils.mcp_server.tools._readonly", - "je_auto_control.utils.mcp_server.tools._handlers_accessibility_executor", - "je_auto_control.utils.mcp_server.tools._handlers_automation_executor", - "je_auto_control.utils.mcp_server.tools._handlers_data_executor", - "je_auto_control.utils.mcp_server.tools._handlers_desktop_executor", - "je_auto_control.utils.mcp_server.tools._handlers_mobile_executor", - "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", + "je_auto_control.utils.gettext_catalog", + "je_auto_control.utils.gettext_catalog.*", + "je_auto_control.utils.governance", + "je_auto_control.utils.governance.*", + "je_auto_control.utils.grid_locator", + "je_auto_control.utils.grounding_consensus", + "je_auto_control.utils.guardrail", + "je_auto_control.utils.guardrail.*", + "je_auto_control.utils.heading_segment", + "je_auto_control.utils.heading_segment.*", + "je_auto_control.utils.heal_analytics", + "je_auto_control.utils.heal_analytics.*", + "je_auto_control.utils.hotkey", + "je_auto_control.utils.hotkey.backends", + "je_auto_control.utils.hotkey.backends.base", + "je_auto_control.utils.hsv_segment", + "je_auto_control.utils.http_cassette", + "je_auto_control.utils.http_cassette.*", + "je_auto_control.utils.http_client", + "je_auto_control.utils.http_conditional", + "je_auto_control.utils.http_conditional.*", + "je_auto_control.utils.http_content", + "je_auto_control.utils.http_content.*", + "je_auto_control.utils.http_headers", + "je_auto_control.utils.http_problem", + "je_auto_control.utils.http_problem.*", + "je_auto_control.utils.humanize", + "je_auto_control.utils.humanize.*", + "je_auto_control.utils.i18n_test", + "je_auto_control.utils.icon_classify", + "je_auto_control.utils.idempotency", + "je_auto_control.utils.idempotency.*", + "je_auto_control.utils.idle_keepawake", + "je_auto_control.utils.idle_keepawake.*", + "je_auto_control.utils.image_dedup", + "je_auto_control.utils.image_quality", + "je_auto_control.utils.ime_state", + "je_auto_control.utils.ime_state.*", + "je_auto_control.utils.img_histogram", + "je_auto_control.utils.input_macro", + "je_auto_control.utils.input_reach", + "je_auto_control.utils.input_reach.*", + "je_auto_control.utils.json", + "je_auto_control.utils.json_contract", + "je_auto_control.utils.json_patch", + "je_auto_control.utils.json_schema", + "je_auto_control.utils.json_schema.ecma_regex", + "je_auto_control.utils.json_store", + "je_auto_control.utils.json_store.*", + "je_auto_control.utils.jsonpath", + "je_auto_control.utils.jsonpath.*", + "je_auto_control.utils.jwt", + "je_auto_control.utils.key_hold", + "je_auto_control.utils.key_hold.*", + "je_auto_control.utils.keyboard_layout", + "je_auto_control.utils.keyboard_layout.*", + "je_auto_control.utils.layered_config", + "je_auto_control.utils.layered_config.*", + "je_auto_control.utils.legacy_accessible", + "je_auto_control.utils.legacy_accessible.*", + "je_auto_control.utils.license_policy", + "je_auto_control.utils.license_policy.*", + "je_auto_control.utils.link_header", + "je_auto_control.utils.link_header.*", + "je_auto_control.utils.list_format", + "je_auto_control.utils.list_format.*", + "je_auto_control.utils.llm", + "je_auto_control.utils.llm.backends.base", + "je_auto_control.utils.llm.backends.null_backend", + "je_auto_control.utils.locale_collation", + "je_auto_control.utils.locale_collation.*", + "je_auto_control.utils.locale_parse", + "je_auto_control.utils.locale_parse.*", + "je_auto_control.utils.locator_chain", + "je_auto_control.utils.locator_repair", + "je_auto_control.utils.locator_repair.*", + "je_auto_control.utils.lock_session", + "je_auto_control.utils.lock_session.*", + "je_auto_control.utils.logging", + "je_auto_control.utils.logging.secret_scope", + "je_auto_control.utils.loop_guard", + "je_auto_control.utils.loop_guard.*", + "je_auto_control.utils.marks_layout", + "je_auto_control.utils.marks_layout.*", + "je_auto_control.utils.match_autothresh", + "je_auto_control.utils.match_ensemble", + "je_auto_control.utils.match_stability", + "je_auto_control.utils.match_trust", + "je_auto_control.utils.mcp_registry", + "je_auto_control.utils.mcp_registry.*", + "je_auto_control.utils.mcp_server", "je_auto_control.utils.mcp_server._argument_policy", "je_auto_control.utils.mcp_server._authz", "je_auto_control.utils.mcp_server._call_run", - "je_auto_control.utils.mcp_server._tool_calls", + "je_auto_control.utils.mcp_server._client_requests", "je_auto_control.utils.mcp_server._http_origin", "je_auto_control.utils.mcp_server._http_responses", + "je_auto_control.utils.mcp_server._http_stateless", + "je_auto_control.utils.mcp_server._input_required", + "je_auto_control.utils.mcp_server._origin_policies", + "je_auto_control.utils.mcp_server._stateless", + "je_auto_control.utils.mcp_server._tool_calls", + "je_auto_control.utils.mcp_server._tool_notifications", + "je_auto_control.utils.mcp_server.audit", + "je_auto_control.utils.mcp_server.context", "je_auto_control.utils.mcp_server.disclosure", "je_auto_control.utils.mcp_server.discovery", + "je_auto_control.utils.mcp_server.http_sessions", + "je_auto_control.utils.mcp_server.log_bridge", + "je_auto_control.utils.mcp_server.prompts", + "je_auto_control.utils.mcp_server.rate_limit", + "je_auto_control.utils.mcp_server.resources", + "je_auto_control.utils.mcp_server.stdio", + "je_auto_control.utils.mcp_server.tools", + "je_auto_control.utils.mcp_server.tools._agent_tasks", + "je_auto_control.utils.mcp_server.tools._base", + "je_auto_control.utils.mcp_server.tools._capabilities", + "je_auto_control.utils.mcp_server.tools._diagnostics", + "je_auto_control.utils.mcp_server.tools._factories", + "je_auto_control.utils.mcp_server.tools._handlers_accessibility_executor", + "je_auto_control.utils.mcp_server.tools._handlers_automation_executor", + "je_auto_control.utils.mcp_server.tools._handlers_data_executor", + "je_auto_control.utils.mcp_server.tools._handlers_desktop_executor", + "je_auto_control.utils.mcp_server.tools._handlers_input", + "je_auto_control.utils.mcp_server.tools._handlers_journal", + "je_auto_control.utils.mcp_server.tools._handlers_mobile_executor", + "je_auto_control.utils.mcp_server.tools._handlers_qa", + "je_auto_control.utils.mcp_server.tools._handlers_remote", + "je_auto_control.utils.mcp_server.tools._handlers_runs", + "je_auto_control.utils.mcp_server.tools._handlers_scheduling", + "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", + "je_auto_control.utils.mcp_server.tools._healing_evaluation", + "je_auto_control.utils.mcp_server.tools._healing_run", + "je_auto_control.utils.mcp_server.tools._healing_source", + "je_auto_control.utils.mcp_server.tools._readonly", + "je_auto_control.utils.mcp_server.tools._template_candidates", + "je_auto_control.utils.media_assert", + "je_auto_control.utils.message_format", + "je_auto_control.utils.modifier_state", + "je_auto_control.utils.modifier_state.*", + "je_auto_control.utils.monitor_layout", "je_auto_control.utils.monitor_layout.macos_frame", - "je_auto_control.utils.process_memory", - "je_auto_control.utils.process_memory.*", + "je_auto_control.utils.monitor_layout.monitor_layout", + "je_auto_control.utils.motion_regions", + "je_auto_control.utils.mouse_path", + "je_auto_control.utils.mouse_path.*", + "je_auto_control.utils.mouse_relative", + "je_auto_control.utils.mouse_relative.*", + "je_auto_control.utils.multipart", + "je_auto_control.utils.multipart.*", + "je_auto_control.utils.near_dup", + "je_auto_control.utils.near_dup.*", + "je_auto_control.utils.notify", + "je_auto_control.utils.notify.*", + "je_auto_control.utils.notify_channels", + "je_auto_control.utils.notify_channels.*", + "je_auto_control.utils.observability", + "je_auto_control.utils.observability.metrics", + "je_auto_control.utils.observation", + "je_auto_control.utils.observation.*", + "je_auto_control.utils.observation_delta", + "je_auto_control.utils.observation_delta.*", + "je_auto_control.utils.observer", + "je_auto_control.utils.observer.*", + "je_auto_control.utils.ocr", + "je_auto_control.utils.ocr.structure", "je_auto_control.utils.ocr.tesseract_setup", + "je_auto_control.utils.ocr.text_span", + "je_auto_control.utils.office", + "je_auto_control.utils.office.*", + "je_auto_control.utils.optimistic", + "je_auto_control.utils.optimistic.*", + "je_auto_control.utils.otlp_export", + "je_auto_control.utils.otlp_export.*", + "je_auto_control.utils.otp", + "je_auto_control.utils.otp.*", + "je_auto_control.utils.outbox", + "je_auto_control.utils.outbox.*", + "je_auto_control.utils.package_manager", + "je_auto_control.utils.path_guard", "je_auto_control.utils.path_guard.policy", - "je_auto_control.utils.rbac.__main__", - "je_auto_control.utils.rbac.admin", - "je_auto_control.utils.rbac.authorization", - "je_auto_control.utils.rbac.cli", - "je_auto_control.utils.rbac.command_review", - "je_auto_control.utils.rbac.deferred", - "je_auto_control.utils.rbac.policy", + "je_auto_control.utils.pdf", + "je_auto_control.utils.percentiles", + "je_auto_control.utils.percentiles.*", + "je_auto_control.utils.perceptual_diff", + "je_auto_control.utils.pii_text", + "je_auto_control.utils.pii_text.*", + "je_auto_control.utils.platform_id", + "je_auto_control.utils.platform_id.*", + "je_auto_control.utils.plugin_loader", + "je_auto_control.utils.plugin_loader.*", + "je_auto_control.utils.plugin_sdk", + "je_auto_control.utils.plugin_sdk.*", + "je_auto_control.utils.postcondition", + "je_auto_control.utils.preprocess", + "je_auto_control.utils.process_doc", + "je_auto_control.utils.process_doc.*", + "je_auto_control.utils.process_memory", + "je_auto_control.utils.process_memory.*", + "je_auto_control.utils.process_mining", + "je_auto_control.utils.profiler", + "je_auto_control.utils.profiler.profiler", + "je_auto_control.utils.project", + "je_auto_control.utils.project.create_project_structure", + "je_auto_control.utils.project.template", + "je_auto_control.utils.project.template.template_executor", + "je_auto_control.utils.provenance", + "je_auto_control.utils.provenance.*", + "je_auto_control.utils.pytest_plugin", + "je_auto_control.utils.pytest_plugin.plugin", + "je_auto_control.utils.qr", + "je_auto_control.utils.quarantine", + "je_auto_control.utils.quarantine.*", + "je_auto_control.utils.rate_limit", + "je_auto_control.utils.rbac", + "je_auto_control.utils.rbac.*", + "je_auto_control.utils.readability", + "je_auto_control.utils.readability.*", + "je_auto_control.utils.reading_flow", + "je_auto_control.utils.recording_edit", + "je_auto_control.utils.recurrence", + "je_auto_control.utils.redaction", + "je_auto_control.utils.redaction.engine", + "je_auto_control.utils.referential", + "je_auto_control.utils.referential.*", + "je_auto_control.utils.remote_desktop", + "je_auto_control.utils.remote_desktop._export_bindings", + "je_auto_control.utils.remote_desktop._optional", + "je_auto_control.utils.remote_desktop._optional.*", + "je_auto_control.utils.remote_desktop.audio_retirement", + "je_auto_control.utils.remote_desktop.auth", + "je_auto_control.utils.remote_desktop.clipboard_delivery", + "je_auto_control.utils.remote_desktop.clipboard_sync", + "je_auto_control.utils.remote_desktop.file_receipts", + "je_auto_control.utils.remote_desktop.file_sync", + "je_auto_control.utils.remote_desktop.host_id", + "je_auto_control.utils.remote_desktop.input_send_queue", + "je_auto_control.utils.remote_desktop.media_retirement", + "je_auto_control.utils.remote_desktop.presence", + "je_auto_control.utils.remote_desktop.rate_limit", + "je_auto_control.utils.remote_desktop.relay", + "je_auto_control.utils.remote_desktop.resume_tokens", + "je_auto_control.utils.remote_desktop.session_actions", + "je_auto_control.utils.remote_desktop.totp", + "je_auto_control.utils.remote_desktop.video_codec", + "je_auto_control.utils.remote_desktop.viewer_id", + "je_auto_control.utils.remote_desktop.wake_on_lan", + "je_auto_control.utils.remote_desktop.webrtc_file_callbacks", + "je_auto_control.utils.remote_desktop.webrtc_file_commit", + "je_auto_control.utils.remote_desktop.webrtc_file_receive", + "je_auto_control.utils.remote_desktop.webrtc_file_tasks", + "je_auto_control.utils.remote_desktop.webrtc_file_write", + "je_auto_control.utils.remote_desktop.webrtc_inspector", + "je_auto_control.utils.remote_desktop.webrtc_media_owners", + "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", + "je_auto_control.utils.remote_desktop.webrtc_retirement", + "je_auto_control.utils.resilience", + "je_auto_control.utils.resilience.*", + "je_auto_control.utils.rest_api", + "je_auto_control.utils.rest_api.rest_auth", + "je_auto_control.utils.rest_api.rest_metrics", + "je_auto_control.utils.rest_api.rest_openapi", + "je_auto_control.utils.rest_api.rest_registry", + "je_auto_control.utils.retry_budget", + "je_auto_control.utils.retry_budget.*", + "je_auto_control.utils.rich_clipboard", + "je_auto_control.utils.rotated_match", + "je_auto_control.utils.run_diff", + "je_auto_control.utils.run_history", + "je_auto_control.utils.run_history.*", + "je_auto_control.utils.saga", + "je_auto_control.utils.saga.*", + "je_auto_control.utils.saliency", + "je_auto_control.utils.sarif", + "je_auto_control.utils.sarif.*", + "je_auto_control.utils.sbom", + "je_auto_control.utils.scale_detect", + "je_auto_control.utils.scheduler", + "je_auto_control.utils.scheduler.cron", + "je_auto_control.utils.schema_compat", + "je_auto_control.utils.screen_grid", + "je_auto_control.utils.screen_grid.*", + "je_auto_control.utils.screen_state", + "je_auto_control.utils.script_vars", "je_auto_control.utils.script_vars.execution", - "je_auto_control.utils.self_healing.evaluation", - "je_auto_control.utils.self_healing.verification", + "je_auto_control.utils.script_vars.ref_guard", + "je_auto_control.utils.script_vars.scope", + "je_auto_control.utils.scroll_find", + "je_auto_control.utils.scroll_find.*", + "je_auto_control.utils.search_index", + "je_auto_control.utils.secret_ref", + "je_auto_control.utils.secret_ref.*", + "je_auto_control.utils.secrets", + "je_auto_control.utils.secrets_scan", + "je_auto_control.utils.selection_view", + "je_auto_control.utils.self_healing", + "je_auto_control.utils.self_healing.*", + "je_auto_control.utils.semantic_recording", + "je_auto_control.utils.semantic_recording.replay", + "je_auto_control.utils.sequence_gap", + "je_auto_control.utils.sequence_gap.*", + "je_auto_control.utils.session_guard", + "je_auto_control.utils.session_guard.*", + "je_auto_control.utils.set_of_marks", + "je_auto_control.utils.set_of_marks.*", + "je_auto_control.utils.settle_detector", + "je_auto_control.utils.settle_detector.*", + "je_auto_control.utils.shape_locator", + "je_auto_control.utils.shell_open", + "je_auto_control.utils.shell_open.*", + "je_auto_control.utils.shell_process", + "je_auto_control.utils.skill_library", + "je_auto_control.utils.skill_library.*", + "je_auto_control.utils.slo", + "je_auto_control.utils.smart_waits", + "je_auto_control.utils.smoothing", + "je_auto_control.utils.smoothing.*", + "je_auto_control.utils.socket_server", + "je_auto_control.utils.soft_assert", + "je_auto_control.utils.sql", + "je_auto_control.utils.sqlite_support", + "je_auto_control.utils.sse_client", + "je_auto_control.utils.ssim", + "je_auto_control.utils.start_exe", + "je_auto_control.utils.start_exe.*", + "je_auto_control.utils.state_machine", + "je_auto_control.utils.stats", + "je_auto_control.utils.stats.*", + "je_auto_control.utils.step_repair", + "je_auto_control.utils.step_repair.*", + "je_auto_control.utils.step_timeline", + "je_auto_control.utils.step_timeline.*", + "je_auto_control.utils.stubs", + "je_auto_control.utils.stubs.*", + "je_auto_control.utils.subpixel_match", + "je_auto_control.utils.system_volume", + "je_auto_control.utils.system_volume.*", + "je_auto_control.utils.table_grid_fill", + "je_auto_control.utils.table_pattern", + "je_auto_control.utils.test_data", + "je_auto_control.utils.test_data.*", + "je_auto_control.utils.test_record", + "je_auto_control.utils.test_select", + "je_auto_control.utils.test_shard", + "je_auto_control.utils.test_shard.*", + "je_auto_control.utils.test_suite", + "je_auto_control.utils.test_suite.*", + "je_auto_control.utils.text_blocks", + "je_auto_control.utils.text_blocks.*", + "je_auto_control.utils.text_diff", + "je_auto_control.utils.text_normalize", + "je_auto_control.utils.text_normalize.*", + "je_auto_control.utils.text_regions", + "je_auto_control.utils.text_similarity", + "je_auto_control.utils.text_unicode", + "je_auto_control.utils.text_unicode.*", + "je_auto_control.utils.theme_normalize", + "je_auto_control.utils.theme_normalize.*", + "je_auto_control.utils.thread_bound", + "je_auto_control.utils.time_travel", + "je_auto_control.utils.time_travel.controller", + "je_auto_control.utils.timeouts", + "je_auto_control.utils.timeseries", + "je_auto_control.utils.timeseries.*", + "je_auto_control.utils.tls_acme", + "je_auto_control.utils.tool_use_schema", + "je_auto_control.utils.trace_context", + "je_auto_control.utils.trace_context.*", + "je_auto_control.utils.trajectory_eval", + "je_auto_control.utils.trajectory_eval.*", + "je_auto_control.utils.transform_window", + "je_auto_control.utils.trash", + "je_auto_control.utils.trash.*", + "je_auto_control.utils.triggers", + "je_auto_control.utils.tween_drag", + "je_auto_control.utils.tween_drag.*", + "je_auto_control.utils.url_canon", + "je_auto_control.utils.url_canon.*", + "je_auto_control.utils.usb", + "je_auto_control.utils.usb.passthrough", "je_auto_control.utils.usb.passthrough._client_requests", + "je_auto_control.utils.usb.passthrough.backend", "je_auto_control.utils.usb.passthrough.client_errors", "je_auto_control.utils.usb.passthrough.client_handle", + "je_auto_control.utils.usb.passthrough.commands", + "je_auto_control.utils.usb.passthrough.descriptor", + "je_auto_control.utils.usb.passthrough.flags", + "je_auto_control.utils.usb.passthrough.key_provider", + "je_auto_control.utils.usb.passthrough.loopback", + "je_auto_control.utils.usb.passthrough.viewer_client", + "je_auto_control.utils.usb.passthrough.webrtc_channel", + "je_auto_control.utils.usb.usb_devices", + "je_auto_control.utils.usb.usb_watcher", + "je_auto_control.utils.usbip", + "je_auto_control.utils.usbip.protocol", + "je_auto_control.utils.verify_field", + "je_auto_control.utils.verify_field.*", + "je_auto_control.utils.vex", + "je_auto_control.utils.vex.*", + "je_auto_control.utils.video_report", + "je_auto_control.utils.video_report.*", + "je_auto_control.utils.virtualized", + "je_auto_control.utils.virtualized.*", + "je_auto_control.utils.vision", + "je_auto_control.utils.vision.backends.base", + "je_auto_control.utils.vision.backends.null_backend", + "je_auto_control.utils.vision.frame_capture", + "je_auto_control.utils.vision.vlm_api", + "je_auto_control.utils.visual_match", + "je_auto_control.utils.visual_regression", + "je_auto_control.utils.voice", + "je_auto_control.utils.voice.*", + "je_auto_control.utils.vuln_scan", + "je_auto_control.utils.watchdog", + "je_auto_control.utils.watchdog.*", + "je_auto_control.utils.watcher", + "je_auto_control.utils.watcher.*", + "je_auto_control.utils.webrunner_bridge", + "je_auto_control.utils.window_capture", + "je_auto_control.utils.window_geometry", + "je_auto_control.utils.window_geometry.*", + "je_auto_control.utils.window_layout", + "je_auto_control.utils.window_layout.*", + "je_auto_control.utils.window_zorder", + "je_auto_control.utils.work_queue", + "je_auto_control.utils.work_queue.*", + "je_auto_control.utils.xml", + "je_auto_control.utils.xml.change_xml_structure", + "je_auto_control.utils.xml.xml_file", + "je_auto_control.windows", + "je_auto_control.windows.core", + "je_auto_control.windows.core.utils", + "je_auto_control.windows.core.utils.win32_keypress_check", "je_auto_control.windows.core.utils.win32_layout_vk", + "je_auto_control.windows.core.utils.win32_vk", + "je_auto_control.windows.interception", + "je_auto_control.windows.interception._dll", + "je_auto_control.windows.interception.keyboard", + "je_auto_control.windows.keyboard", + "je_auto_control.windows.keyboard.*", + "je_auto_control.windows.message", + "je_auto_control.windows.mouse", + "je_auto_control.windows.record", + "je_auto_control.windows.record.win32_record", + "je_auto_control.windows.screen", + "je_auto_control.windows.screen.*", + "je_auto_control.windows.window", + "je_auto_control.wrapper", + "je_auto_control.wrapper._input_observer", + "je_auto_control.wrapper._platform_linux", + "je_auto_control.wrapper._platform_osx", + "je_auto_control.wrapper._platform_wayland", "je_auto_control.wrapper.capabilities", "je_auto_control.wrapper.device_context", "je_auto_control.wrapper.device_frame", "je_auto_control.wrapper.mobile_commands", "je_auto_control.wrapper.mobile_extensions", - "je_auto_control.gui._tab_task", - "je_auto_control.gui.remote_desktop.connection_recent", - "je_auto_control.utils.executor.run_control", - "je_auto_control.utils.executor.result_hook", - "je_auto_control.utils.thread_bound", - "je_auto_control.gui._dispose", - "je_auto_control.gui._slow_op", - "je_auto_control.gui._weak_call", - "je_auto_control.gui._qt_typed", - "je_auto_control.utils.accessibility.backends.windows_automation", - "je_auto_control.utils.accessibility.backends.windows_events", - "je_auto_control.utils.remote_desktop.input_send_queue", - "je_auto_control.gui.adaptive", - "je_auto_control.gui.adaptive.*", - "je_auto_control.gui.adaptive_window", - "je_auto_control.gui._arrow_icons", + "je_auto_control.wrapper.platform_wrapper", + "je_auto_control.wrapper.window_backends", + "je_auto_control.wrapper.window_backends.base", + "je_auto_control.wrapper.window_backends.null_backend", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index 9fba4bcac..b2ae4a16d 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -5,63 +5,30 @@ # (which may not grow). Each is debt, not an exemption: this list may only # shrink. Move a module into the strict block once mypy passes it there, and # delete its line. -je_auto_control._export_bindings -je_auto_control._lazy_exports je_auto_control.gui.agent_observation_view je_auto_control.gui.agent_tasks_tab je_auto_control.gui.agent_transfer_view -je_auto_control.gui.config_sync_worker -je_auto_control.gui.diagnostics_capabilities -je_auto_control.gui.healing_evaluation_panel -je_auto_control.gui.healing_evaluation_worker -je_auto_control.gui.journal_browser -je_auto_control.gui.journal_browser_worker -je_auto_control.gui.journal_candidate_dialog -je_auto_control.gui.journal_candidate_panel -je_auto_control.gui.journal_candidate_worker -je_auto_control.gui.manual_run_controls -je_auto_control.gui.mcp_discovery_view -je_auto_control.gui.remote_desktop.folder_sync_controls -je_auto_control.gui.remote_desktop.folder_sync_io -je_auto_control.gui.tab_task_controller je_auto_control.gui.template_candidate_panel -je_auto_control.gui.template_candidate_worker -je_auto_control.gui.workspace -je_auto_control.gui.workspace_settings -je_auto_control.linux_wayland._input_state -je_auto_control.utils.agent_runtime -je_auto_control.utils.agent_runtime.__main__ -je_auto_control.utils.agent_runtime.activity je_auto_control.utils.agent_runtime.activity_windows -je_auto_control.utils.agent_runtime.android_action_result je_auto_control.utils.agent_runtime.android_adapter je_auto_control.utils.agent_runtime.android_commands je_auto_control.utils.agent_runtime.android_control -je_auto_control.utils.agent_runtime.android_geometry je_auto_control.utils.agent_runtime.android_hierarchy je_auto_control.utils.agent_runtime.android_input_evidence je_auto_control.utils.agent_runtime.android_input_windows je_auto_control.utils.agent_runtime.android_scope -je_auto_control.utils.agent_runtime.android_session -je_auto_control.utils.agent_runtime.android_transport je_auto_control.utils.agent_runtime.api je_auto_control.utils.agent_runtime.browser_commands -je_auto_control.utils.agent_runtime.browser_environment je_auto_control.utils.agent_runtime.browser_readonly_scope je_auto_control.utils.agent_runtime.browser_retirement je_auto_control.utils.agent_runtime.browser_target je_auto_control.utils.agent_runtime.browser_transfers -je_auto_control.utils.agent_runtime.browser_validation je_auto_control.utils.agent_runtime.browser_verification je_auto_control.utils.agent_runtime.browser_workflows -je_auto_control.utils.agent_runtime.budget_clock je_auto_control.utils.agent_runtime.cli -je_auto_control.utils.agent_runtime.client je_auto_control.utils.agent_runtime.commands je_auto_control.utils.agent_runtime.completion_contract je_auto_control.utils.agent_runtime.completion_recovery -je_auto_control.utils.agent_runtime.context -je_auto_control.utils.agent_runtime.control_admission je_auto_control.utils.agent_runtime.dag_admission je_auto_control.utils.agent_runtime.dag_batch_recording je_auto_control.utils.agent_runtime.dag_batches @@ -74,69 +41,43 @@ je_auto_control.utils.agent_runtime.dag_retention je_auto_control.utils.agent_runtime.dag_service_client je_auto_control.utils.agent_runtime.dag_transfer_checks je_auto_control.utils.agent_runtime.dag_transfer_stop -je_auto_control.utils.agent_runtime.delegation je_auto_control.utils.agent_runtime.dialog_scope -je_auto_control.utils.agent_runtime.document_launch je_auto_control.utils.agent_runtime.errors je_auto_control.utils.agent_runtime.evidence -je_auto_control.utils.agent_runtime.evidence_cache je_auto_control.utils.agent_runtime.evidence_handoff je_auto_control.utils.agent_runtime.file_dialog_scope je_auto_control.utils.agent_runtime.file_target je_auto_control.utils.agent_runtime.handoff_records -je_auto_control.utils.agent_runtime.helper_environment je_auto_control.utils.agent_runtime.helper_owner_linux -je_auto_control.utils.agent_runtime.images je_auto_control.utils.agent_runtime.input_journal je_auto_control.utils.agent_runtime.input_ledger -je_auto_control.utils.agent_runtime.jobs je_auto_control.utils.agent_runtime.local_evidence je_auto_control.utils.agent_runtime.manifest_evidence je_auto_control.utils.agent_runtime.model_tools -je_auto_control.utils.agent_runtime.models je_auto_control.utils.agent_runtime.native_channel je_auto_control.utils.agent_runtime.native_control -je_auto_control.utils.agent_runtime.native_job je_auto_control.utils.agent_runtime.native_recovery je_auto_control.utils.agent_runtime.native_scope je_auto_control.utils.agent_runtime.native_target je_auto_control.utils.agent_runtime.native_worker je_auto_control.utils.agent_runtime.observation_refs -je_auto_control.utils.agent_runtime.ollama je_auto_control.utils.agent_runtime.origin_policy je_auto_control.utils.agent_runtime.owned_channel_factory -je_auto_control.utils.agent_runtime.owner_service_nested -je_auto_control.utils.agent_runtime.owner_service_wire -je_auto_control.utils.agent_runtime.ownership -je_auto_control.utils.agent_runtime.parent_watch -je_auto_control.utils.agent_runtime.path_identity -je_auto_control.utils.agent_runtime.policy je_auto_control.utils.agent_runtime.presence_broker je_auto_control.utils.agent_runtime.presence_channel_linux -je_auto_control.utils.agent_runtime.presence_endpoint_linux je_auto_control.utils.agent_runtime.presence_frames je_auto_control.utils.agent_runtime.presence_handshake je_auto_control.utils.agent_runtime.presence_host je_auto_control.utils.agent_runtime.presence_messages_linux -je_auto_control.utils.agent_runtime.presence_native_types je_auto_control.utils.agent_runtime.presence_owner -je_auto_control.utils.agent_runtime.presence_peer_linux -je_auto_control.utils.agent_runtime.presence_pipe_linux -je_auto_control.utils.agent_runtime.presence_pipe_windows -je_auto_control.utils.agent_runtime.presence_platform je_auto_control.utils.agent_runtime.presence_pool je_auto_control.utils.agent_runtime.presence_protocol -je_auto_control.utils.agent_runtime.presence_quartz je_auto_control.utils.agent_runtime.presence_reader -je_auto_control.utils.agent_runtime.presence_security_windows je_auto_control.utils.agent_runtime.presence_server je_auto_control.utils.agent_runtime.presence_session_windows je_auto_control.utils.agent_runtime.presence_state -je_auto_control.utils.agent_runtime.presence_win32 je_auto_control.utils.agent_runtime.presence_windows je_auto_control.utils.agent_runtime.presence_worker -je_auto_control.utils.agent_runtime.presence_x11 -je_auto_control.utils.agent_runtime.readiness je_auto_control.utils.agent_runtime.readonly_target je_auto_control.utils.agent_runtime.readonly_worker je_auto_control.utils.agent_runtime.receipts @@ -145,16 +86,12 @@ je_auto_control.utils.agent_runtime.remote_effect je_auto_control.utils.agent_runtime.remote_journal je_auto_control.utils.agent_runtime.remote_target je_auto_control.utils.agent_runtime.remote_worker -je_auto_control.utils.agent_runtime.resume_gate je_auto_control.utils.agent_runtime.retained_browser je_auto_control.utils.agent_runtime.retained_browser_runtime je_auto_control.utils.agent_runtime.retained_browser_target -je_auto_control.utils.agent_runtime.retention je_auto_control.utils.agent_runtime.routes je_auto_control.utils.agent_runtime.runner je_auto_control.utils.agent_runtime.runtime -je_auto_control.utils.agent_runtime.runtime_lock -je_auto_control.utils.agent_runtime.service je_auto_control.utils.agent_runtime.skill_completion je_auto_control.utils.agent_runtime.skill_execution je_auto_control.utils.agent_runtime.skill_parameters @@ -163,8 +100,6 @@ je_auto_control.utils.agent_runtime.skill_recording je_auto_control.utils.agent_runtime.store je_auto_control.utils.agent_runtime.submission je_auto_control.utils.agent_runtime.target_config -je_auto_control.utils.agent_runtime.target_continuity -je_auto_control.utils.agent_runtime.target_factory je_auto_control.utils.agent_runtime.target_profiles je_auto_control.utils.agent_runtime.targets je_auto_control.utils.agent_runtime.task_authority @@ -173,25 +108,20 @@ je_auto_control.utils.agent_runtime.task_recovery je_auto_control.utils.agent_runtime.task_skills je_auto_control.utils.agent_runtime.task_triggers je_auto_control.utils.agent_runtime.transfer_adoption -je_auto_control.utils.agent_runtime.transfer_cache je_auto_control.utils.agent_runtime.transfer_destination_scope je_auto_control.utils.agent_runtime.transfer_evidence je_auto_control.utils.agent_runtime.transfer_evidence_contract je_auto_control.utils.agent_runtime.transfer_evidence_management -je_auto_control.utils.agent_runtime.transfer_files je_auto_control.utils.agent_runtime.transfer_host je_auto_control.utils.agent_runtime.transfer_import je_auto_control.utils.agent_runtime.transfer_import_contract je_auto_control.utils.agent_runtime.transfer_import_files -je_auto_control.utils.agent_runtime.transfer_import_jobs je_auto_control.utils.agent_runtime.transfer_import_ledger je_auto_control.utils.agent_runtime.transfer_lineage je_auto_control.utils.agent_runtime.transfer_management je_auto_control.utils.agent_runtime.transfer_models -je_auto_control.utils.agent_runtime.transfer_operations je_auto_control.utils.agent_runtime.transfer_privacy je_auto_control.utils.agent_runtime.transfer_protocol -je_auto_control.utils.agent_runtime.transfer_records je_auto_control.utils.agent_runtime.transfer_routing je_auto_control.utils.agent_runtime.transfer_selection je_auto_control.utils.agent_runtime.transfer_source @@ -203,139 +133,16 @@ je_auto_control.utils.agent_runtime.trigger_history je_auto_control.utils.agent_runtime.trigger_reauthorization je_auto_control.utils.agent_runtime.trigger_registration je_auto_control.utils.agent_runtime.verification -je_auto_control.utils.agent_runtime.window_pixels -je_auto_control.utils.agent_runtime.wire_data je_auto_control.utils.agent_runtime.workflow_desktop -je_auto_control.utils.agent_runtime.workflow_files je_auto_control.utils.agent_runtime.workflow_specs je_auto_control.utils.agent_runtime.workflow_values je_auto_control.utils.agent_runtime.workflow_wait je_auto_control.utils.agent_runtime.workspace_scope -je_auto_control.utils.cancellable_process -je_auto_control.utils.codegen.candidate_archive -je_auto_control.utils.codegen.candidate_models -je_auto_control.utils.codegen.candidate_validation -je_auto_control.utils.codegen.journal_cli -je_auto_control.utils.codegen.journal_commands -je_auto_control.utils.codegen.journal_selection -je_auto_control.utils.codegen.journal_source -je_auto_control.utils.codegen.journal_steps -je_auto_control.utils.config_sync.adapter_commands -je_auto_control.utils.config_sync.adapter_factory -je_auto_control.utils.config_sync.adapter_ledger -je_auto_control.utils.config_sync.adapter_profiles -je_auto_control.utils.config_sync.adapter_protocol -je_auto_control.utils.config_sync.adapter_references -je_auto_control.utils.config_sync.adapter_schema -je_auto_control.utils.config_sync.adapter_sources -je_auto_control.utils.config_sync.adapter_state -je_auto_control.utils.config_sync.asset_commands -je_auto_control.utils.config_sync.asset_models -je_auto_control.utils.config_sync.blob_binding -je_auto_control.utils.config_sync.blob_codec -je_auto_control.utils.config_sync.blob_http -je_auto_control.utils.config_sync.blob_models -je_auto_control.utils.config_sync.blob_routes -je_auto_control.utils.config_sync.blob_schema -je_auto_control.utils.config_sync.blob_store -je_auto_control.utils.config_sync.causal_client -je_auto_control.utils.config_sync.causal_commands -je_auto_control.utils.config_sync.causal_legacy -je_auto_control.utils.config_sync.causal_merge -je_auto_control.utils.config_sync.causal_models -je_auto_control.utils.config_sync.causal_receipt -je_auto_control.utils.config_sync.causal_routes -je_auto_control.utils.config_sync.causal_state -je_auto_control.utils.config_sync.causal_store -je_auto_control.utils.config_sync.causal_validation -je_auto_control.utils.config_sync.causal_wire -je_auto_control.utils.config_sync.commands -je_auto_control.utils.config_sync.contract -je_auto_control.utils.config_sync.control_adoption -je_auto_control.utils.config_sync.control_delivery -je_auto_control.utils.config_sync.control_models -je_auto_control.utils.config_sync.control_store -je_auto_control.utils.config_sync.database -je_auto_control.utils.config_sync.http_commands -je_auto_control.utils.config_sync.outbox_batch -je_auto_control.utils.config_sync.outbox_lease -je_auto_control.utils.config_sync.outbox_models -je_auto_control.utils.config_sync.outbox_schema -je_auto_control.utils.config_sync.peers -je_auto_control.utils.config_sync.profile_bindings -je_auto_control.utils.config_sync.profile_commands -je_auto_control.utils.config_sync.profile_load -je_auto_control.utils.config_sync.profile_models -je_auto_control.utils.config_sync.profile_native -je_auto_control.utils.config_sync.profile_runtime -je_auto_control.utils.config_sync.routes -je_auto_control.utils.config_sync.workspace_assets -je_auto_control.utils.config_sync.workspace_commands -je_auto_control.utils.config_sync.workspace_config -je_auto_control.utils.config_sync.workspace_models -je_auto_control.utils.config_sync.workspace_options -je_auto_control.utils.config_sync.workspace_preferences -je_auto_control.utils.config_sync.workspace_review -je_auto_control.utils.config_sync.workspace_schema -je_auto_control.utils.config_sync.workspace_store -je_auto_control.utils.config_sync.workspace_sync -je_auto_control.utils.config_sync.workspace_transport -je_auto_control.utils.cv2_utils.locator_frame je_auto_control.utils.dag.batch_contract je_auto_control.utils.dag.batch_execution je_auto_control.utils.dag.inspection je_auto_control.utils.dag.managed_tasks -je_auto_control.utils.dag.task_contract -je_auto_control.utils.dbus_client.cancellable_io -je_auto_control.utils.diagnostics.capability_commands -je_auto_control.utils.exception.cancellation -je_auto_control.utils.exception.control_signals je_auto_control.utils.executor.dispatch -je_auto_control.utils.logging.secret_scope je_auto_control.utils.mcp_server._call_authority je_auto_control.utils.mcp_server._disclosure_server -je_auto_control.utils.mcp_server._origin_policies -je_auto_control.utils.mcp_server._tool_notifications -je_auto_control.utils.mcp_server.stdio -je_auto_control.utils.mcp_server.tools._agent_tasks -je_auto_control.utils.mcp_server.tools._capabilities -je_auto_control.utils.mcp_server.tools._diagnostics je_auto_control.utils.mcp_server.tools._discovery -je_auto_control.utils.mcp_server.tools._handlers_journal -je_auto_control.utils.mcp_server.tools._healing_evaluation -je_auto_control.utils.mcp_server.tools._healing_run -je_auto_control.utils.mcp_server.tools._healing_source -je_auto_control.utils.mcp_server.tools._template_candidates -je_auto_control.utils.remote_desktop._export_bindings -je_auto_control.utils.remote_desktop._optional -je_auto_control.utils.remote_desktop._optional.file_transfer -je_auto_control.utils.remote_desktop._optional.hw_codec -je_auto_control.utils.remote_desktop._optional.mic_uplink -je_auto_control.utils.remote_desktop._optional.multi_viewer -je_auto_control.utils.remote_desktop._optional.session_recorder -je_auto_control.utils.remote_desktop._optional.webrtc -je_auto_control.utils.remote_desktop.clipboard_delivery -je_auto_control.utils.remote_desktop.file_receipts -je_auto_control.utils.remote_desktop.webrtc_file_callbacks -je_auto_control.utils.remote_desktop.webrtc_file_commit -je_auto_control.utils.remote_desktop.webrtc_file_receive -je_auto_control.utils.remote_desktop.webrtc_file_tasks -je_auto_control.utils.remote_desktop.webrtc_file_write -je_auto_control.utils.run_history.commands -je_auto_control.utils.run_history.context -je_auto_control.utils.run_history.manual -je_auto_control.utils.script_vars.ref_guard -je_auto_control.utils.self_healing.commands -je_auto_control.utils.self_healing.evaluation_io -je_auto_control.utils.self_healing.evaluation_models -je_auto_control.utils.self_healing.frame_locators -je_auto_control.utils.self_healing.requests -je_auto_control.utils.self_healing.runtime_evidence -je_auto_control.utils.self_healing.source_inspection -je_auto_control.utils.self_healing.template_bundle -je_auto_control.utils.self_healing.template_candidates -je_auto_control.utils.self_healing.template_commands -je_auto_control.utils.self_healing.template_images -je_auto_control.utils.self_healing.template_models -je_auto_control.utils.vision.frame_capture -je_auto_control.wrapper._input_observer diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 276567681..fc3ff8a4e 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -14,26 +14,12 @@ # written later under the same name is new and therefore strict. # je_auto_control -je_auto_control.__main__ -je_auto_control.android je_auto_control.android.adb_client je_auto_control.android.client -je_auto_control.android.find -je_auto_control.api -je_auto_control.api.core je_auto_control.cli -je_auto_control.gui je_auto_control.gui._auto_click_tab -je_auto_control.gui._daemon_thread -je_auto_control.gui._i18n_helpers -je_auto_control.gui._image_detect_tab je_auto_control.gui._record_tab -je_auto_control.gui._report_tab -je_auto_control.gui._screen_geometry -je_auto_control.gui._screenshot_tab je_auto_control.gui._script_tab -je_auto_control.gui._validators -je_auto_control.gui._worker_thread je_auto_control.gui.a11y_audit_tab je_auto_control.gui.accessibility_tab je_auto_control.gui.admin_console_tab @@ -44,7 +30,6 @@ je_auto_control.gui.computer_use_tab je_auto_control.gui.dag_tab je_auto_control.gui.data_source_tab je_auto_control.gui.device_matrix_tab -je_auto_control.gui.diagnostics_tab je_auto_control.gui.email_triggers_tab je_auto_control.gui.flakiness_tab je_auto_control.gui.flow_editor @@ -53,12 +38,7 @@ je_auto_control.gui.flow_editor.scene je_auto_control.gui.flow_editor.tab je_auto_control.gui.hotkeys_tab je_auto_control.gui.inspector_tab -je_auto_control.gui.language_wrapper -je_auto_control.gui.language_wrapper.english -je_auto_control.gui.language_wrapper.japanese je_auto_control.gui.language_wrapper.multi_language_wrapper -je_auto_control.gui.language_wrapper.simplified_chinese -je_auto_control.gui.language_wrapper.traditional_chinese je_auto_control.gui.live_hud_tab je_auto_control.gui.llm_planner_tab je_auto_control.gui.main_widget @@ -69,9 +49,7 @@ je_auto_control.gui.plugins_tab je_auto_control.gui.presence_tab je_auto_control.gui.profiler_tab je_auto_control.gui.recording_editor_tab -je_auto_control.gui.remote_desktop je_auto_control.gui.remote_desktop._helpers -je_auto_control.gui.remote_desktop.advanced_group je_auto_control.gui.remote_desktop.annotation_overlay je_auto_control.gui.remote_desktop.blanking_overlay je_auto_control.gui.remote_desktop.connection_screen @@ -79,31 +57,22 @@ je_auto_control.gui.remote_desktop.frame_display je_auto_control.gui.remote_desktop.host_panel je_auto_control.gui.remote_desktop.remote_screen_window je_auto_control.gui.remote_desktop.sparkline -je_auto_control.gui.remote_desktop.tab je_auto_control.gui.remote_desktop.tray_icon -je_auto_control.gui.remote_desktop.trusted_group je_auto_control.gui.remote_desktop.viewer_panel je_auto_control.gui.remote_desktop.viewer_screen_window je_auto_control.gui.remote_desktop.webrtc_dialogs je_auto_control.gui.remote_desktop.webrtc_known_hosts je_auto_control.gui.remote_desktop.webrtc_panel je_auto_control.gui.remote_desktop.webrtc_workers -je_auto_control.gui.remote_desktop_tab je_auto_control.gui.rest_api_tab je_auto_control.gui.run_history_tab je_auto_control.gui.run_history_timeline je_auto_control.gui.scheduler_tab je_auto_control.gui.script_builder je_auto_control.gui.script_builder.builder_tab -je_auto_control.gui.script_builder.command_schema -je_auto_control.gui.script_builder.step_form_view -je_auto_control.gui.script_builder.step_list_view je_auto_control.gui.script_builder.step_model je_auto_control.gui.secrets_tab -je_auto_control.gui.selector je_auto_control.gui.selector.region_overlay -je_auto_control.gui.selector.region_selector -je_auto_control.gui.selector.template_cropper je_auto_control.gui.self_healing_tab je_auto_control.gui.test_suite_tab je_auto_control.gui.trace_replay_tab @@ -117,629 +86,164 @@ je_auto_control.gui.vlm_tab je_auto_control.gui.webhooks_tab je_auto_control.gui.webrunner_tab je_auto_control.gui.window_tab -je_auto_control.ios je_auto_control.ios.client -je_auto_control.ios.find -je_auto_control.ios.input -je_auto_control.ios.screen -je_auto_control.linux_wayland je_auto_control.linux_wayland._ctypes_bind -je_auto_control.linux_wayland._dbus_client -je_auto_control.linux_wayland._detect -je_auto_control.linux_wayland._layout je_auto_control.linux_wayland._select_input -je_auto_control.linux_wayland._ydotool_cli -je_auto_control.linux_wayland.capture je_auto_control.linux_wayland.keyboard -je_auto_control.linux_wayland.keymap je_auto_control.linux_wayland.libei je_auto_control.linux_wayland.listener je_auto_control.linux_wayland.mouse -je_auto_control.linux_wayland.oeffis -je_auto_control.linux_wayland.portal -je_auto_control.linux_wayland.record -je_auto_control.linux_wayland.screen -je_auto_control.linux_with_x11 -je_auto_control.linux_with_x11.core -je_auto_control.linux_with_x11.core.utils -je_auto_control.linux_with_x11.core.utils.x11_linux_display -je_auto_control.linux_with_x11.core.utils.x11_linux_vk -je_auto_control.linux_with_x11.keyboard -je_auto_control.linux_with_x11.keyboard.x11_linux_keyboard_control -je_auto_control.linux_with_x11.listener je_auto_control.linux_with_x11.listener.x11_linux_listener -je_auto_control.linux_with_x11.mouse -je_auto_control.linux_with_x11.mouse.x11_linux_mouse_control -je_auto_control.linux_with_x11.record je_auto_control.linux_with_x11.record.x11_linux_record -je_auto_control.linux_with_x11.screen -je_auto_control.linux_with_x11.screen.x11_linux_screen -je_auto_control.linux_with_x11.uinput je_auto_control.linux_with_x11.uinput._device -je_auto_control.linux_with_x11.uinput.keyboard -je_auto_control.linux_with_x11.uinput.mouse -je_auto_control.osx -je_auto_control.osx.core -je_auto_control.osx.core.utils -je_auto_control.osx.core.utils.osx_vk -je_auto_control.osx.keyboard -je_auto_control.osx.keyboard.osx_keyboard -je_auto_control.osx.keyboard.osx_keyboard_check -je_auto_control.osx.listener je_auto_control.osx.listener.osx_listener -je_auto_control.osx.mouse je_auto_control.osx.mouse.osx_mouse -je_auto_control.osx.pid -je_auto_control.osx.pid.pid_control -je_auto_control.osx.record -je_auto_control.osx.record.osx_record -je_auto_control.osx.screen -je_auto_control.osx.screen.osx_screen -je_auto_control.utils -je_auto_control.utils.a11y_audit -je_auto_control.utils.a11y_audit.audit -je_auto_control.utils.a11y_audit.wcag -je_auto_control.utils.a2a -je_auto_control.utils.a2a.agent_card -je_auto_control.utils.ab_locator je_auto_control.utils.ab_locator.runner -je_auto_control.utils.ab_locator.store -je_auto_control.utils.accessibility je_auto_control.utils.accessibility.accessibility_api -je_auto_control.utils.accessibility.backends -je_auto_control.utils.accessibility.backends.base -je_auto_control.utils.accessibility.backends.linux_backend je_auto_control.utils.accessibility.backends.macos_backend -je_auto_control.utils.accessibility.backends.null_backend je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.accessibility.backends.windows_query je_auto_control.utils.accessibility.backends.windows_reads je_auto_control.utils.accessibility.backends.windows_state je_auto_control.utils.accessibility.element -je_auto_control.utils.accessibility.recorder -je_auto_control.utils.accessibility.tree -je_auto_control.utils.acme_v2 je_auto_control.utils.acme_v2.client -je_auto_control.utils.acme_v2.jws -je_auto_control.utils.act_in_view je_auto_control.utils.act_in_view.act_in_view -je_auto_control.utils.act_modes -je_auto_control.utils.act_modes.act_modes -je_auto_control.utils.action_effect je_auto_control.utils.action_effect.action_effect -je_auto_control.utils.action_grounding -je_auto_control.utils.action_grounding.action_grounding -je_auto_control.utils.action_lint -je_auto_control.utils.action_lint.__main__ je_auto_control.utils.action_lint.linter -je_auto_control.utils.action_lint.schema -je_auto_control.utils.action_signing -je_auto_control.utils.action_signing._key_file je_auto_control.utils.action_signing.cipher -je_auto_control.utils.action_signing.signer -je_auto_control.utils.actionability je_auto_control.utils.actionability.actionability -je_auto_control.utils.adaptive_timeout -je_auto_control.utils.adaptive_timeout.adaptive_timeout -je_auto_control.utils.admin je_auto_control.utils.admin.admin_client -je_auto_control.utils.agent je_auto_control.utils.agent.agent_loop -je_auto_control.utils.agent.backends -je_auto_control.utils.agent.backends._computer_toolset -je_auto_control.utils.agent.backends.anthropic -je_auto_control.utils.agent.backends.anthropic_computer_use -je_auto_control.utils.agent.backends.base -je_auto_control.utils.agent.backends.openai -je_auto_control.utils.agent.computer_use -je_auto_control.utils.agent_memory -je_auto_control.utils.agent_memory.agent_memory -je_auto_control.utils.agent_replay -je_auto_control.utils.agent_replay.agent_replay -je_auto_control.utils.agent_trace -je_auto_control.utils.agent_trace.agent_trace -je_auto_control.utils.anchor_locator -je_auto_control.utils.anchor_locator.locator -je_auto_control.utils.annotate -je_auto_control.utils.annotate.annotate -je_auto_control.utils.anomaly -je_auto_control.utils.anomaly.anomaly -je_auto_control.utils.app_idle -je_auto_control.utils.app_idle.app_idle -je_auto_control.utils.approval je_auto_control.utils.approval.approval_test -je_auto_control.utils.artifact_store je_auto_control.utils.artifact_store.s3_store -je_auto_control.utils.assertion -je_auto_control.utils.assertion.assertions -je_auto_control.utils.assertion.combinators -je_auto_control.utils.assets -je_auto_control.utils.assets.assets -je_auto_control.utils.ax_events -je_auto_control.utils.ax_events.ax_events -je_auto_control.utils.ax_props -je_auto_control.utils.ax_props.ax_props -je_auto_control.utils.ax_text je_auto_control.utils.ax_text.ax_text -je_auto_control.utils.ax_tree_walk -je_auto_control.utils.ax_tree_walk.ax_tree_walk -je_auto_control.utils.baggage -je_auto_control.utils.baggage.baggage -je_auto_control.utils.barcode je_auto_control.utils.barcode.barcode -je_auto_control.utils.bidi_check -je_auto_control.utils.bidi_check.bidi_check -je_auto_control.utils.bulkhead je_auto_control.utils.bulkhead.bulkhead -je_auto_control.utils.callback je_auto_control.utils.callback.callback_function_executor -je_auto_control.utils.canonical_log -je_auto_control.utils.canonical_log.canonical_log -je_auto_control.utils.change_localize je_auto_control.utils.change_localize.change_localize -je_auto_control.utils.chaos -je_auto_control.utils.chaos.chaos -je_auto_control.utils.chatops -je_auto_control.utils.chatops.handlers -je_auto_control.utils.chatops.router je_auto_control.utils.chatops.slack_bot -je_auto_control.utils.checkpoint -je_auto_control.utils.checkpoint.checkpoint -je_auto_control.utils.checksum -je_auto_control.utils.checksum.checksum -je_auto_control.utils.ci_annotations -je_auto_control.utils.ci_annotations.ci_annotations -je_auto_control.utils.cli_output -je_auto_control.utils.clipboard je_auto_control.utils.clipboard.clipboard -je_auto_control.utils.clipboard.win32_clipboard_api -je_auto_control.utils.clipboard_files -je_auto_control.utils.clipboard_files.clipboard_files -je_auto_control.utils.clipboard_formats je_auto_control.utils.clipboard_formats.clipboard_formats -je_auto_control.utils.clipboard_history -je_auto_control.utils.clipboard_history.clipboard_history -je_auto_control.utils.clipboard_rich_formats -je_auto_control.utils.clipboard_rich_formats.clipboard_rich_formats -je_auto_control.utils.codegen je_auto_control.utils.codegen.codegen -je_auto_control.utils.color_match je_auto_control.utils.color_match.color_match -je_auto_control.utils.color_region je_auto_control.utils.color_region.color_region -je_auto_control.utils.color_stats -je_auto_control.utils.color_stats.color_stats -je_auto_control.utils.column_layout -je_auto_control.utils.column_layout.column_layout -je_auto_control.utils.compliance je_auto_control.utils.compliance.compliance_report -je_auto_control.utils.config_bundle je_auto_control.utils.config_bundle.__main__ je_auto_control.utils.config_bundle.config_bundle -je_auto_control.utils.config_redaction -je_auto_control.utils.config_redaction.config_redaction -je_auto_control.utils.config_schema -je_auto_control.utils.config_schema.config_schema -je_auto_control.utils.config_sync -je_auto_control.utils.confusables -je_auto_control.utils.confusables.confusables -je_auto_control.utils.contrast_map je_auto_control.utils.contrast_map.contrast_map -je_auto_control.utils.control_patterns je_auto_control.utils.control_patterns.control_patterns -je_auto_control.utils.cookie_jar -je_auto_control.utils.cookie_jar.cookie_jar -je_auto_control.utils.coordinate_space -je_auto_control.utils.coordinate_space.coordinate_space je_auto_control.utils.cost_telemetry je_auto_control.utils.cost_telemetry.pricing -je_auto_control.utils.cost_telemetry.store -je_auto_control.utils.critic_features -je_auto_control.utils.critic_features.critic_features -je_auto_control.utils.critical_exit -je_auto_control.utils.critical_exit.critical_exit -je_auto_control.utils.cua_action je_auto_control.utils.cua_action.cua_action -je_auto_control.utils.cv2_utils je_auto_control.utils.cv2_utils.blobs -je_auto_control.utils.cv2_utils.frame_clock -je_auto_control.utils.cv2_utils.image_file -je_auto_control.utils.cv2_utils.optional -je_auto_control.utils.cv2_utils.region_capture -je_auto_control.utils.cv2_utils.screen_grabber je_auto_control.utils.cv2_utils.screen_record -je_auto_control.utils.cv2_utils.screenshot -je_auto_control.utils.cv2_utils.template_detection je_auto_control.utils.cv2_utils.video_recording -je_auto_control.utils.cvd_simulate -je_auto_control.utils.cvd_simulate.cvd_simulate -je_auto_control.utils.dag -je_auto_control.utils.dag.graph je_auto_control.utils.dag.runner -je_auto_control.utils.data_drift -je_auto_control.utils.data_drift.data_drift -je_auto_control.utils.data_profile -je_auto_control.utils.data_profile.data_profile -je_auto_control.utils.data_quality je_auto_control.utils.data_quality.data_quality -je_auto_control.utils.data_source -je_auto_control.utils.data_source.data_source -je_auto_control.utils.dataset_diff -je_auto_control.utils.dataset_diff.dataset_diff -je_auto_control.utils.dbus_client je_auto_control.utils.dbus_client.session_bus -je_auto_control.utils.decision_table -je_auto_control.utils.decision_table.decision_table -je_auto_control.utils.dedup_window -je_auto_control.utils.dedup_window.dedup_window je_auto_control.utils.deprecation -je_auto_control.utils.deterministic je_auto_control.utils.deterministic.deterministic -je_auto_control.utils.device_matrix -je_auto_control.utils.device_matrix.matrix -je_auto_control.utils.diagnostics je_auto_control.utils.diagnostics.__main__ -je_auto_control.utils.diagnostics.diagnostics -je_auto_control.utils.dotenv -je_auto_control.utils.dotenv.dotenv -je_auto_control.utils.edge_lines je_auto_control.utils.edge_lines.edge_lines -je_auto_control.utils.edge_match je_auto_control.utils.edge_match.edge_match -je_auto_control.utils.egress -je_auto_control.utils.egress.egress_policy -je_auto_control.utils.element_diff je_auto_control.utils.element_diff.element_diff -je_auto_control.utils.element_parse -je_auto_control.utils.element_parse.element_parse -je_auto_control.utils.element_proposal -je_auto_control.utils.element_proposal.element_proposal -je_auto_control.utils.element_repository -je_auto_control.utils.element_repository.element_repository -je_auto_control.utils.element_scoring -je_auto_control.utils.element_scoring.element_scoring -je_auto_control.utils.email_send -je_auto_control.utils.email_send.email_sender -je_auto_control.utils.ensure_state -je_auto_control.utils.ensure_state.ensure_state -je_auto_control.utils.events -je_auto_control.utils.events.cloud_events -je_auto_control.utils.exception -je_auto_control.utils.exception.exception_tags -je_auto_control.utils.exception.exceptions -je_auto_control.utils.executor je_auto_control.utils.executor.action_executor -je_auto_control.utils.executor.action_redaction je_auto_control.utils.executor.action_schema -je_auto_control.utils.executor.flags je_auto_control.utils.executor.flow_control je_auto_control.utils.executor.flow_data_commands je_auto_control.utils.executor.mouse_aliases -je_auto_control.utils.expect_poll -je_auto_control.utils.expect_poll.expect_poll -je_auto_control.utils.failure_bundle je_auto_control.utils.failure_bundle.bundle -je_auto_control.utils.failure_hooks je_auto_control.utils.failure_hooks.backends -je_auto_control.utils.failure_hooks.manager -je_auto_control.utils.failure_hooks.report -je_auto_control.utils.failure_signature -je_auto_control.utils.failure_signature.failure_signature -je_auto_control.utils.feature_flags je_auto_control.utils.feature_flags.feature_flags -je_auto_control.utils.feature_match je_auto_control.utils.feature_match.feature_match -je_auto_control.utils.field_entry -je_auto_control.utils.field_entry.field_entry -je_auto_control.utils.file_assoc -je_auto_control.utils.file_assoc.file_assoc -je_auto_control.utils.file_dialog -je_auto_control.utils.file_dialog.file_dialog -je_auto_control.utils.file_drop -je_auto_control.utils.file_drop.file_drop -je_auto_control.utils.file_process -je_auto_control.utils.file_process.get_dir_file_list -je_auto_control.utils.flake_cluster -je_auto_control.utils.flake_cluster.flake_cluster -je_auto_control.utils.flakiness -je_auto_control.utils.flakiness.flakiness -je_auto_control.utils.flow_debugger -je_auto_control.utils.flow_debugger.flow_debugger -je_auto_control.utils.focus_order -je_auto_control.utils.focus_order.focus_order -je_auto_control.utils.form_fields je_auto_control.utils.form_fields.form_fields -je_auto_control.utils.fuzzy je_auto_control.utils.fuzzy.fuzzy_match -je_auto_control.utils.gamepad je_auto_control.utils.gamepad._facade -je_auto_control.utils.generate_report je_auto_control.utils.generate_report.generate_html_report -je_auto_control.utils.generate_report.generate_json_report -je_auto_control.utils.generate_report.generate_xml_report -je_auto_control.utils.gettext_catalog -je_auto_control.utils.gettext_catalog.gettext_catalog -je_auto_control.utils.governance -je_auto_control.utils.governance.credential_broker -je_auto_control.utils.governance.governance -je_auto_control.utils.grid_locator je_auto_control.utils.grid_locator.grid_locator -je_auto_control.utils.grounding_consensus je_auto_control.utils.grounding_consensus.grounding_consensus -je_auto_control.utils.guardrail -je_auto_control.utils.guardrail.guardrail -je_auto_control.utils.heading_segment -je_auto_control.utils.heading_segment.heading_segment -je_auto_control.utils.heal_analytics -je_auto_control.utils.heal_analytics.heal_analytics -je_auto_control.utils.hotkey -je_auto_control.utils.hotkey.backends -je_auto_control.utils.hotkey.backends.base je_auto_control.utils.hotkey.backends.linux_backend je_auto_control.utils.hotkey.backends.macos_backend je_auto_control.utils.hotkey.backends.windows_backend je_auto_control.utils.hotkey.hotkey_daemon -je_auto_control.utils.hsv_segment je_auto_control.utils.hsv_segment.hsv_segment -je_auto_control.utils.http_cassette -je_auto_control.utils.http_cassette.http_cassette -je_auto_control.utils.http_client je_auto_control.utils.http_client.http_client -je_auto_control.utils.http_conditional -je_auto_control.utils.http_conditional.http_conditional -je_auto_control.utils.http_content -je_auto_control.utils.http_content.http_content -je_auto_control.utils.http_headers -je_auto_control.utils.http_problem -je_auto_control.utils.http_problem.http_problem -je_auto_control.utils.humanize -je_auto_control.utils.humanize.motion -je_auto_control.utils.humanize.typing -je_auto_control.utils.i18n_test je_auto_control.utils.i18n_test.i18n_test -je_auto_control.utils.icon_classify je_auto_control.utils.icon_classify.icon_classify -je_auto_control.utils.idempotency -je_auto_control.utils.idempotency.idempotency -je_auto_control.utils.idle_keepawake -je_auto_control.utils.idle_keepawake.idle_keepawake -je_auto_control.utils.image_dedup je_auto_control.utils.image_dedup.perceptual_hash -je_auto_control.utils.image_quality je_auto_control.utils.image_quality.image_quality -je_auto_control.utils.ime_state -je_auto_control.utils.ime_state.ime_state -je_auto_control.utils.img_histogram je_auto_control.utils.img_histogram.img_histogram -je_auto_control.utils.input_macro je_auto_control.utils.input_macro.input_macro je_auto_control.utils.input_macro.recorder_base -je_auto_control.utils.input_reach -je_auto_control.utils.input_reach.input_reach -je_auto_control.utils.json je_auto_control.utils.json.json_file -je_auto_control.utils.json_contract je_auto_control.utils.json_contract.json_contract -je_auto_control.utils.json_patch je_auto_control.utils.json_patch.json_patch -je_auto_control.utils.json_schema -je_auto_control.utils.json_schema.ecma_regex je_auto_control.utils.json_schema.json_schema -je_auto_control.utils.json_store -je_auto_control.utils.json_store.json_store -je_auto_control.utils.jsonpath -je_auto_control.utils.jsonpath.jsonpath -je_auto_control.utils.jwt je_auto_control.utils.jwt.jwt_codec -je_auto_control.utils.key_hold -je_auto_control.utils.key_hold.key_hold -je_auto_control.utils.keyboard_layout -je_auto_control.utils.keyboard_layout.keyboard_layout -je_auto_control.utils.layered_config -je_auto_control.utils.layered_config.layered_config -je_auto_control.utils.legacy_accessible -je_auto_control.utils.legacy_accessible.legacy_accessible -je_auto_control.utils.license_policy -je_auto_control.utils.license_policy.license_policy -je_auto_control.utils.link_header -je_auto_control.utils.link_header.link_header -je_auto_control.utils.list_format -je_auto_control.utils.list_format.list_format -je_auto_control.utils.llm je_auto_control.utils.llm.backends je_auto_control.utils.llm.backends.anthropic_backend -je_auto_control.utils.llm.backends.base -je_auto_control.utils.llm.backends.null_backend je_auto_control.utils.llm.planner -je_auto_control.utils.locale_collation -je_auto_control.utils.locale_collation.locale_collation -je_auto_control.utils.locale_parse -je_auto_control.utils.locale_parse.locale_parse -je_auto_control.utils.locator_chain je_auto_control.utils.locator_chain.locator_chain -je_auto_control.utils.locator_repair -je_auto_control.utils.locator_repair.locator_repair -je_auto_control.utils.lock_session -je_auto_control.utils.lock_session.lock_session -je_auto_control.utils.logging je_auto_control.utils.logging.logging_instance -je_auto_control.utils.loop_guard -je_auto_control.utils.loop_guard.loop_guard -je_auto_control.utils.marks_layout -je_auto_control.utils.marks_layout.marks_layout -je_auto_control.utils.match_autothresh je_auto_control.utils.match_autothresh.match_autothresh -je_auto_control.utils.match_ensemble je_auto_control.utils.match_ensemble.match_ensemble -je_auto_control.utils.match_stability je_auto_control.utils.match_stability.match_stability -je_auto_control.utils.match_trust je_auto_control.utils.match_trust.match_trust -je_auto_control.utils.mcp_registry -je_auto_control.utils.mcp_registry.registry -je_auto_control.utils.mcp_server je_auto_control.utils.mcp_server.__main__ -je_auto_control.utils.mcp_server._client_requests -je_auto_control.utils.mcp_server._http_stateless -je_auto_control.utils.mcp_server._input_required je_auto_control.utils.mcp_server._protocol -je_auto_control.utils.mcp_server._stateless je_auto_control.utils.mcp_server._subscriptions -je_auto_control.utils.mcp_server.audit -je_auto_control.utils.mcp_server.context je_auto_control.utils.mcp_server.fake_backend -je_auto_control.utils.mcp_server.http_sessions je_auto_control.utils.mcp_server.http_transport -je_auto_control.utils.mcp_server.log_bridge je_auto_control.utils.mcp_server.plugin_watcher -je_auto_control.utils.mcp_server.prompts -je_auto_control.utils.mcp_server.rate_limit -je_auto_control.utils.mcp_server.resources je_auto_control.utils.mcp_server.server -je_auto_control.utils.mcp_server.tools -je_auto_control.utils.mcp_server.tools._base -je_auto_control.utils.mcp_server.tools._factories je_auto_control.utils.mcp_server.tools._handlers -je_auto_control.utils.mcp_server.tools._handlers_input je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations -je_auto_control.utils.mcp_server.tools._handlers_qa -je_auto_control.utils.mcp_server.tools._handlers_remote -je_auto_control.utils.mcp_server.tools._handlers_runs -je_auto_control.utils.mcp_server.tools._handlers_scheduling je_auto_control.utils.mcp_server.tools._handlers_screen je_auto_control.utils.mcp_server.tools._handlers_system je_auto_control.utils.mcp_server.tools._validation je_auto_control.utils.mcp_server.tools.plugin_tools -je_auto_control.utils.media_assert je_auto_control.utils.media_assert.media -je_auto_control.utils.message_format je_auto_control.utils.message_format.message_format -je_auto_control.utils.modifier_state -je_auto_control.utils.modifier_state.modifier_state -je_auto_control.utils.monitor_layout je_auto_control.utils.monitor_layout.logical_frame -je_auto_control.utils.monitor_layout.monitor_layout -je_auto_control.utils.motion_regions je_auto_control.utils.motion_regions.motion_regions -je_auto_control.utils.mouse_path -je_auto_control.utils.mouse_path.mouse_path -je_auto_control.utils.mouse_relative -je_auto_control.utils.mouse_relative.mouse_relative -je_auto_control.utils.multipart -je_auto_control.utils.multipart.multipart -je_auto_control.utils.near_dup -je_auto_control.utils.near_dup.near_dup -je_auto_control.utils.notify -je_auto_control.utils.notify.notifier -je_auto_control.utils.notify_channels -je_auto_control.utils.notify_channels.notify_channels -je_auto_control.utils.observability je_auto_control.utils.observability.exporter -je_auto_control.utils.observability.metrics je_auto_control.utils.observability.tracing -je_auto_control.utils.observation -je_auto_control.utils.observation.observation -je_auto_control.utils.observation_delta -je_auto_control.utils.observation_delta.observation_delta -je_auto_control.utils.observer -je_auto_control.utils.observer.observer -je_auto_control.utils.ocr je_auto_control.utils.ocr.backends je_auto_control.utils.ocr.backends.base je_auto_control.utils.ocr.backends.easyocr_backend je_auto_control.utils.ocr.backends.paddleocr_backend je_auto_control.utils.ocr.backends.tesseract_backend je_auto_control.utils.ocr.ocr_engine -je_auto_control.utils.ocr.structure -je_auto_control.utils.ocr.text_span -je_auto_control.utils.office -je_auto_control.utils.office.office -je_auto_control.utils.optimistic -je_auto_control.utils.optimistic.optimistic -je_auto_control.utils.otlp_export -je_auto_control.utils.otlp_export.otlp_export -je_auto_control.utils.otp -je_auto_control.utils.otp.otp -je_auto_control.utils.outbox -je_auto_control.utils.outbox.outbox -je_auto_control.utils.package_manager je_auto_control.utils.package_manager.package_manager_class -je_auto_control.utils.path_guard je_auto_control.utils.path_guard.path_guard -je_auto_control.utils.pdf je_auto_control.utils.pdf.pdf_reader -je_auto_control.utils.percentiles -je_auto_control.utils.percentiles.percentiles -je_auto_control.utils.perceptual_diff je_auto_control.utils.perceptual_diff.perceptual_diff -je_auto_control.utils.pii_text -je_auto_control.utils.pii_text.pii_text -je_auto_control.utils.platform_id -je_auto_control.utils.plugin_loader -je_auto_control.utils.plugin_loader.plugin_loader -je_auto_control.utils.plugin_sdk -je_auto_control.utils.plugin_sdk.plugin_sdk -je_auto_control.utils.postcondition je_auto_control.utils.postcondition.postcondition -je_auto_control.utils.preprocess je_auto_control.utils.preprocess.preprocess -je_auto_control.utils.process_doc -je_auto_control.utils.process_doc.process_doc -je_auto_control.utils.process_mining je_auto_control.utils.process_mining.process_mining -je_auto_control.utils.profiler -je_auto_control.utils.profiler.profiler je_auto_control.utils.profiler.resource_profiler -je_auto_control.utils.project -je_auto_control.utils.project.create_project_structure -je_auto_control.utils.project.template -je_auto_control.utils.project.template.template_executor je_auto_control.utils.project.template.template_keyword -je_auto_control.utils.provenance -je_auto_control.utils.provenance.provenance -je_auto_control.utils.pytest_plugin je_auto_control.utils.pytest_plugin.bdd_steps je_auto_control.utils.pytest_plugin.keywords -je_auto_control.utils.pytest_plugin.plugin -je_auto_control.utils.qr je_auto_control.utils.qr.qr -je_auto_control.utils.quarantine -je_auto_control.utils.quarantine.store -je_auto_control.utils.rate_limit je_auto_control.utils.rate_limit.rate_limit -je_auto_control.utils.rbac -je_auto_control.utils.rbac.users -je_auto_control.utils.readability -je_auto_control.utils.readability.readability -je_auto_control.utils.reading_flow je_auto_control.utils.reading_flow.reading_flow -je_auto_control.utils.recording_edit je_auto_control.utils.recording_edit.editor -je_auto_control.utils.recurrence je_auto_control.utils.recurrence.recurrence -je_auto_control.utils.redaction -je_auto_control.utils.redaction.engine je_auto_control.utils.redaction.policies je_auto_control.utils.redaction.rules -je_auto_control.utils.referential -je_auto_control.utils.referential.referential -je_auto_control.utils.remote_desktop je_auto_control.utils.remote_desktop.adaptive_bitrate je_auto_control.utils.remote_desktop.address_book je_auto_control.utils.remote_desktop.audio je_auto_control.utils.remote_desktop.audit_log -je_auto_control.utils.remote_desktop.auth -je_auto_control.utils.remote_desktop.clipboard_sync je_auto_control.utils.remote_desktop.connect_coordinator -je_auto_control.utils.remote_desktop.file_sync je_auto_control.utils.remote_desktop.file_transfer je_auto_control.utils.remote_desktop.fingerprint je_auto_control.utils.remote_desktop.host je_auto_control.utils.remote_desktop.host_access je_auto_control.utils.remote_desktop.host_capture je_auto_control.utils.remote_desktop.host_client -je_auto_control.utils.remote_desktop.host_id je_auto_control.utils.remote_desktop.host_service je_auto_control.utils.remote_desktop.hw_codec je_auto_control.utils.remote_desktop.input_dispatch @@ -748,31 +252,21 @@ je_auto_control.utils.remote_desktop.jpeg_recorder_encrypted je_auto_control.utils.remote_desktop.lan_discovery je_auto_control.utils.remote_desktop.multi_viewer je_auto_control.utils.remote_desktop.permissions -je_auto_control.utils.remote_desktop.presence je_auto_control.utils.remote_desktop.protocol -je_auto_control.utils.remote_desktop.rate_limit je_auto_control.utils.remote_desktop.registry -je_auto_control.utils.remote_desktop.relay -je_auto_control.utils.remote_desktop.resume_tokens -je_auto_control.utils.remote_desktop.session_actions je_auto_control.utils.remote_desktop.session_quality_cache je_auto_control.utils.remote_desktop.session_recorder je_auto_control.utils.remote_desktop.signaling_client je_auto_control.utils.remote_desktop.signaling_server -je_auto_control.utils.remote_desktop.totp je_auto_control.utils.remote_desktop.transport je_auto_control.utils.remote_desktop.trust_list je_auto_control.utils.remote_desktop.turn_config -je_auto_control.utils.remote_desktop.video_codec je_auto_control.utils.remote_desktop.viewer -je_auto_control.utils.remote_desktop.viewer_id -je_auto_control.utils.remote_desktop.wake_on_lan je_auto_control.utils.remote_desktop.webrtc_audio je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host je_auto_control.utils.remote_desktop.webrtc_host_auth je_auto_control.utils.remote_desktop.webrtc_host_media -je_auto_control.utils.remote_desktop.webrtc_inspector je_auto_control.utils.remote_desktop.webrtc_mic je_auto_control.utils.remote_desktop.webrtc_stats je_auto_control.utils.remote_desktop.webrtc_transport @@ -780,271 +274,78 @@ je_auto_control.utils.remote_desktop.webrtc_viewer je_auto_control.utils.remote_desktop.ws_host je_auto_control.utils.remote_desktop.ws_protocol je_auto_control.utils.remote_desktop.ws_viewer -je_auto_control.utils.resilience -je_auto_control.utils.resilience.resilience -je_auto_control.utils.rest_api je_auto_control.utils.rest_api.__main__ -je_auto_control.utils.rest_api.rest_auth je_auto_control.utils.rest_api.rest_handlers -je_auto_control.utils.rest_api.rest_metrics -je_auto_control.utils.rest_api.rest_openapi -je_auto_control.utils.rest_api.rest_registry je_auto_control.utils.rest_api.rest_server -je_auto_control.utils.retry_budget -je_auto_control.utils.retry_budget.retry_budget -je_auto_control.utils.rich_clipboard je_auto_control.utils.rich_clipboard.rich_clipboard -je_auto_control.utils.rotated_match je_auto_control.utils.rotated_match.rotated_match -je_auto_control.utils.run_diff je_auto_control.utils.run_diff.run_diff -je_auto_control.utils.run_history -je_auto_control.utils.run_history.artifact_manager -je_auto_control.utils.run_history.history_store -je_auto_control.utils.run_history.run_outcome -je_auto_control.utils.saga -je_auto_control.utils.saga.saga -je_auto_control.utils.saliency je_auto_control.utils.saliency.saliency -je_auto_control.utils.sarif -je_auto_control.utils.sarif.sarif -je_auto_control.utils.sbom je_auto_control.utils.sbom.sbom -je_auto_control.utils.scale_detect je_auto_control.utils.scale_detect.scale_detect -je_auto_control.utils.scheduler -je_auto_control.utils.scheduler.cron je_auto_control.utils.scheduler.scheduler -je_auto_control.utils.schema_compat je_auto_control.utils.schema_compat.schema_compat -je_auto_control.utils.screen_grid -je_auto_control.utils.screen_grid.screen_grid -je_auto_control.utils.screen_state je_auto_control.utils.screen_state.screen_state -je_auto_control.utils.script_vars je_auto_control.utils.script_vars.interpolate -je_auto_control.utils.script_vars.scope -je_auto_control.utils.scroll_find -je_auto_control.utils.scroll_find.scroll_find -je_auto_control.utils.search_index je_auto_control.utils.search_index.search_index -je_auto_control.utils.secret_ref -je_auto_control.utils.secret_ref.secret_ref -je_auto_control.utils.secrets je_auto_control.utils.secrets.secret_store -je_auto_control.utils.secrets_scan je_auto_control.utils.secrets_scan.secrets_scan -je_auto_control.utils.selection_view je_auto_control.utils.selection_view.selection_view -je_auto_control.utils.self_healing -je_auto_control.utils.self_healing.heal_log -je_auto_control.utils.self_healing.locator -je_auto_control.utils.semantic_recording je_auto_control.utils.semantic_recording.enrich -je_auto_control.utils.semantic_recording.replay je_auto_control.utils.semantic_recording.self_healing -je_auto_control.utils.sequence_gap -je_auto_control.utils.sequence_gap.sequence_gap -je_auto_control.utils.session_guard -je_auto_control.utils.session_guard.session_guard -je_auto_control.utils.set_of_marks -je_auto_control.utils.set_of_marks.set_of_marks -je_auto_control.utils.settle_detector -je_auto_control.utils.settle_detector.settle_detector -je_auto_control.utils.shape_locator je_auto_control.utils.shape_locator.shape_locator -je_auto_control.utils.shell_open -je_auto_control.utils.shell_open.shell_open -je_auto_control.utils.shell_process je_auto_control.utils.shell_process.shell_exec -je_auto_control.utils.skill_library -je_auto_control.utils.skill_library.skill_library -je_auto_control.utils.slo je_auto_control.utils.slo.slo -je_auto_control.utils.smart_waits je_auto_control.utils.smart_waits.waits -je_auto_control.utils.smoothing -je_auto_control.utils.smoothing.smoothing -je_auto_control.utils.socket_server je_auto_control.utils.socket_server.auto_control_socket_server -je_auto_control.utils.soft_assert je_auto_control.utils.soft_assert.soft_assert -je_auto_control.utils.sql je_auto_control.utils.sql.sql_query -je_auto_control.utils.sqlite_support -je_auto_control.utils.sse_client je_auto_control.utils.sse_client.sse_client -je_auto_control.utils.ssim je_auto_control.utils.ssim.ssim -je_auto_control.utils.start_exe -je_auto_control.utils.start_exe.start_another_process -je_auto_control.utils.state_machine je_auto_control.utils.state_machine.engine -je_auto_control.utils.stats -je_auto_control.utils.stats.stats -je_auto_control.utils.step_repair -je_auto_control.utils.step_repair.step_repair -je_auto_control.utils.step_timeline -je_auto_control.utils.step_timeline.step_timeline -je_auto_control.utils.stubs -je_auto_control.utils.stubs.__main__ -je_auto_control.utils.stubs.generator -je_auto_control.utils.subpixel_match je_auto_control.utils.subpixel_match.subpixel_match -je_auto_control.utils.system_volume -je_auto_control.utils.system_volume.system_volume -je_auto_control.utils.table_grid_fill je_auto_control.utils.table_grid_fill.table_grid_fill -je_auto_control.utils.table_pattern je_auto_control.utils.table_pattern.table_pattern -je_auto_control.utils.test_data -je_auto_control.utils.test_data.test_data -je_auto_control.utils.test_record je_auto_control.utils.test_record.record_test_class -je_auto_control.utils.test_select je_auto_control.utils.test_select.test_select -je_auto_control.utils.test_shard -je_auto_control.utils.test_shard.test_shard -je_auto_control.utils.test_suite -je_auto_control.utils.test_suite.reports -je_auto_control.utils.test_suite.result -je_auto_control.utils.test_suite.runner -je_auto_control.utils.text_blocks -je_auto_control.utils.text_blocks.text_blocks -je_auto_control.utils.text_diff je_auto_control.utils.text_diff.text_diff -je_auto_control.utils.text_normalize -je_auto_control.utils.text_normalize.text_normalize -je_auto_control.utils.text_regions je_auto_control.utils.text_regions.text_regions -je_auto_control.utils.text_similarity je_auto_control.utils.text_similarity.text_similarity -je_auto_control.utils.text_unicode -je_auto_control.utils.text_unicode.text_unicode -je_auto_control.utils.theme_normalize -je_auto_control.utils.theme_normalize.theme_normalize -je_auto_control.utils.time_travel -je_auto_control.utils.time_travel.controller je_auto_control.utils.time_travel.player -je_auto_control.utils.timeouts -je_auto_control.utils.timeseries -je_auto_control.utils.timeseries.timeseries -je_auto_control.utils.tls_acme je_auto_control.utils.tls_acme.challenge je_auto_control.utils.tls_acme.keys je_auto_control.utils.tls_acme.renewal -je_auto_control.utils.tool_use_schema je_auto_control.utils.tool_use_schema.schema -je_auto_control.utils.trace_context -je_auto_control.utils.trace_context.trace_context -je_auto_control.utils.trajectory_eval -je_auto_control.utils.trajectory_eval.trajectory_eval -je_auto_control.utils.transform_window je_auto_control.utils.transform_window.transform_window -je_auto_control.utils.trash -je_auto_control.utils.trash.trash -je_auto_control.utils.triggers je_auto_control.utils.triggers.email_trigger je_auto_control.utils.triggers.trigger_engine je_auto_control.utils.triggers.webhook_server -je_auto_control.utils.tween_drag -je_auto_control.utils.tween_drag.tween_drag -je_auto_control.utils.url_canon -je_auto_control.utils.url_canon.url_canon -je_auto_control.utils.usb -je_auto_control.utils.usb.passthrough je_auto_control.utils.usb.passthrough.acl -je_auto_control.utils.usb.passthrough.backend -je_auto_control.utils.usb.passthrough.commands -je_auto_control.utils.usb.passthrough.descriptor -je_auto_control.utils.usb.passthrough.flags je_auto_control.utils.usb.passthrough.iokit_backend -je_auto_control.utils.usb.passthrough.key_provider -je_auto_control.utils.usb.passthrough.loopback je_auto_control.utils.usb.passthrough.protocol je_auto_control.utils.usb.passthrough.session -je_auto_control.utils.usb.passthrough.viewer_client -je_auto_control.utils.usb.passthrough.webrtc_channel je_auto_control.utils.usb.passthrough.winusb_backend -je_auto_control.utils.usb.usb_devices -je_auto_control.utils.usb.usb_watcher -je_auto_control.utils.usbip je_auto_control.utils.usbip.backend je_auto_control.utils.usbip.libusb_backend -je_auto_control.utils.usbip.protocol je_auto_control.utils.usbip.server -je_auto_control.utils.verify_field -je_auto_control.utils.verify_field.verify_field -je_auto_control.utils.vex -je_auto_control.utils.vex.vex -je_auto_control.utils.video_report -je_auto_control.utils.video_report.video_report -je_auto_control.utils.virtualized -je_auto_control.utils.virtualized.virtualized -je_auto_control.utils.vision je_auto_control.utils.vision.backends je_auto_control.utils.vision.backends._parse je_auto_control.utils.vision.backends.anthropic_backend -je_auto_control.utils.vision.backends.base -je_auto_control.utils.vision.backends.null_backend je_auto_control.utils.vision.backends.openai_backend -je_auto_control.utils.vision.vlm_api -je_auto_control.utils.visual_match je_auto_control.utils.visual_match.visual_match -je_auto_control.utils.visual_regression je_auto_control.utils.visual_regression.compare -je_auto_control.utils.voice -je_auto_control.utils.voice.voice_router -je_auto_control.utils.vuln_scan je_auto_control.utils.vuln_scan.vuln_scan -je_auto_control.utils.watchdog -je_auto_control.utils.watchdog.popup_watchdog -je_auto_control.utils.watcher -je_auto_control.utils.watcher.watcher -je_auto_control.utils.webrunner_bridge je_auto_control.utils.webrunner_bridge.bridge -je_auto_control.utils.window_capture je_auto_control.utils.window_capture.window_capture -je_auto_control.utils.window_geometry -je_auto_control.utils.window_geometry.window_geometry -je_auto_control.utils.window_layout -je_auto_control.utils.window_layout.window_layout -je_auto_control.utils.window_zorder je_auto_control.utils.window_zorder.window_zorder -je_auto_control.utils.work_queue -je_auto_control.utils.work_queue.work_queue -je_auto_control.utils.xml -je_auto_control.utils.xml.change_xml_structure je_auto_control.utils.xml.change_xml_structure.change_xml_structure -je_auto_control.utils.xml.xml_file je_auto_control.utils.xml.xml_file.xml_file -je_auto_control.windows -je_auto_control.windows.core -je_auto_control.windows.core.utils je_auto_control.windows.core.utils.win32_ctype_input -je_auto_control.windows.core.utils.win32_keypress_check -je_auto_control.windows.core.utils.win32_vk -je_auto_control.windows.interception -je_auto_control.windows.interception._dll -je_auto_control.windows.interception.keyboard je_auto_control.windows.interception.mouse -je_auto_control.windows.keyboard -je_auto_control.windows.keyboard.win32_ctype_keyboard_control -je_auto_control.windows.message je_auto_control.windows.message.window_message -je_auto_control.windows.mouse je_auto_control.windows.mouse.win32_ctype_mouse_control -je_auto_control.windows.record je_auto_control.windows.record.win32_input_hook -je_auto_control.windows.record.win32_record -je_auto_control.windows.screen -je_auto_control.windows.screen.win32_screen -je_auto_control.windows.window je_auto_control.windows.window.windows_window_manage -je_auto_control.wrapper -je_auto_control.wrapper._platform_linux -je_auto_control.wrapper._platform_osx -je_auto_control.wrapper._platform_wayland je_auto_control.wrapper._platform_windows je_auto_control.wrapper.auto_control_image je_auto_control.wrapper.auto_control_keyboard @@ -1053,10 +354,6 @@ je_auto_control.wrapper.auto_control_record je_auto_control.wrapper.auto_control_screen je_auto_control.wrapper.auto_control_window je_auto_control.wrapper.backend_contract -je_auto_control.wrapper.platform_wrapper -je_auto_control.wrapper.window_backends -je_auto_control.wrapper.window_backends.base je_auto_control.wrapper.window_backends.macos_backend -je_auto_control.wrapper.window_backends.null_backend je_auto_control.wrapper.window_backends.windows_backend je_auto_control.wrapper.window_backends.x11_backend From 2fc23e55e7b27acbecd6f0dd924fa25910f04f2a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 11:59:26 +0800 Subject: [PATCH 123/161] Annotate 149 one-error modules and hold them to the strict tier Each had a single missing annotation or bare generic between it and the strict flags. Four whose correct annotation exposes a real type error, and the modules that alias ImageSource to Any, stay listed. --- Progress.md | 2 +- architecture_explore.md | 106 +++++------ docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + je_auto_control/__init__.py | 4 +- je_auto_control/cli.py | 3 +- je_auto_control/gui/assertions_tab.py | 4 +- je_auto_control/gui/data_source_tab.py | 4 +- je_auto_control/gui/email_triggers_tab.py | 4 +- je_auto_control/gui/flow_editor/__init__.py | 4 +- je_auto_control/gui/main_widget.py | 2 +- je_auto_control/gui/plugins_tab.py | 4 +- je_auto_control/gui/presence_tab.py | 4 +- je_auto_control/gui/profiler_tab.py | 4 +- .../gui/remote_desktop/blanking_overlay.py | 4 +- .../gui/remote_desktop/sparkline.py | 4 +- je_auto_control/gui/rest_api_tab.py | 2 +- je_auto_control/gui/run_history_timeline.py | 4 +- .../gui/script_builder/__init__.py | 3 +- je_auto_control/gui/secrets_tab.py | 4 +- je_auto_control/gui/trace_replay_tab.py | 4 +- je_auto_control/gui/webrunner_tab.py | 2 +- je_auto_control/gui/window_tab.py | 4 +- .../linux_with_x11/uinput/_device.py | 2 +- je_auto_control/osx/listener/osx_listener.py | 2 +- je_auto_control/osx/mouse/osx_mouse.py | 4 +- je_auto_control/utils/ab_locator/runner.py | 2 +- .../utils/act_in_view/act_in_view.py | 4 +- .../utils/action_effect/action_effect.py | 2 +- .../utils/action_signing/cipher.py | 7 +- .../utils/agent_runtime/activity_windows.py | 2 +- .../utils/agent_runtime/android_commands.py | 3 +- .../utils/agent_runtime/android_control.py | 4 +- .../agent_runtime/android_input_evidence.py | 2 +- .../agent_runtime/android_input_windows.py | 2 +- je_auto_control/utils/agent_runtime/api.py | 2 +- .../agent_runtime/browser_readonly_scope.py | 2 +- .../utils/agent_runtime/commands.py | 2 +- .../utils/agent_runtime/dag_retention.py | 2 +- .../utils/agent_runtime/dialog_scope.py | 2 +- je_auto_control/utils/agent_runtime/errors.py | 4 +- .../utils/agent_runtime/file_dialog_scope.py | 2 +- .../utils/agent_runtime/file_target.py | 2 +- .../utils/agent_runtime/local_evidence.py | 2 +- .../utils/agent_runtime/native_control.py | 2 +- .../utils/agent_runtime/native_recovery.py | 2 +- .../agent_runtime/owned_channel_factory.py | 2 +- .../agent_runtime/presence_messages_linux.py | 3 +- .../agent_runtime/presence_session_windows.py | 2 +- .../utils/agent_runtime/transfer_models.py | 2 +- .../utils/agent_runtime/transport.py | 2 +- .../utils/agent_runtime/trigger_history.py | 2 +- .../utils/agent_runtime/workflow_wait.py | 2 +- .../utils/agent_runtime/workspace_scope.py | 2 +- .../utils/approval/approval_test.py | 4 +- .../utils/artifact_store/s3_store.py | 2 +- je_auto_control/utils/ax_text/ax_text.py | 7 +- je_auto_control/utils/barcode/barcode.py | 2 +- je_auto_control/utils/bulkhead/bulkhead.py | 2 +- .../utils/change_localize/change_localize.py | 4 +- .../clipboard_formats/clipboard_formats.py | 2 +- .../utils/compliance/compliance_report.py | 4 +- .../utils/config_bundle/__main__.py | 2 +- .../utils/config_bundle/config_bundle.py | 4 +- .../utils/contrast_map/contrast_map.py | 5 +- .../control_patterns/control_patterns.py | 7 +- .../utils/cost_telemetry/pricing.py | 2 +- .../utils/cua_action/cua_action.py | 2 +- je_auto_control/utils/cv2_utils/blobs.py | 2 +- .../utils/data_quality/data_quality.py | 2 +- .../utils/deterministic/deterministic.py | 4 +- je_auto_control/utils/diagnostics/__main__.py | 2 +- .../utils/edge_lines/edge_lines.py | 2 +- je_auto_control/utils/executor/dispatch.py | 2 +- .../utils/executor/flow_data_commands.py | 7 +- .../utils/executor/mouse_aliases.py | 4 +- .../utils/failure_bundle/bundle.py | 4 +- .../utils/failure_hooks/backends.py | 6 +- je_auto_control/utils/fuzzy/fuzzy_match.py | 2 +- .../utils/icon_classify/icon_classify.py | 2 +- .../utils/image_dedup/perceptual_hash.py | 4 +- .../utils/image_quality/image_quality.py | 2 +- .../utils/img_histogram/img_histogram.py | 4 +- je_auto_control/utils/json/json_file.py | 4 +- je_auto_control/utils/jwt/jwt_codec.py | 4 +- .../utils/llm/backends/__init__.py | 4 +- .../utils/llm/backends/anthropic_backend.py | 2 +- .../utils/locator_chain/locator_chain.py | 6 +- je_auto_control/utils/mcp_server/__main__.py | 2 +- .../utils/mcp_server/_disclosure_server.py | 2 +- je_auto_control/utils/mcp_server/_protocol.py | 2 +- .../utils/mcp_server/_subscriptions.py | 2 +- .../mcp_server/tools/_handlers_screen.py | 7 +- .../utils/mcp_server/tools/_validation.py | 2 +- .../utils/monitor_layout/logical_frame.py | 2 +- .../utils/motion_regions/motion_regions.py | 2 +- .../utils/observability/exporter.py | 4 +- .../utils/ocr/backends/__init__.py | 2 +- je_auto_control/utils/ocr/backends/base.py | 4 +- je_auto_control/utils/pdf/pdf_reader.py | 7 +- .../utils/profiler/resource_profiler.py | 3 +- je_auto_control/utils/qr/qr.py | 2 +- .../utils/recurrence/recurrence.py | 4 +- je_auto_control/utils/redaction/policies.py | 4 +- je_auto_control/utils/redaction/rules.py | 2 +- .../utils/remote_desktop/adaptive_bitrate.py | 7 +- .../remote_desktop/connect_coordinator.py | 2 +- .../utils/remote_desktop/file_transfer.py | 2 +- .../utils/remote_desktop/host_capture.py | 5 +- .../utils/remote_desktop/input_dispatch.py | 2 +- .../utils/remote_desktop/jpeg_recorder.py | 4 +- .../remote_desktop/jpeg_recorder_encrypted.py | 2 +- .../utils/remote_desktop/permissions.py | 2 +- .../remote_desktop/session_quality_cache.py | 4 +- .../utils/remote_desktop/turn_config.py | 2 +- .../utils/remote_desktop/webrtc_host_auth.py | 2 +- .../utils/remote_desktop/ws_host.py | 3 +- .../utils/remote_desktop/ws_protocol.py | 4 +- .../utils/remote_desktop/ws_viewer.py | 3 +- je_auto_control/utils/rest_api/__main__.py | 2 +- .../utils/rest_api/rest_handlers.py | 4 +- je_auto_control/utils/scheduler/scheduler.py | 4 +- .../utils/script_vars/interpolate.py | 2 +- .../utils/search_index/search_index.py | 4 +- .../utils/secrets_scan/secrets_scan.py | 2 +- .../utils/selection_view/selection_view.py | 7 +- .../utils/semantic_recording/enrich.py | 8 +- .../utils/semantic_recording/self_healing.py | 2 +- je_auto_control/utils/slo/slo.py | 4 +- je_auto_control/utils/smart_waits/waits.py | 2 +- .../auto_control_socket_server.py | 3 +- je_auto_control/utils/sql/sql_query.py | 4 +- .../utils/sse_client/sse_client.py | 4 +- je_auto_control/utils/state_machine/engine.py | 2 +- .../utils/subpixel_match/subpixel_match.py | 2 +- .../utils/table_pattern/table_pattern.py | 7 +- je_auto_control/utils/tls_acme/challenge.py | 4 +- je_auto_control/utils/tls_acme/keys.py | 2 +- .../transform_window/transform_window.py | 7 +- .../utils/triggers/trigger_engine.py | 4 +- .../utils/usb/passthrough/protocol.py | 2 +- .../utils/usb/passthrough/session.py | 2 +- .../utils/usb/passthrough/winusb_backend.py | 2 +- je_auto_control/utils/usbip/backend.py | 4 +- .../utils/vision/backends/_parse.py | 4 +- je_auto_control/utils/vuln_scan/vuln_scan.py | 2 +- .../utils/window_zorder/window_zorder.py | 4 +- je_auto_control/windows/interception/mouse.py | 4 +- .../windows/window/windows_window_manage.py | 2 +- je_auto_control/wrapper/_platform_windows.py | 4 +- je_auto_control/wrapper/auto_control_mouse.py | 2 +- .../wrapper/auto_control_window.py | 3 +- .../window_backends/windows_backend.py | 3 +- pyproject.toml | 176 ++++++++++++++---- test/verify/typing_not_yet_strict.txt | 26 --- test/verify/typing_strict_baseline.txt | 117 ------------ 156 files changed, 468 insertions(+), 446 deletions(-) diff --git a/Progress.md b/Progress.md index 503172688..500a83945 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的 896 個舊模組(U-20261115-05,共 1,039 個)。仍缺:`test/verify/typing_strict_baseline.txt` 344 個與 `typing_not_yet_strict.txt` 141 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台合計約 2,500 個錯誤,集中在 478 個檔案;其中 6 個只差模組層級的 `X = Any` 別名),以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05、-06,共 1,182 個)。仍缺:`test/verify/typing_strict_baseline.txt` 227 個與 `typing_not_yet_strict.txt` 115 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台約 2,400 個錯誤,集中在 331 個檔案;其中 12 個影像/定位模組只差模組層級的 `X = Any` 別名,要先為 `ImageSource` 等定一個共用型別;`android/client.py`、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py` 補上正確註記會露出真的型別錯誤),以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 402e6f2e5..82066570b 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,544 | -| 程式碼總行數 | 237,633 | +| 程式碼總行數 | 237,687 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -169,7 +169,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `je_auto_control/_lazy_exports.py` | 29 | 公開名稱的來源屬性/模組繫結與首次存取解析;保留並行的明確指派。 | | `je_auto_control/_export_bindings.py` | 1,839 | 由具體型別宣告產生的公開名稱來源查表;CI 檢查產生結果與順序。 | | `je_auto_control/__main__.py` | 106 | 舊版 argparse 進入點:`-e` 執行單檔、`-d` 執行整個目錄、`--execute_str` 執行 JSON 字串、`-c` 建立專案。 | -| `je_auto_control/cli.py` | 455 | **主 CLI**(`je_auto_control` console script)。子命令:`run`(含 `--var`/`--dry-run`/`--journal`)、`journal`(依 run 篩選與有界遮罩快照)、`validate`/`lint`、`list-commands`、`fmt`、`record`、`codegen`、`failure-bundle`、`list-jobs`、`start-server`、`start-rest`、`version`。所有子命令延遲匯入,確保不碰 Qt。 | +| `je_auto_control/cli.py` | 456 | **主 CLI**(`je_auto_control` console script)。子命令:`run`(含 `--var`/`--dry-run`/`--journal`)、`journal`(依 run 篩選與有界遮罩快照)、`validate`/`lint`、`list-commands`、`fmt`、`record`、`codegen`、`failure-bundle`、`list-jobs`、`start-server`、`start-rest`、`version`。所有子命令延遲匯入,確保不碰 Qt。 | | `je_auto_control/api/__init__.py` | 100 | 版本化整合進入點。 | | `je_auto_control/api/core.py` | 73 | **穩定無頭 API 門面**:暴露 `execute_action`、`execute_action_with_vars`、`generate_code`、`run_diagnostics`、`create_failure_bundle`、`failure_bundle_on_error`、`FailureBundleOptions`,另提供 `BackendContext`/`CapabilityStatus`/`CapabilitySnapshot`/`probe_capabilities`,以及 `CancellationToken`/`TaskProgress`/`cancellation_scope`。mypy 型別契約以此為起點,現已擴到整包(見「設定基線」)。 | | `je_auto_control/utils/cli_output.py` | 44 | 本套件命令列工具與 stdio 伺服器的標準串流:不論碼頁一律 UTF-8。 | @@ -197,8 +197,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `wrapper/auto_control_screen.py` | 111 | 螢幕 API:`screen_size`、`screenshot`(可指定區域)、`get_pixel`。 | | `wrapper/auto_control_image.py` | 89 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | | `wrapper/auto_control_record.py` | 124 | 錄製 API:`record`/`stop_record`/`record_to_json`(支援 stop event 與逾時)。 | -| `wrapper/auto_control_window.py` | 337 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | -| `wrapper/window_backends/` | 1,148 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | +| `wrapper/auto_control_window.py` | 338 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | +| `wrapper/window_backends/` | 1,149 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | ### 5.3 平台後端 @@ -292,19 +292,19 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,546 行。 +> 25 個套件、約 19,552 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/action_lint/` | 429 | action 檔 linter 與 JSON Schema 產生器;block 與一般指令共用巢狀 body 走訪(CI 用 `python -m` 進入點) | -| `utils/action_signing/` | 1,079 | action 檔 HMAC-SHA256 簽章與 Fernet 加密,`execute_files` 會強制驗簽 | +| `utils/action_signing/` | 1,082 | action 檔 HMAC-SHA256 簽章與 Fernet 加密,`execute_files` 會強制驗簽 | | `utils/checkpoint/` | 129 | 流程檢查點與續跑,讓長 action list 具持久性 | | `utils/codegen/` | 1,363 | 由 action list 或結構化日誌產生 pytest/Python/Robot 候選;來源清單、靜態/乾跑驗證與原子 ZIP 審閱匯出。 | | `utils/dag/` | 1,352 | 跨主機動作/受管任務 DAG;權限及停止傳遞、目的地完成/釋放驗證、去重與未知結果審閱 | | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,752 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,755 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | | `utils/input_macro/` | 477 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | @@ -437,7 +437,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.6 OCR 與文字理解 -> 19 個套件、約 3,818 行。 +> 19 個套件、約 3,820 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -450,7 +450,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/guardrail/` | 117 | 針對畫面/OCR 文字的啟發式 prompt-injection 防護 | | `utils/heading_segment/` | 71 | 判定 OCR 行是標題或內文,建出文件大綱 | | `utils/near_dup/` | 108 | 近似重複文字偵測(SimHash/MinHash) | -| `utils/ocr/` | 1,382 | OCR 引擎門面 + 三個後端(Tesseract/EasyOCR/PaddleOCR)、版面結構化與跨詞比對(`text_span`)、Tesseract 的尋找/設定/健康檢查(`tesseract_setup`) | +| `utils/ocr/` | 1,384 | OCR 引擎門面 + 三個後端(Tesseract/EasyOCR/PaddleOCR)、版面結構化與跨詞比對(`text_span`)、Tesseract 的尋找/設定/健康檢查(`tesseract_setup`) | | `utils/pii_text/` | 141 | 自由文字中的 PII 偵測與遮蔽(email/電話/SSN/卡號/IP/IBAN) | | `utils/readability/` | 140 | 可讀性評分(Flesch、Flesch-Kincaid、Gunning Fog、SMOG、ARI) | | `utils/reading_flow/` | 165 | 以遞迴 XY-cut 推導欄位感知的閱讀順序 | @@ -463,7 +463,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,909 行。 +> 16 個套件、約 4,925 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -471,22 +471,22 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/accessibility/` | 3,374 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | -| `utils/ax_text/` | 102 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | +| `utils/ax_text/` | 105 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | | `utils/ax_tree_walk/` | 119 | 可讀、可定址的無障礙樹後處理(角色名 + 節點路徑) | -| `utils/contrast_map/` | 130 | 取樣實際顏色以評定畫面文字的可讀性(WCAG) | -| `utils/control_patterns/` | 88 | 延伸 UIA 控制項模式動作(Expand/Select/Range/Scroll) | +| `utils/contrast_map/` | 131 | 取樣實際顏色以評定畫面文字的可讀性(WCAG) | +| `utils/control_patterns/` | 91 | 延伸 UIA 控制項模式動作(Expand/Select/Range/Scroll) | | `utils/cvd_simulate/` | 140 | 模擬色覺缺陷並標示在該狀況下會撞色的顏色 | | `utils/element_repository/` | 118 | 原生 UI 元素的具名定位器倉庫(object repository) | | `utils/focus_order/` | 117 | 鍵盤焦點順序:預期 Tab 序列、WCAG 稽核與設定焦點 | | `utils/legacy_accessible/` | 45 | MSAA 橋接,處理 UIA 無法建模的舊控制項 | -| `utils/selection_view/` | 57 | 容器選取狀態與檢視切換(Selection/MultipleView 模式) | -| `utils/table_pattern/` | 65 | 原生表格的表頭與儲存格定址(UIA TablePattern/GridItem) | -| `utils/transform_window/` | 70 | 以 UIA Transform/Window 模式移動、調整大小與視窗狀態 | +| `utils/selection_view/` | 60 | 容器選取狀態與檢視切換(Selection/MultipleView 模式) | +| `utils/table_pattern/` | 68 | 原生表格的表頭與儲存格定址(UIA TablePattern/GridItem) | +| `utils/transform_window/` | 73 | 以 UIA Transform/Window 模式移動、調整大小與視窗狀態 | | `utils/virtualized/` | 43 | 實體化虛擬化清單/網格中的離屏項目 | ### 5.4.8 元素定位、自我修復與智慧等待 -> 23 個套件、約 6,339 行。 +> 23 個套件、約 6,343 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -510,19 +510,19 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/screen_state/` | 191 | 語義畫面狀態:快照/差異與結構化畫面描述 | | `utils/scroll_find/` | 103 | 捲動直到目標影像/文字可見 | | `utils/self_healing/` | 2,236 | 執行時自癒定位與固定 PNG 版本比較、明確母體/延遲/來源報告 | -| `utils/semantic_recording/` | 498 | 為錄製內容加上語義錨點,支援換機重播與自癒重播 | +| `utils/semantic_recording/` | 502 | 為錄製內容加上語義錨點,支援換機重播與自癒重播 | | `utils/settle_detector/` | 79 | 以純函式介面判定 UI 是否已靜止 | | `utils/smart_waits/` | 663 | 智慧等待:以影格差異取代 `time.sleep` | ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,951 行。 +> 14 個套件、約 52,958 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,253 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,967 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 25,971 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -530,21 +530,21 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,228 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,231 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 666 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,226 行。 +> 6 個套件、約 32,232 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,900 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,906 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,578 行。 +> 24 個套件、約 7,579 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -585,7 +585,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/outbox/` | 107 | 交易式 outbox,保證至少一次的事件投遞 | | `utils/pytest_plugin/` | 283 | pytest 外掛 + BDD step library(`pytest11` entry point) | | `utils/rest_api/` | 2,226 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | -| `utils/socket_server/` | 163 | 執行 action JSON 的執行緒式 TCP 指令伺服器(預設綁 127.0.0.1) | +| `utils/socket_server/` | 164 | 執行 action JSON 的執行緒式 TCP 指令伺服器(預設綁 127.0.0.1) | | `utils/sse_client/` | 142 | Server-Sent Events 用戶端解析 | | `utils/tls_acme/` | 475 | TLS 自動化:HTTP-01 挑戰伺服器、金鑰/CSR、自動續期 | | `utils/url_canon/` | 194 | RFC 3986 URL 正規化與查詢字串工具 | @@ -593,7 +593,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.12 報表、可觀測性與測試治理 -> 34 個套件、約 7,984 行。 +> 34 個套件、約 7,987 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -604,7 +604,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/canonical_log/` | 96 | canonical log line 與結構化 JSON 日誌 | | `utils/ci_annotations/` | 65 | 由執行結果輸出 CI 工作流程註記(GitHub Actions) | | `utils/compliance/` | 166 | 合規:把治理證據對應到 SOC2/ISO 27001 控制項 | -| `utils/failure_hooks/` | 415 | 失敗 → 工單自動化:開 Jira/Linear/GitHub issue | +| `utils/failure_hooks/` | 417 | 失敗 → 工單自動化:開 Jira/Linear/GitHub issue | | `utils/failure_signature/` | 76 | 把錯誤訊息正規化成穩定的 SHA-256 失敗簽章並分群 | | `utils/flake_cluster/` | 112 | 以共同失敗 Jaccard 相似度為易碎測試分群 | | `utils/flakiness/` | 151 | 以執行歷史分析不穩定測試 | @@ -615,7 +615,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/percentiles/` | 119 | 可合併的串流延遲摘要與精確百分位數 | | `utils/process_doc/` | 108 | 由錄製的 action list 產生逐步 SOP 文件 | | `utils/process_mining/` | 131 | 流程探勘:從動作日誌挖掘可自動化的候選 | -| `utils/profiler/` | 451 | 逐動作效能剖析器 + 資源剖析器 | +| `utils/profiler/` | 452 | 逐動作效能剖析器 + 資源剖析器 | | `utils/quarantine/` | 204 | 易碎測試隔離區,讓套件執行器跳過已知不穩定案例 | | `utils/run_diff/` | 143 | 兩次執行軌跡的差異(LCS 對齊:新增/移除/狀態翻轉/退化) | | `utils/run_history/` | 706 | 執行歷史、產出物與非擁有式 journal 連結;明確手動 scope 與既有 owner 的 context 傳入本機 workers,清理 history 不刪日誌檔 | @@ -634,7 +634,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.13 資料來源、結構驗證與 i18n -> 24 個套件、約 5,197 行。 +> 24 個套件、約 5,200 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -656,7 +656,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/locale_parse/` | 80 | 地區感知數字/貨幣/日期解析與格式化(選用 babel) | | `utils/message_format/` | 389 | ICU-lite MessageFormat(plural/select/selectordinal) | | `utils/office/` | 198 | Office 文件無頭讀寫(Excel/Word/PowerPoint) | -| `utils/pdf/` | 117 | PDF 讀取與斷言(選用 pypdf 後端) | +| `utils/pdf/` | 120 | PDF 讀取與斷言(選用 pypdf 後端) | | `utils/referential/` | 83 | 跨資料集的參照完整性檢查 | | `utils/schema_compat/` | 177 | JSON Schema 相容性分級 | | `utils/sql/` | 88 | 對 SQLite 的臨時唯讀 SQL 查詢 | @@ -744,19 +744,19 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | | `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,752 行)— 執行核心 +#### `utils/executor/`(10,755 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `action_executor.py` | 8,679 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | | `flow_control.py` | 726 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | -| `flow_data_commands.py` | 272 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | +| `flow_data_commands.py` | 275 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | | `action_schema.py` | 225 | action list 的結構驗證:形狀、參數型別、未知指令拒絕。單一走訪同時支援兩種消費方式:`validate_actions()` 遇到第一個問題就拋、`unknown_command_names()` 收齊全部不認得的名字(REST `/execute` 用它回 400)。 | | `action_redaction.py` | 196 | 記錄與紀錄鍵用的遮蔽:`AC_secret_*` 的參數(金庫通行碼、機密值)在寫進 log、當成結果紀錄的鍵之前換成 `***`,巢狀在區塊指令裡的也一樣。 | | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,228 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,231 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -764,7 +764,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers.py` | 547 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | | `tools/_handlers_qa.py` | 619 | 同一種 adapter,QA 主題:斷言 DSL、資料驅動、SQL/PDF/郵件/HTTP 步驟、codegen、視覺回歸、狀態機、flaky 偵測與隔離、suite runner、無障礙稽核、裝置矩陣、媒體斷言。從 `_handlers.py` 依主題拆出的第一塊(750 行上限);兩者互不引用。 | | `tools/_handlers_input.py` | 221 | 同一種 adapter,輸入主題:滑鼠、鍵盤、虛擬手把(ViGEm)。 | -| `tools/_handlers_screen.py` | 349 | 同一種 adapter,螢幕主題:擷取、像素、影像與文字搜尋、螢幕錄影。 | +| `tools/_handlers_screen.py` | 352 | 同一種 adapter,螢幕主題:擷取、像素、影像與文字搜尋、螢幕錄影。 | | `tools/_handlers_system.py` | 592 | 同一種 adapter,桌面工作階段:視窗(狀態操作依正規化的後端成敗回覆)、行程與 shell、開檔、閒置與睡眠、音量、鎖定、輸入法狀態、欄位驗證與重試、色彩對比、變更排序、元件分類、剪貼簿。 | | `tools/_handlers_runs.py` | 124 | 同一種 adapter,執行主題:executor、執行歷史、錄製、動作檔。 | | `tools/_template_candidates.py` | 91 | 五個候選樣板工具,含縮圖、固定樣本驗證、路徑根目錄與取消。 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,900 行/77 檔) +#### `utils/remote_desktop/`(16,906 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -840,7 +840,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `multi_viewer.py` | 519 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | -| `host_capture.py` | 323 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | +| `host_capture.py` | 324 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | | `ws_protocol.py` | 318 | 最小 RFC 6455 WebSocket 框架與握手。 | | `file_transfer.py` | 484 | 分塊檔案傳輸。 | | `relay.py` | 316 | NAT 穿透失敗時的 TCP 中繼。 | @@ -865,7 +865,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | | `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | -| `adaptive_bitrate.py` | 148 | 依統計調整主機擷取 FPS。 | +| `adaptive_bitrate.py` | 151 | 依統計調整主機擷取 FPS。 | | `signaling_client.py` | 194 | 純標準庫的訊令用戶端。 | | `trust_list.py` | 139 | 自動接受的檢視端信任清單。 | | `webrtc_inspector.py` | 138 | 行程級的 `StatsSnapshot` 滾動視窗。 | @@ -881,7 +881,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `resume_tokens.py` / `session_quality_cache.py` / `rate_limit.py` | 94 / 85 / 84 | 快速重連 token、每 session 品質快取、檢視端限流。 | | `host_id.py` / `viewer_id.py` | 83 / 79 | 主機與檢視端的持久身分。 | | `permissions.py` / `clipboard_sync.py` / `wake_on_lan.py` / `session_actions.py` / `auth.py` | 64 / 137 / 56 / 40 / 28 | 逐 session 權限、剪貼簿同步、WOL、SAS 注入與螢幕遮蔽、HMAC 挑戰回應。 | -| `ws_host.py` / `ws_viewer.py` / `jpeg_recorder.py` | 40 / 29 / 146 | WebSocket 傳輸變體與 TCP 路徑錄影。 | +| `ws_host.py` / `ws_viewer.py` / `jpeg_recorder.py` | 41 / 30 / 146 | WebSocket 傳輸變體與 TCP 路徑錄影。 | #### `utils/usb/`(5,069 行)與 `utils/usbip/`(1,008 行) @@ -1045,7 +1045,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,967 行/182 檔) +#### `utils/agent_runtime/`(25,971 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1055,7 +1055,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `activity_windows.py` | 102 | Owned Win32 presence-only hooks; no key values, coordinates or input contents are retained. | | `android_action_result.py` | 59 | Decode complete Android command phases without claiming input retirement or task completion. | | `android_adapter.py` | 201 | Bridge checked Android sessions into the owned worker only with explicit trusted device-control leases. | -| `android_commands.py` | 188 | Compile finite Android inputs behind same-connection identity checks; never dispatch raw model shell. | +| `android_commands.py` | 189 | Compile finite Android inputs behind same-connection identity checks; never dispatch raw model shell. | | `android_control.py` | 56 | Trusted Android control leases require real device fencing and independent per-command settlement. | | `android_geometry.py` | 99 | Exact half-open Android touch-region coverage for whole pointer paths, including swipe interiors. | | `android_hierarchy.py` | 287 | Parse bounded Android app hierarchies with explicit host text grants and private freshness signatures. | @@ -1095,7 +1095,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `delegation.py` | 43 | Short-lived, authenticated principal forwarding across the local service boundary. | | `dialog_scope.py` | 54 | Pause managed desktop work at unsaved-content or unrecognized modal windows. | | `document_launch.py` | 46 | Bounded document handoff runs outside the disposable native input helper's process tree. | -| `errors.py` | 21 | Typed failures for managed tasks, observations and control ownership. | +| `errors.py` | 23 | Typed failures for managed tasks, observations and control ownership. | | `evidence.py` | 215 | Service-owned task provenance, redacted artifacts and thirty-day metadata retention. | | `evidence_cache.py` | 92 | Database-bound evidence paths never turn historical journal references into filesystem ownership. | | `evidence_handoff.py` | 368 | Explicit revocable evidence-only grants preserve ordinary task ownership and input isolation. | @@ -1137,7 +1137,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence_broker.py` | 182 | Private broker with internally selected source ownership and normal busy/lease-lost results. | | `presence_handshake.py` | 77 | Fresh byte challenges bound to native peer identity, birth and process-object liveness. | | `presence_host.py` | 115 | Lazy host-owned source lifetimes and fixed per-helper capabilities, never task-selected authority. | -| `presence_messages_linux.py` | 102 | Authenticate each Linux packet and retire every received descriptor before delivery. | +| `presence_messages_linux.py` | 103 | Authenticate each Linux packet and retire every received descriptor before delivery. | | `presence_native_types.py` | 16 | Resource-free native structure size and pointer views for presence components. | | `presence_owner.py` | 38 | Closed bounded owner-only line envelopes for private presence helpers. | | `presence_peer_linux.py` | 218 | Retain Linux connected-process evidence only; no desktop session or input authority. | @@ -1356,8 +1356,8 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | screenshot | `_screenshot_tab.py` | 180 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 158 | 樣板裁切、定位、定位全部、定位並點擊。 | | record | `_record_tab.py` | 166 | 錄製/停止/回放/存檔/載入。 | -| script_builder | `script_builder/` | 6,956 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | -| flow_editor | `flow_editor/` | 496 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | +| script_builder | `script_builder/` | 6,957 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | +| flow_editor | `flow_editor/` | 498 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | | script | `_script_tab.py` | 183 | 載入/執行單檔或整個目錄、內建編輯器執行。 | | recording_editor | `recording_editor_tab.py` | 255 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | @@ -1549,28 +1549,28 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,906 | -| `utils/mcp_server/` | 63 | 22,228 | -| `utils/remote_desktop/` | 77 | 16,900 | -| `utils/executor/` | 11 | 10,752 | +| `gui/` | 166 | 43,909 | +| `utils/mcp_server/` | 63 | 22,231 | +| `utils/remote_desktop/` | 77 | 16,906 | +| `utils/executor/` | 11 | 10,755 | | `utils/usb/` | 20 | 5,069 | -| `je_auto_control/`(頂層 3 檔) | 5 | 5,167 | +| `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | | `utils/accessibility/` | 16 | 3,374 | -| `wrapper/` | 25 | 6,044 | +| `wrapper/` | 25 | 6,046 | | `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | | `linux_wayland/` | 24 | 4,437 | | `utils/triggers/` | 4 | 1,408 | -| `utils/ocr/` | 10 | 1,382 | +| `utils/ocr/` | 10 | 1,384 | | `utils/usbip/` | 5 | 1,008 | | `utils/assertion/` | 3 | 888 | | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,503 | -| **總計** | **1,532** | **236,888** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,537 | +| **總計** | **1,532** | **236,942** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index f6fd0ffce..e801a3020 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -681,3 +681,11 @@ - **Tests:** `test/verify/typing_contract_verify.py` (three platforms) and `--extras` (real PySide6 6.12.0 / aiortc 1.15.0 / av types, the versions CI pins): 0 modules failing in either. `test_typing_modernization_contract.py`: 14 passed. - **Files:** `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `test/verify/typing_not_yet_strict.txt`, the three constructors, `Progress.md`. - **Open items:** `Progress.md` › H (the 485 modules still outside the tier). + +## U-20261115-06 · 2026-11-15 · 143 more modules join the strict typing tier after one-line fixes · #done #typing + +- **What:** the next stage of `Progress.md` › H after U-20261115-05: the 153 files whose only strict error was one missing annotation or one unparameterised generic (90 `type-arg`, 63 `no-untyped-def`). +- **Change:** annotation-only edits in 149 of them, with types read from the code (`Any` only for JSON payloads, numpy/cv2 arrays, Quartz, ctypes and `*args`/`**kwargs`, as elsewhere); lazily imported types come in under `TYPE_CHECKING`. The facade imports `Any as _Any`, so `__all__` is unchanged; `host_capture.py` declares `_latest_frame: Optional[bytes]` in its existing `TYPE_CHECKING` block; `locator_chain.LocatorChain.__init__` gains `-> None`. Four stay unchanged because the correct annotation exposes a real type error: `android/client.py` (a starred tuple in an `except`), `linux_wayland/libei.py` (`oeffis.connect_eis_fd`'s return type), `utils/logging/logging_instance.py` (`FileHandler._open` vs `open()`'s `IO[Any]`), `utils/accessibility/accessibility_api.py` (`tuple(el.bounds)` vs a 4-tuple). 143 modules are promoted (strict tier 1,039 → 1,182; baseline 344 → 227, not-yet-strict 141 → 115); six more image modules bound `ImageSource = Any` and stay out with the first six. +- **Tests:** mypy with both flags: 2,396 / 2,384 / 2,384 errors in 331 / 330 / 330 files (win32 / linux / darwin), from 2,552 / 2,538 / 2,540 in 478 / 476 / 478, and no new error in any other file. `typing_contract_verify.py` and `--extras`: 0 modules failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the headless tests of the touched modules: 988 passed, 19 skipped, and `test_locator_chain` 9 passed. +- **Files:** 150 modules under `je_auto_control/`, `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `test/verify/typing_not_yet_strict.txt`, `architecture_explore.md` (line counts), `Progress.md`. +- **Open items:** `Progress.md` › H (342 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index cff0053c0..ec7f0e9d0 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-06 | 2026-11-15 | 143 more modules join the strict typing tier after one-line fixes | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-05 | 2026-11-15 | 896 older modules join the strict typing tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-04 | 2026-11-15 | The approval gate binds maker and checker to the RBAC user | #done #rbac #governance | [2026-11-b](2026-11-b.md) | | U-20261115-03 | 2026-11-15 | Every AC_* command has an RBAC decision | #done #rbac #security | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/__init__.py b/je_auto_control/__init__.py index a9b13ff10..21206f5b6 100644 --- a/je_auto_control/__init__.py +++ b/je_auto_control/__init__.py @@ -1,6 +1,6 @@ """Public automation exports, resolved from their original owners on first access.""" import sys as _sys -from typing import TYPE_CHECKING as _TYPE_CHECKING +from typing import TYPE_CHECKING as _TYPE_CHECKING, Any as _Any from je_auto_control._export_bindings import EXPORTS as _EXPORTS from je_auto_control._lazy_exports import resolve_export as _resolve_export @@ -1961,7 +1961,7 @@ windows_window_manage = None # type: ignore[assignment] -def start_autocontrol_gui(*args, **kwargs): +def start_autocontrol_gui(*args: _Any, **kwargs: _Any) -> None: """Launch the GUI (imports PySide6 lazily so headless usage stays Qt-free).""" from je_auto_control.gui import start_autocontrol_gui as _impl return _impl(*args, **kwargs) diff --git a/je_auto_control/cli.py b/je_auto_control/cli.py index d8552543d..ddf896350 100644 --- a/je_auto_control/cli.py +++ b/je_auto_control/cli.py @@ -33,6 +33,7 @@ import threading import time from contextlib import AbstractContextManager, ExitStack, closing, contextmanager, nullcontext +from types import FrameType from typing import Callable, Dict, Iterator, List, Optional, Sequence from je_auto_control.utils.logging.secret_scope import scrub_secret_text, secret_log_scope @@ -295,7 +296,7 @@ def cmd_start_rest(args: argparse.Namespace) -> int: def _run_until_signal(shutdown: Callable[[], None]) -> None: stopping = {"flag": False} - def _handler(_signum, _frame): + def _handler(_signum: int, _frame: Optional[FrameType]) -> None: stopping["flag"] = True signal.signal(signal.SIGINT, _handler) diff --git a/je_auto_control/gui/assertions_tab.py b/je_auto_control/gui/assertions_tab.py index 0b4386a17..a73ce31ee 100644 --- a/je_auto_control/gui/assertions_tab.py +++ b/je_auto_control/gui/assertions_tab.py @@ -5,7 +5,7 @@ outcome instead of crashing the tab. """ import functools -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtWidgets import ( QCheckBox, QComboBox, QFormLayout, QLabel, QLineEdit, @@ -88,7 +88,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("assert_run", self._on_run), diff --git a/je_auto_control/gui/data_source_tab.py b/je_auto_control/gui/data_source_tab.py index 8b3fb9f57..533d566a1 100644 --- a/je_auto_control/gui/data_source_tab.py +++ b/je_auto_control/gui/data_source_tab.py @@ -4,7 +4,7 @@ builds a source spec dict from the form and renders the returned rows. """ import json -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtWidgets import ( QAbstractItemView, QComboBox, QFileDialog, QHBoxLayout, QLabel, QLineEdit, @@ -77,7 +77,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("ds_load", self._on_load), diff --git a/je_auto_control/gui/email_triggers_tab.py b/je_auto_control/gui/email_triggers_tab.py index ea0634e27..febfe6354 100644 --- a/je_auto_control/gui/email_triggers_tab.py +++ b/je_auto_control/gui/email_triggers_tab.py @@ -5,7 +5,7 @@ and a trigger already being polled finishes, so no message is marked seen without its script having fired. """ -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import QTimer, Qt from PySide6.QtWidgets import ( @@ -141,7 +141,7 @@ def _pair(self, label_key: str, field: QWidget, min_width: int = 0) -> QWidget: pair.setMinimumWidth(min_width) return pair - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("eml_start", self._on_start), diff --git a/je_auto_control/gui/flow_editor/__init__.py b/je_auto_control/gui/flow_editor/__init__.py index 3a8fce496..7fa2fd4d1 100644 --- a/je_auto_control/gui/flow_editor/__init__.py +++ b/je_auto_control/gui/flow_editor/__init__.py @@ -13,6 +13,8 @@ import FlowEditorTab`` still works — Python falls through to ``__getattr__`` when the attribute is not pre-bound. """ +from typing import Any + from je_auto_control.gui.flow_editor.layout import ( FlowEdge, FlowLayout, FlowNodePosition, layout_steps, ) @@ -27,7 +29,7 @@ } -def __getattr__(name): +def __getattr__(name: str) -> Any: target = _LAZY_SUBMODULES.get(name) if target is None: raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/je_auto_control/gui/main_widget.py b/je_auto_control/gui/main_widget.py index b2d02fb38..42224a64a 100644 --- a/je_auto_control/gui/main_widget.py +++ b/je_auto_control/gui/main_widget.py @@ -79,7 +79,7 @@ def _stop_auto_click(self) -> None: entry.widget.dispose() stop_all_script_runs() - def keyPressEvent(self, event: QKeyEvent): + def keyPressEvent(self, event: QKeyEvent) -> None: if event.modifiers() == Qt.KeyboardModifier.ControlModifier and event.key() == Qt.Key.Key_4: self._stop_auto_click() else: diff --git a/je_auto_control/gui/plugins_tab.py b/je_auto_control/gui/plugins_tab.py index 418704727..ee7778b63 100644 --- a/je_auto_control/gui/plugins_tab.py +++ b/je_auto_control/gui/plugins_tab.py @@ -1,5 +1,5 @@ """Plugins tab: load extra AC_ commands from a user directory.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtWidgets import ( QFileDialog, QFormLayout, QLabel, QLineEdit, QListWidget, QMessageBox, @@ -47,7 +47,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("browse", self._browse), diff --git a/je_auto_control/gui/presence_tab.py b/je_auto_control/gui/presence_tab.py index c58e0fda1..c1d56d07e 100644 --- a/je_auto_control/gui/presence_tab.py +++ b/je_auto_control/gui/presence_tab.py @@ -6,7 +6,7 @@ table auto-refreshes when the registry notifies of a change. """ import functools -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import Qt, QTimer, Signal from PySide6.QtWidgets import ( @@ -90,7 +90,7 @@ def _build_layout(self) -> None: header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch) self._apply_translations() - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("presence_refresh_btn", self.refresh), diff --git a/je_auto_control/gui/profiler_tab.py b/je_auto_control/gui/profiler_tab.py index ab34c7239..81ff13013 100644 --- a/je_auto_control/gui/profiler_tab.py +++ b/je_auto_control/gui/profiler_tab.py @@ -1,5 +1,5 @@ """Profiler tab: visualise per-action wall-clock hot spots.""" -from typing import List, Optional +from typing import Callable, List, Optional, Tuple from PySide6.QtCore import QTimer, Qt from PySide6.QtWidgets import ( @@ -87,7 +87,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("prof_enable", self._toggle_enable), diff --git a/je_auto_control/gui/remote_desktop/blanking_overlay.py b/je_auto_control/gui/remote_desktop/blanking_overlay.py index 031b64ffa..02e10327b 100644 --- a/je_auto_control/gui/remote_desktop/blanking_overlay.py +++ b/je_auto_control/gui/remote_desktop/blanking_overlay.py @@ -13,7 +13,7 @@ from typing import List, Optional -from PySide6.QtCore import Qt +from PySide6.QtCore import QRect, Qt from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import QLabel, QVBoxLayout, QWidget @@ -23,7 +23,7 @@ class _BlankingWindow(QWidget): """One blanking window per screen.""" - def __init__(self, geometry, parent: Optional[QWidget] = None) -> None: + def __init__(self, geometry: QRect, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self.setWindowFlags( Qt.WindowType.FramelessWindowHint diff --git a/je_auto_control/gui/remote_desktop/sparkline.py b/je_auto_control/gui/remote_desktop/sparkline.py index c7067d891..94fac9510 100644 --- a/je_auto_control/gui/remote_desktop/sparkline.py +++ b/je_auto_control/gui/remote_desktop/sparkline.py @@ -9,7 +9,7 @@ from typing import Optional from PySide6.QtCore import Qt -from PySide6.QtGui import QColor, QPainter, QPen, QPolygonF +from PySide6.QtGui import QColor, QPaintEvent, QPainter, QPen, QPolygonF from PySide6.QtCore import QPointF from PySide6.QtWidgets import QSizePolicy, QWidget @@ -40,7 +40,7 @@ def clear(self) -> None: self._values.clear() self.update() - def paintEvent(self, _event) -> None: # noqa: N802 Qt override + def paintEvent(self, _event: QPaintEvent) -> None: # noqa: N802 Qt override painter = QPainter(self) try: painter.fillRect(self.rect(), self._bg_color or self.palette().base().color()) diff --git a/je_auto_control/gui/rest_api_tab.py b/je_auto_control/gui/rest_api_tab.py index 55474ca33..a17cbb440 100644 --- a/je_auto_control/gui/rest_api_tab.py +++ b/je_auto_control/gui/rest_api_tab.py @@ -79,7 +79,7 @@ def _build_layout(self) -> None: root.addWidget(ResponsiveBox(self._build_config_group(), self._build_status_group())) root.addWidget(self._users_panel, stretch=1) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, object]]: """Expose tab commands to the window-level Actions menu.""" return [ ("rest_start", self._on_start), diff --git a/je_auto_control/gui/run_history_timeline.py b/je_auto_control/gui/run_history_timeline.py index 4730315c5..8226180cd 100644 --- a/je_auto_control/gui/run_history_timeline.py +++ b/je_auto_control/gui/run_history_timeline.py @@ -11,7 +11,7 @@ from typing import List, Optional, Sequence, Tuple from PySide6.QtCore import QRectF, Qt, Signal -from PySide6.QtGui import QColor, QFont, QFontMetrics, QMouseEvent, QPainter +from PySide6.QtGui import QColor, QFont, QFontMetrics, QMouseEvent, QPaintEvent, QPainter from PySide6.QtWidgets import QSizePolicy, QWidget from je_auto_control.utils.run_history.history_store import ( @@ -61,7 +61,7 @@ def set_highlighted(self, run_id: Optional[int]) -> None: self._highlight_id = run_id self.update() - def paintEvent(self, event) -> None: + def paintEvent(self, event: QPaintEvent) -> None: del event painter = QPainter(self) try: diff --git a/je_auto_control/gui/script_builder/__init__.py b/je_auto_control/gui/script_builder/__init__.py index f9b1ab6fd..261961e7e 100644 --- a/je_auto_control/gui/script_builder/__init__.py +++ b/je_auto_control/gui/script_builder/__init__.py @@ -11,9 +11,10 @@ Callers reach the tab via attribute access, which falls through to :func:`__getattr__` and loads the Qt submodule on demand. """ +from typing import Any -def __getattr__(name): +def __getattr__(name: str) -> Any: if name == "ScriptBuilderTab": import importlib module = importlib.import_module( diff --git a/je_auto_control/gui/secrets_tab.py b/je_auto_control/gui/secrets_tab.py index 9e58c8146..0c1cf7e28 100644 --- a/je_auto_control/gui/secrets_tab.py +++ b/je_auto_control/gui/secrets_tab.py @@ -1,5 +1,5 @@ """Secrets tab: unlock the vault and manage ${secrets.NAME} entries.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtWidgets import ( QAbstractItemView, QFormLayout, QGroupBox, QInputDialog, QLabel, @@ -60,7 +60,7 @@ def _build_layout(self) -> None: set_role(self._status_label, "hint") root.addWidget(self._status_label) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("secret_unlock", self._on_unlock), diff --git a/je_auto_control/gui/trace_replay_tab.py b/je_auto_control/gui/trace_replay_tab.py index 1ee1f8659..857fea4a1 100644 --- a/je_auto_control/gui/trace_replay_tab.py +++ b/je_auto_control/gui/trace_replay_tab.py @@ -7,7 +7,7 @@ :class:`TraceReplayController` so it can be unit-tested without Qt. """ import json -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import Qt from PySide6.QtGui import QPixmap @@ -74,7 +74,7 @@ def _build_layout(self) -> None: root.addWidget(self._status) self._apply_translations() - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("trace_open_btn", self._on_open), diff --git a/je_auto_control/gui/webrunner_tab.py b/je_auto_control/gui/webrunner_tab.py index a8eff07b7..dea78f1e2 100644 --- a/je_auto_control/gui/webrunner_tab.py +++ b/je_auto_control/gui/webrunner_tab.py @@ -88,7 +88,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("web_browse", self._on_browse_screenshot), diff --git a/je_auto_control/gui/window_tab.py b/je_auto_control/gui/window_tab.py index 612315ee0..e9d240064 100644 --- a/je_auto_control/gui/window_tab.py +++ b/je_auto_control/gui/window_tab.py @@ -1,5 +1,5 @@ """Window Manager tab: list, focus, close windows.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( @@ -83,7 +83,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("win_refresh", self.refresh), diff --git a/je_auto_control/linux_with_x11/uinput/_device.py b/je_auto_control/linux_with_x11/uinput/_device.py index f256d2d7d..a43fd501e 100644 --- a/je_auto_control/linux_with_x11/uinput/_device.py +++ b/je_auto_control/linux_with_x11/uinput/_device.py @@ -210,7 +210,7 @@ def emit(ev_type: int, code: int, value: int, *, sync: bool = True) -> None: os.write(fd, _pack_input_event(EV_SYN, SYN_REPORT, 0)) -def emit_combo(events: list, *, sync: bool = True) -> None: +def emit_combo(events: list[tuple[int, int, int]], *, sync: bool = True) -> None: """Write a batch of (type, code, value) events, then SYN_REPORT.""" fd = _ensure_fd() for ev_type, code, value in events: diff --git a/je_auto_control/osx/listener/osx_listener.py b/je_auto_control/osx/listener/osx_listener.py index 429145344..28ac53a25 100644 --- a/je_auto_control/osx/listener/osx_listener.py +++ b/je_auto_control/osx/listener/osx_listener.py @@ -198,7 +198,7 @@ def _run(self, stop: threading.Event) -> None: Quartz.CFRunLoopRemoveSource( run_loop, source, kCFRunLoopDefaultMode) - def _callback(self, proxy, event_type, event, _refcon): + def _callback(self, proxy: Any, event_type: int, event: Any, _refcon: Any) -> Any: """Called by the window server on the tap thread, for every event.""" # Anything escaping here tears down the run loop, and the recording # then stops without saying so — one unexpected event shape would end diff --git a/je_auto_control/osx/mouse/osx_mouse.py b/je_auto_control/osx/mouse/osx_mouse.py index ddec885e5..5dd3a9e7d 100644 --- a/je_auto_control/osx/mouse/osx_mouse.py +++ b/je_auto_control/osx/mouse/osx_mouse.py @@ -1,6 +1,6 @@ import sys import time -from typing import Tuple +from typing import Any, Tuple from je_auto_control.utils.exception.exception_tags import osx_import_error_message from je_auto_control.utils.exception.exceptions import ( @@ -66,7 +66,7 @@ def mouse_event(event: int, x: int, y: int, mouse_button: int, def _build_mouse_event(event: int, x: int, y: int, mouse_button: int, - click_count: int = 1): + click_count: int = 1) -> Any: """ The Quartz event ``mouse_event`` posts, not yet posted 建立(但不送出)滑鼠事件 diff --git a/je_auto_control/utils/ab_locator/runner.py b/je_auto_control/utils/ab_locator/runner.py index 6b1f8413a..a663d6f5b 100644 --- a/je_auto_control/utils/ab_locator/runner.py +++ b/je_auto_control/utils/ab_locator/runner.py @@ -100,7 +100,7 @@ def report_for(target_id: str, return target_store.report(target_id) -def _run_one(item) -> Tuple[str, StrategyResult]: +def _run_one(item: Tuple[str, Locator]) -> Tuple[str, StrategyResult]: name, locator = item started = time.monotonic() try: diff --git a/je_auto_control/utils/act_in_view/act_in_view.py b/je_auto_control/utils/act_in_view/act_in_view.py index 37665deeb..9697d9473 100644 --- a/je_auto_control/utils/act_in_view/act_in_view.py +++ b/je_auto_control/utils/act_in_view/act_in_view.py @@ -19,7 +19,7 @@ :func:`actionability.act_when_ready`. Imports no ``PySide6``. """ from dataclasses import dataclass -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from je_auto_control.utils.actionability import GateConfig, act_when_ready from je_auto_control.utils.exception.exceptions import AutoControlActionException @@ -66,7 +66,7 @@ def act_in_view(target: str, action: Callable[[List[int]], Any], *, cx, cy = int(found["coords"][0]), int(found["coords"][1]) locate = plan.locator or _default_locator(plan.kind, _DEFAULT_THRESHOLD, _DEFAULT_LANG) - def target_box(): + def target_box() -> Optional[Tuple[int, int, int, int]]: # Located again on every poll: a constant box could never disappear # or move, so the visibility and stability gates checked nothing. coords = locate(target) diff --git a/je_auto_control/utils/action_effect/action_effect.py b/je_auto_control/utils/action_effect/action_effect.py index 3429e4e02..47ff8cfd8 100644 --- a/je_auto_control/utils/action_effect/action_effect.py +++ b/je_auto_control/utils/action_effect/action_effect.py @@ -50,7 +50,7 @@ def _action_point(action: Any) -> Optional[List[int]]: def _changed_elements(before: Sequence[Element], after: Sequence[Element], - iou_threshold: float, move_threshold: int): + iou_threshold: float, move_threshold: int) -> List[Element]: """Return every element that was added / removed / changed between two frames.""" from je_auto_control.utils.element_diff import match_elements from je_auto_control.utils.observation_delta.observation_delta import ( diff --git a/je_auto_control/utils/action_signing/cipher.py b/je_auto_control/utils/action_signing/cipher.py index e7cc2302a..aacc54197 100644 --- a/je_auto_control/utils/action_signing/cipher.py +++ b/je_auto_control/utils/action_signing/cipher.py @@ -14,7 +14,7 @@ import hashlib import os from pathlib import Path -from typing import Optional +from typing import TYPE_CHECKING, Optional, Tuple, Type from je_auto_control.utils.action_signing._key_file import load_or_create_key_file from je_auto_control.utils.exception.exceptions import ( @@ -22,6 +22,9 @@ ) from je_auto_control.utils.logging.logging_instance import autocontrol_logger +if TYPE_CHECKING: + from cryptography.fernet import Fernet, InvalidToken + def _default_key_path() -> Path: """``~/.je_auto_control/action_encryption_key``, resolved at call time.""" @@ -38,7 +41,7 @@ def _default_key_path() -> Path: KeyType = Optional[bytes | str] -def _fernet_types() -> tuple: +def _fernet_types() -> Tuple[Type["Fernet"], Type["InvalidToken"]]: """Return ``(Fernet, InvalidToken)``, or explain why encryption is off. ``cryptography`` publishes no ``win_arm64`` wheel, so on Windows arm64 it diff --git a/je_auto_control/utils/agent_runtime/activity_windows.py b/je_auto_control/utils/agent_runtime/activity_windows.py index d7c693802..126239dc3 100644 --- a/je_auto_control/utils/agent_runtime/activity_windows.py +++ b/je_auto_control/utils/agent_runtime/activity_windows.py @@ -61,7 +61,7 @@ def start(self) -> None: def alive(self) -> bool: return self._thread.is_alive() and not self.error - def stop(self) -> list: + def stop(self) -> list[dict[str, Any]]: super().stop() self._thread.join(timeout=1) if self._thread.is_alive(): diff --git a/je_auto_control/utils/agent_runtime/android_commands.py b/je_auto_control/utils/agent_runtime/android_commands.py index f69559423..d29e2c5c7 100644 --- a/je_auto_control/utils/agent_runtime/android_commands.py +++ b/je_auto_control/utils/agent_runtime/android_commands.py @@ -142,7 +142,8 @@ def compile_android_input_probe(snapshot: AndroidSnapshot) -> str: return script -def _check_evidence(evidence: AndroidInputEvidence, snapshot: AndroidSnapshot, name: str, arguments: dict) -> None: +def _check_evidence(evidence: AndroidInputEvidence, snapshot: AndroidSnapshot, name: str, + arguments: dict[str, Any]) -> None: if not isinstance(evidence, AndroidInputEvidence) or evidence.snapshot != snapshot: raise AgentTaskError("Android input evidence belongs to a different device/boot/window snapshot") if name == "AC_android_tap": diff --git a/je_auto_control/utils/agent_runtime/android_control.py b/je_auto_control/utils/agent_runtime/android_control.py index 247630083..63a4c9587 100644 --- a/je_auto_control/utils/agent_runtime/android_control.py +++ b/je_auto_control/utils/agent_runtime/android_control.py @@ -3,7 +3,7 @@ import re from dataclasses import dataclass, field -from typing import Callable, ContextManager, Protocol +from typing import Any, Callable, ContextManager, Protocol from je_auto_control.utils.agent_runtime.android_action_result import AndroidActionResult from je_auto_control.utils.agent_runtime.android_commands import AndroidActionProposal @@ -28,7 +28,7 @@ class AndroidCommandLease: epoch: str device_fence: Callable[[], ContextManager[None]] = field(repr=False) checkpoint: Callable[[], None] = field(repr=False) - settle: Callable[[AndroidActionResult], dict] = field(repr=False) + settle: Callable[[AndroidActionResult], dict[str, Any]] = field(repr=False) def __post_init__(self) -> None: if not isinstance(self.proposal, AndroidActionProposal) or self.proposal.input_evidence is None: diff --git a/je_auto_control/utils/agent_runtime/android_input_evidence.py b/je_auto_control/utils/agent_runtime/android_input_evidence.py index 1f1f7c91d..0acb5ae9d 100644 --- a/je_auto_control/utils/agent_runtime/android_input_evidence.py +++ b/je_auto_control/utils/agent_runtime/android_input_evidence.py @@ -115,7 +115,7 @@ def _connections(block: str, snapshot: AndroidSnapshot) -> None: _target_connection(rows, snapshot) -def _target_connection(rows: list[re.Match], snapshot: AndroidSnapshot) -> None: +def _target_connection(rows: list[re.Match[str]], snapshot: AndroidSnapshot) -> None: if len({row["fd"] for row in rows}) != len(rows): raise AgentTaskError("Android native channel descriptors are duplicated") if any(row["channel"] != row["window"] for row in rows): diff --git a/je_auto_control/utils/agent_runtime/android_input_windows.py b/je_auto_control/utils/agent_runtime/android_input_windows.py index 1ad92a10c..540ed92d1 100644 --- a/je_auto_control/utils/agent_runtime/android_input_windows.py +++ b/je_auto_control/utils/agent_runtime/android_input_windows.py @@ -90,7 +90,7 @@ def _window(line: str, index: int, snapshot: AndroidSnapshot) -> AndroidInputWin _flags(match["flags"]), target, alpha) -def _target(match: re.Match, owner: tuple[int, int], snapshot: AndroidSnapshot) -> None: +def _target(match: re.Match[str], owner: tuple[int, int], snapshot: AndroidSnapshot) -> None: if match["app"] != snapshot.activity or owner[0] <= 0 or owner[1] // 100000 != snapshot.user: raise AgentTaskError("Android input-window application/owner does not match the reviewed focus") if any(re.fullmatch(r"0x[1-9a-f][0-9a-f]*", match[key]) is None for key in ("app_token", "token")): diff --git a/je_auto_control/utils/agent_runtime/api.py b/je_auto_control/utils/agent_runtime/api.py index 49f8e09fc..10b6d8988 100644 --- a/je_auto_control/utils/agent_runtime/api.py +++ b/je_auto_control/utils/agent_runtime/api.py @@ -175,7 +175,7 @@ def finish_agent_task(task_id: str) -> dict[str, Any]: return _task_call("finish", task_id) -def _task_call(operation: str, task_id: str, extra: dict | None = None) -> dict[str, Any]: +def _task_call(operation: str, task_id: str, extra: dict[str, Any] | None = None) -> dict[str, Any]: client = AgentRuntimeClient() try: return client.call(operation, {"task_id": task_id, **(extra or {})}) diff --git a/je_auto_control/utils/agent_runtime/browser_readonly_scope.py b/je_auto_control/utils/agent_runtime/browser_readonly_scope.py index f6cc20801..499602496 100644 --- a/je_auto_control/utils/agent_runtime/browser_readonly_scope.py +++ b/je_auto_control/utils/agent_runtime/browser_readonly_scope.py @@ -8,7 +8,7 @@ from je_auto_control.utils.agent_runtime.errors import AgentTaskError -def _fixed(value: dict) -> str: +def _fixed(value: dict[str, Any]) -> str: result = dict(value) result.pop("roots") options = dict(result["options"]) diff --git a/je_auto_control/utils/agent_runtime/commands.py b/je_auto_control/utils/agent_runtime/commands.py index 2a4e24af3..71cd72260 100644 --- a/je_auto_control/utils/agent_runtime/commands.py +++ b/je_auto_control/utils/agent_runtime/commands.py @@ -22,7 +22,7 @@ _ID = {"task_id": {"type": "string", "minLength": 1}} # name: (function, JSON properties, required, read_only, host_management) -CATALOG: dict[str, tuple[Any, dict, tuple[str, ...], bool, bool]] = { +CATALOG: dict[str, tuple[Any, dict[str, Any], tuple[str, ...], bool, bool]] = { "AC_agent_transfer": (api.manage_agent_transfer, {"operation": {"type": "string", "enum": list(TRANSFER_OPERATIONS)}, "request": {"type": "object"}}, ("operation",), False, False), diff --git a/je_auto_control/utils/agent_runtime/dag_retention.py b/je_auto_control/utils/agent_runtime/dag_retention.py index 026fca19b..3228d9cf5 100644 --- a/je_auto_control/utils/agent_runtime/dag_retention.py +++ b/je_auto_control/utils/agent_runtime/dag_retention.py @@ -38,7 +38,7 @@ def protects_task(store: Any, task_id: str) -> bool: return row is not None -def prune_batches(runtime: Any, cutoff: float, identity: Any) -> dict: +def prune_batches(runtime: Any, cutoff: float, identity: Any) -> dict[str, Any]: """Collect up to one thousand visible settled batches; unresolved work has no automatic expiry.""" with runtime.store.connection() as connection: rows = connection.execute("SELECT id,owner FROM agent_dag_batches WHERE updated Any: return user -def _window_metadata(hwnd: int) -> dict: +def _window_metadata(hwnd: int) -> dict[str, Any]: user = _dialog_library() owner = user.GetWindow(hwnd, 4) # GW_OWNER; parent/owner is not an input authority grant. name = ctypes.create_unicode_buffer(256) diff --git a/je_auto_control/utils/agent_runtime/errors.py b/je_auto_control/utils/agent_runtime/errors.py index 76ca91d34..3807224b1 100644 --- a/je_auto_control/utils/agent_runtime/errors.py +++ b/je_auto_control/utils/agent_runtime/errors.py @@ -1,4 +1,6 @@ """Typed failures for managed tasks, observations and control ownership.""" +from typing import Any + from je_auto_control.utils.exception.exceptions import AutoControlException @@ -18,4 +20,4 @@ class AgentHumanReview(AgentTaskError): """A dialog or unsaved-content gate requires explicit human review before continuing.""" #: Verification reports the review was raised on, recorded with the waiting_user state. - reports: tuple = () + reports: tuple[dict[str, Any], ...] = () diff --git a/je_auto_control/utils/agent_runtime/file_dialog_scope.py b/je_auto_control/utils/agent_runtime/file_dialog_scope.py index 09f2ad448..a19614f9d 100644 --- a/je_auto_control/utils/agent_runtime/file_dialog_scope.py +++ b/je_auto_control/utils/agent_runtime/file_dialog_scope.py @@ -54,7 +54,7 @@ def type_path(self, path: str) -> None: @contextmanager -def scoped_file_dialog(target: Any, window_id: int, process_id: int, arguments: dict) -> Iterator[None]: +def scoped_file_dialog(target: Any, window_id: int, process_id: int, arguments: dict[str, Any]) -> Iterator[None]: """Keep the public executor call/journal intact while replacing only its trusted driver seam.""" if "driver" in arguments: raise AgentTaskError("managed file dialogs cannot override their host driver") diff --git a/je_auto_control/utils/agent_runtime/file_target.py b/je_auto_control/utils/agent_runtime/file_target.py index 0c7c5ea5c..1ceba8ed9 100644 --- a/je_auto_control/utils/agent_runtime/file_target.py +++ b/je_auto_control/utils/agent_runtime/file_target.py @@ -30,6 +30,6 @@ def perform(self, name: str, arguments: dict[str, Any]) -> Any: def cleanup(self) -> None: """File operations hold no desktop input resources.""" - def validate_input(self, _event: dict) -> None: + def validate_input(self, _event: dict[str, Any]) -> None: """Refuse any unexpected native input, including inside nested commands.""" raise AgentTaskError("file tasks cannot drive native input") diff --git a/je_auto_control/utils/agent_runtime/local_evidence.py b/je_auto_control/utils/agent_runtime/local_evidence.py index 34364fe21..9f4fa2815 100644 --- a/je_auto_control/utils/agent_runtime/local_evidence.py +++ b/je_auto_control/utils/agent_runtime/local_evidence.py @@ -17,7 +17,7 @@ def check() -> None: # Entering the scope is the check: it refuses a revoked or read-only caller. pass - def read(operation: str, body: dict, _timeout: float) -> dict: + def read(operation: str, body: dict[str, Any], _timeout: float) -> dict[str, Any]: check() if operation == "lookup": return runtime.lookup(body["idempotency_key"], body.get("spec")) diff --git a/je_auto_control/utils/agent_runtime/native_control.py b/je_auto_control/utils/agent_runtime/native_control.py index 473e7dc16..bcb8e0d48 100644 --- a/je_auto_control/utils/agent_runtime/native_control.py +++ b/je_auto_control/utils/agent_runtime/native_control.py @@ -53,7 +53,7 @@ def _run(self) -> None: with self._mutex: self._error = type(error).__name__ - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Expose only a coarse error class; a notification never proves successful input cleanup.""" with self._mutex: return {'notice': 'requested' if self._sent else 'not_requested', 'cleanup_error': self._error} diff --git a/je_auto_control/utils/agent_runtime/native_recovery.py b/je_auto_control/utils/agent_runtime/native_recovery.py index 56d55b4bc..600a61d0a 100644 --- a/je_auto_control/utils/agent_runtime/native_recovery.py +++ b/je_auto_control/utils/agent_runtime/native_recovery.py @@ -24,7 +24,7 @@ def no_held_input() -> None: raise AgentTaskError("release held keys and mouse buttons manually before input recovery") -def recover_target(runtime: Any, target: str, note: str) -> dict: +def recover_target(runtime: Any, target: str, note: str) -> dict[str, Any]: """Require host authority and a registered target's explicit recovery implementation.""" owner = current_authorization() if owner is not None and not owner.allows(Capability.MANAGE_HOSTS): diff --git a/je_auto_control/utils/agent_runtime/owned_channel_factory.py b/je_auto_control/utils/agent_runtime/owned_channel_factory.py index 3998552a5..917d56d97 100644 --- a/je_auto_control/utils/agent_runtime/owned_channel_factory.py +++ b/je_auto_control/utils/agent_runtime/owned_channel_factory.py @@ -25,7 +25,7 @@ def retired(self) -> bool: """True only once the helper is proven settled.""" def request(self, operation: str, payload: Any, *, timeout: float, check: Callable[[], None] = ..., - on_event: Callable[[dict], None] | None = None) -> Any: + on_event: Callable[[dict[str, Any]], None] | None = None) -> Any: """Send one operation and return its reply.""" def close(self) -> None: diff --git a/je_auto_control/utils/agent_runtime/presence_messages_linux.py b/je_auto_control/utils/agent_runtime/presence_messages_linux.py index a9132502b..f360bf523 100644 --- a/je_auto_control/utils/agent_runtime/presence_messages_linux.py +++ b/je_auto_control/utils/agent_runtime/presence_messages_linux.py @@ -5,6 +5,7 @@ import os import socket import struct +from typing import Any from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.presence_frames import decode_frame @@ -79,7 +80,7 @@ def _sender(ancillary: list[tuple[int, int, bytes]], abi: _AncillaryABI) -> tupl return descriptor, pid, uid, gid -def _receive(connection: socket.socket, peer: LinuxPeerProcess) -> dict: +def _receive(connection: socket.socket, peer: LinuxPeerProcess) -> dict[str, Any]: """Consume once under the channel's exclusive lease; EAGAIN preserves that lease.""" abi = _ancillary_abi() truncation = getattr(socket, 'MSG_TRUNC') | getattr(socket, 'MSG_CTRUNC') diff --git a/je_auto_control/utils/agent_runtime/presence_session_windows.py b/je_auto_control/utils/agent_runtime/presence_session_windows.py index b233df3ee..9e04aaf37 100644 --- a/je_auto_control/utils/agent_runtime/presence_session_windows.py +++ b/je_auto_control/utils/agent_runtime/presence_session_windows.py @@ -78,6 +78,6 @@ def check(self) -> None: self._state = 'unavailable' raise AgentTaskError('physical-console session support could not be established') from error - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Report only the last coarse classification; passive metadata never authorizes input.""" return {'state': self._state, 'native_evidence': 'not_recorded'} diff --git a/je_auto_control/utils/agent_runtime/transfer_models.py b/je_auto_control/utils/agent_runtime/transfer_models.py index 1b5ee3f45..f93b28029 100644 --- a/je_auto_control/utils/agent_runtime/transfer_models.py +++ b/je_auto_control/utils/agent_runtime/transfer_models.py @@ -182,7 +182,7 @@ def _manifest_files(files: tuple[TransferFile, ...]) -> None: _portable_files(tuple(AssetFile(item.name, item.blob.sha256, item.blob.size) for item in files)) -def _review_envelope(reply: Mapping) -> tuple[Mapping, TransferManifest]: +def _review_envelope(reply: Mapping[str, Any]) -> tuple[Mapping[str, Any], TransferManifest]: """Parse the shared closed review envelope before source or destination identity checks.""" value = _object(reply, {'review', 'digest', 'manifest', 'review_expires', 'approval_required'}) _hex(value['review'], 32) diff --git a/je_auto_control/utils/agent_runtime/transport.py b/je_auto_control/utils/agent_runtime/transport.py index 9f58472f2..f222c2121 100644 --- a/je_auto_control/utils/agent_runtime/transport.py +++ b/je_auto_control/utils/agent_runtime/transport.py @@ -106,7 +106,7 @@ def _local_path(url: str, token: str | None) -> str: raise AgentTaskError("delegation requires an explicit authenticated local service route") from None -def _raise_reply_error(reply: dict) -> NoReturn: +def _raise_reply_error(reply: dict[str, Any]) -> NoReturn: payload = reply.get("json") detail = payload.get("error", "operation failed") if isinstance(payload, dict) else "invalid JSON reply" if isinstance(payload, dict) and payload.get("error_type") == "stale_observation": diff --git a/je_auto_control/utils/agent_runtime/trigger_history.py b/je_auto_control/utils/agent_runtime/trigger_history.py index 7a345dcb2..6e0ea682a 100644 --- a/je_auto_control/utils/agent_runtime/trigger_history.py +++ b/je_auto_control/utils/agent_runtime/trigger_history.py @@ -22,7 +22,7 @@ def require_current(connection: Any, identifier: str) -> None: raise AgentTaskError("trigger has a reviewed replacement; use that registration") -def event_state(connection: Any, identifier: str, event_hash: str) -> tuple[dict | None, int]: +def event_state(connection: Any, identifier: str, event_hash: str) -> tuple[dict[str, Any] | None, int]: """Read deduplication and pending count from the same original or renewed event namespace.""" family = lineage(connection, identifier) if family is None: diff --git a/je_auto_control/utils/agent_runtime/workflow_wait.py b/je_auto_control/utils/agent_runtime/workflow_wait.py index e3a5429f5..02bf70591 100644 --- a/je_auto_control/utils/agent_runtime/workflow_wait.py +++ b/je_auto_control/utils/agent_runtime/workflow_wait.py @@ -9,7 +9,7 @@ from je_auto_control.utils.agent_runtime.workflow_files import task_policy -def workflow_wait(selector: dict, expected: Any, state: bool = False, timeout_seconds: float = 5) -> Any: +def workflow_wait(selector: dict[str, Any], expected: Any, state: bool = False, timeout_seconds: float = 5) -> Any: """Wait for one scoped control's exact value/state without replaying set, invoke or submit.""" from je_auto_control.utils.agent_runtime.workflow_desktop import workflow_control policy = task_policy() diff --git a/je_auto_control/utils/agent_runtime/workspace_scope.py b/je_auto_control/utils/agent_runtime/workspace_scope.py index 754126e71..6af37e114 100644 --- a/je_auto_control/utils/agent_runtime/workspace_scope.py +++ b/je_auto_control/utils/agent_runtime/workspace_scope.py @@ -14,7 +14,7 @@ def bootstrap_allowed(spec: AgentTaskSpec | None) -> bool: return bool(spec is not None and spec.apps and any(action["tool"] == "AC_focus_window" for action in spec.actions)) -def focus_approved(spec: AgentTaskSpec | None, arguments: dict) -> Any: +def focus_approved(spec: AgentTaskSpec | None, arguments: dict[str, Any]) -> Any: """Wait for one approved application window without touching an unrelated foreground app.""" from je_auto_control.utils.agent_runtime.native_scope import check_window_arguments from je_auto_control.utils.tool_use_schema import run_tool_call diff --git a/je_auto_control/utils/approval/approval_test.py b/je_auto_control/utils/approval/approval_test.py index ed05fa92a..d2e63a236 100644 --- a/je_auto_control/utils/approval/approval_test.py +++ b/je_auto_control/utils/approval/approval_test.py @@ -19,7 +19,7 @@ import re from dataclasses import dataclass from pathlib import Path -from typing import Any, List +from typing import Any, List, Tuple DEFAULT_DIR = ".approvals" @@ -57,7 +57,7 @@ def _safe_extension(extension: str) -> str: return ext -def _paths(name: str, approvals_dir: str, extension: str): +def _paths(name: str, approvals_dir: str, extension: str) -> Tuple[Path, Path]: base = Path(approvals_dir) ext = _safe_extension(extension) return (base / f"{_safe_name(name)}.approved.{ext}", diff --git a/je_auto_control/utils/artifact_store/s3_store.py b/je_auto_control/utils/artifact_store/s3_store.py index 7efba3960..1b0871c8a 100644 --- a/je_auto_control/utils/artifact_store/s3_store.py +++ b/je_auto_control/utils/artifact_store/s3_store.py @@ -113,7 +113,7 @@ def url(self, key: str) -> str: return f"s3://{self._bucket}/{self._key(key)}" -_STATE: dict = {"store": None} +_STATE: dict[str, Optional[S3ArtifactStore]] = {"store": None} def set_default_store(store: Optional[S3ArtifactStore]) -> None: diff --git a/je_auto_control/utils/ax_text/ax_text.py b/je_auto_control/utils/ax_text/ax_text.py index d61ccc2b5..aee356341 100644 --- a/je_auto_control/utils/ax_text/ax_text.py +++ b/je_auto_control/utils/ax_text/ax_text.py @@ -17,10 +17,13 @@ platform by injecting a fake backend; the real UIA calls live in the Windows backend. Imports no ``PySide6``. """ -from typing import Any, Dict, Optional +from typing import TYPE_CHECKING, Any, Dict, Optional +if TYPE_CHECKING: + from je_auto_control.utils.accessibility.backends.base import AccessibilityBackend -def _backend(): + +def _backend() -> "AccessibilityBackend": from je_auto_control.utils.accessibility.backends import get_backend return get_backend() diff --git a/je_auto_control/utils/barcode/barcode.py b/je_auto_control/utils/barcode/barcode.py index 593b7eed3..1607492ec 100644 --- a/je_auto_control/utils/barcode/barcode.py +++ b/je_auto_control/utils/barcode/barcode.py @@ -18,7 +18,7 @@ Decoder = Callable[[Any], List[Dict[str, Any]]] -def _default_decoder(image) -> List[Dict[str, Any]]: +def _default_decoder(image: Any) -> List[Dict[str, Any]]: """Decode 1-D barcodes with ``cv2.barcode`` (empty if the module is absent).""" import cv2 if not hasattr(cv2, "barcode"): diff --git a/je_auto_control/utils/bulkhead/bulkhead.py b/je_auto_control/utils/bulkhead/bulkhead.py index 62a9dcb00..07b75be27 100644 --- a/je_auto_control/utils/bulkhead/bulkhead.py +++ b/je_auto_control/utils/bulkhead/bulkhead.py @@ -64,7 +64,7 @@ def __exit__(self, *_exc: Any) -> Literal[False]: self.release() return False - def run(self, func: Callable, *args: Any, **kwargs: Any) -> Any: + def run(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: """Run ``func`` under a permit (raises ``BulkheadFullError`` if full).""" with self: return func(*args, **kwargs) diff --git a/je_auto_control/utils/change_localize/change_localize.py b/je_auto_control/utils/change_localize/change_localize.py index 18cfc62d6..22661bac1 100644 --- a/je_auto_control/utils/change_localize/change_localize.py +++ b/je_auto_control/utils/change_localize/change_localize.py @@ -16,10 +16,10 @@ the loaders reuse :mod:`visual_match`. The ranking is pure and fully testable. Imports no ``PySide6``. """ -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Tuple -def _unpack(item: Any) -> tuple: +def _unpack(item: Any) -> Tuple[Any, Any]: """Return ``(box, score)`` from a ``{box, score}`` dict or a ``(box, score)``.""" if isinstance(item, dict): return item["box"], item["score"] diff --git a/je_auto_control/utils/clipboard_formats/clipboard_formats.py b/je_auto_control/utils/clipboard_formats/clipboard_formats.py index 35d08bac2..b68bc5643 100644 --- a/je_auto_control/utils/clipboard_formats/clipboard_formats.py +++ b/je_auto_control/utils/clipboard_formats/clipboard_formats.py @@ -107,7 +107,7 @@ def keyed(formats: Sequence[_Format]) -> Dict[Tuple[int, str], Dict[str, Any]]: # --- Win32 live enumeration ------------------------------------------------ -def _format_name(user32, format_id: int) -> str: +def _format_name(user32: Any, format_id: int) -> str: import ctypes buffer = ctypes.create_unicode_buffer(256) if user32.GetClipboardFormatNameW(format_id, buffer, 256): diff --git a/je_auto_control/utils/compliance/compliance_report.py b/je_auto_control/utils/compliance/compliance_report.py index b3058a771..37eea1ace 100644 --- a/je_auto_control/utils/compliance/compliance_report.py +++ b/je_auto_control/utils/compliance/compliance_report.py @@ -16,7 +16,7 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, List, Mapping, Optional, Sequence +from typing import Any, Dict, List, Mapping, Optional, Sequence, Set STATUS_SATISFIED = "satisfied" STATUS_GAP = "gap" @@ -71,7 +71,7 @@ def _framework_key(name: str) -> str: return "".join(ch for ch in str(name).upper() if ch.isalnum()) -def _wanted_frameworks(frameworks: Optional[Sequence[str]]) -> Optional[set]: +def _wanted_frameworks(frameworks: Optional[Sequence[str]]) -> Optional[Set[str]]: """The requested framework keys, or ``None`` for all; unknown names are a ``ValueError``.""" if isinstance(frameworks, str): # "SOC2" was walked letter by letter: unknown frameworks 2, C, O, S. diff --git a/je_auto_control/utils/config_bundle/__main__.py b/je_auto_control/utils/config_bundle/__main__.py index 498e22eea..c0347fc52 100644 --- a/je_auto_control/utils/config_bundle/__main__.py +++ b/je_auto_control/utils/config_bundle/__main__.py @@ -40,7 +40,7 @@ def _build_arg_parser() -> argparse.ArgumentParser: return parser -def main(argv: Optional[list] = None) -> int: +def main(argv: Optional[list[str]] = None) -> int: args = _build_arg_parser().parse_args(argv) try: if args.action == "export": diff --git a/je_auto_control/utils/config_bundle/config_bundle.py b/je_auto_control/utils/config_bundle/config_bundle.py index 7ff012410..7db18f544 100644 --- a/je_auto_control/utils/config_bundle/config_bundle.py +++ b/je_auto_control/utils/config_bundle/config_bundle.py @@ -37,7 +37,7 @@ from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.json_store.json_store import atomic_write_text @@ -175,7 +175,7 @@ def apply(self, bundle: Any, *, dry_run: bool = False) -> ImportReport: ) return report - def _validate(self, bundle: Any) -> tuple: + def _validate(self, bundle: Any) -> Tuple[Dict[str, Any], Dict[str, Any]]: if not isinstance(bundle, dict): raise ConfigBundleError("bundle must be a JSON object") manifest = bundle.get("manifest") diff --git a/je_auto_control/utils/contrast_map/contrast_map.py b/je_auto_control/utils/contrast_map/contrast_map.py index 441b67092..a0725aeb3 100644 --- a/je_auto_control/utils/contrast_map/contrast_map.py +++ b/je_auto_control/utils/contrast_map/contrast_map.py @@ -17,7 +17,7 @@ The grading and split are pure and reuse :func:`a11y_audit.contrast_ratio`, so they are fully testable without a screen. Imports no ``PySide6``. """ -from typing import Any, Callable, Dict, List, Optional, Sequence +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.a11y_audit import contrast_ratio from je_auto_control.utils.a11y_audit.audit import relative_luminance @@ -60,7 +60,8 @@ def _mean_color(pixels: Sequence[Sequence[int]]) -> RGB: return [totals[0] // count, totals[1] // count, totals[2] // count] -def _partition_by_luminance(rgbs: Sequence[Sequence[int]]) -> tuple: +def _partition_by_luminance(rgbs: Sequence[Sequence[int]] + ) -> Tuple[List[Sequence[int]], List[Sequence[int]]]: """Split RGB pixels into (darker, lighter) groups at the mean luminance.""" lums = [relative_luminance(rgb) for rgb in rgbs] average = sum(lums) / len(lums) diff --git a/je_auto_control/utils/control_patterns/control_patterns.py b/je_auto_control/utils/control_patterns/control_patterns.py index 83e9f2e3a..d8d6f37dd 100644 --- a/je_auto_control/utils/control_patterns/control_patterns.py +++ b/je_auto_control/utils/control_patterns/control_patterns.py @@ -12,10 +12,13 @@ unit-testable on any platform by injecting a fake backend; the real UIA calls live in the Windows backend. Imports no ``PySide6``. """ -from typing import Any, Dict, Optional +from typing import TYPE_CHECKING, Any, Dict, Optional +if TYPE_CHECKING: + from je_auto_control.utils.accessibility.backends.base import AccessibilityBackend -def _backend(): + +def _backend() -> "AccessibilityBackend": from je_auto_control.utils.accessibility.backends import get_backend return get_backend() diff --git a/je_auto_control/utils/cost_telemetry/pricing.py b/je_auto_control/utils/cost_telemetry/pricing.py index d2ae96f48..52b7da376 100644 --- a/je_auto_control/utils/cost_telemetry/pricing.py +++ b/je_auto_control/utils/cost_telemetry/pricing.py @@ -96,7 +96,7 @@ def estimate_usd(model: str, input_tokens: int, output_tokens: int, return round(cost, 6) -def known_models() -> list: +def known_models() -> list[str]: """Sorted list of every model the default pricing table covers.""" return sorted(_DEFAULT_PRICING) diff --git a/je_auto_control/utils/cua_action/cua_action.py b/je_auto_control/utils/cua_action/cua_action.py index 58f933508..3011eff3c 100644 --- a/je_auto_control/utils/cua_action/cua_action.py +++ b/je_auto_control/utils/cua_action/cua_action.py @@ -86,7 +86,7 @@ def canonical_action(action_type: str, **fields: Any) -> Dict[str, Any]: return result -def _xy(coordinate) -> Dict[str, int]: +def _xy(coordinate: Any) -> Dict[str, int]: if not coordinate: return {} return {"x": int(coordinate[0]), "y": int(coordinate[1])} diff --git a/je_auto_control/utils/cv2_utils/blobs.py b/je_auto_control/utils/cv2_utils/blobs.py index 770f96695..2895c532a 100644 --- a/je_auto_control/utils/cv2_utils/blobs.py +++ b/je_auto_control/utils/cv2_utils/blobs.py @@ -8,7 +8,7 @@ from typing import Any, Dict, List, Tuple -def connected_boxes(mask, min_area: int = 1, *, +def connected_boxes(mask: Any, min_area: int = 1, *, origin: Tuple[int, int] = (0, 0)) -> List[Dict[str, Any]]: """Return ``{x, y, width, height, area, center}`` per blob, largest first. diff --git a/je_auto_control/utils/data_quality/data_quality.py b/je_auto_control/utils/data_quality/data_quality.py index d88d10dcd..04ecb4e34 100644 --- a/je_auto_control/utils/data_quality/data_quality.py +++ b/je_auto_control/utils/data_quality/data_quality.py @@ -97,7 +97,7 @@ def _is_allowed(value: Any, allowed: Any) -> bool: def _validate_row(index: int, row: Dict[str, Any], schema: Dict[str, Any], - seen_unique: Dict[str, set]) -> List[Dict[str, Any]]: + seen_unique: Dict[str, Set[Any]]) -> List[Dict[str, Any]]: errors: List[Dict[str, Any]] = [] for field, rule in schema.items(): if field not in row or row[field] in (None, ""): diff --git a/je_auto_control/utils/deterministic/deterministic.py b/je_auto_control/utils/deterministic/deterministic.py index 6187d1233..134e2c8f2 100644 --- a/je_auto_control/utils/deterministic/deterministic.py +++ b/je_auto_control/utils/deterministic/deterministic.py @@ -21,7 +21,7 @@ Imports no ``PySide6``. """ import random -from typing import Any, Dict, Literal, Optional +from typing import Any, Dict, List, Literal, Optional from unittest import mock _UNSET = object() @@ -60,7 +60,7 @@ def __init__(self, seed: int = 0, else float(freeze_time)) self._rng_state: Any = _UNSET self._numpy_state: Any = None - self._patches: list = [] + self._patches: List[Any] = [] @property def seed(self) -> int: diff --git a/je_auto_control/utils/diagnostics/__main__.py b/je_auto_control/utils/diagnostics/__main__.py index 73ad802b6..98879d2a9 100644 --- a/je_auto_control/utils/diagnostics/__main__.py +++ b/je_auto_control/utils/diagnostics/__main__.py @@ -18,7 +18,7 @@ } -def main(_argv: Optional[list] = None) -> int: +def main(_argv: Optional[list[str]] = None) -> int: report = run_diagnostics() for check in report.checks: tag = _SEVERITY_TAG.get(check.severity, "? ") diff --git a/je_auto_control/utils/edge_lines/edge_lines.py b/je_auto_control/utils/edge_lines/edge_lines.py index 1f294c52c..38ae48c1b 100644 --- a/je_auto_control/utils/edge_lines/edge_lines.py +++ b/je_auto_control/utils/edge_lines/edge_lines.py @@ -37,7 +37,7 @@ def _orientation(angle: float) -> str: return "diagonal" -def _segments(gray, min_length: int, max_gap: int): +def _segments(gray: Any, min_length: int, max_gap: int) -> Any: import cv2 import numpy as np # Canny takes 8-bit only: a 16-bit or float image raised cv2.error. diff --git a/je_auto_control/utils/executor/dispatch.py b/je_auto_control/utils/executor/dispatch.py index 745188ad9..e1188ceb5 100644 --- a/je_auto_control/utils/executor/dispatch.py +++ b/je_auto_control/utils/executor/dispatch.py @@ -69,7 +69,7 @@ def execute_one(executor: Executor, name: str, arguments: Optional[Mapping[str, _RUNNING.value, _STRICT_BODIES.value = previous, strict -def _prepare(executor: Executor, name: str, arguments: Optional[Mapping[str, Any]]) -> list: +def _prepare(executor: Executor, name: str, arguments: Optional[Mapping[str, Any]]) -> list[Any]: from je_auto_control.utils.executor.action_schema import validate_actions if not isinstance(name, str) or name not in executor.known_commands(): diff --git a/je_auto_control/utils/executor/flow_data_commands.py b/je_auto_control/utils/executor/flow_data_commands.py index 0ec8452ad..0372bea86 100644 --- a/je_auto_control/utils/executor/flow_data_commands.py +++ b/je_auto_control/utils/executor/flow_data_commands.py @@ -10,11 +10,14 @@ flow-control commands, which is the only table the executor reads. """ import json -from typing import Any, Callable, Dict, Mapping +from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping from je_auto_control.utils.exception.exceptions import AutoControlActionException from je_auto_control.utils.executor.flags import as_bool +if TYPE_CHECKING: + import datetime + def exec_shell_to_var(executor: Any, args: Mapping[str, Any]) -> Dict[str, Any]: """Run a shell command and store its stdout in a flow variable. @@ -59,7 +62,7 @@ def exec_shell_to_var(executor: Any, args: Mapping[str, Any]) -> Dict[str, Any]: "returncode": completed.returncode} -def _now(): +def _now() -> "datetime.datetime": import datetime as _dt return _dt.datetime.now() diff --git a/je_auto_control/utils/executor/mouse_aliases.py b/je_auto_control/utils/executor/mouse_aliases.py index a37515504..e52bb1623 100644 --- a/je_auto_control/utils/executor/mouse_aliases.py +++ b/je_auto_control/utils/executor/mouse_aliases.py @@ -5,7 +5,7 @@ not threaded through ``mouse_keycode``. Generating the three callables from one factory keeps the registration sites identical across executors. """ -from typing import Callable, Optional, Tuple +from typing import Callable, Dict, Optional, Tuple from je_auto_control.wrapper.auto_control_mouse import click_mouse @@ -27,7 +27,7 @@ def click(x: Optional[int] = None, click_mouse_right: ClickFn = _make_button_click("mouse_right") click_mouse_middle: ClickFn = _make_button_click("mouse_middle") -MOUSE_BUTTON_COMMANDS: dict = { +MOUSE_BUTTON_COMMANDS: Dict[str, ClickFn] = { "AC_mouse_left": click_mouse_left, "AC_mouse_right": click_mouse_right, "AC_mouse_middle": click_mouse_middle, diff --git a/je_auto_control/utils/failure_bundle/bundle.py b/je_auto_control/utils/failure_bundle/bundle.py index fa92cf90e..8ddd71892 100644 --- a/je_auto_control/utils/failure_bundle/bundle.py +++ b/je_auto_control/utils/failure_bundle/bundle.py @@ -17,7 +17,7 @@ from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path -from typing import Any, Iterable, Mapping +from typing import Any, Iterable, Iterator, Mapping from je_auto_control.utils.config_redaction import ( redact_config, @@ -200,7 +200,7 @@ def failure_bundle_on_error( context: Mapping[str, Any] | None = None, events: Iterable[Mapping[str, Any]] = (), options: FailureBundleOptions | None = None, -): +) -> Iterator[None]: """Create a bundle when the wrapped block raises, then re-raise it. The block's own exception is always the one that propagates: a bundle diff --git a/je_auto_control/utils/failure_hooks/backends.py b/je_auto_control/utils/failure_hooks/backends.py index e8c042a18..4dd46746d 100644 --- a/je_auto_control/utils/failure_hooks/backends.py +++ b/je_auto_control/utils/failure_hooks/backends.py @@ -8,7 +8,7 @@ import base64 from dataclasses import dataclass -from typing import Any, Dict, Optional, Protocol +from typing import Any, Callable, Dict, Optional, Protocol from je_auto_control.utils.failure_hooks.report import ( FailureReport, TicketResult, @@ -121,7 +121,9 @@ def _post_json(backend_name: str, url: str, body: Dict[str, Any], *, id_key: Optional[str] = None, url_key: Optional[str] = None, url_template: Optional[str] = None, - response_extractor=None) -> TicketResult: + response_extractor: Optional[ + Callable[[str, Dict[str, Any]], TicketResult]] = None, + ) -> TicketResult: """Shared HTTP POST helper used by every backend.""" if not url.startswith(_ALLOWED_SCHEMES): return TicketResult( diff --git a/je_auto_control/utils/fuzzy/fuzzy_match.py b/je_auto_control/utils/fuzzy/fuzzy_match.py index b76dc7269..2b3ace302 100644 --- a/je_auto_control/utils/fuzzy/fuzzy_match.py +++ b/je_auto_control/utils/fuzzy/fuzzy_match.py @@ -34,7 +34,7 @@ def _lcs_length(left: str, right: str) -> int: """Length of the longest common subsequence (bit-parallel, Allison-Dix).""" if len(left) < len(right): left, right = right, left - masks: dict = {} + masks: dict[str, int] = {} for position, char in enumerate(right): masks[char] = masks.get(char, 0) | (1 << position) full = (1 << len(right)) - 1 diff --git a/je_auto_control/utils/icon_classify/icon_classify.py b/je_auto_control/utils/icon_classify/icon_classify.py index f51d8ee0d..59b6dab0b 100644 --- a/je_auto_control/utils/icon_classify/icon_classify.py +++ b/je_auto_control/utils/icon_classify/icon_classify.py @@ -92,7 +92,7 @@ def _shape(binary: Any) -> Tuple[float, int]: return min(1.0, 4.0 * math.pi * area / (perimeter * perimeter)), vertices -def _foreground(binary): +def _foreground(binary: Any) -> Any: """The widget's pixels: the Otsu ink, flipped when it is the background. ``THRESH_BINARY_INV`` takes dark ink on a light background, so on a dark diff --git a/je_auto_control/utils/image_dedup/perceptual_hash.py b/je_auto_control/utils/image_dedup/perceptual_hash.py index db9624f52..2fce34343 100644 --- a/je_auto_control/utils/image_dedup/perceptual_hash.py +++ b/je_auto_control/utils/image_dedup/perceptual_hash.py @@ -10,10 +10,10 @@ injectable, so clustering is unit-testable without any image. Imports no ``PySide6``. """ -from typing import Any, Callable, List, Optional, Sequence +from typing import Any, Callable, List, Optional, Sequence, Tuple -def _gray_resized(image: Any, size: tuple) -> Any: +def _gray_resized(image: Any, size: Tuple[int, int]) -> Any: """``image`` (PIL, RGB ndarray or path) as a resized grayscale PIL image. An ndarray was passed to ``Image.open`` and failed with a bare diff --git a/je_auto_control/utils/image_quality/image_quality.py b/je_auto_control/utils/image_quality/image_quality.py index b5b0113f2..fbbd15ed1 100644 --- a/je_auto_control/utils/image_quality/image_quality.py +++ b/je_auto_control/utils/image_quality/image_quality.py @@ -23,7 +23,7 @@ ImageSource = Any -def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]): +def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: """An 8-bit gray frame: a uint16 mid-gray read as brightness 32028 and ``too_bright``.""" from je_auto_control.utils.preprocess.preprocess import _as_uint8, _eight_bit from je_auto_control.utils.visual_match.visual_match import _haystack_gray diff --git a/je_auto_control/utils/img_histogram/img_histogram.py b/je_auto_control/utils/img_histogram/img_histogram.py index 713c74627..9317cb49a 100644 --- a/je_auto_control/utils/img_histogram/img_histogram.py +++ b/je_auto_control/utils/img_histogram/img_histogram.py @@ -11,7 +11,7 @@ headless-testable on synthetic arrays. ``cv2.calcHist`` / ``cv2.compareHist`` are base OpenCV; OpenCV + NumPy come in via ``je_open_cv``. Imports no ``PySide6``. """ -from typing import Any, List, Optional, Sequence +from typing import Any, List, Optional, Sequence, Tuple # Reuse the RGB loader / screen grab (single source of truth, no copy). from je_auto_control.utils.color_region.color_region import _grab_rgb, _to_rgb @@ -20,7 +20,7 @@ _SIMILARITY_METHODS = ("correlation", "intersection") -def _convert(rgb, space: str): +def _convert(rgb: Any, space: str) -> Tuple[Any, List[List[int]]]: import cv2 if space == "hsv": return (cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV), diff --git a/je_auto_control/utils/json/json_file.py b/je_auto_control/utils/json/json_file.py index bbad7b45b..d3cf1789c 100644 --- a/je_auto_control/utils/json/json_file.py +++ b/je_auto_control/utils/json/json_file.py @@ -2,7 +2,7 @@ import os from pathlib import Path from threading import Lock -from typing import Dict, List +from typing import Any, Dict, List from je_auto_control.utils.exception.exception_tags import cant_find_json_error_message, cant_save_json_error_message from je_auto_control.utils.exception.exceptions import AutoControlJsonActionException @@ -55,7 +55,7 @@ def read_executable_action_json(json_file_path: str) -> List[List[Dict[str, Dict raise AutoControlJsonActionException(f"{cant_find_json_error_message}: {repr(error)}") from error -def write_action_json(json_save_path: str, action_json: list | dict) -> None: +def write_action_json(json_save_path: str, action_json: List[Any] | Dict[str, Any]) -> None: """ Write action JSON file. 寫入動作 JSON 檔案 diff --git a/je_auto_control/utils/jwt/jwt_codec.py b/je_auto_control/utils/jwt/jwt_codec.py index add5e28ed..93d7ad568 100644 --- a/je_auto_control/utils/jwt/jwt_codec.py +++ b/je_auto_control/utils/jwt/jwt_codec.py @@ -25,7 +25,7 @@ import re import time from dataclasses import dataclass -from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Union +from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union from je_auto_control.utils.exception.exceptions import AutoControlException @@ -153,7 +153,7 @@ def _json_object(segment: str, what: str) -> Dict[str, Any]: return value -def _split_token(token: str) -> tuple: +def _split_token(token: str) -> Tuple[str, str, str]: if not isinstance(token, str): raise JwtError("token must be a string") parts = token.split(".") diff --git a/je_auto_control/utils/llm/backends/__init__.py b/je_auto_control/utils/llm/backends/__init__.py index f0420433a..4627a0d9a 100644 --- a/je_auto_control/utils/llm/backends/__init__.py +++ b/je_auto_control/utils/llm/backends/__init__.py @@ -7,7 +7,7 @@ through :class:`LLMNotAvailableError` rather than ``ImportError``. """ import os -from typing import Optional +from typing import Optional, Tuple from je_auto_control.utils.llm.backends.base import ( LLMBackend, LLMNotAvailableError, @@ -44,7 +44,7 @@ def _build_backend() -> LLMBackend: ) -def _preference_order(preferred: str): +def _preference_order(preferred: str) -> Tuple[str, ...]: if preferred == "anthropic": return ("anthropic",) if os.environ.get("ANTHROPIC_API_KEY"): diff --git a/je_auto_control/utils/llm/backends/anthropic_backend.py b/je_auto_control/utils/llm/backends/anthropic_backend.py index 45d03a840..f2fd84cd5 100644 --- a/je_auto_control/utils/llm/backends/anthropic_backend.py +++ b/je_auto_control/utils/llm/backends/anthropic_backend.py @@ -67,7 +67,7 @@ def complete(self, prompt: str, return _join_text_blocks(response) -def _join_text_blocks(response) -> str: +def _join_text_blocks(response: object) -> str: """Concatenate every text block in an Anthropic response.""" parts = [] for block in getattr(response, "content", []) or []: diff --git a/je_auto_control/utils/locator_chain/locator_chain.py b/je_auto_control/utils/locator_chain/locator_chain.py index 2459678f8..de4d67f3c 100644 --- a/je_auto_control/utils/locator_chain/locator_chain.py +++ b/je_auto_control/utils/locator_chain/locator_chain.py @@ -11,7 +11,7 @@ Pure-stdlib, imports no ``PySide6``. """ import math -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple Box = Dict[str, Any] @@ -28,10 +28,10 @@ def _area(box: Box) -> int: class Candidates: """An immutable, chainable set of element boxes.""" - def __init__(self, boxes: Sequence[Box]): + def __init__(self, boxes: Sequence[Box]) -> None: self._boxes: List[Box] = [dict(box) for box in boxes] - def __iter__(self): + def __iter__(self) -> Iterator[Box]: return iter(self._boxes) def __len__(self) -> int: diff --git a/je_auto_control/utils/mcp_server/__main__.py b/je_auto_control/utils/mcp_server/__main__.py index 570b20aa7..f48342785 100644 --- a/je_auto_control/utils/mcp_server/__main__.py +++ b/je_auto_control/utils/mcp_server/__main__.py @@ -64,7 +64,7 @@ def _build_parser() -> argparse.ArgumentParser: return parser -def main(argv: Optional[list] = None) -> None: +def main(argv: Optional[list[str]] = None) -> None: """CLI entry point. Performs the requested action and returns ``None``.""" parser = _build_parser() args = parser.parse_args(argv) diff --git a/je_auto_control/utils/mcp_server/_disclosure_server.py b/je_auto_control/utils/mcp_server/_disclosure_server.py index f068d5aad..e2971e31c 100644 --- a/je_auto_control/utils/mcp_server/_disclosure_server.py +++ b/je_auto_control/utils/mcp_server/_disclosure_server.py @@ -93,7 +93,7 @@ def _session_tool_view(self, *, stateless: bool | None = None) -> ToolView: self._disclosure_views[connection] = self._new_tool_view(False) return self._disclosure_views[connection] - def _tool_worker_for_request(self, callback: Callable[[], None], params: dict) -> Callable[[], None]: + def _tool_worker_for_request(self, callback: Callable[[], None], params: dict[str, Any]) -> Callable[[], None]: meta = params.get("_meta") stateless = isinstance(meta, dict) and "io.modelcontextprotocol/protocolVersion" in meta return self._capture_tool_worker(callback, view=self._session_tool_view(stateless=stateless)) diff --git a/je_auto_control/utils/mcp_server/_protocol.py b/je_auto_control/utils/mcp_server/_protocol.py index b40be0fe0..d529693b8 100644 --- a/je_auto_control/utils/mcp_server/_protocol.py +++ b/je_auto_control/utils/mcp_server/_protocol.py @@ -181,7 +181,7 @@ def _is_hashable(value: Any) -> bool: return True -def _coerce_params(raw: Any, msg_id: Any) -> tuple: +def _coerce_params(raw: Any, msg_id: Any) -> Tuple[Dict[str, Any], Optional[str]]: """Normalise JSON-RPC ``params`` to a dict. Returns ``(params, error_line)``. Every handler here expects an object; diff --git a/je_auto_control/utils/mcp_server/_subscriptions.py b/je_auto_control/utils/mcp_server/_subscriptions.py index c804478c0..c03b7f926 100644 --- a/je_auto_control/utils/mcp_server/_subscriptions.py +++ b/je_auto_control/utils/mcp_server/_subscriptions.py @@ -142,7 +142,7 @@ def _notify_tools_list_changed(self, connection_id: Any = _ALL_TOOL_CONNECTIONS) "MCP failed to send tools/list_changed", ) - def _tool_change_listeners(self, connection_id: Any) -> list: + def _tool_change_listeners(self, connection_id: Any) -> List[Tuple[Any, Listener]]: with self._listeners_lock: return [(key, listener) for key, listener in self._listeners.items() if listener.tools_list_changed diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_screen.py b/je_auto_control/utils/mcp_server/tools/_handlers_screen.py index 2ef730516..2383dab61 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_screen.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_screen.py @@ -8,11 +8,14 @@ import io import math import os -from typing import Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional from je_auto_control.utils.mcp_server.tools._base import MCPContent from je_auto_control.utils.timeouts import clamp_poll_interval, deadline_after +if TYPE_CHECKING: + from PIL import Image + # === Screen / image / OCR =================================================== @@ -74,7 +77,7 @@ def list_monitors() -> List[Dict[str, Any]]: ] -def _grab_monitor(index: int): +def _grab_monitor(index: int) -> "Image.Image": """Capture a single monitor through the platform grabber; returns a PIL Image.""" from je_auto_control.utils.cv2_utils.screen_grabber import mss_grabber from PIL import Image diff --git a/je_auto_control/utils/mcp_server/tools/_validation.py b/je_auto_control/utils/mcp_server/tools/_validation.py index ab2dbd315..8486552d9 100644 --- a/je_auto_control/utils/mcp_server/tools/_validation.py +++ b/je_auto_control/utils/mcp_server/tools/_validation.py @@ -93,7 +93,7 @@ def _validate_object(schema: Dict[str, Any], value: Dict[str, Any], return None -def _validate_array(schema: Dict[str, Any], value: list, +def _validate_array(schema: Dict[str, Any], value: List[Any], path: str) -> Optional[str]: item_schema = schema.get("items") if not isinstance(item_schema, dict): diff --git a/je_auto_control/utils/monitor_layout/logical_frame.py b/je_auto_control/utils/monitor_layout/logical_frame.py index b93c57245..c52066a0b 100644 --- a/je_auto_control/utils/monitor_layout/logical_frame.py +++ b/je_auto_control/utils/monitor_layout/logical_frame.py @@ -124,7 +124,7 @@ def _load_image_grab() -> Any: return image_grabber() -def _resample(): +def _resample() -> int: """Pillow's high-quality downscale filter, across Pillow versions.""" from PIL import Image return getattr(getattr(Image, "Resampling", Image), "LANCZOS") diff --git a/je_auto_control/utils/motion_regions/motion_regions.py b/je_auto_control/utils/motion_regions/motion_regions.py index 07c73cb09..6d6f016bd 100644 --- a/je_auto_control/utils/motion_regions/motion_regions.py +++ b/je_auto_control/utils/motion_regions/motion_regions.py @@ -19,7 +19,7 @@ ImageSource = Any -def _diff_mask(before: ImageSource, after: ImageSource, threshold: int, blur: int): +def _diff_mask(before: ImageSource, after: ImageSource, threshold: int, blur: int) -> Any: """Return the binary motion mask between two frames (same size required).""" import cv2 from je_auto_control.utils.preprocess.preprocess import _as_uint8, _eight_bit diff --git a/je_auto_control/utils/observability/exporter.py b/je_auto_control/utils/observability/exporter.py index ed5a67767..b88856b79 100644 --- a/je_auto_control/utils/observability/exporter.py +++ b/je_auto_control/utils/observability/exporter.py @@ -3,7 +3,7 @@ import http.server import threading -from typing import Optional +from typing import Any, Optional from je_auto_control.utils.http_headers import LocalThreadingHTTPServer from je_auto_control.utils.observability.metrics import ( @@ -41,7 +41,7 @@ def do_GET(self) -> None: # noqa: N802 BaseHTTPRequestHandler protocol # Silence the default access log to keep the operator's stderr clean — # the scrape happens every 15 s and would otherwise drown real logs. - def log_message(self, format: str, *args) -> None: # noqa: A002, D401 # pylint: disable=W0622 # reason: signature dictated by BaseHTTPRequestHandler + def log_message(self, format: str, *args: Any) -> None: # noqa: A002, D401 # pylint: disable=W0622 # reason: signature dictated by BaseHTTPRequestHandler return diff --git a/je_auto_control/utils/ocr/backends/__init__.py b/je_auto_control/utils/ocr/backends/__init__.py index b836b7e6e..753c0e756 100644 --- a/je_auto_control/utils/ocr/backends/__init__.py +++ b/je_auto_control/utils/ocr/backends/__init__.py @@ -8,7 +8,7 @@ OCRBackend, OCRBackendNotAvailableError, ) -_cached: dict = {} +_cached: dict[str, OCRBackend] = {} def get_backend(name: Optional[str] = None) -> OCRBackend: diff --git a/je_auto_control/utils/ocr/backends/base.py b/je_auto_control/utils/ocr/backends/base.py index 598d6eb87..3b45d0de4 100644 --- a/je_auto_control/utils/ocr/backends/base.py +++ b/je_auto_control/utils/ocr/backends/base.py @@ -13,6 +13,8 @@ from je_auto_control.utils.exception.exceptions import AutoControlException if TYPE_CHECKING: # pragma: no cover + from PIL import Image + from je_auto_control.utils.ocr.ocr_engine import TextMatch @@ -31,7 +33,7 @@ def available(self) -> bool: """True if the backend's dependencies are importable.""" def image_to_matches(self, - image, + image: "Image.Image", lang: str, min_confidence: float) -> "List[TextMatch]": """Extract text from ``image`` (PIL.Image) at confidence ≥ threshold. diff --git a/je_auto_control/utils/pdf/pdf_reader.py b/je_auto_control/utils/pdf/pdf_reader.py index 42c2e0e61..49835c4a8 100644 --- a/je_auto_control/utils/pdf/pdf_reader.py +++ b/je_auto_control/utils/pdf/pdf_reader.py @@ -8,12 +8,15 @@ """ import functools import os -from typing import Any, Callable, Dict, Iterable, List, Optional, TypeVar, Union +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, TypeVar, Union from je_auto_control.utils.exception.exceptions import ( AutoControlActionException, AutoControlAssertionException, ) +if TYPE_CHECKING: + from pypdf import PdfReader + PageSelector = Optional[Union[int, Iterable[int]]] _Result = TypeVar("_Result") @@ -41,7 +44,7 @@ def wrapper(*args: Any, **kwargs: Any) -> _Result: return wrapper -def _open_pdf(path: str): +def _open_pdf(path: str) -> "PdfReader": """Return a ``pypdf.PdfReader`` for an existing PDF; raise if unavailable.""" try: from pypdf import PdfReader diff --git a/je_auto_control/utils/profiler/resource_profiler.py b/je_auto_control/utils/profiler/resource_profiler.py index 317e32345..51ec8618a 100644 --- a/je_auto_control/utils/profiler/resource_profiler.py +++ b/je_auto_control/utils/profiler/resource_profiler.py @@ -24,6 +24,7 @@ import time from contextlib import contextmanager from dataclasses import dataclass, field +from types import ModuleType from typing import Any, Dict, Iterator, List, Optional, Tuple @@ -61,7 +62,7 @@ def to_dict(self) -> Dict[str, Any]: } -def _try_psutil(): +def _try_psutil() -> Optional[ModuleType]: try: import psutil # noqa: F401 return psutil diff --git a/je_auto_control/utils/qr/qr.py b/je_auto_control/utils/qr/qr.py index dae56f041..dead9f973 100644 --- a/je_auto_control/utils/qr/qr.py +++ b/je_auto_control/utils/qr/qr.py @@ -19,7 +19,7 @@ QRDecoder = Callable[[Any], List[str]] -def _load_np(source: ImageSource, region: Optional[Sequence[int]]): +def _load_np(source: ImageSource, region: Optional[Sequence[int]]) -> Any: import numpy as np from PIL import Image if isinstance(source, Image.Image): diff --git a/je_auto_control/utils/recurrence/recurrence.py b/je_auto_control/utils/recurrence/recurrence.py index d5e43e377..4b185212e 100644 --- a/je_auto_control/utils/recurrence/recurrence.py +++ b/je_auto_control/utils/recurrence/recurrence.py @@ -17,7 +17,7 @@ import datetime as _dt from calendar import monthrange from dataclasses import dataclass -from typing import Dict, Iterator, List, Optional, Tuple +from typing import Dict, Iterator, List, Optional, Set, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException @@ -241,7 +241,7 @@ def _monthly_dates(year: int, month: int, dtstart: _dt.datetime, return _setpos(sorted(set(chosen)), rule.by_set_pos) -def _weekday_set(dtstart: _dt.datetime, rule: Recurrence) -> set: +def _weekday_set(dtstart: _dt.datetime, rule: Recurrence) -> Set[int]: if rule.by_day: return {weekday for _, weekday in rule.by_day} return {dtstart.weekday()} diff --git a/je_auto_control/utils/redaction/policies.py b/je_auto_control/utils/redaction/policies.py index b3f1d7711..c6575ea60 100644 --- a/je_auto_control/utils/redaction/policies.py +++ b/je_auto_control/utils/redaction/policies.py @@ -19,7 +19,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Optional, Sequence, Tuple +from typing import Any, Dict, Optional, Sequence, Tuple # Detector tag constants (avoid magic strings in the engine + tests). @@ -61,7 +61,7 @@ def with_extra_regions( overlay_color=self.overlay_color, ) - def to_dict(self) -> dict: + def to_dict(self) -> Dict[str, Any]: """JSON-safe snapshot for transport over the REST / MCP wire.""" return { "detectors": list(self.detectors), diff --git a/je_auto_control/utils/redaction/rules.py b/je_auto_control/utils/redaction/rules.py index 932a6bb82..3c056966b 100644 --- a/je_auto_control/utils/redaction/rules.py +++ b/je_auto_control/utils/redaction/rules.py @@ -48,7 +48,7 @@ ) -_REGEX_BY_DETECTOR: Dict[str, re.Pattern] = { +_REGEX_BY_DETECTOR: Dict[str, re.Pattern[str]] = { DETECTOR_EMAIL: _RE_EMAIL, DETECTOR_CREDIT_CARD: _RE_CREDIT_CARD, DETECTOR_SSN: _RE_SSN, diff --git a/je_auto_control/utils/remote_desktop/adaptive_bitrate.py b/je_auto_control/utils/remote_desktop/adaptive_bitrate.py index a6e185947..c62f1bd3d 100644 --- a/je_auto_control/utils/remote_desktop/adaptive_bitrate.py +++ b/je_auto_control/utils/remote_desktop/adaptive_bitrate.py @@ -16,11 +16,14 @@ from __future__ import annotations import threading -from typing import Optional +from typing import TYPE_CHECKING, Optional from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.webrtc_stats import StatsSnapshot +if TYPE_CHECKING: + from je_auto_control.utils.remote_desktop.webrtc_transport import ScreenVideoTrack + _LOSS_DOWN_PCT = 5.0 _LOSS_UP_PCT = 1.0 @@ -34,7 +37,7 @@ class AdaptiveBitrateController: """Adjusts a ScreenVideoTrack's target FPS based on stats samples.""" - def __init__(self, video_track, *, max_fps: Optional[int] = None, + def __init__(self, video_track: ScreenVideoTrack, *, max_fps: Optional[int] = None, floor_fps: int = _FLOOR_FPS, max_bitrate_kbps: int = 0) -> None: self._track = video_track diff --git a/je_auto_control/utils/remote_desktop/connect_coordinator.py b/je_auto_control/utils/remote_desktop/connect_coordinator.py index 3f1b58d0f..b3e60cc0e 100644 --- a/je_auto_control/utils/remote_desktop/connect_coordinator.py +++ b/je_auto_control/utils/remote_desktop/connect_coordinator.py @@ -66,7 +66,7 @@ def is_direct(self) -> bool: return self.kind in ("tcp", "ws", "wss") -def _parse_host_port(rest: str) -> tuple: +def _parse_host_port(rest: str) -> tuple[str, int, str]: """Split ``host:port[/path]`` and validate each piece.""" if "/" in rest: authority, _slash, path = rest.partition("/") diff --git a/je_auto_control/utils/remote_desktop/file_transfer.py b/je_auto_control/utils/remote_desktop/file_transfer.py index 4b3526ebc..176e0d96d 100644 --- a/je_auto_control/utils/remote_desktop/file_transfer.py +++ b/je_auto_control/utils/remote_desktop/file_transfer.py @@ -427,7 +427,7 @@ def _end_cancelled(channel: Any, transfer_id: str) -> None: autocontrol_logger.debug("file transfer %s: cancel notice not sent: %r", transfer_id, error) -def send_file(channel, source_path: str, dest_path: str, +def send_file(channel: Any, source_path: str, dest_path: str, on_progress: Optional[ProgressCallback] = None, chunk_size: int = DEFAULT_CHUNK_SIZE, transfer_id: Optional[str] = None, *, diff --git a/je_auto_control/utils/remote_desktop/host_capture.py b/je_auto_control/utils/remote_desktop/host_capture.py index 0b57c3c76..8b2886fb5 100644 --- a/je_auto_control/utils/remote_desktop/host_capture.py +++ b/je_auto_control/utils/remote_desktop/host_capture.py @@ -12,7 +12,7 @@ import time from io import BytesIO from typing import ( - TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, + TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, ) from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -188,6 +188,7 @@ class FrameProductionMixin: _cursor_provider: Optional[CursorProvider] _cursor_lock: threading.Lock _latest_cursor_payload: Optional[bytes] + _latest_frame: Optional[bytes] _codec_provider: CodecProvider _latest_seq: int _period: float @@ -305,7 +306,7 @@ def _capture_loop(self, stop: threading.Event) -> None: next_tick = time.monotonic() stop.wait(sleep_for) - def _encode_for_wire(self, jpeg_bytes: bytes): + def _encode_for_wire(self, jpeg_bytes: bytes) -> Iterator[bytes]: """Wrap codec output with a 1-byte tag (skipped for JPEG).""" provider = self._codec_provider if provider.name == CODEC_JPEG: diff --git a/je_auto_control/utils/remote_desktop/input_dispatch.py b/je_auto_control/utils/remote_desktop/input_dispatch.py index a3d7dcac0..e01e6d329 100644 --- a/je_auto_control/utils/remote_desktop/input_dispatch.py +++ b/je_auto_control/utils/remote_desktop/input_dispatch.py @@ -25,7 +25,7 @@ class InputDispatchError(AutoControlException, ValueError): } -def _import_wrappers(): +def _import_wrappers() -> Dict[str, Callable[..., Any]]: """Lazy import so headless/viewer-only consumers stay platform-agnostic.""" from je_auto_control.wrapper.auto_control_keyboard import ( press_keyboard_key, release_keyboard_key, write, diff --git a/je_auto_control/utils/remote_desktop/jpeg_recorder.py b/je_auto_control/utils/remote_desktop/jpeg_recorder.py index a2ae920b5..b4a98d9ac 100644 --- a/je_auto_control/utils/remote_desktop/jpeg_recorder.py +++ b/je_auto_control/utils/remote_desktop/jpeg_recorder.py @@ -26,7 +26,7 @@ import threading import time from pathlib import Path -from typing import Dict, List, Optional, TypedDict +from typing import Any, Dict, List, Optional, TypedDict _MANIFEST_FILENAME = "manifest.json" @@ -138,7 +138,7 @@ def stop(self) -> Path: return self.manifest_path -def load_manifest(path) -> Dict: +def load_manifest(path: str | os.PathLike[str]) -> Dict[str, Any]: """Read a manifest.json written by :class:`JpegSequenceRecorder`.""" return json.loads(Path(path).read_text(encoding="utf-8")) diff --git a/je_auto_control/utils/remote_desktop/jpeg_recorder_encrypted.py b/je_auto_control/utils/remote_desktop/jpeg_recorder_encrypted.py index e21d5c3bc..4087f2efa 100644 --- a/je_auto_control/utils/remote_desktop/jpeg_recorder_encrypted.py +++ b/je_auto_control/utils/remote_desktop/jpeg_recorder_encrypted.py @@ -192,7 +192,7 @@ def stop(self) -> Path: return self.manifest_path -def verify_manifest(manifest_path, hmac_key: bytes) -> bool: +def verify_manifest(manifest_path: str | os.PathLike[str], hmac_key: bytes) -> bool: """Recompute the manifest signature and verify it in constant time. A manifest that is not a signed JSON object is ``False``, not an diff --git a/je_auto_control/utils/remote_desktop/permissions.py b/je_auto_control/utils/remote_desktop/permissions.py index bd5131d5f..7d0ddd830 100644 --- a/je_auto_control/utils/remote_desktop/permissions.py +++ b/je_auto_control/utils/remote_desktop/permissions.py @@ -51,7 +51,7 @@ def none(cls) -> "SessionPermissions": def from_read_only(cls, read_only: bool) -> "SessionPermissions": return cls.view_only() if read_only else cls.full_control() - def to_dict(self) -> dict: + def to_dict(self) -> dict[str, bool]: return { "allow_view": self.allow_view, "allow_audio": self.allow_audio, diff --git a/je_auto_control/utils/remote_desktop/session_quality_cache.py b/je_auto_control/utils/remote_desktop/session_quality_cache.py index c43659010..e9c5d1a0c 100644 --- a/je_auto_control/utils/remote_desktop/session_quality_cache.py +++ b/je_auto_control/utils/remote_desktop/session_quality_cache.py @@ -20,7 +20,7 @@ from __future__ import annotations import threading -from typing import Any, Dict +from typing import Any, Dict, List class SessionQualityCache: @@ -76,7 +76,7 @@ def __contains__(self, session_id: object) -> bool: with self._lock: return session_id in self._qualities - def known_sessions(self) -> list: + def known_sessions(self) -> List[str]: """Return a list snapshot of currently-tracked session ids.""" with self._lock: return list(self._qualities.keys()) diff --git a/je_auto_control/utils/remote_desktop/turn_config.py b/je_auto_control/utils/remote_desktop/turn_config.py index aae78b3e7..b5e98bb9a 100644 --- a/je_auto_control/utils/remote_desktop/turn_config.py +++ b/je_auto_control/utils/remote_desktop/turn_config.py @@ -209,7 +209,7 @@ def _build_arg_parser() -> argparse.ArgumentParser: return parser -def main(argv: Optional[list] = None) -> int: +def main(argv: Optional[list[str]] = None) -> int: args = _build_arg_parser().parse_args(argv) try: output_dir = validate_path(args.output_dir) diff --git a/je_auto_control/utils/remote_desktop/webrtc_host_auth.py b/je_auto_control/utils/remote_desktop/webrtc_host_auth.py index 94ce3ce65..28a9aeaca 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host_auth.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host_auth.py @@ -56,7 +56,7 @@ class ViewerAuthMixin: _on_authenticated: Optional[Callable[[], None]] _on_pending_viewer: Optional[Callable[[], None]] _send_ctrl: Callable[[Mapping[str, Any]], None] - _spawn_bg: Callable[[Any], asyncio.Task] + _spawn_bg: Callable[[Any], asyncio.Task[Any]] _async_stop: Callable[[], Coroutine[Any, Any, None]] def _handle_send_sas(self) -> None: diff --git a/je_auto_control/utils/remote_desktop/ws_host.py b/je_auto_control/utils/remote_desktop/ws_host.py index 0cf59c03c..481122358 100644 --- a/je_auto_control/utils/remote_desktop/ws_host.py +++ b/je_auto_control/utils/remote_desktop/ws_host.py @@ -8,6 +8,7 @@ ``ssl_context`` already supported by the parent. """ import socket +from typing import Any from je_auto_control.utils.remote_desktop.host import RemoteDesktopHost from je_auto_control.utils.remote_desktop.transport import ( @@ -24,7 +25,7 @@ class WebSocketDesktopHost(RemoteDesktopHost): """Speak the same protocol as :class:`RemoteDesktopHost` over WebSockets.""" def _build_channel(self, sock: socket.socket, - address) -> MessageChannel: + address: Any) -> MessageChannel: del address sock.settimeout(_HANDSHAKE_TIMEOUT_S) try: diff --git a/je_auto_control/utils/remote_desktop/ws_protocol.py b/je_auto_control/utils/remote_desktop/ws_protocol.py index 702c513f1..749b771c4 100644 --- a/je_auto_control/utils/remote_desktop/ws_protocol.py +++ b/je_auto_control/utils/remote_desktop/ws_protocol.py @@ -14,7 +14,7 @@ import socket import struct import threading -from typing import Optional, Tuple +from typing import Dict, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.remote_desktop.protocol import ProtocolError @@ -139,7 +139,7 @@ def _parse_status(response: str) -> int: return int(parts[1]) -def _parse_headers(text: str) -> dict: +def _parse_headers(text: str) -> Dict[str, str]: headers = {} for line in text.split("\r\n"): if ":" in line: diff --git a/je_auto_control/utils/remote_desktop/ws_viewer.py b/je_auto_control/utils/remote_desktop/ws_viewer.py index 9ccbd46f0..a8a3bac3b 100644 --- a/je_auto_control/utils/remote_desktop/ws_viewer.py +++ b/je_auto_control/utils/remote_desktop/ws_viewer.py @@ -5,6 +5,7 @@ handshake before falling back to the shared auth + receive loop. """ import socket +from typing import Any from je_auto_control.utils.remote_desktop.transport import ( MessageChannel, WsMessageChannel, @@ -18,7 +19,7 @@ class WebSocketDesktopViewer(RemoteDesktopViewer): """Speak the same protocol as :class:`RemoteDesktopViewer` over WebSockets.""" - def __init__(self, *args, path: str = _DEFAULT_PATH, **kwargs) -> None: + def __init__(self, *args: Any, path: str = _DEFAULT_PATH, **kwargs: Any) -> None: super().__init__(*args, **kwargs) if not isinstance(path, str) or not path.startswith("/"): raise ValueError("path must be an absolute URL path starting with '/'") diff --git a/je_auto_control/utils/rest_api/__main__.py b/je_auto_control/utils/rest_api/__main__.py index 4cc1c233f..d8031f89d 100644 --- a/je_auto_control/utils/rest_api/__main__.py +++ b/je_auto_control/utils/rest_api/__main__.py @@ -35,7 +35,7 @@ def _build_arg_parser() -> argparse.ArgumentParser: return parser -def main(argv: Optional[list] = None) -> int: +def main(argv: Optional[list[str]] = None) -> int: args = _build_arg_parser().parse_args(argv) server = RestApiServer( host=args.host, port=args.port, token=args.token, diff --git a/je_auto_control/utils/rest_api/rest_handlers.py b/je_auto_control/utils/rest_api/rest_handlers.py index 854790fa9..0015f63c0 100644 --- a/je_auto_control/utils/rest_api/rest_handlers.py +++ b/je_auto_control/utils/rest_api/rest_handlers.py @@ -10,7 +10,7 @@ import base64 import io from dataclasses import dataclass -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from urllib.parse import parse_qs from je_auto_control.utils.exception.exceptions import ( @@ -385,7 +385,7 @@ def _usb_vid_pid(body: Dict[str, Any]) -> Tuple[str, str, Optional[str]]: ) -def _usb_command(thunk) -> HandlerResult: +def _usb_command(thunk: Callable[[], Dict[str, Any]]) -> HandlerResult: """Run a passthrough command thunk and map errors to status codes.""" try: return 200, thunk() diff --git a/je_auto_control/utils/scheduler/scheduler.py b/je_auto_control/utils/scheduler/scheduler.py index d2ac43b3c..05dea2d4f 100644 --- a/je_auto_control/utils/scheduler/scheduler.py +++ b/je_auto_control/utils/scheduler/scheduler.py @@ -8,7 +8,7 @@ import time import uuid from dataclasses import dataclass, field -from typing import Callable, Dict, List, Optional, Set +from typing import Any, Callable, Dict, List, Optional, Set from je_auto_control.utils.json.json_file import read_executable_action_json from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -65,7 +65,7 @@ def is_cron(self) -> bool: class Scheduler: """Thread-safe scheduler that polls jobs on a background thread.""" - def __init__(self, executor: Optional[Callable[[list], object]] = None, + def __init__(self, executor: Optional[Callable[[List[Any]], object]] = None, tick_seconds: float = 0.5) -> None: from je_auto_control.utils.executor.action_executor import execute_action self._execute = executor or execute_action diff --git a/je_auto_control/utils/script_vars/interpolate.py b/je_auto_control/utils/script_vars/interpolate.py index d8ce2c017..04ff719de 100644 --- a/je_auto_control/utils/script_vars/interpolate.py +++ b/je_auto_control/utils/script_vars/interpolate.py @@ -40,7 +40,7 @@ def interpolate_value(value: Any, variables: Mapping[str, Any]) -> Any: return value -def interpolate_actions(actions: list, variables: Mapping[str, Any]) -> list: +def interpolate_actions(actions: List[Any], variables: Mapping[str, Any]) -> List[Any]: """Return a new action list with placeholders substituted.""" return interpolate_value(actions, variables) diff --git a/je_auto_control/utils/search_index/search_index.py b/je_auto_control/utils/search_index/search_index.py index 0f51048f0..8090ea7cc 100644 --- a/je_auto_control/utils/search_index/search_index.py +++ b/je_auto_control/utils/search_index/search_index.py @@ -15,7 +15,7 @@ from collections import Counter from dataclasses import dataclass from typing import ( - Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union, + Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union, ) # \w: "[a-z0-9]+" dropped every non-ASCII character, so "登入" was never @@ -109,7 +109,7 @@ def remove(self, doc_id: str) -> bool: return True @classmethod - def build(cls, docs: Docs, **kwargs) -> "SearchIndex": + def build(cls, docs: Docs, **kwargs: Any) -> "SearchIndex": """Build an index from a ``{doc_id: text}`` map or ``(id, text)`` pairs.""" index = cls(**kwargs) items = docs.items() if isinstance(docs, dict) else docs diff --git a/je_auto_control/utils/secrets_scan/secrets_scan.py b/je_auto_control/utils/secrets_scan/secrets_scan.py index 631e1243e..d625fcc75 100644 --- a/je_auto_control/utils/secrets_scan/secrets_scan.py +++ b/je_auto_control/utils/secrets_scan/secrets_scan.py @@ -23,7 +23,7 @@ }) _KEY_WORD = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+") -_VALUE_PATTERNS: Tuple[Tuple[str, "re.Pattern"], ...] = ( +_VALUE_PATTERNS: Tuple[Tuple[str, "re.Pattern[str]"], ...] = ( ("aws-access-key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")), ("private-key-block", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----")), ("bearer-token", re.compile(r"(?i)\bBearer\s+[a-z0-9._-]{16,}")), diff --git a/je_auto_control/utils/selection_view/selection_view.py b/je_auto_control/utils/selection_view/selection_view.py index 64c385400..0565988fb 100644 --- a/je_auto_control/utils/selection_view/selection_view.py +++ b/je_auto_control/utils/selection_view/selection_view.py @@ -15,10 +15,13 @@ seam — headless-testable via a fake backend; the real UIA calls live in the Windows backend. Imports no ``PySide6``. """ -from typing import Any, Dict, Optional +from typing import TYPE_CHECKING, Any, Dict, Optional +if TYPE_CHECKING: + from je_auto_control.utils.accessibility.backends.base import AccessibilityBackend -def _backend(): + +def _backend() -> "AccessibilityBackend": from je_auto_control.utils.accessibility.backends import get_backend return get_backend() diff --git a/je_auto_control/utils/semantic_recording/enrich.py b/je_auto_control/utils/semantic_recording/enrich.py index f8aa91319..299184b81 100644 --- a/je_auto_control/utils/semantic_recording/enrich.py +++ b/je_auto_control/utils/semantic_recording/enrich.py @@ -1,7 +1,10 @@ """Annotate recorded actions with anchor metadata for portable replay.""" from __future__ import annotations -from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Sequence + +if TYPE_CHECKING: + from je_auto_control.utils.accessibility.element import AccessibilityElement _CLICK_ACTIONS = frozenset({ @@ -69,7 +72,8 @@ def _default_a11y_backend(x: int, y: int) -> Optional[Dict[str, Any]]: }) -def _smallest_containing(elements, x: int, y: int): +def _smallest_containing(elements: Sequence[AccessibilityElement], x: int, + y: int) -> Optional[AccessibilityElement]: """Pick the smallest element whose bounding box covers ``(x, y)``. "Smallest" because a click usually lands on a button nested inside diff --git a/je_auto_control/utils/semantic_recording/self_healing.py b/je_auto_control/utils/semantic_recording/self_healing.py index 56763c71d..09b8441bc 100644 --- a/je_auto_control/utils/semantic_recording/self_healing.py +++ b/je_auto_control/utils/semantic_recording/self_healing.py @@ -205,7 +205,7 @@ def _remember_moved_press(action: Mapping[str, Any], step: StepResult, def self_healing_replay(actions: Sequence[Mapping[str, Any]], - **kwargs) -> ReplayResult: + **kwargs: Any) -> ReplayResult: """Convenience wrapper: ``SelfHealingReplayer(...).replay(actions)``.""" return SelfHealingReplayer(**kwargs).replay(actions) diff --git a/je_auto_control/utils/slo/slo.py b/je_auto_control/utils/slo/slo.py index 77615a8ef..38cfa26a6 100644 --- a/je_auto_control/utils/slo/slo.py +++ b/je_auto_control/utils/slo/slo.py @@ -12,7 +12,7 @@ """ import time from dataclasses import dataclass -from typing import Any, Dict, List, Mapping, Optional, Sequence +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException @@ -47,7 +47,7 @@ def _window(records: Sequence[Mapping[str, Any]], window_s: Optional[float], if cutoff <= float(r.get("timestamp", now)) <= now] -def _counts(records: Sequence[Mapping[str, Any]]) -> tuple: +def _counts(records: Sequence[Mapping[str, Any]]) -> Tuple[int, int]: total = len(records) good = sum(1 for r in records if r.get("ok")) return good, total diff --git a/je_auto_control/utils/smart_waits/waits.py b/je_auto_control/utils/smart_waits/waits.py index 7c80a3aef..e34f153a4 100644 --- a/je_auto_control/utils/smart_waits/waits.py +++ b/je_auto_control/utils/smart_waits/waits.py @@ -268,7 +268,7 @@ def _default_window_finder(title: str, case_sensitive: bool) -> bool: def _title_matches(titles: List[str], pattern: str, - compiled: Optional["re.Pattern"]) -> bool: + compiled: Optional["re.Pattern[str]"]) -> bool: if compiled is not None: return any(compiled.search(title) for title in titles) return any(pattern in title for title in titles) diff --git a/je_auto_control/utils/socket_server/auto_control_socket_server.py b/je_auto_control/utils/socket_server/auto_control_socket_server.py index 4866c0c13..bcc3f3b5d 100644 --- a/je_auto_control/utils/socket_server/auto_control_socket_server.py +++ b/je_auto_control/utils/socket_server/auto_control_socket_server.py @@ -1,4 +1,5 @@ import json +import socket import socketserver import threading @@ -14,7 +15,7 @@ _COMMAND_TERMINATOR = b"\n" -def _read_command(request) -> str: +def _read_command(request: socket.socket) -> str: """Read one newline-terminated command, spanning as many TCP reads as needed. A single ``recv`` returns whatever one TCP segment carried, not the whole diff --git a/je_auto_control/utils/sql/sql_query.py b/je_auto_control/utils/sql/sql_query.py index 546ec6acd..ab8c62832 100644 --- a/je_auto_control/utils/sql/sql_query.py +++ b/je_auto_control/utils/sql/sql_query.py @@ -9,7 +9,7 @@ """ from contextlib import closing from pathlib import Path -from typing import TYPE_CHECKING, Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from urllib.parse import quote from je_auto_control.utils.data_source.data_source import ( @@ -52,7 +52,7 @@ def _shape(cursor: "sqlite3.Cursor", fetch: str) -> _FetchResult: def query_sqlite(database: str, query: str, - params: Optional[list | tuple | dict] = None, + params: Optional[List[Any] | Tuple[Any, ...] | Dict[str, Any]] = None, fetch: str = "all") -> _FetchResult: """Run a read-only SELECT/WITH against ``database`` and return its result. diff --git a/je_auto_control/utils/sse_client/sse_client.py b/je_auto_control/utils/sse_client/sse_client.py index 814ab7aba..ea0ac1bcb 100644 --- a/je_auto_control/utils/sse_client/sse_client.py +++ b/je_auto_control/utils/sse_client/sse_client.py @@ -11,7 +11,7 @@ """ import re from dataclasses import dataclass -from typing import List, Optional +from typing import Any, Dict, List, Optional _LINE_SPLIT = re.compile(r"\r\n|\r|\n") _BOM = chr(0xFEFF) @@ -26,7 +26,7 @@ class SSEEvent: id: Optional[str] = None retry: Optional[int] = None - def to_dict(self) -> dict: + def to_dict(self) -> Dict[str, Any]: """Return a JSON-friendly view of the event.""" return {"event": self.event, "data": self.data, "id": self.id, "retry": self.retry} diff --git a/je_auto_control/utils/state_machine/engine.py b/je_auto_control/utils/state_machine/engine.py index ad85b9d25..4fa91735d 100644 --- a/je_auto_control/utils/state_machine/engine.py +++ b/je_auto_control/utils/state_machine/engine.py @@ -241,7 +241,7 @@ def _reject_unknown_guards(transition: Mapping[str, Any]) -> None: f"unknown guard {unknown[0]!r}; use 'predicate' for other checks") -def run_state_machine(spec: Mapping[str, Any], **kwargs) -> Dict[str, Any]: +def run_state_machine(spec: Mapping[str, Any], **kwargs: Any) -> Dict[str, Any]: """Convenience wrapper: build a :class:`StateMachine` and run it.""" return StateMachine(spec, **kwargs).run() diff --git a/je_auto_control/utils/subpixel_match/subpixel_match.py b/je_auto_control/utils/subpixel_match/subpixel_match.py index 7a3aa0189..9df641141 100644 --- a/je_auto_control/utils/subpixel_match/subpixel_match.py +++ b/je_auto_control/utils/subpixel_match/subpixel_match.py @@ -54,7 +54,7 @@ def _parabola_offset(low: float, mid: float, high: float) -> float: return max(-0.5, min(0.5, offset)) -def refine_peak(score_map, peak_xy: Tuple[int, int]) -> Tuple[float, float]: +def refine_peak(score_map: Any, peak_xy: Tuple[int, int]) -> Tuple[float, float]: """Return the sub-pixel ``(offset_x, offset_y)`` of a peak via 3x3 quadratic fit.""" peak_x, peak_y = int(peak_xy[0]), int(peak_xy[1]) height, width = score_map.shape diff --git a/je_auto_control/utils/table_pattern/table_pattern.py b/je_auto_control/utils/table_pattern/table_pattern.py index 315b7a49c..35fbfb5c8 100644 --- a/je_auto_control/utils/table_pattern/table_pattern.py +++ b/je_auto_control/utils/table_pattern/table_pattern.py @@ -13,10 +13,13 @@ seam, so the headless core is unit-testable by injecting a fake backend; the real UIA calls live in the Windows backend. Imports no ``PySide6``. """ -from typing import Any, Dict, Optional +from typing import TYPE_CHECKING, Any, Dict, Optional +if TYPE_CHECKING: + from je_auto_control.utils.accessibility.backends.base import AccessibilityBackend -def _backend(): + +def _backend() -> "AccessibilityBackend": from je_auto_control.utils.accessibility.backends import get_backend return get_backend() diff --git a/je_auto_control/utils/tls_acme/challenge.py b/je_auto_control/utils/tls_acme/challenge.py index 99d7be943..b2581f329 100644 --- a/je_auto_control/utils/tls_acme/challenge.py +++ b/je_auto_control/utils/tls_acme/challenge.py @@ -6,7 +6,7 @@ import subprocess # nosec B404 # reason: needed to drive certbot import threading from pathlib import Path -from typing import Dict, List, Optional +from typing import Any, Dict, List, Optional from je_auto_control.utils.http_headers import LocalThreadingHTTPServer @@ -40,7 +40,7 @@ def do_GET(self) -> None: # noqa: N802 BaseHTTPRequestHandler protocol # Silence the default stderr access log; this server is short-lived # and noisy logging on every challenge poll just confuses the user. - def log_message(self, format: str, *args) -> None: # noqa: A002, D401 # pylint: disable=W0622 # reason: signature dictated by BaseHTTPRequestHandler + def log_message(self, format: str, *args: Any) -> None: # noqa: A002, D401 # pylint: disable=W0622 # reason: signature dictated by BaseHTTPRequestHandler return diff --git a/je_auto_control/utils/tls_acme/keys.py b/je_auto_control/utils/tls_acme/keys.py index 44b23662a..1cd88f40b 100644 --- a/je_auto_control/utils/tls_acme/keys.py +++ b/je_auto_control/utils/tls_acme/keys.py @@ -37,7 +37,7 @@ def to_pem(self) -> bytes: encryption_algorithm=serialization.NoEncryption(), ) - def save_pem(self, path) -> Path: + def save_pem(self, path: str | os.PathLike[str]) -> Path: target = Path(os.path.expanduser(str(path))) target.parent.mkdir(parents=True, exist_ok=True) # Atomic and 0600 from creation: write_bytes made the key readable diff --git a/je_auto_control/utils/transform_window/transform_window.py b/je_auto_control/utils/transform_window/transform_window.py index 6302a2c6d..a5acb79e4 100644 --- a/je_auto_control/utils/transform_window/transform_window.py +++ b/je_auto_control/utils/transform_window/transform_window.py @@ -16,10 +16,13 @@ seam — headless-testable via a fake backend; the real UIA calls live in the Windows backend. Imports no ``PySide6``. """ -from typing import Optional +from typing import TYPE_CHECKING, Optional +if TYPE_CHECKING: + from je_auto_control.utils.accessibility.backends.base import AccessibilityBackend -def _backend(): + +def _backend() -> "AccessibilityBackend": from je_auto_control.utils.accessibility.backends import get_backend return get_backend() diff --git a/je_auto_control/utils/triggers/trigger_engine.py b/je_auto_control/utils/triggers/trigger_engine.py index 03537914b..f35bbcede 100644 --- a/je_auto_control/utils/triggers/trigger_engine.py +++ b/je_auto_control/utils/triggers/trigger_engine.py @@ -12,7 +12,7 @@ import time import uuid from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Callable, ClassVar, Dict, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.json.json_file import read_executable_action_json @@ -239,7 +239,7 @@ def is_fired(self) -> bool: class TriggerEngine: """Polls registered triggers on a background thread.""" - def __init__(self, executor: Optional[Callable[[list], object]] = None, + def __init__(self, executor: Optional[Callable[[List[Any]], object]] = None, tick_seconds: float = 0.25) -> None: from je_auto_control.utils.executor.action_executor import execute_action self._execute = executor or execute_action diff --git a/je_auto_control/utils/usb/passthrough/protocol.py b/je_auto_control/utils/usb/passthrough/protocol.py index d20c57519..e0d00cc66 100644 --- a/je_auto_control/utils/usb/passthrough/protocol.py +++ b/je_auto_control/utils/usb/passthrough/protocol.py @@ -100,7 +100,7 @@ def encode_frame(frame: Frame) -> bytes: def fragment_payload(op: "Opcode", claim_id: int, payload: bytes, - *, base_flags: int = 0) -> list: + *, base_flags: int = 0) -> list[Frame]: """Split ``payload`` into EOF-terminated frames (open question 2). A payload that fits in a single frame yields exactly one frame with diff --git a/je_auto_control/utils/usb/passthrough/session.py b/je_auto_control/utils/usb/passthrough/session.py index dd41d392e..9c6451f89 100644 --- a/je_auto_control/utils/usb/passthrough/session.py +++ b/je_auto_control/utils/usb/passthrough/session.py @@ -678,7 +678,7 @@ def _encode_json_payload(obj: object) -> bytes: return json.dumps(obj, ensure_ascii=False).encode("utf-8") -def _decode_json_payload(payload: bytes) -> dict: +def _decode_json_payload(payload: bytes) -> Dict[str, Any]: if not payload: raise ValueError("empty payload") decoded = json.loads(payload.decode("utf-8")) diff --git a/je_auto_control/utils/usb/passthrough/winusb_backend.py b/je_auto_control/utils/usb/passthrough/winusb_backend.py index b9968137c..ca4659349 100644 --- a/je_auto_control/utils/usb/passthrough/winusb_backend.py +++ b/je_auto_control/utils/usb/passthrough/winusb_backend.py @@ -453,7 +453,7 @@ def _resolve_interface_detail(info_set: int, return text or None -def _parse_vid_pid(path: str) -> tuple: +def _parse_vid_pid(path: str) -> tuple[Optional[str], Optional[str]]: """Extract VID/PID from a Windows device interface path.""" match = _VID_PID_RE.search(path) if not match: diff --git a/je_auto_control/utils/usbip/backend.py b/je_auto_control/utils/usbip/backend.py index 0a1e6faef..383098e29 100644 --- a/je_auto_control/utils/usbip/backend.py +++ b/je_auto_control/utils/usbip/backend.py @@ -2,7 +2,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Tuple from je_auto_control.utils.usbip.protocol import UsbIpDevice @@ -59,7 +59,7 @@ class FakeUrbBackend(UrbBackend): def __init__(self, devices: Optional[List[UsbIpDevice]] = None) -> None: self._devices = list(devices or []) - self._urb_responses: Dict[tuple, List[UrbResponse]] = {} + self._urb_responses: Dict[Tuple[int, int, int], List[UrbResponse]] = {} self.received: List[UrbRequest] = [] def add_device(self, device: UsbIpDevice) -> None: diff --git a/je_auto_control/utils/vision/backends/_parse.py b/je_auto_control/utils/vision/backends/_parse.py index d57549cb0..3b867d74f 100644 --- a/je_auto_control/utils/vision/backends/_parse.py +++ b/je_auto_control/utils/vision/backends/_parse.py @@ -1,6 +1,6 @@ """Shared parsing helpers for VLM backend responses.""" import re -from typing import Optional, Tuple +from typing import Any, Dict, Optional, Tuple # Anchored so a pair is never cut out of a longer number: "123456, 7" read as # (23456, 7). Decimals are read whole and rounded, and "x=", "x:", '"x":' @@ -42,7 +42,7 @@ def parse_coords(text: str) -> Optional[Tuple[int, int]]: ) -def read_usage(response: object, input_name: str, output_name: str): +def read_usage(response: object, input_name: str, output_name: str) -> Optional[Dict[str, Any]]: """``{"input_tokens", "output_tokens"}`` from an SDK response, or ``None``. The SDKs name the two counts differently (``input_tokens`` / diff --git a/je_auto_control/utils/vuln_scan/vuln_scan.py b/je_auto_control/utils/vuln_scan/vuln_scan.py index 667f1f881..604af7f99 100644 --- a/je_auto_control/utils/vuln_scan/vuln_scan.py +++ b/je_auto_control/utils/vuln_scan/vuln_scan.py @@ -238,7 +238,7 @@ def match_package(ecosystem: str, name: str, version: str, def scan_components(components: Sequence[Mapping[str, Any]], advisories: Optional[Sequence[Mapping[str, Any]]] = None, *, - fetcher: Optional[Callable[[str, str], Sequence]] = None + fetcher: Optional[Callable[[str, str], Sequence[Mapping[str, Any]]]] = None ) -> List[Dict[str, Any]]: """Scan SBOM ``components`` against ``advisories`` (and an optional fetcher).""" base = list(advisories or []) diff --git a/je_auto_control/utils/window_zorder/window_zorder.py b/je_auto_control/utils/window_zorder/window_zorder.py index e62ee7f6a..71ca1caa0 100644 --- a/je_auto_control/utils/window_zorder/window_zorder.py +++ b/je_auto_control/utils/window_zorder/window_zorder.py @@ -12,7 +12,7 @@ (returning ``False`` on other platforms). Imports no ``PySide6``. """ import sys -from typing import Any, Callable, Dict, Optional +from typing import Any, Callable, Dict, List, Optional ZOrderDriver = Callable[[str, str], bool] @@ -20,7 +20,7 @@ _ACTIONS = {"top": 0, "bottom": 1, "topmost": -1, "notopmost": -2} -def available_actions() -> list: +def available_actions() -> List[str]: """Return the supported z-order action names.""" return list(_ACTIONS) diff --git a/je_auto_control/windows/interception/mouse.py b/je_auto_control/windows/interception/mouse.py index e3eb9fa3f..2256efbbc 100644 --- a/je_auto_control/windows/interception/mouse.py +++ b/je_auto_control/windows/interception/mouse.py @@ -140,8 +140,8 @@ def mouse_event(event: int, x: int, y: int, dw_data: int = 0) -> None: _send_stroke(event, x=int(x), y=int(y), rolling=int(dw_data)) -def send_mouse_event_to_window(window, mouse_keycode: Tuple[int, int, int], - x: int = 0, y: int = 0): +def send_mouse_event_to_window(window: object, mouse_keycode: Tuple[int, int, int], + x: int = 0, y: int = 0) -> None: """Targeted-window injection — degraded to focused-window for the driver. Interception talks to the kernel HID stack, not a single window diff --git a/je_auto_control/windows/window/windows_window_manage.py b/je_auto_control/windows/window/windows_window_manage.py index b77d8c744..965fc7a78 100644 --- a/je_auto_control/windows/window/windows_window_manage.py +++ b/je_auto_control/windows/window/windows_window_manage.py @@ -171,7 +171,7 @@ def get_all_window_hwnd() -> List[Tuple[int, str]]: """ window_info: List[Tuple[int, str]] = [] - def _foreach_window(hwnd, _l_param) -> bool: + def _foreach_window(hwnd: int, _l_param: int) -> bool: if _is_listable(hwnd): length = _user32.GetWindowTextLengthW(hwnd) buff = create_unicode_buffer(length + 1) diff --git a/je_auto_control/wrapper/_platform_windows.py b/je_auto_control/wrapper/_platform_windows.py index be577a1e1..5db58ea2e 100644 --- a/je_auto_control/wrapper/_platform_windows.py +++ b/je_auto_control/wrapper/_platform_windows.py @@ -1,5 +1,5 @@ import os -from typing import Dict, Tuple +from typing import Any, Dict, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -104,7 +104,7 @@ def _select_input_backend() -> Tuple[Win32KeyboardBackend, Win32MouseBackend]: return interception_keyboard, interception_mouse -def _build_mouse_keys_table(mouse_module) -> dict: +def _build_mouse_keys_table(mouse_module: Any) -> Dict[str, Tuple[int, int, int]]: """Map logical button names to the *selected* backend's flag tuples. The table must be built from the module ``_select_input_backend`` diff --git a/je_auto_control/wrapper/auto_control_mouse.py b/je_auto_control/wrapper/auto_control_mouse.py index 376a86c4e..b082ff1b2 100644 --- a/je_auto_control/wrapper/auto_control_mouse.py +++ b/je_auto_control/wrapper/auto_control_mouse.py @@ -75,7 +75,7 @@ def _mouse_input(kind: str, keycode: MouseKeycode, x: int, y: int) -> None: raise AutoControlMouseException("managed mouse input requires a reviewed button") -def get_mouse_table() -> dict: +def get_mouse_table() -> Dict[str, MouseKeycode]: """ 取得滑鼠按鍵對應表 Get mouse keys table diff --git a/je_auto_control/wrapper/auto_control_window.py b/je_auto_control/wrapper/auto_control_window.py index 4eff407a9..58cbaaba5 100644 --- a/je_auto_control/wrapper/auto_control_window.py +++ b/je_auto_control/wrapper/auto_control_window.py @@ -19,6 +19,7 @@ from je_auto_control.utils.executor.run_control import pause from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.wrapper.window_backends import get_backend +from je_auto_control.wrapper.window_backends.base import WindowManageBackend from je_auto_control.utils.timeouts import clamp_poll_interval, deadline_after #: How long focus_window waits for the window to become the foreground one. @@ -56,7 +57,7 @@ def find_window(title_substring: str, return None -def _became_foreground(backend, hwnd: int, settle_s: float) -> bool: +def _became_foreground(backend: WindowManageBackend, hwnd: int, settle_s: float) -> bool: """Poll until ``hwnd`` is the foreground window or ``settle_s`` runs out.""" deadline = time.monotonic() + max(0.0, float(settle_s)) while True: diff --git a/je_auto_control/wrapper/window_backends/windows_backend.py b/je_auto_control/wrapper/window_backends/windows_backend.py index c10ec800b..e1b0146b9 100644 --- a/je_auto_control/wrapper/window_backends/windows_backend.py +++ b/je_auto_control/wrapper/window_backends/windows_backend.py @@ -1,5 +1,6 @@ """Windows window-management backend, over the existing Win32 module.""" import sys +from types import ModuleType from typing import List, Optional, Tuple from je_auto_control.wrapper.window_backends.base import WindowManageBackend @@ -21,7 +22,7 @@ def __init__(self) -> None: self.available = sys.platform in ("win32", "cygwin", "msys") @property - def _wm(self): + def _wm(self) -> ModuleType: """The Win32 module, imported lazily so other platforms never load it.""" from je_auto_control.windows.window import windows_window_manage diff --git a/pyproject.toml b/pyproject.toml index 6a61e6988..5bd07a982 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -355,6 +355,7 @@ ignore_missing_imports = true # as a whole is named with `.*` as well, so a file added to it is covered the # day it is written. Nothing here loosens a setting from `[tool.mypy]`. module = [ + "je_auto_control", "je_auto_control.__main__", "je_auto_control._export_bindings", "je_auto_control._lazy_exports", @@ -366,6 +367,7 @@ module = [ "je_auto_control.android.session", "je_auto_control.api", "je_auto_control.api.*", + "je_auto_control.cli", "je_auto_control.gui", "je_auto_control.gui._arrow_icons", "je_auto_control.gui._daemon_thread", @@ -387,11 +389,15 @@ module = [ "je_auto_control.gui.adaptive", "je_auto_control.gui.adaptive.*", "je_auto_control.gui.adaptive_window", + "je_auto_control.gui.assertions_tab", "je_auto_control.gui.config_sync_tab", "je_auto_control.gui.config_sync_worker", + "je_auto_control.gui.data_source_tab", "je_auto_control.gui.diagnostics_capabilities", "je_auto_control.gui.diagnostics_tab", + "je_auto_control.gui.email_triggers_tab", "je_auto_control.gui.failed_stops_view", + "je_auto_control.gui.flow_editor", "je_auto_control.gui.healing_evaluation_panel", "je_auto_control.gui.healing_evaluation_worker", "je_auto_control.gui.journal_browser", @@ -404,19 +410,25 @@ module = [ "je_auto_control.gui.language_wrapper.japanese", "je_auto_control.gui.language_wrapper.simplified_chinese", "je_auto_control.gui.language_wrapper.traditional_chinese", + "je_auto_control.gui.main_widget", "je_auto_control.gui.manual_run_controls", "je_auto_control.gui.mcp_discovery_view", "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", + "je_auto_control.gui.plugins_tab", + "je_auto_control.gui.presence_tab", + "je_auto_control.gui.profiler_tab", "je_auto_control.gui.rbac_users_panel", "je_auto_control.gui.remote_desktop", "je_auto_control.gui.remote_desktop._connect_task", "je_auto_control.gui.remote_desktop._host_ops", "je_auto_control.gui.remote_desktop._webrtc_types", "je_auto_control.gui.remote_desktop.advanced_group", + "je_auto_control.gui.remote_desktop.blanking_overlay", "je_auto_control.gui.remote_desktop.connection_recent", "je_auto_control.gui.remote_desktop.folder_sync_controls", "je_auto_control.gui.remote_desktop.folder_sync_io", + "je_auto_control.gui.remote_desktop.sparkline", "je_auto_control.gui.remote_desktop.tab", "je_auto_control.gui.remote_desktop.trusted_group", "je_auto_control.gui.remote_desktop.view_approvals", @@ -436,10 +448,14 @@ module = [ "je_auto_control.gui.remote_desktop.webrtc_viewer_media", "je_auto_control.gui.remote_desktop.webrtc_viewer_ui", "je_auto_control.gui.remote_desktop_tab", + "je_auto_control.gui.rest_api_tab", + "je_auto_control.gui.run_history_timeline", + "je_auto_control.gui.script_builder", "je_auto_control.gui.script_builder.command_schema", "je_auto_control.gui.script_builder.one_time_dialog", "je_auto_control.gui.script_builder.step_form_view", "je_auto_control.gui.script_builder.step_list_view", + "je_auto_control.gui.secrets_tab", "je_auto_control.gui.selector", "je_auto_control.gui.selector.region_selector", "je_auto_control.gui.selector.template_cropper", @@ -448,6 +464,9 @@ module = [ "je_auto_control.gui.task_controller", "je_auto_control.gui.template_candidate_worker", "je_auto_control.gui.theme", + "je_auto_control.gui.trace_replay_tab", + "je_auto_control.gui.webrunner_tab", + "je_auto_control.gui.window_tab", "je_auto_control.gui.workspace", "je_auto_control.gui.workspace_details", "je_auto_control.gui.workspace_settings", @@ -487,28 +506,16 @@ module = [ "je_auto_control.linux_with_x11.screen", "je_auto_control.linux_with_x11.screen.*", "je_auto_control.linux_with_x11.uinput", - "je_auto_control.linux_with_x11.uinput.keyboard", - "je_auto_control.linux_with_x11.uinput.mouse", + "je_auto_control.linux_with_x11.uinput.*", "je_auto_control.osx", - "je_auto_control.osx.core", - "je_auto_control.osx.core.*", - "je_auto_control.osx.keyboard", - "je_auto_control.osx.keyboard.*", - "je_auto_control.osx.listener", - "je_auto_control.osx.mouse", - "je_auto_control.osx.pid", - "je_auto_control.osx.pid.*", - "je_auto_control.osx.record", - "je_auto_control.osx.record.*", - "je_auto_control.osx.screen", - "je_auto_control.osx.screen.*", + "je_auto_control.osx.*", "je_auto_control.utils", "je_auto_control.utils.a11y_audit", "je_auto_control.utils.a11y_audit.*", "je_auto_control.utils.a2a", "je_auto_control.utils.a2a.*", "je_auto_control.utils.ab_locator", - "je_auto_control.utils.ab_locator.store", + "je_auto_control.utils.ab_locator.*", "je_auto_control.utils.accessibility", "je_auto_control.utils.accessibility.backends", "je_auto_control.utils.accessibility.backends.base", @@ -521,9 +528,11 @@ module = [ "je_auto_control.utils.acme_v2", "je_auto_control.utils.acme_v2.jws", "je_auto_control.utils.act_in_view", + "je_auto_control.utils.act_in_view.*", "je_auto_control.utils.act_modes", "je_auto_control.utils.act_modes.*", "je_auto_control.utils.action_effect", + "je_auto_control.utils.action_effect.*", "je_auto_control.utils.action_grounding", "je_auto_control.utils.action_grounding.*", "je_auto_control.utils.action_journal", @@ -532,11 +541,7 @@ module = [ "je_auto_control.utils.action_lint.__main__", "je_auto_control.utils.action_lint.schema", "je_auto_control.utils.action_signing", - "je_auto_control.utils.action_signing._key_file", - "je_auto_control.utils.action_signing._private_file", - "je_auto_control.utils.action_signing.asymmetric", - "je_auto_control.utils.action_signing.config", - "je_auto_control.utils.action_signing.signer", + "je_auto_control.utils.action_signing.*", "je_auto_control.utils.actionability", "je_auto_control.utils.adaptive_timeout", "je_auto_control.utils.adaptive_timeout.*", @@ -552,25 +557,42 @@ module = [ "je_auto_control.utils.agent_runtime", "je_auto_control.utils.agent_runtime.__main__", "je_auto_control.utils.agent_runtime.activity", + "je_auto_control.utils.agent_runtime.activity_windows", "je_auto_control.utils.agent_runtime.android_action_result", + "je_auto_control.utils.agent_runtime.android_commands", + "je_auto_control.utils.agent_runtime.android_control", "je_auto_control.utils.agent_runtime.android_geometry", + "je_auto_control.utils.agent_runtime.android_input_evidence", + "je_auto_control.utils.agent_runtime.android_input_windows", "je_auto_control.utils.agent_runtime.android_session", "je_auto_control.utils.agent_runtime.android_transport", + "je_auto_control.utils.agent_runtime.api", "je_auto_control.utils.agent_runtime.browser_environment", + "je_auto_control.utils.agent_runtime.browser_readonly_scope", "je_auto_control.utils.agent_runtime.browser_validation", "je_auto_control.utils.agent_runtime.budget_clock", "je_auto_control.utils.agent_runtime.client", + "je_auto_control.utils.agent_runtime.commands", "je_auto_control.utils.agent_runtime.context", "je_auto_control.utils.agent_runtime.control_admission", + "je_auto_control.utils.agent_runtime.dag_retention", "je_auto_control.utils.agent_runtime.delegation", + "je_auto_control.utils.agent_runtime.dialog_scope", "je_auto_control.utils.agent_runtime.document_launch", + "je_auto_control.utils.agent_runtime.errors", "je_auto_control.utils.agent_runtime.evidence_cache", + "je_auto_control.utils.agent_runtime.file_dialog_scope", + "je_auto_control.utils.agent_runtime.file_target", "je_auto_control.utils.agent_runtime.helper_environment", "je_auto_control.utils.agent_runtime.images", "je_auto_control.utils.agent_runtime.jobs", + "je_auto_control.utils.agent_runtime.local_evidence", "je_auto_control.utils.agent_runtime.models", + "je_auto_control.utils.agent_runtime.native_control", "je_auto_control.utils.agent_runtime.native_job", + "je_auto_control.utils.agent_runtime.native_recovery", "je_auto_control.utils.agent_runtime.ollama", + "je_auto_control.utils.agent_runtime.owned_channel_factory", "je_auto_control.utils.agent_runtime.owner_service_nested", "je_auto_control.utils.agent_runtime.owner_service_wire", "je_auto_control.utils.agent_runtime.ownership", @@ -578,6 +600,7 @@ module = [ "je_auto_control.utils.agent_runtime.path_identity", "je_auto_control.utils.agent_runtime.policy", "je_auto_control.utils.agent_runtime.presence_endpoint_linux", + "je_auto_control.utils.agent_runtime.presence_messages_linux", "je_auto_control.utils.agent_runtime.presence_native_types", "je_auto_control.utils.agent_runtime.presence_peer_linux", "je_auto_control.utils.agent_runtime.presence_pipe_linux", @@ -585,6 +608,7 @@ module = [ "je_auto_control.utils.agent_runtime.presence_platform", "je_auto_control.utils.agent_runtime.presence_quartz", "je_auto_control.utils.agent_runtime.presence_security_windows", + "je_auto_control.utils.agent_runtime.presence_session_windows", "je_auto_control.utils.agent_runtime.presence_win32", "je_auto_control.utils.agent_runtime.presence_x11", "je_auto_control.utils.agent_runtime.readiness", @@ -597,11 +621,16 @@ module = [ "je_auto_control.utils.agent_runtime.transfer_cache", "je_auto_control.utils.agent_runtime.transfer_files", "je_auto_control.utils.agent_runtime.transfer_import_jobs", + "je_auto_control.utils.agent_runtime.transfer_models", "je_auto_control.utils.agent_runtime.transfer_operations", "je_auto_control.utils.agent_runtime.transfer_records", + "je_auto_control.utils.agent_runtime.transport", + "je_auto_control.utils.agent_runtime.trigger_history", "je_auto_control.utils.agent_runtime.window_pixels", "je_auto_control.utils.agent_runtime.wire_data", "je_auto_control.utils.agent_runtime.workflow_files", + "je_auto_control.utils.agent_runtime.workflow_wait", + "je_auto_control.utils.agent_runtime.workspace_scope", "je_auto_control.utils.agent_trace", "je_auto_control.utils.agent_trace.*", "je_auto_control.utils.anchor_locator", @@ -613,7 +642,9 @@ module = [ "je_auto_control.utils.app_idle", "je_auto_control.utils.app_idle.*", "je_auto_control.utils.approval", + "je_auto_control.utils.approval.*", "je_auto_control.utils.artifact_store", + "je_auto_control.utils.artifact_store.*", "je_auto_control.utils.assertion", "je_auto_control.utils.assertion.*", "je_auto_control.utils.assets", @@ -623,6 +654,7 @@ module = [ "je_auto_control.utils.ax_props", "je_auto_control.utils.ax_props.*", "je_auto_control.utils.ax_text", + "je_auto_control.utils.ax_text.*", "je_auto_control.utils.ax_tree_walk", "je_auto_control.utils.ax_tree_walk.*", "je_auto_control.utils.baggage", @@ -631,11 +663,13 @@ module = [ "je_auto_control.utils.bidi_check", "je_auto_control.utils.bidi_check.*", "je_auto_control.utils.bulkhead", + "je_auto_control.utils.bulkhead.*", "je_auto_control.utils.callback", "je_auto_control.utils.cancellable_process", "je_auto_control.utils.canonical_log", "je_auto_control.utils.canonical_log.*", "je_auto_control.utils.change_localize", + "je_auto_control.utils.change_localize.*", "je_auto_control.utils.chaos", "je_auto_control.utils.chaos.*", "je_auto_control.utils.chatops", @@ -653,6 +687,7 @@ module = [ "je_auto_control.utils.clipboard_files", "je_auto_control.utils.clipboard_files.*", "je_auto_control.utils.clipboard_formats", + "je_auto_control.utils.clipboard_formats.*", "je_auto_control.utils.clipboard_history", "je_auto_control.utils.clipboard_history.*", "je_auto_control.utils.clipboard_rich_formats", @@ -675,7 +710,9 @@ module = [ "je_auto_control.utils.column_layout", "je_auto_control.utils.column_layout.*", "je_auto_control.utils.compliance", + "je_auto_control.utils.compliance.*", "je_auto_control.utils.config_bundle", + "je_auto_control.utils.config_bundle.*", "je_auto_control.utils.config_redaction", "je_auto_control.utils.config_redaction.*", "je_auto_control.utils.config_schema", @@ -685,18 +722,23 @@ module = [ "je_auto_control.utils.confusables", "je_auto_control.utils.confusables.*", "je_auto_control.utils.contrast_map", + "je_auto_control.utils.contrast_map.*", "je_auto_control.utils.control_patterns", + "je_auto_control.utils.control_patterns.*", "je_auto_control.utils.cookie_jar", "je_auto_control.utils.cookie_jar.*", "je_auto_control.utils.coordinate_space", "je_auto_control.utils.coordinate_space.*", + "je_auto_control.utils.cost_telemetry.pricing", "je_auto_control.utils.cost_telemetry.store", "je_auto_control.utils.critic_features", "je_auto_control.utils.critic_features.*", "je_auto_control.utils.critical_exit", "je_auto_control.utils.critical_exit.*", "je_auto_control.utils.cua_action", + "je_auto_control.utils.cua_action.*", "je_auto_control.utils.cv2_utils", + "je_auto_control.utils.cv2_utils.blobs", "je_auto_control.utils.cv2_utils.frame_clock", "je_auto_control.utils.cv2_utils.image_file", "je_auto_control.utils.cv2_utils.locator_frame", @@ -715,6 +757,7 @@ module = [ "je_auto_control.utils.data_profile", "je_auto_control.utils.data_profile.*", "je_auto_control.utils.data_quality", + "je_auto_control.utils.data_quality.*", "je_auto_control.utils.data_source", "je_auto_control.utils.data_source.*", "je_auto_control.utils.dataset_diff", @@ -726,11 +769,11 @@ module = [ "je_auto_control.utils.dedup_window", "je_auto_control.utils.dedup_window.*", "je_auto_control.utils.deterministic", + "je_auto_control.utils.deterministic.*", "je_auto_control.utils.device_matrix", "je_auto_control.utils.device_matrix.*", "je_auto_control.utils.diagnostics", - "je_auto_control.utils.diagnostics.capability_commands", - "je_auto_control.utils.diagnostics.diagnostics", + "je_auto_control.utils.diagnostics.*", "je_auto_control.utils.dotenv", "je_auto_control.utils.dotenv.*", "je_auto_control.utils.edge_lines", @@ -756,15 +799,18 @@ module = [ "je_auto_control.utils.exception.*", "je_auto_control.utils.executor", "je_auto_control.utils.executor.action_redaction", + "je_auto_control.utils.executor.dispatch", "je_auto_control.utils.executor.flags", + "je_auto_control.utils.executor.flow_data_commands", + "je_auto_control.utils.executor.mouse_aliases", "je_auto_control.utils.executor.result_hook", "je_auto_control.utils.executor.run_control", "je_auto_control.utils.expect_poll", "je_auto_control.utils.expect_poll.*", "je_auto_control.utils.failure_bundle", + "je_auto_control.utils.failure_bundle.*", "je_auto_control.utils.failure_hooks", - "je_auto_control.utils.failure_hooks.manager", - "je_auto_control.utils.failure_hooks.report", + "je_auto_control.utils.failure_hooks.*", "je_auto_control.utils.failure_signature", "je_auto_control.utils.failure_signature.*", "je_auto_control.utils.feature_flags", @@ -789,6 +835,7 @@ module = [ "je_auto_control.utils.focus_order.*", "je_auto_control.utils.form_fields", "je_auto_control.utils.fuzzy", + "je_auto_control.utils.fuzzy.*", "je_auto_control.utils.gamepad", "je_auto_control.utils.generate_report", "je_auto_control.utils.generate_report.generate_json_report", @@ -824,11 +871,13 @@ module = [ "je_auto_control.utils.humanize.*", "je_auto_control.utils.i18n_test", "je_auto_control.utils.icon_classify", + "je_auto_control.utils.icon_classify.*", "je_auto_control.utils.idempotency", "je_auto_control.utils.idempotency.*", "je_auto_control.utils.idle_keepawake", "je_auto_control.utils.idle_keepawake.*", "je_auto_control.utils.image_dedup", + "je_auto_control.utils.image_dedup.*", "je_auto_control.utils.image_quality", "je_auto_control.utils.ime_state", "je_auto_control.utils.ime_state.*", @@ -837,6 +886,7 @@ module = [ "je_auto_control.utils.input_reach", "je_auto_control.utils.input_reach.*", "je_auto_control.utils.json", + "je_auto_control.utils.json.*", "je_auto_control.utils.json_contract", "je_auto_control.utils.json_patch", "je_auto_control.utils.json_schema", @@ -846,6 +896,7 @@ module = [ "je_auto_control.utils.jsonpath", "je_auto_control.utils.jsonpath.*", "je_auto_control.utils.jwt", + "je_auto_control.utils.jwt.*", "je_auto_control.utils.key_hold", "je_auto_control.utils.key_hold.*", "je_auto_control.utils.keyboard_layout", @@ -861,13 +912,14 @@ module = [ "je_auto_control.utils.list_format", "je_auto_control.utils.list_format.*", "je_auto_control.utils.llm", - "je_auto_control.utils.llm.backends.base", - "je_auto_control.utils.llm.backends.null_backend", + "je_auto_control.utils.llm.backends", + "je_auto_control.utils.llm.backends.*", "je_auto_control.utils.locale_collation", "je_auto_control.utils.locale_collation.*", "je_auto_control.utils.locale_parse", "je_auto_control.utils.locale_parse.*", "je_auto_control.utils.locator_chain", + "je_auto_control.utils.locator_chain.*", "je_auto_control.utils.locator_repair", "je_auto_control.utils.locator_repair.*", "je_auto_control.utils.lock_session", @@ -885,16 +937,20 @@ module = [ "je_auto_control.utils.mcp_registry", "je_auto_control.utils.mcp_registry.*", "je_auto_control.utils.mcp_server", + "je_auto_control.utils.mcp_server.__main__", "je_auto_control.utils.mcp_server._argument_policy", "je_auto_control.utils.mcp_server._authz", "je_auto_control.utils.mcp_server._call_run", "je_auto_control.utils.mcp_server._client_requests", + "je_auto_control.utils.mcp_server._disclosure_server", "je_auto_control.utils.mcp_server._http_origin", "je_auto_control.utils.mcp_server._http_responses", "je_auto_control.utils.mcp_server._http_stateless", "je_auto_control.utils.mcp_server._input_required", "je_auto_control.utils.mcp_server._origin_policies", + "je_auto_control.utils.mcp_server._protocol", "je_auto_control.utils.mcp_server._stateless", + "je_auto_control.utils.mcp_server._subscriptions", "je_auto_control.utils.mcp_server._tool_calls", "je_auto_control.utils.mcp_server._tool_notifications", "je_auto_control.utils.mcp_server.audit", @@ -924,19 +980,20 @@ module = [ "je_auto_control.utils.mcp_server.tools._handlers_remote", "je_auto_control.utils.mcp_server.tools._handlers_runs", "je_auto_control.utils.mcp_server.tools._handlers_scheduling", + "je_auto_control.utils.mcp_server.tools._handlers_screen", "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", "je_auto_control.utils.mcp_server.tools._healing_evaluation", "je_auto_control.utils.mcp_server.tools._healing_run", "je_auto_control.utils.mcp_server.tools._healing_source", "je_auto_control.utils.mcp_server.tools._readonly", "je_auto_control.utils.mcp_server.tools._template_candidates", + "je_auto_control.utils.mcp_server.tools._validation", "je_auto_control.utils.media_assert", "je_auto_control.utils.message_format", "je_auto_control.utils.modifier_state", "je_auto_control.utils.modifier_state.*", "je_auto_control.utils.monitor_layout", - "je_auto_control.utils.monitor_layout.macos_frame", - "je_auto_control.utils.monitor_layout.monitor_layout", + "je_auto_control.utils.monitor_layout.*", "je_auto_control.utils.motion_regions", "je_auto_control.utils.mouse_path", "je_auto_control.utils.mouse_path.*", @@ -951,6 +1008,7 @@ module = [ "je_auto_control.utils.notify_channels", "je_auto_control.utils.notify_channels.*", "je_auto_control.utils.observability", + "je_auto_control.utils.observability.exporter", "je_auto_control.utils.observability.metrics", "je_auto_control.utils.observation", "je_auto_control.utils.observation.*", @@ -959,6 +1017,8 @@ module = [ "je_auto_control.utils.observer", "je_auto_control.utils.observer.*", "je_auto_control.utils.ocr", + "je_auto_control.utils.ocr.backends", + "je_auto_control.utils.ocr.backends.base", "je_auto_control.utils.ocr.structure", "je_auto_control.utils.ocr.tesseract_setup", "je_auto_control.utils.ocr.text_span", @@ -976,6 +1036,7 @@ module = [ "je_auto_control.utils.path_guard", "je_auto_control.utils.path_guard.policy", "je_auto_control.utils.pdf", + "je_auto_control.utils.pdf.*", "je_auto_control.utils.percentiles", "je_auto_control.utils.percentiles.*", "je_auto_control.utils.perceptual_diff", @@ -995,7 +1056,7 @@ module = [ "je_auto_control.utils.process_memory.*", "je_auto_control.utils.process_mining", "je_auto_control.utils.profiler", - "je_auto_control.utils.profiler.profiler", + "je_auto_control.utils.profiler.*", "je_auto_control.utils.project", "je_auto_control.utils.project.create_project_structure", "je_auto_control.utils.project.template", @@ -1005,6 +1066,7 @@ module = [ "je_auto_control.utils.pytest_plugin", "je_auto_control.utils.pytest_plugin.plugin", "je_auto_control.utils.qr", + "je_auto_control.utils.qr.*", "je_auto_control.utils.quarantine", "je_auto_control.utils.quarantine.*", "je_auto_control.utils.rate_limit", @@ -1015,29 +1077,40 @@ module = [ "je_auto_control.utils.reading_flow", "je_auto_control.utils.recording_edit", "je_auto_control.utils.recurrence", + "je_auto_control.utils.recurrence.*", "je_auto_control.utils.redaction", - "je_auto_control.utils.redaction.engine", + "je_auto_control.utils.redaction.*", "je_auto_control.utils.referential", "je_auto_control.utils.referential.*", "je_auto_control.utils.remote_desktop", "je_auto_control.utils.remote_desktop._export_bindings", "je_auto_control.utils.remote_desktop._optional", "je_auto_control.utils.remote_desktop._optional.*", + "je_auto_control.utils.remote_desktop.adaptive_bitrate", "je_auto_control.utils.remote_desktop.audio_retirement", "je_auto_control.utils.remote_desktop.auth", "je_auto_control.utils.remote_desktop.clipboard_delivery", "je_auto_control.utils.remote_desktop.clipboard_sync", + "je_auto_control.utils.remote_desktop.connect_coordinator", "je_auto_control.utils.remote_desktop.file_receipts", "je_auto_control.utils.remote_desktop.file_sync", + "je_auto_control.utils.remote_desktop.file_transfer", + "je_auto_control.utils.remote_desktop.host_capture", "je_auto_control.utils.remote_desktop.host_id", + "je_auto_control.utils.remote_desktop.input_dispatch", "je_auto_control.utils.remote_desktop.input_send_queue", + "je_auto_control.utils.remote_desktop.jpeg_recorder", + "je_auto_control.utils.remote_desktop.jpeg_recorder_encrypted", "je_auto_control.utils.remote_desktop.media_retirement", + "je_auto_control.utils.remote_desktop.permissions", "je_auto_control.utils.remote_desktop.presence", "je_auto_control.utils.remote_desktop.rate_limit", "je_auto_control.utils.remote_desktop.relay", "je_auto_control.utils.remote_desktop.resume_tokens", "je_auto_control.utils.remote_desktop.session_actions", + "je_auto_control.utils.remote_desktop.session_quality_cache", "je_auto_control.utils.remote_desktop.totp", + "je_auto_control.utils.remote_desktop.turn_config", "je_auto_control.utils.remote_desktop.video_codec", "je_auto_control.utils.remote_desktop.viewer_id", "je_auto_control.utils.remote_desktop.wake_on_lan", @@ -1046,14 +1119,20 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_file_receive", "je_auto_control.utils.remote_desktop.webrtc_file_tasks", "je_auto_control.utils.remote_desktop.webrtc_file_write", + "je_auto_control.utils.remote_desktop.webrtc_host_auth", "je_auto_control.utils.remote_desktop.webrtc_inspector", "je_auto_control.utils.remote_desktop.webrtc_media_owners", "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", "je_auto_control.utils.remote_desktop.webrtc_retirement", + "je_auto_control.utils.remote_desktop.ws_host", + "je_auto_control.utils.remote_desktop.ws_protocol", + "je_auto_control.utils.remote_desktop.ws_viewer", "je_auto_control.utils.resilience", "je_auto_control.utils.resilience.*", "je_auto_control.utils.rest_api", + "je_auto_control.utils.rest_api.__main__", "je_auto_control.utils.rest_api.rest_auth", + "je_auto_control.utils.rest_api.rest_handlers", "je_auto_control.utils.rest_api.rest_metrics", "je_auto_control.utils.rest_api.rest_openapi", "je_auto_control.utils.rest_api.rest_registry", @@ -1072,27 +1151,28 @@ module = [ "je_auto_control.utils.sbom", "je_auto_control.utils.scale_detect", "je_auto_control.utils.scheduler", - "je_auto_control.utils.scheduler.cron", + "je_auto_control.utils.scheduler.*", "je_auto_control.utils.schema_compat", "je_auto_control.utils.screen_grid", "je_auto_control.utils.screen_grid.*", "je_auto_control.utils.screen_state", "je_auto_control.utils.script_vars", - "je_auto_control.utils.script_vars.execution", - "je_auto_control.utils.script_vars.ref_guard", - "je_auto_control.utils.script_vars.scope", + "je_auto_control.utils.script_vars.*", "je_auto_control.utils.scroll_find", "je_auto_control.utils.scroll_find.*", "je_auto_control.utils.search_index", + "je_auto_control.utils.search_index.*", "je_auto_control.utils.secret_ref", "je_auto_control.utils.secret_ref.*", "je_auto_control.utils.secrets", "je_auto_control.utils.secrets_scan", + "je_auto_control.utils.secrets_scan.*", "je_auto_control.utils.selection_view", + "je_auto_control.utils.selection_view.*", "je_auto_control.utils.self_healing", "je_auto_control.utils.self_healing.*", "je_auto_control.utils.semantic_recording", - "je_auto_control.utils.semantic_recording.replay", + "je_auto_control.utils.semantic_recording.*", "je_auto_control.utils.sequence_gap", "je_auto_control.utils.sequence_gap.*", "je_auto_control.utils.session_guard", @@ -1108,18 +1188,24 @@ module = [ "je_auto_control.utils.skill_library", "je_auto_control.utils.skill_library.*", "je_auto_control.utils.slo", + "je_auto_control.utils.slo.*", "je_auto_control.utils.smart_waits", + "je_auto_control.utils.smart_waits.*", "je_auto_control.utils.smoothing", "je_auto_control.utils.smoothing.*", "je_auto_control.utils.socket_server", + "je_auto_control.utils.socket_server.*", "je_auto_control.utils.soft_assert", "je_auto_control.utils.sql", + "je_auto_control.utils.sql.*", "je_auto_control.utils.sqlite_support", "je_auto_control.utils.sse_client", + "je_auto_control.utils.sse_client.*", "je_auto_control.utils.ssim", "je_auto_control.utils.start_exe", "je_auto_control.utils.start_exe.*", "je_auto_control.utils.state_machine", + "je_auto_control.utils.state_machine.*", "je_auto_control.utils.stats", "je_auto_control.utils.stats.*", "je_auto_control.utils.step_repair", @@ -1133,6 +1219,7 @@ module = [ "je_auto_control.utils.system_volume.*", "je_auto_control.utils.table_grid_fill", "je_auto_control.utils.table_pattern", + "je_auto_control.utils.table_pattern.*", "je_auto_control.utils.test_data", "je_auto_control.utils.test_data.*", "je_auto_control.utils.test_record", @@ -1159,15 +1246,19 @@ module = [ "je_auto_control.utils.timeseries", "je_auto_control.utils.timeseries.*", "je_auto_control.utils.tls_acme", + "je_auto_control.utils.tls_acme.challenge", + "je_auto_control.utils.tls_acme.keys", "je_auto_control.utils.tool_use_schema", "je_auto_control.utils.trace_context", "je_auto_control.utils.trace_context.*", "je_auto_control.utils.trajectory_eval", "je_auto_control.utils.trajectory_eval.*", "je_auto_control.utils.transform_window", + "je_auto_control.utils.transform_window.*", "je_auto_control.utils.trash", "je_auto_control.utils.trash.*", "je_auto_control.utils.triggers", + "je_auto_control.utils.triggers.trigger_engine", "je_auto_control.utils.tween_drag", "je_auto_control.utils.tween_drag.*", "je_auto_control.utils.url_canon", @@ -1183,11 +1274,15 @@ module = [ "je_auto_control.utils.usb.passthrough.flags", "je_auto_control.utils.usb.passthrough.key_provider", "je_auto_control.utils.usb.passthrough.loopback", + "je_auto_control.utils.usb.passthrough.protocol", + "je_auto_control.utils.usb.passthrough.session", "je_auto_control.utils.usb.passthrough.viewer_client", "je_auto_control.utils.usb.passthrough.webrtc_channel", + "je_auto_control.utils.usb.passthrough.winusb_backend", "je_auto_control.utils.usb.usb_devices", "je_auto_control.utils.usb.usb_watcher", "je_auto_control.utils.usbip", + "je_auto_control.utils.usbip.backend", "je_auto_control.utils.usbip.protocol", "je_auto_control.utils.verify_field", "je_auto_control.utils.verify_field.*", @@ -1198,6 +1293,7 @@ module = [ "je_auto_control.utils.virtualized", "je_auto_control.utils.virtualized.*", "je_auto_control.utils.vision", + "je_auto_control.utils.vision.backends._parse", "je_auto_control.utils.vision.backends.base", "je_auto_control.utils.vision.backends.null_backend", "je_auto_control.utils.vision.frame_capture", @@ -1207,6 +1303,7 @@ module = [ "je_auto_control.utils.voice", "je_auto_control.utils.voice.*", "je_auto_control.utils.vuln_scan", + "je_auto_control.utils.vuln_scan.*", "je_auto_control.utils.watchdog", "je_auto_control.utils.watchdog.*", "je_auto_control.utils.watcher", @@ -1218,6 +1315,7 @@ module = [ "je_auto_control.utils.window_layout", "je_auto_control.utils.window_layout.*", "je_auto_control.utils.window_zorder", + "je_auto_control.utils.window_zorder.*", "je_auto_control.utils.work_queue", "je_auto_control.utils.work_queue.*", "je_auto_control.utils.xml", @@ -1230,8 +1328,7 @@ module = [ "je_auto_control.windows.core.utils.win32_layout_vk", "je_auto_control.windows.core.utils.win32_vk", "je_auto_control.windows.interception", - "je_auto_control.windows.interception._dll", - "je_auto_control.windows.interception.keyboard", + "je_auto_control.windows.interception.*", "je_auto_control.windows.keyboard", "je_auto_control.windows.keyboard.*", "je_auto_control.windows.message", @@ -1241,11 +1338,15 @@ module = [ "je_auto_control.windows.screen", "je_auto_control.windows.screen.*", "je_auto_control.windows.window", + "je_auto_control.windows.window.*", "je_auto_control.wrapper", "je_auto_control.wrapper._input_observer", "je_auto_control.wrapper._platform_linux", "je_auto_control.wrapper._platform_osx", "je_auto_control.wrapper._platform_wayland", + "je_auto_control.wrapper._platform_windows", + "je_auto_control.wrapper.auto_control_mouse", + "je_auto_control.wrapper.auto_control_window", "je_auto_control.wrapper.capabilities", "je_auto_control.wrapper.device_context", "je_auto_control.wrapper.device_frame", @@ -1255,6 +1356,7 @@ module = [ "je_auto_control.wrapper.window_backends", "je_auto_control.wrapper.window_backends.base", "je_auto_control.wrapper.window_backends.null_backend", + "je_auto_control.wrapper.window_backends.windows_backend", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index b2ae4a16d..2bf8b840e 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -9,24 +9,16 @@ je_auto_control.gui.agent_observation_view je_auto_control.gui.agent_tasks_tab je_auto_control.gui.agent_transfer_view je_auto_control.gui.template_candidate_panel -je_auto_control.utils.agent_runtime.activity_windows je_auto_control.utils.agent_runtime.android_adapter -je_auto_control.utils.agent_runtime.android_commands -je_auto_control.utils.agent_runtime.android_control je_auto_control.utils.agent_runtime.android_hierarchy -je_auto_control.utils.agent_runtime.android_input_evidence -je_auto_control.utils.agent_runtime.android_input_windows je_auto_control.utils.agent_runtime.android_scope -je_auto_control.utils.agent_runtime.api je_auto_control.utils.agent_runtime.browser_commands -je_auto_control.utils.agent_runtime.browser_readonly_scope je_auto_control.utils.agent_runtime.browser_retirement je_auto_control.utils.agent_runtime.browser_target je_auto_control.utils.agent_runtime.browser_transfers je_auto_control.utils.agent_runtime.browser_verification je_auto_control.utils.agent_runtime.browser_workflows je_auto_control.utils.agent_runtime.cli -je_auto_control.utils.agent_runtime.commands je_auto_control.utils.agent_runtime.completion_contract je_auto_control.utils.agent_runtime.completion_recovery je_auto_control.utils.agent_runtime.dag_admission @@ -37,44 +29,33 @@ je_auto_control.utils.agent_runtime.dag_continuation_evidence je_auto_control.utils.agent_runtime.dag_continuation_plan je_auto_control.utils.agent_runtime.dag_jobs je_auto_control.utils.agent_runtime.dag_local -je_auto_control.utils.agent_runtime.dag_retention je_auto_control.utils.agent_runtime.dag_service_client je_auto_control.utils.agent_runtime.dag_transfer_checks je_auto_control.utils.agent_runtime.dag_transfer_stop -je_auto_control.utils.agent_runtime.dialog_scope -je_auto_control.utils.agent_runtime.errors je_auto_control.utils.agent_runtime.evidence je_auto_control.utils.agent_runtime.evidence_handoff -je_auto_control.utils.agent_runtime.file_dialog_scope -je_auto_control.utils.agent_runtime.file_target je_auto_control.utils.agent_runtime.handoff_records je_auto_control.utils.agent_runtime.helper_owner_linux je_auto_control.utils.agent_runtime.input_journal je_auto_control.utils.agent_runtime.input_ledger -je_auto_control.utils.agent_runtime.local_evidence je_auto_control.utils.agent_runtime.manifest_evidence je_auto_control.utils.agent_runtime.model_tools je_auto_control.utils.agent_runtime.native_channel -je_auto_control.utils.agent_runtime.native_control -je_auto_control.utils.agent_runtime.native_recovery je_auto_control.utils.agent_runtime.native_scope je_auto_control.utils.agent_runtime.native_target je_auto_control.utils.agent_runtime.native_worker je_auto_control.utils.agent_runtime.observation_refs je_auto_control.utils.agent_runtime.origin_policy -je_auto_control.utils.agent_runtime.owned_channel_factory je_auto_control.utils.agent_runtime.presence_broker je_auto_control.utils.agent_runtime.presence_channel_linux je_auto_control.utils.agent_runtime.presence_frames je_auto_control.utils.agent_runtime.presence_handshake je_auto_control.utils.agent_runtime.presence_host -je_auto_control.utils.agent_runtime.presence_messages_linux je_auto_control.utils.agent_runtime.presence_owner je_auto_control.utils.agent_runtime.presence_pool je_auto_control.utils.agent_runtime.presence_protocol je_auto_control.utils.agent_runtime.presence_reader je_auto_control.utils.agent_runtime.presence_server -je_auto_control.utils.agent_runtime.presence_session_windows je_auto_control.utils.agent_runtime.presence_state je_auto_control.utils.agent_runtime.presence_windows je_auto_control.utils.agent_runtime.presence_worker @@ -119,7 +100,6 @@ je_auto_control.utils.agent_runtime.transfer_import_files je_auto_control.utils.agent_runtime.transfer_import_ledger je_auto_control.utils.agent_runtime.transfer_lineage je_auto_control.utils.agent_runtime.transfer_management -je_auto_control.utils.agent_runtime.transfer_models je_auto_control.utils.agent_runtime.transfer_privacy je_auto_control.utils.agent_runtime.transfer_protocol je_auto_control.utils.agent_runtime.transfer_routing @@ -127,22 +107,16 @@ je_auto_control.utils.agent_runtime.transfer_selection je_auto_control.utils.agent_runtime.transfer_source je_auto_control.utils.agent_runtime.transfer_staging je_auto_control.utils.agent_runtime.transfer_transport -je_auto_control.utils.agent_runtime.transport je_auto_control.utils.agent_runtime.trigger_config -je_auto_control.utils.agent_runtime.trigger_history je_auto_control.utils.agent_runtime.trigger_reauthorization je_auto_control.utils.agent_runtime.trigger_registration je_auto_control.utils.agent_runtime.verification je_auto_control.utils.agent_runtime.workflow_desktop je_auto_control.utils.agent_runtime.workflow_specs je_auto_control.utils.agent_runtime.workflow_values -je_auto_control.utils.agent_runtime.workflow_wait -je_auto_control.utils.agent_runtime.workspace_scope je_auto_control.utils.dag.batch_contract je_auto_control.utils.dag.batch_execution je_auto_control.utils.dag.inspection je_auto_control.utils.dag.managed_tasks -je_auto_control.utils.executor.dispatch je_auto_control.utils.mcp_server._call_authority -je_auto_control.utils.mcp_server._disclosure_server je_auto_control.utils.mcp_server.tools._discovery diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index fc3ff8a4e..47e4b9372 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -13,26 +13,20 @@ # * A deleted or renamed module loses its line in the same change; a module # written later under the same name is new and therefore strict. # -je_auto_control je_auto_control.android.adb_client je_auto_control.android.client -je_auto_control.cli je_auto_control.gui._auto_click_tab je_auto_control.gui._record_tab je_auto_control.gui._script_tab je_auto_control.gui.a11y_audit_tab je_auto_control.gui.accessibility_tab je_auto_control.gui.admin_console_tab -je_auto_control.gui.assertions_tab je_auto_control.gui.audit_log_tab je_auto_control.gui.chatops_tab je_auto_control.gui.computer_use_tab je_auto_control.gui.dag_tab -je_auto_control.gui.data_source_tab je_auto_control.gui.device_matrix_tab -je_auto_control.gui.email_triggers_tab je_auto_control.gui.flakiness_tab -je_auto_control.gui.flow_editor je_auto_control.gui.flow_editor.layout je_auto_control.gui.flow_editor.scene je_auto_control.gui.flow_editor.tab @@ -41,22 +35,16 @@ je_auto_control.gui.inspector_tab je_auto_control.gui.language_wrapper.multi_language_wrapper je_auto_control.gui.live_hud_tab je_auto_control.gui.llm_planner_tab -je_auto_control.gui.main_widget je_auto_control.gui.main_window je_auto_control.gui.media_checks_tab je_auto_control.gui.ocr_tab -je_auto_control.gui.plugins_tab -je_auto_control.gui.presence_tab -je_auto_control.gui.profiler_tab je_auto_control.gui.recording_editor_tab je_auto_control.gui.remote_desktop._helpers je_auto_control.gui.remote_desktop.annotation_overlay -je_auto_control.gui.remote_desktop.blanking_overlay je_auto_control.gui.remote_desktop.connection_screen je_auto_control.gui.remote_desktop.frame_display je_auto_control.gui.remote_desktop.host_panel je_auto_control.gui.remote_desktop.remote_screen_window -je_auto_control.gui.remote_desktop.sparkline je_auto_control.gui.remote_desktop.tray_icon je_auto_control.gui.remote_desktop.viewer_panel je_auto_control.gui.remote_desktop.viewer_screen_window @@ -64,18 +52,13 @@ je_auto_control.gui.remote_desktop.webrtc_dialogs je_auto_control.gui.remote_desktop.webrtc_known_hosts je_auto_control.gui.remote_desktop.webrtc_panel je_auto_control.gui.remote_desktop.webrtc_workers -je_auto_control.gui.rest_api_tab je_auto_control.gui.run_history_tab -je_auto_control.gui.run_history_timeline je_auto_control.gui.scheduler_tab -je_auto_control.gui.script_builder je_auto_control.gui.script_builder.builder_tab je_auto_control.gui.script_builder.step_model -je_auto_control.gui.secrets_tab je_auto_control.gui.selector.region_overlay je_auto_control.gui.self_healing_tab je_auto_control.gui.test_suite_tab -je_auto_control.gui.trace_replay_tab je_auto_control.gui.triggers_tab je_auto_control.gui.usb_browser_tab je_auto_control.gui.usb_devices_tab @@ -84,8 +67,6 @@ je_auto_control.gui.usb_passthrough_prompt je_auto_control.gui.variables_tab je_auto_control.gui.vlm_tab je_auto_control.gui.webhooks_tab -je_auto_control.gui.webrunner_tab -je_auto_control.gui.window_tab je_auto_control.ios.client je_auto_control.linux_wayland._ctypes_bind je_auto_control.linux_wayland._select_input @@ -95,10 +76,6 @@ je_auto_control.linux_wayland.listener je_auto_control.linux_wayland.mouse je_auto_control.linux_with_x11.listener.x11_linux_listener je_auto_control.linux_with_x11.record.x11_linux_record -je_auto_control.linux_with_x11.uinput._device -je_auto_control.osx.listener.osx_listener -je_auto_control.osx.mouse.osx_mouse -je_auto_control.utils.ab_locator.runner je_auto_control.utils.accessibility.accessibility_api je_auto_control.utils.accessibility.backends.macos_backend je_auto_control.utils.accessibility.backends.windows_backend @@ -107,57 +84,32 @@ je_auto_control.utils.accessibility.backends.windows_reads je_auto_control.utils.accessibility.backends.windows_state je_auto_control.utils.accessibility.element je_auto_control.utils.acme_v2.client -je_auto_control.utils.act_in_view.act_in_view -je_auto_control.utils.action_effect.action_effect je_auto_control.utils.action_lint.linter -je_auto_control.utils.action_signing.cipher je_auto_control.utils.actionability.actionability je_auto_control.utils.admin.admin_client je_auto_control.utils.agent.agent_loop -je_auto_control.utils.approval.approval_test -je_auto_control.utils.artifact_store.s3_store -je_auto_control.utils.ax_text.ax_text je_auto_control.utils.barcode.barcode -je_auto_control.utils.bulkhead.bulkhead je_auto_control.utils.callback.callback_function_executor -je_auto_control.utils.change_localize.change_localize je_auto_control.utils.chatops.slack_bot je_auto_control.utils.clipboard.clipboard -je_auto_control.utils.clipboard_formats.clipboard_formats je_auto_control.utils.codegen.codegen je_auto_control.utils.color_match.color_match je_auto_control.utils.color_region.color_region -je_auto_control.utils.compliance.compliance_report -je_auto_control.utils.config_bundle.__main__ -je_auto_control.utils.config_bundle.config_bundle -je_auto_control.utils.contrast_map.contrast_map -je_auto_control.utils.control_patterns.control_patterns je_auto_control.utils.cost_telemetry -je_auto_control.utils.cost_telemetry.pricing -je_auto_control.utils.cua_action.cua_action -je_auto_control.utils.cv2_utils.blobs je_auto_control.utils.cv2_utils.screen_record je_auto_control.utils.cv2_utils.video_recording je_auto_control.utils.dag.runner -je_auto_control.utils.data_quality.data_quality je_auto_control.utils.dbus_client.session_bus je_auto_control.utils.deprecation -je_auto_control.utils.deterministic.deterministic -je_auto_control.utils.diagnostics.__main__ je_auto_control.utils.edge_lines.edge_lines je_auto_control.utils.edge_match.edge_match je_auto_control.utils.element_diff.element_diff je_auto_control.utils.executor.action_executor je_auto_control.utils.executor.action_schema je_auto_control.utils.executor.flow_control -je_auto_control.utils.executor.flow_data_commands -je_auto_control.utils.executor.mouse_aliases -je_auto_control.utils.failure_bundle.bundle -je_auto_control.utils.failure_hooks.backends je_auto_control.utils.feature_flags.feature_flags je_auto_control.utils.feature_match.feature_match je_auto_control.utils.form_fields.form_fields -je_auto_control.utils.fuzzy.fuzzy_match je_auto_control.utils.gamepad._facade je_auto_control.utils.generate_report.generate_html_report je_auto_control.utils.grid_locator.grid_locator @@ -169,29 +121,19 @@ je_auto_control.utils.hotkey.hotkey_daemon je_auto_control.utils.hsv_segment.hsv_segment je_auto_control.utils.http_client.http_client je_auto_control.utils.i18n_test.i18n_test -je_auto_control.utils.icon_classify.icon_classify -je_auto_control.utils.image_dedup.perceptual_hash je_auto_control.utils.image_quality.image_quality je_auto_control.utils.img_histogram.img_histogram je_auto_control.utils.input_macro.input_macro je_auto_control.utils.input_macro.recorder_base -je_auto_control.utils.json.json_file je_auto_control.utils.json_contract.json_contract je_auto_control.utils.json_patch.json_patch je_auto_control.utils.json_schema.json_schema -je_auto_control.utils.jwt.jwt_codec -je_auto_control.utils.llm.backends -je_auto_control.utils.llm.backends.anthropic_backend je_auto_control.utils.llm.planner -je_auto_control.utils.locator_chain.locator_chain je_auto_control.utils.logging.logging_instance je_auto_control.utils.match_autothresh.match_autothresh je_auto_control.utils.match_ensemble.match_ensemble je_auto_control.utils.match_stability.match_stability je_auto_control.utils.match_trust.match_trust -je_auto_control.utils.mcp_server.__main__ -je_auto_control.utils.mcp_server._protocol -je_auto_control.utils.mcp_server._subscriptions je_auto_control.utils.mcp_server.fake_backend je_auto_control.utils.mcp_server.http_transport je_auto_control.utils.mcp_server.plugin_watcher @@ -199,83 +141,55 @@ je_auto_control.utils.mcp_server.server je_auto_control.utils.mcp_server.tools._handlers je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations -je_auto_control.utils.mcp_server.tools._handlers_screen je_auto_control.utils.mcp_server.tools._handlers_system -je_auto_control.utils.mcp_server.tools._validation je_auto_control.utils.mcp_server.tools.plugin_tools je_auto_control.utils.media_assert.media je_auto_control.utils.message_format.message_format -je_auto_control.utils.monitor_layout.logical_frame je_auto_control.utils.motion_regions.motion_regions -je_auto_control.utils.observability.exporter je_auto_control.utils.observability.tracing -je_auto_control.utils.ocr.backends -je_auto_control.utils.ocr.backends.base je_auto_control.utils.ocr.backends.easyocr_backend je_auto_control.utils.ocr.backends.paddleocr_backend je_auto_control.utils.ocr.backends.tesseract_backend je_auto_control.utils.ocr.ocr_engine je_auto_control.utils.package_manager.package_manager_class je_auto_control.utils.path_guard.path_guard -je_auto_control.utils.pdf.pdf_reader je_auto_control.utils.perceptual_diff.perceptual_diff je_auto_control.utils.postcondition.postcondition je_auto_control.utils.preprocess.preprocess je_auto_control.utils.process_mining.process_mining -je_auto_control.utils.profiler.resource_profiler je_auto_control.utils.project.template.template_keyword je_auto_control.utils.pytest_plugin.bdd_steps je_auto_control.utils.pytest_plugin.keywords -je_auto_control.utils.qr.qr je_auto_control.utils.rate_limit.rate_limit je_auto_control.utils.reading_flow.reading_flow je_auto_control.utils.recording_edit.editor -je_auto_control.utils.recurrence.recurrence -je_auto_control.utils.redaction.policies -je_auto_control.utils.redaction.rules -je_auto_control.utils.remote_desktop.adaptive_bitrate je_auto_control.utils.remote_desktop.address_book je_auto_control.utils.remote_desktop.audio je_auto_control.utils.remote_desktop.audit_log -je_auto_control.utils.remote_desktop.connect_coordinator -je_auto_control.utils.remote_desktop.file_transfer je_auto_control.utils.remote_desktop.fingerprint je_auto_control.utils.remote_desktop.host je_auto_control.utils.remote_desktop.host_access -je_auto_control.utils.remote_desktop.host_capture je_auto_control.utils.remote_desktop.host_client je_auto_control.utils.remote_desktop.host_service je_auto_control.utils.remote_desktop.hw_codec -je_auto_control.utils.remote_desktop.input_dispatch -je_auto_control.utils.remote_desktop.jpeg_recorder -je_auto_control.utils.remote_desktop.jpeg_recorder_encrypted je_auto_control.utils.remote_desktop.lan_discovery je_auto_control.utils.remote_desktop.multi_viewer -je_auto_control.utils.remote_desktop.permissions je_auto_control.utils.remote_desktop.protocol je_auto_control.utils.remote_desktop.registry -je_auto_control.utils.remote_desktop.session_quality_cache je_auto_control.utils.remote_desktop.session_recorder je_auto_control.utils.remote_desktop.signaling_client je_auto_control.utils.remote_desktop.signaling_server je_auto_control.utils.remote_desktop.transport je_auto_control.utils.remote_desktop.trust_list -je_auto_control.utils.remote_desktop.turn_config je_auto_control.utils.remote_desktop.viewer je_auto_control.utils.remote_desktop.webrtc_audio je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host -je_auto_control.utils.remote_desktop.webrtc_host_auth je_auto_control.utils.remote_desktop.webrtc_host_media je_auto_control.utils.remote_desktop.webrtc_mic je_auto_control.utils.remote_desktop.webrtc_stats je_auto_control.utils.remote_desktop.webrtc_transport je_auto_control.utils.remote_desktop.webrtc_viewer -je_auto_control.utils.remote_desktop.ws_host -je_auto_control.utils.remote_desktop.ws_protocol -je_auto_control.utils.remote_desktop.ws_viewer -je_auto_control.utils.rest_api.__main__ -je_auto_control.utils.rest_api.rest_handlers je_auto_control.utils.rest_api.rest_server je_auto_control.utils.rich_clipboard.rich_clipboard je_auto_control.utils.rotated_match.rotated_match @@ -283,77 +197,46 @@ je_auto_control.utils.run_diff.run_diff je_auto_control.utils.saliency.saliency je_auto_control.utils.sbom.sbom je_auto_control.utils.scale_detect.scale_detect -je_auto_control.utils.scheduler.scheduler je_auto_control.utils.schema_compat.schema_compat je_auto_control.utils.screen_state.screen_state -je_auto_control.utils.script_vars.interpolate -je_auto_control.utils.search_index.search_index je_auto_control.utils.secrets.secret_store -je_auto_control.utils.secrets_scan.secrets_scan -je_auto_control.utils.selection_view.selection_view -je_auto_control.utils.semantic_recording.enrich -je_auto_control.utils.semantic_recording.self_healing je_auto_control.utils.shape_locator.shape_locator je_auto_control.utils.shell_process.shell_exec -je_auto_control.utils.slo.slo -je_auto_control.utils.smart_waits.waits -je_auto_control.utils.socket_server.auto_control_socket_server je_auto_control.utils.soft_assert.soft_assert -je_auto_control.utils.sql.sql_query -je_auto_control.utils.sse_client.sse_client je_auto_control.utils.ssim.ssim -je_auto_control.utils.state_machine.engine je_auto_control.utils.subpixel_match.subpixel_match je_auto_control.utils.table_grid_fill.table_grid_fill -je_auto_control.utils.table_pattern.table_pattern je_auto_control.utils.test_record.record_test_class je_auto_control.utils.test_select.test_select je_auto_control.utils.text_diff.text_diff je_auto_control.utils.text_regions.text_regions je_auto_control.utils.text_similarity.text_similarity je_auto_control.utils.time_travel.player -je_auto_control.utils.tls_acme.challenge -je_auto_control.utils.tls_acme.keys je_auto_control.utils.tls_acme.renewal je_auto_control.utils.tool_use_schema.schema -je_auto_control.utils.transform_window.transform_window je_auto_control.utils.triggers.email_trigger -je_auto_control.utils.triggers.trigger_engine je_auto_control.utils.triggers.webhook_server je_auto_control.utils.usb.passthrough.acl je_auto_control.utils.usb.passthrough.iokit_backend -je_auto_control.utils.usb.passthrough.protocol -je_auto_control.utils.usb.passthrough.session -je_auto_control.utils.usb.passthrough.winusb_backend -je_auto_control.utils.usbip.backend je_auto_control.utils.usbip.libusb_backend je_auto_control.utils.usbip.server je_auto_control.utils.vision.backends -je_auto_control.utils.vision.backends._parse je_auto_control.utils.vision.backends.anthropic_backend je_auto_control.utils.vision.backends.openai_backend je_auto_control.utils.visual_match.visual_match je_auto_control.utils.visual_regression.compare -je_auto_control.utils.vuln_scan.vuln_scan je_auto_control.utils.webrunner_bridge.bridge je_auto_control.utils.window_capture.window_capture -je_auto_control.utils.window_zorder.window_zorder je_auto_control.utils.xml.change_xml_structure.change_xml_structure je_auto_control.utils.xml.xml_file.xml_file je_auto_control.windows.core.utils.win32_ctype_input -je_auto_control.windows.interception.mouse je_auto_control.windows.message.window_message je_auto_control.windows.mouse.win32_ctype_mouse_control je_auto_control.windows.record.win32_input_hook -je_auto_control.windows.window.windows_window_manage -je_auto_control.wrapper._platform_windows je_auto_control.wrapper.auto_control_image je_auto_control.wrapper.auto_control_keyboard -je_auto_control.wrapper.auto_control_mouse je_auto_control.wrapper.auto_control_record je_auto_control.wrapper.auto_control_screen -je_auto_control.wrapper.auto_control_window je_auto_control.wrapper.backend_contract je_auto_control.wrapper.window_backends.macos_backend -je_auto_control.wrapper.window_backends.windows_backend je_auto_control.wrapper.window_backends.x11_backend From 3711e0135069843472e2fd7e30183b218fca8207 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 12:29:25 +0800 Subject: [PATCH 124/161] Annotate 137 modules and hold 127 more to the strict typing tier These had two or three missing annotations or bare generics each. Seven whose correct annotation exposes a real type error stay listed, as do the image modules that alias ImageSource to Any. --- Progress.md | 2 +- architecture_explore.md | 106 ++++++------ docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + je_auto_control/android/adb_client.py | 5 +- je_auto_control/gui/accessibility_tab.py | 8 +- je_auto_control/gui/agent_observation_view.py | 4 +- je_auto_control/gui/agent_transfer_view.py | 6 +- je_auto_control/gui/audit_log_tab.py | 8 +- je_auto_control/gui/chatops_tab.py | 6 +- je_auto_control/gui/device_matrix_tab.py | 6 +- je_auto_control/gui/flakiness_tab.py | 8 +- je_auto_control/gui/hotkeys_tab.py | 7 +- je_auto_control/gui/inspector_tab.py | 8 +- je_auto_control/gui/live_hud_tab.py | 7 +- je_auto_control/gui/main_window.py | 8 +- je_auto_control/gui/media_checks_tab.py | 8 +- .../gui/remote_desktop/frame_display.py | 8 +- .../gui/remote_desktop/host_panel.py | 4 +- .../remote_desktop/remote_screen_window.py | 10 +- .../gui/remote_desktop/tray_icon.py | 6 +- .../remote_desktop/viewer_screen_window.py | 8 +- je_auto_control/gui/run_history_tab.py | 10 +- je_auto_control/gui/scheduler_tab.py | 7 +- .../gui/script_builder/builder_tab.py | 6 +- .../gui/selector/region_overlay.py | 10 +- je_auto_control/gui/self_healing_tab.py | 8 +- .../gui/template_candidate_panel.py | 4 +- je_auto_control/gui/test_suite_tab.py | 9 +- je_auto_control/gui/usb_passthrough_prompt.py | 8 +- je_auto_control/gui/variables_tab.py | 8 +- je_auto_control/gui/webhooks_tab.py | 6 +- je_auto_control/linux_wayland/_ctypes_bind.py | 4 +- .../linux_wayland/_select_input.py | 11 +- je_auto_control/linux_wayland/listener.py | 6 +- je_auto_control/linux_wayland/mouse.py | 11 +- .../linux_with_x11/record/x11_linux_record.py | 6 +- .../utils/accessibility/element.py | 6 +- je_auto_control/utils/acme_v2/client.py | 6 +- je_auto_control/utils/action_lint/linter.py | 4 +- je_auto_control/utils/admin/admin_client.py | 8 +- .../utils/agent_runtime/android_scope.py | 5 +- .../utils/agent_runtime/browser_retirement.py | 4 +- .../utils/agent_runtime/browser_transfers.py | 6 +- je_auto_control/utils/agent_runtime/cli.py | 4 +- .../agent_runtime/completion_contract.py | 5 +- .../utils/agent_runtime/dag_jobs.py | 6 +- .../utils/agent_runtime/dag_service_client.py | 6 +- .../utils/agent_runtime/helper_owner_linux.py | 4 +- .../utils/agent_runtime/manifest_evidence.py | 8 +- .../utils/agent_runtime/model_tools.py | 4 +- .../utils/agent_runtime/native_scope.py | 4 +- .../utils/agent_runtime/origin_policy.py | 6 +- .../agent_runtime/presence_channel_linux.py | 6 +- .../utils/agent_runtime/presence_handshake.py | 4 +- .../utils/agent_runtime/presence_owner.py | 6 +- .../utils/agent_runtime/presence_protocol.py | 4 +- .../utils/agent_runtime/presence_reader.py | 4 +- .../utils/agent_runtime/presence_server.py | 4 +- .../utils/agent_runtime/presence_worker.py | 4 +- .../utils/agent_runtime/receipts.py | 4 +- .../utils/agent_runtime/runtime.py | 6 +- .../utils/agent_runtime/submission.py | 6 +- .../utils/agent_runtime/target_config.py | 4 +- .../utils/agent_runtime/transfer_adoption.py | 4 +- .../transfer_destination_scope.py | 4 +- .../utils/agent_runtime/transfer_privacy.py | 4 +- .../agent_runtime/trigger_registration.py | 4 +- .../utils/agent_runtime/workflow_desktop.py | 4 +- .../utils/agent_runtime/workflow_values.py | 4 +- je_auto_control/utils/chatops/slack_bot.py | 4 +- .../utils/color_region/color_region.py | 4 +- .../utils/cost_telemetry/__init__.py | 7 +- .../utils/cv2_utils/video_recording.py | 8 +- je_auto_control/utils/dag/managed_tasks.py | 6 +- .../utils/dbus_client/session_bus.py | 6 +- je_auto_control/utils/deprecation.py | 8 +- .../utils/edge_match/edge_match.py | 7 +- .../utils/element_diff/element_diff.py | 6 +- .../utils/feature_flags/feature_flags.py | 6 +- .../utils/form_fields/form_fields.py | 6 +- .../generate_report/generate_html_report.py | 5 +- .../utils/hotkey/backends/windows_backend.py | 8 +- je_auto_control/utils/hotkey/hotkey_daemon.py | 6 +- je_auto_control/utils/i18n_test/i18n_test.py | 6 +- je_auto_control/utils/llm/planner.py | 4 +- .../match_autothresh/match_autothresh.py | 8 +- .../utils/match_trust/match_trust.py | 7 +- .../utils/mcp_server/_call_authority.py | 4 +- .../utils/mcp_server/fake_backend.py | 6 +- .../utils/mcp_server/http_transport.py | 5 +- .../utils/mcp_server/plugin_watcher.py | 8 +- .../utils/mcp_server/tools/plugin_tools.py | 9 +- je_auto_control/utils/media_assert/media.py | 8 +- .../utils/ocr/backends/tesseract_backend.py | 11 +- je_auto_control/utils/ocr/ocr_engine.py | 6 +- .../package_manager/package_manager_class.py | 17 +- .../utils/path_guard/path_guard.py | 6 +- .../utils/process_mining/process_mining.py | 6 +- .../project/template/template_keyword.py | 6 +- .../utils/pytest_plugin/bdd_steps.py | 6 +- .../utils/pytest_plugin/keywords.py | 6 +- .../utils/reading_flow/reading_flow.py | 4 +- .../utils/remote_desktop/audit_log.py | 8 +- .../utils/remote_desktop/fingerprint.py | 8 +- .../utils/remote_desktop/host_access.py | 6 +- .../utils/remote_desktop/host_client.py | 8 +- .../utils/remote_desktop/protocol.py | 5 +- .../utils/remote_desktop/registry.py | 8 +- .../utils/remote_desktop/session_recorder.py | 6 +- .../utils/remote_desktop/transport.py | 8 +- .../utils/remote_desktop/trust_list.py | 6 +- .../utils/remote_desktop/viewer.py | 9 +- .../utils/remote_desktop/webrtc_mic.py | 6 +- .../utils/rich_clipboard/rich_clipboard.py | 4 +- je_auto_control/utils/sbom/sbom.py | 6 +- .../utils/shape_locator/shape_locator.py | 6 +- .../utils/soft_assert/soft_assert.py | 10 +- .../utils/test_record/record_test_class.py | 8 +- .../utils/test_select/test_select.py | 9 +- je_auto_control/utils/text_diff/text_diff.py | 4 +- .../utils/text_regions/text_regions.py | 6 +- .../utils/text_similarity/text_similarity.py | 8 +- je_auto_control/utils/time_travel/player.py | 6 +- je_auto_control/utils/tls_acme/renewal.py | 4 +- .../utils/usb/passthrough/iokit_backend.py | 6 +- je_auto_control/utils/usbip/server.py | 4 +- .../utils/vision/backends/__init__.py | 6 +- .../utils/webrunner_bridge/bridge.py | 8 +- .../utils/window_capture/window_capture.py | 9 +- .../change_xml_structure.py | 8 +- .../utils/xml/xml_file/xml_file.py | 7 +- .../windows/core/utils/win32_ctype_input.py | 6 +- .../mouse/win32_ctype_mouse_control.py | 8 +- je_auto_control/wrapper/auto_control_image.py | 8 +- .../wrapper/auto_control_record.py | 8 +- .../wrapper/auto_control_screen.py | 6 +- pyproject.toml | 155 ++++++++++++++---- test/verify/typing_not_yet_strict.txt | 34 ---- test/verify/typing_strict_baseline.txt | 93 ----------- 140 files changed, 642 insertions(+), 611 deletions(-) diff --git a/Progress.md b/Progress.md index 500a83945..eba9b9335 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05、-06,共 1,182 個)。仍缺:`test/verify/typing_strict_baseline.txt` 227 個與 `typing_not_yet_strict.txt` 115 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台約 2,400 個錯誤,集中在 331 個檔案;其中 12 個影像/定位模組只差模組層級的 `X = Any` 別名,要先為 `ImageSource` 等定一個共用型別;`android/client.py`、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py` 補上正確註記會露出真的型別錯誤),以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~07,共 1,309 個)。仍缺:`test/verify/typing_strict_baseline.txt` 134 個與 `typing_not_yet_strict.txt` 81 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台約 2,050 個錯誤,集中在 198 個檔案;其中 18 個影像/定位模組只差模組層級的 `ImageSource = Any` 之類的別名,要先定一個共用型別;另有 11 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)),以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 82066570b..ef4700c84 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,544 | -| 程式碼總行數 | 237,687 | +| 程式碼總行數 | 237,739 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -248,7 +248,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `uinput/keyboard.py` | 44 | uinput 鍵盤後端,介面與 X11 版一致。 | | `uinput/mouse.py` | 130 | uinput 滑鼠後端。 | -#### Linux Wayland(`linux_wayland/`,24 檔/4,437 行) +#### Linux Wayland(`linux_wayland/`,24 檔/4,445 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -257,7 +257,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `_ctypes_bind.py` | 75 | libei/liboeffis 共用的 ctypes 載入與 prototype 綁定。 | | `_dbus_client.py` | 24 | 只用標準函式庫的 D-Bus session bus 客戶端(連線/認證/`Hello`/`AddMatch`/一次方法呼叫/等訊號)。portal 的回應是**指名送給發出呼叫的那條連線**,所以訂閱與呼叫必須同一條連線——這是 `gdbus monitor` + `gdbus call` 兩個行程做不到的事。 | | `_input_state.py` | 47 | 不含 Qt/原生載入的失敗中繼資料與有界 cause 分類;先保留取消,再阻止權限拒絕改走 CLI。 | -| `_select_input.py` | 103 | 決定使用原生 libei 或 CLI shim;`active_backend()` 是 keyboard/mouse 的唯一入口,`emitted()` 僅容許未分類的選用後端缺席退回 CLI;明確原生選擇、權限/裝置/協定拒絕保持失敗。 | +| `_select_input.py` | 106 | 決定使用原生 libei 或 CLI shim;`active_backend()` 是 keyboard/mouse 的唯一入口,`emitted()` 僅容許未分類的選用後端缺席退回 CLI;明確原生選擇、權限/裝置/協定拒絕保持失敗。 | | `_layout.py` | 83 | 版面原點的共用查詢。擷取與輸入不是同一個座標空間,差的就是這個原點:libei 的 region offset 是 `uint32`(描述不了負原點),`ydotool mousemove --absolute` 的原點是合成器夾取的那個角落——兩條路都要減掉它,所以放在這裡而不是各自複製。讀數快取一秒——擷取那一側刻意不快取,但 ydotool 每次絕對移動都會問,不快取等於每次移動多開一個 `wlr-randr` 行程。 | | `oeffis.py` | 223 | liboeffis 綁定:跑完 RemoteDesktop portal 交握,交出 EIS fd;請求後的拒絕/逾時/失敗保留明確狀態。 | | `libei.py` | 671 | libei 綁定、撤銷閂鎖與只快取中繼資料的失敗狀態;完整握手(seat 綁定能力 → 由事件取得 device → start_emulating → 每次發送後 frame)。公開預設存取轉交 ei_default;直接建構仍在程序內。另負責絕對指標的座標空間:讀回裝置的 region,把版面座標映射進去,沒有任何 region 涵蓋就以 failed 拒絕,停止隱含 CLI 備援與後續點擊(不撤銷 sender)。 快取觀測不讀事件,完整就緒涵蓋全部請求的事件種類。 | @@ -265,19 +265,19 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `ei_worker.py` | 161 | 子程序原生 EI 擁有者;逐請求回覆與輸入清理。 | | `ei_transport.py` | 255 | 共用 owned channel 的 EI 客戶端;期限、取消、ACK 鎖內驗證與失敗保留。 | | `ei_default.py` | 121 | 預設 EI 客戶端快取、被動診斷與明確重設。 | -| `mouse.py` | 387 | 滑鼠後端:移動、按鈕與捲動都 libei 優先,僅選用缺席時退回 ydotool;權限/裝置拒絕不重送;送往 libei 時垂直捲動軸取負(kernel `REL_WHEEL` 與 `wl_pointer` 正負號相反)。退到 ydotool 的絕對移動會先減掉版面原點(`--absolute` 是相對於版面左上角,不是版面座標的 `(0, 0)`),並依 `pointer_accel_mode()` 處理指標加速度——倍率讀不回來,只有操作者知道,所以由 `JE_AUTOCONTROL_WAYLAND_POINTER_ACCEL` 宣告:未設定=每個行程警告一次後照送、`flat`=已關掉加速度故靜靜送出、`strict`=拒絕這次移動。 | +| `mouse.py` | 390 | 滑鼠後端:移動、按鈕與捲動都 libei 優先,僅選用缺席時退回 ydotool;權限/裝置拒絕不重送;送往 libei 時垂直捲動軸取負(kernel `REL_WHEEL` 與 `wl_pointer` 正負號相反)。退到 ydotool 的絕對移動會先減掉版面原點(`--absolute` 是相對於版面左上角,不是版面座標的 `(0, 0)`),並依 `pointer_accel_mode()` 處理指標加速度——倍率讀不回來,只有操作者知道,所以由 `JE_AUTOCONTROL_WAYLAND_POINTER_ACCEL` 宣告:未設定=每個行程警告一次後照送、`flat`=已關掉加速度故靜靜送出、`strict`=拒絕這次移動。 | | `keyboard.py` | 206 | 鍵盤後端:按鍵/組合鍵 libei 優先,權限拒絕不改走 CLI;中斷時逐一釋放原後端已按下的鍵。文字仍用 wtype。 | | `keymap.py` | 155 | 友善鍵名 → evdev key code。 | | `capture.py` | 250 | 擷取分層:操作者自訂指令 → grim → gnome-screenshot → spectacle → portal。 | | `portal.py` | 234 | `org.freedesktop.portal.Screenshot` 最後備援,直接講 D-Bus;未完成請求在原始 bus 上限時 Request.Close,保留原始控制,已完成 Response 不重複關閉。只需 session bus,不需 gdbus。 | | `screen.py` | 296 | 螢幕後端;發布 `grab_image` 與 `layout_origin`(擷取畫面左上角的版面座標,有螢幕在主螢幕左側/上方時為負),全框架的擷取都經由它。 | -| `listener.py` / `record.py` | 58 / 45 | 監聽與錄製 stub(Wayland 限制)。 | +| `listener.py` / `record.py` | 60 / 45 | 監聽與錄製 stub(Wayland 限制)。 | #### 行動裝置 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `android/adb_client.py` | 337 | `adb` CLI 的薄封裝。 | +| `android/adb_client.py` | 338 | `adb` CLI 的薄封裝。 | | `android/client.py` | 129 | `uiautomator2.Device` 的延遲封裝。 | | `android/find.py` | 108 | uiautomator2 widget 樹的元素查詢。 | | `ios/client.py` | 126 | `facebook-wda`(WebDriverAgent)封裝。 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,552 行。 +> 25 個套件、約 19,556 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -300,7 +300,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/action_signing/` | 1,082 | action 檔 HMAC-SHA256 簽章與 Fernet 加密,`execute_files` 會強制驗簽 | | `utils/checkpoint/` | 129 | 流程檢查點與續跑,讓長 action list 具持久性 | | `utils/codegen/` | 1,363 | 由 action list 或結構化日誌產生 pytest/Python/Robot 候選;來源清單、靜態/乾跑驗證與原子 ZIP 審閱匯出。 | -| `utils/dag/` | 1,352 | 跨主機動作/受管任務 DAG;權限及停止傳遞、目的地完成/釋放驗證、去重與未知結果審閱 | +| `utils/dag/` | 1,354 | 跨主機動作/受管任務 DAG;權限及停止傳遞、目的地完成/釋放驗證、去重與未知結果審閱 | | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | @@ -312,7 +312,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/loop_guard/` | 158 | 機械式卡死迴圈偵測(agent loop 用) | | `utils/plugin_loader/` | 147 | 掃描外部 Python 外掛目錄並註冊其 `AC_` callable | | `utils/plugin_sdk/` | 80 | 外掛 SDK:透過 entry points 發佈/載入第三方 `AC_*` 指令 | -| `utils/project/` | 183 | 專案腳手架:建立目錄結構與範本 action 檔 | +| `utils/project/` | 185 | 專案腳手架:建立目錄結構與範本 action 檔 | | `utils/recording_edit/` | 165 | 不重錄的前提下裁切/過濾/縮放已錄製的 action list | | `utils/saga/` | 103 | Saga 協調器:失敗時以 LIFO 補償動作回滾 | | `utils/script_vars/` | 377 | 執行期變數作用域、插值與 context-local vault guard;受管操作拒絕隱式秘密存取 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,859 行。 +> 15 個套件、約 4,864 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -337,7 +337,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/failure_bundle/` | 229 | 可攜、已遮蔽的失敗診斷 ZIP(截圖 + 診斷 + log 尾段) | | `utils/file_process/` | 40 | 目錄檔案列舉(`execute_dir` 的後端) | | `utils/logging/` | 358 | `autocontrol_logger`、共用 handler、executor/CLI/REST/MCP/背景 run 的 vault 值遮罩與持久化診斷快照 | -| `utils/package_manager/` | 193 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | +| `utils/package_manager/` | 198 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | | `utils/process_memory/` | 1,063 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測與失敗 handle 回收;檔案證據不等於載入程式碼身分,可信啟動及 runtime 整合待完成 | @@ -393,7 +393,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,562 行。 +> 37 個套件、約 6,564 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -405,7 +405,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/coordinate_space/` | 93 | 模型網格座標與實體像素之間的座標空間對映 | | `utils/cv2_utils/` | 1,090 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | | `utils/edge_lines/` | 131 | 以 Hough 轉換偵測線條/格線/分隔線 | -| `utils/edge_match/` | 115 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | +| `utils/edge_match/` | 116 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | | `utils/feature_match/` | 143 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | | `utils/hsv_segment/` | 104 | HSV 色彩空間分割(抗光照的顏色遮罩 + blob 框) | | `utils/icon_classify/` | 151 | 從像素形狀判斷一個框是哪一類元件 | @@ -416,7 +416,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/match_autothresh/` | 114 | Otsu 自動門檻,免去手動調 `min_score` | | `utils/match_ensemble/` | 67 | 多樣板共識比對(多張參考圖投票到同一位置) | | `utils/match_stability/` | 70 | 比對前的靜止閘門與跨影格的比對持續性 | -| `utils/match_trust/` | 154 | 樣板比對可信度評分(次峰比 + peak-to-sidelobe) | +| `utils/match_trust/` | 155 | 樣板比對可信度評分(次峰比 + peak-to-sidelobe) | | `utils/monitor_layout/` | 558 | 多螢幕/虛擬桌面幾何(在哪個螢幕、位置、重映射)+ `logical_frame` 以滑鼠座標空間擷取畫面 | | `utils/motion_regions/` | 78 | 兩影格間的局部變化/活動偵測(absdiff) | | `utils/perceptual_diff/` | 202 | 感知式(YIQ)影像差異,抑制反鋸齒邊緣誤報 | @@ -437,7 +437,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.6 OCR 與文字理解 -> 19 個套件、約 3,820 行。 +> 19 個套件、約 3,823 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -450,7 +450,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/guardrail/` | 117 | 針對畫面/OCR 文字的啟發式 prompt-injection 防護 | | `utils/heading_segment/` | 71 | 判定 OCR 行是標題或內文,建出文件大綱 | | `utils/near_dup/` | 108 | 近似重複文字偵測(SimHash/MinHash) | -| `utils/ocr/` | 1,384 | OCR 引擎門面 + 三個後端(Tesseract/EasyOCR/PaddleOCR)、版面結構化與跨詞比對(`text_span`)、Tesseract 的尋找/設定/健康檢查(`tesseract_setup`) | +| `utils/ocr/` | 1,387 | OCR 引擎門面 + 三個後端(Tesseract/EasyOCR/PaddleOCR)、版面結構化與跨詞比對(`text_span`)、Tesseract 的尋找/設定/健康檢查(`tesseract_setup`) | | `utils/pii_text/` | 141 | 自由文字中的 PII 偵測與遮蔽(email/電話/SSN/卡號/IP/IBAN) | | `utils/readability/` | 140 | 可讀性評分(Flesch、Flesch-Kincaid、Gunning Fog、SMOG、ARI) | | `utils/reading_flow/` | 165 | 以遞迴 XY-cut 推導欄位感知的閱讀順序 | @@ -516,35 +516,35 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,958 行。 +> 14 個套件、約 52,967 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,253 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,971 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 25,973 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | -| `utils/cost_telemetry/` | 347 | 每次呼叫的 LLM 成本遙測:token 數 + 估算美金 | +| `utils/cost_telemetry/` | 350 | 每次呼叫的 LLM 成本遙測:token 數 + 估算美金 | | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,231 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,235 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 666 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,232 行。 +> 6 個套件、約 32,238 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `utils/admin/` | 471 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | +| `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,906 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,910 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -593,7 +593,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.12 報表、可觀測性與測試治理 -> 34 個套件、約 7,987 行。 +> 34 個套件、約 7,993 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -608,7 +608,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/failure_signature/` | 76 | 把錯誤訊息正規化成穩定的 SHA-256 失敗簽章並分群 | | `utils/flake_cluster/` | 112 | 以共同失敗 Jaccard 相似度為易碎測試分群 | | `utils/flakiness/` | 151 | 以執行歷史分析不穩定測試 | -| `utils/generate_report/` | 341 | HTML/JSON/XML 三種報表產生器(Template Method) | +| `utils/generate_report/` | 342 | HTML/JSON/XML 三種報表產生器(Template Method) | | `utils/media_assert/` | 273 | 媒體斷言:音訊活動與影片動態檢查 | | `utils/observability/` | 712 | Prometheus 格式指標 + OpenTelemetry 相容 trace + `/metrics` 匯出伺服器 | | `utils/otlp_export/` | 114 | OTLP/JSON span 匯出 | @@ -622,10 +622,10 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/sarif/` | 187 | 以 SARIF 2.1.0 匯出發現項,供 GitHub/Azure code scanning | | `utils/slo/` | 115 | SLO 評估:SLI、錯誤預算與多視窗燃燒率告警 | | `utils/smoothing/` | 67 | 數列移動平均平滑 | -| `utils/soft_assert/` | 79 | 軟斷言:累積檢查並在區塊結束時一次拋出 | +| `utils/soft_assert/` | 81 | 軟斷言:累積檢查並在區塊結束時一次拋出 | | `utils/stats/` | 236 | 描述統計與 A/B 顯著性檢定(純標準庫) | | `utils/step_timeline/` | 87 | 每次執行的步驟瀑布圖與瓶頸(關鍵路徑)步驟排名 | -| `utils/test_select/` | 131 | 以執行歷史做風險導向的測試選取 | +| `utils/test_select/` | 134 | 以執行歷史做風險導向的測試選取 | | `utils/test_shard/` | 106 | 以耗時為權重的套件切分與分片結果合併 | | `utils/test_suite/` | 550 | QA 套件編排:把扁平 action list 評分為測試案例 + CI 報表 | | `utils/time_travel/` | 388 | 錄製 session 的時光回溯除錯(控制器 + 播放器) | @@ -634,7 +634,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.13 資料來源、結構驗證與 i18n -> 24 個套件、約 5,200 行。 +> 24 個套件、約 5,201 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -661,7 +661,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/schema_compat/` | 177 | JSON Schema 相容性分級 | | `utils/sql/` | 88 | 對 SQLite 的臨時唯讀 SQL 查詢 | | `utils/test_data/` | 211 | 帶種子的合成測試資料產生(純標準庫) | -| `utils/xml/` | 298 | XML 檔讀寫與結構變更(`defusedxml`) | +| `utils/xml/` | 299 | XML 檔讀寫與結構變更(`defusedxml`) | ### 5.4.14 安全、機密與合規 @@ -706,7 +706,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.16 系統、視窗與剪貼簿 -> 16 個套件、約 2,750 行。 +> 16 個套件、約 2,753 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -722,7 +722,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/shell_open/` | 99 | Open files with their registered applications and delegate URLs to WebRunner. | | `utils/system_volume/` | 212 | 讀取與控制系統主音量與靜音狀態 | | `utils/trash/` | 93 | 把檔案移到系統資源回收筒(可復原刪除) | -| `utils/window_capture/` | 419 | 逐視窗截圖、視窗版面儲存/還原、貼齊與排列 | +| `utils/window_capture/` | 422 | 逐視窗截圖、視窗版面儲存/還原、貼齊與排列 | | `utils/window_geometry/` | 87 | 視窗客戶區幾何(外框內縮、client→screen 對映) | | `utils/window_layout/` | 137 | 視窗拼貼/版面規劃器(左右半、四象限、網格、層疊) | | `utils/window_zorder/` | 77 | 視窗 z 序控制(最上層/移到最前/送到最後) | @@ -756,7 +756,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,231 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,235 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -792,7 +792,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers_operations.py` | 656 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | | `server.py` | 627 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、resource/prompt 處理器;`tools/call` 的准入、執行與稽核在 `_tool_calls.py`;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | | `_tool_calls.py` | 179 | `tools/call` 路徑(`ToolCallMixin`):請求、RBAC、揭露目錄、schema、參數政策、限流與破壞性確認的准入,以 `ToolCallContext` 執行、寫稽核並轉成結果;失敗截圖在呼叫時才向 `server` 取 `_capture_error_screenshot`。 | -| `http_transport.py` | 622 | MCP 的 HTTP 傳輸;宣告 2026-07-28 的請求走 `_http_stateless.py` 的標頭規則,不發 session。 | +| `http_transport.py` | 623 | MCP 的 HTTP 傳輸;宣告 2026-07-28 的請求走 `_http_stateless.py` 的標頭規則,不發 session。 | | `_http_stateless.py` | 185 | MCP 2026-07-28 在 Streamable HTTP 上的規則:`MCP-Protocol-Version`/`Mcp-Method`/`Mcp-Name` 必須與 body 相符(`=?base64?…?=` 先解碼),不符是 400+`HeaderMismatch`;版本與中繼資料錯誤 400、未知方法 404。純函式,由 `http_transport.py` 回覆。 | | `http_sessions.py` | 301 | MCP 的 HTTP 傳輸用的 session 身分:`Mcp-Session-Id` 註冊表,以及每個 session 那條常駐的 server→client SSE 串流。 | | `_call_authority.py` | 31 | Bind anonymous MCP sessions to operator authority across direct and nested tool calls. | @@ -810,14 +810,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_base.py` | 234 | 工具註冊表的共用型別與輔助;JSON 相容的 MCPToolResult 分離受控失敗旗標與資料。 | | `tools/_readonly.py` | 32 | Read-only registry variants with enforced argument restrictions. 預設/外部/動態目錄共用篩選及呼叫限制。 | | `tools/_validation.py` | 124 | MCP 工具用到的 JSON Schema 子集驗證器。 | -| `tools/plugin_tools.py` | 147 | 把外掛載入的 `AC_*` callable 包成 `MCPTool`。 | +| `tools/plugin_tools.py` | 150 | 把外掛載入的 `AC_*` callable 包成 `MCPTool`。 | | `log_bridge.py` | 118 | 把 Python logging 記錄橋接成 MCP `notifications/message`;2026-07-28 的請求只收到自己設了 `logLevel` 時產生的記錄。 | | `audit.py` | 127 | MCP 工具呼叫稽核記錄。 | | `context.py` | 81 | 傳給 opt-in 工具處理器的每次呼叫上下文,含取消(同時停掉該次呼叫的 `StopToken`)、進度與伺服器路徑政策。 | | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,906 行/77 檔) +#### `utils/remote_desktop/`(16,910 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -832,7 +832,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_media_owners.py` | 249 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | | `webrtc_peer_cleanup.py` | 166 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | | `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | -| `viewer.py` | 745 | TCP 檢視端。 | +| `viewer.py` | 748 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | @@ -877,7 +877,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `file_sync.py` | 388 | 內容摘要鏡像、固定接收收據、離線重試、停止工作擁有權與不可變交接基準。 | | `transport.py` | 126 | 可插拔的型別化訊息傳輸。 | | `host_access.py` | 112 | TCP 主機的檢視端核准與存取控制:`PendingViewer`、權限字串、分享碼的 TOTP 候選值、IP 白名單。`host` 與 `host_client` 共用,所以獨立成模組。 | -| `protocol.py` | 98 | 長度前綴的 TCP 框架。 | +| `protocol.py` | 99 | 長度前綴的 TCP 框架。 | | `resume_tokens.py` / `session_quality_cache.py` / `rate_limit.py` | 94 / 85 / 84 | 快速重連 token、每 session 品質快取、檢視端限流。 | | `host_id.py` / `viewer_id.py` | 83 / 79 | 主機與檢視端的持久身分。 | | `permissions.py` / `clipboard_sync.py` / `wake_on_lan.py` / `session_actions.py` / `auth.py` | 64 / 137 / 56 / 40 / 28 | 逐 session 權限、剪貼簿同步、WOL、SAS 注入與螢幕遮蔽、HMAC 挑戰回應。 | @@ -1045,7 +1045,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,971 行/182 檔) +#### `utils/agent_runtime/`(25,973 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1061,7 +1061,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `android_hierarchy.py` | 287 | Parse bounded Android app hierarchies with explicit host text grants and private freshness signatures. | | `android_input_evidence.py` | 223 | Bind current Android dispatcher geometry and keyguard evidence without granting input authority. | | `android_input_windows.py` | 127 | Decode pinned AOSP input-window records without retaining foreign names or raw window dumps. | -| `android_scope.py` | 87 | Validate bounded Android device, boot and focused-app evidence without publishing raw dumps. | +| `android_scope.py` | 88 | Validate bounded Android device, boot and focused-app evidence without publishing raw dumps. | | `android_session.py` | 143 | Pin Android identity, propose finite commands and dispatch only exact checked proposals. | | `android_transport.py` | 202 | Bounded no-replay ADB smart-socket transport; never starts, kills or upgrades a server. | | `api.py` | 231 | Public service-backed task functions; imports never start services or operate targets. | @@ -1078,7 +1078,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `cli.py` | 132 | Managed-task CLI parsing; the existing CLI owns terminal output. | | `client.py` | 93 | Shared local service client for GUI, CLI, MCP and Python task operations. | | `commands.py` | 135 | One command catalogue shared by executor, MCP and the visual script editor. | -| `completion_contract.py` | 62 | Shared completion evidence and retirement checks without service or DAG transport dependencies. | +| `completion_contract.py` | 63 | Shared completion evidence and retirement checks without service or DAG transport dependencies. | | `completion_recovery.py` | 660 | Explicit post-effect completion review with private lineage and permanent read-only targets. | | `context.py` | 74 | Host-owned operation context shared with local workers, never serialized model authority. | | `control_admission.py` | 29 | Closed runtime stop requests share a bounded reserve separate from ordinary HTTP polling. | @@ -1233,7 +1233,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `transfer_evidence_contract.py` | 108 | Closed portable completion envelopes carry hashes and finite verification, never local authority. | | `transfer_operations.py` | 7 | Closed management names shared by public transfer surfaces, without peer-read operations. | -#### `utils/dag/`(1,352 行/8 檔) +#### `utils/dag/`(1,354 行/8 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1242,7 +1242,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `batch_execution.py` | 95 | Initial execution of a registered graph with durable pre-delivery claims and verified receipts. | | `graph.py` | 168 | DAG types: nodes, definition, topological ordering, cycle detection. | | `inspection.py` | 166 | Inspect keyed DAG requests without submitting work or granting continuation. | -| `managed_tasks.py` | 346 | Bounded task and artifact transports preserve registered-host authority and completion contracts. | +| `managed_tasks.py` | 348 | Bounded task and artifact transports preserve registered-host authority and completion contracts. | | `runner.py` | 440 | DAG runner: schedule nodes with parallel execution + skip cascade. | | `task_contract.py` | 27 | Closed immutable managed-task payloads for existing DAG surfaces. | @@ -1366,16 +1366,16 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 952 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | -| live_hud | `live_hud_tab.py` | 155 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | +| live_hud | `live_hud_tab.py` | 156 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | | llm_planner | `llm_planner_tab.py` | 196 | 自然語言描述 → 預覽 → 執行。 | | computer_use | `computer_use_tab.py` | 164 | 從 GUI 啟動 Anthropic 閉環 agent。 | | agent_tasks | `agent_tasks_tab.py` | 618 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | -| scheduler | `scheduler_tab.py` | 174 | 註冊間隔式 action JSON 執行。 | -| hotkeys | `hotkeys_tab.py` | 166 | 將全域熱鍵綁到 action 檔。 | +| scheduler | `scheduler_tab.py` | 175 | 註冊間隔式 action JSON 執行。 | +| hotkeys | `hotkeys_tab.py` | 167 | 將全域熱鍵綁到 action 檔。 | | triggers | `triggers_tab.py` | 401 | 影像/視窗/像素/檔案事件監看。 | | webhooks | `webhooks_tab.py` | 222 | 將 HTTP 請求綁到 action 腳本。 | | email_triggers | `email_triggers_tab.py` | 254 | 將 IMAP 信箱綁到 action 腳本。 | -| test_suite | `test_suite_tab.py` | 200 | 執行 QA 套件規格並管理易碎隔離區。 | +| test_suite | `test_suite_tab.py` | 201 | 執行 QA 套件規格並管理易碎隔離區。 | | assertions | `assertions_tab.py` | 154 | 執行單一畫面狀態斷言並顯示通過/失敗。 | | data_source | `data_source_tab.py` | 132 | 預覽無頭資料層載入的資料列。 | | flakiness | `flakiness_tab.py` | 115 | 依執行歷史排序間歇失敗的腳本。 | @@ -1549,9 +1549,9 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,909 | -| `utils/mcp_server/` | 63 | 22,231 | -| `utils/remote_desktop/` | 77 | 16,906 | +| `gui/` | 166 | 43,913 | +| `utils/mcp_server/` | 63 | 22,235 | +| `utils/remote_desktop/` | 77 | 16,910 | | `utils/executor/` | 11 | 10,755 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | @@ -1561,16 +1561,16 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/rest_api/` | 8 | 2,226 | | `utils/agent/` | 13 | 2,253 | | `linux_with_x11/` | 19 | 1,382 | -| `linux_wayland/` | 24 | 4,437 | +| `linux_wayland/` | 24 | 4,445 | | `utils/triggers/` | 4 | 1,408 | -| `utils/ocr/` | 10 | 1,384 | +| `utils/ocr/` | 10 | 1,387 | | `utils/usbip/` | 5 | 1,008 | | `utils/assertion/` | 3 | 888 | | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,537 | -| **總計** | **1,532** | **236,942** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,566 | +| **總計** | **1,532** | **236,994** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index e801a3020..762b450ab 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -689,3 +689,11 @@ - **Tests:** mypy with both flags: 2,396 / 2,384 / 2,384 errors in 331 / 330 / 330 files (win32 / linux / darwin), from 2,552 / 2,538 / 2,540 in 478 / 476 / 478, and no new error in any other file. `typing_contract_verify.py` and `--extras`: 0 modules failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the headless tests of the touched modules: 988 passed, 19 skipped, and `test_locator_chain` 9 passed. - **Files:** 150 modules under `je_auto_control/`, `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `test/verify/typing_not_yet_strict.txt`, `architecture_explore.md` (line counts), `Progress.md`. - **Open items:** `Progress.md` › H (342 modules still outside the tier). + +## U-20261115-07 · 2026-11-15 · 127 more modules join the strict typing tier (two or three fixes each) · #done #typing + +- **What:** the next stage of `Progress.md` › H: the 140 files with two or three strict errors (337 in all), the four left unchanged in U-20261115-06 excluded. +- **Change:** annotation-only edits in 133 files, by the same rules as U-20261115-06 (types from the code; `Any` for JSON payloads, numpy/cv2/ctypes values, socket peer addresses and the optional WebRTC classes in `remote_desktop/registry.py`; types of lazily imported dependencies under `TYPE_CHECKING`). Two knock-on fixes: `package_manager`'s `executor` / `callback_executor` are `Optional[...]` once `__init__` returns `None`, and `win32_ctype_input._check_count` returns the tuple ctypes passes it rather than `list`. `video_recording`, `soft_assert`, `record_test_class` and `xml_file` constructors gain `-> None`. Seven stay unchanged because the correct annotation exposes a real error: `actionability` (no narrowing through `visible`), `table_grid_fill` (`None in (...)` does not narrow), `tool_use_schema/schema.py` (`Mapping` passed where `dict` is declared), `ios/client.py` and the Anthropic and OpenAI vision backends (a starred tuple in `except`), `remote_desktop/hw_codec.py` (PyAV's `bit_rate` is `int | None`, a real possible-None division seen only with `--extras`). 127 modules are promoted (strict tier 1,182 → 1,309; baseline 227 → 134, not-yet-strict 115 → 81); six more image modules alias `ImageSource = Any` and stay out (18 in all). +- **Tests:** mypy with both flags: 2,060 / 2,052 / 2,052 errors in 198 / 197 / 197 files (win32 / linux / darwin), from 2,396 / 2,384 / 2,384 in 331 / 330 / 330, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; headless tests of the touched modules 372 passed, 3 skipped (the soft-assert and recorder tests 8 passed); doc, file-length and complexity gates 41 passed. +- **Files:** 137 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. +- **Open items:** `Progress.md` › H (215 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index ec7f0e9d0..1a6954a98 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-07 | 2026-11-15 | 127 more modules join the strict typing tier (two or three fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-06 | 2026-11-15 | 143 more modules join the strict typing tier after one-line fixes | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-05 | 2026-11-15 | 896 older modules join the strict typing tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-04 | 2026-11-15 | The approval gate binds maker and checker to the RBAC user | #done #rbac #governance | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/android/adb_client.py b/je_auto_control/android/adb_client.py index 2d605c9d2..28352cf31 100644 --- a/je_auto_control/android/adb_client.py +++ b/je_auto_control/android/adb_client.py @@ -1,6 +1,7 @@ """AdbClient — thin wrapper around the ``adb`` CLI for Android automation.""" from __future__ import annotations +import os import re import shlex import shutil @@ -147,7 +148,7 @@ def default_serial(self) -> Optional[str]: def run(self, args: Sequence[str], *, serial: Optional[str] = None, input_bytes: Optional[bytes] = None, timeout: Optional[float] = None, - check: bool = True) -> subprocess.CompletedProcess: + check: bool = True) -> subprocess.CompletedProcess[bytes]: """Invoke adb with ``args``. Honours the per-instance default serial.""" cmd: List[str] = [self._adb] target = serial if serial is not None else self._default_serial @@ -321,7 +322,7 @@ def screencap_png(self, *, serial: Optional[str] = None) -> bytes: ) return result.stdout - def save_screenshot(self, file_path, + def save_screenshot(self, file_path: str | os.PathLike[str], *, serial: Optional[str] = None) -> Path: """Persist the live screen capture to ``file_path``; returns the path.""" target = Path(file_path) diff --git a/je_auto_control/gui/accessibility_tab.py b/je_auto_control/gui/accessibility_tab.py index a3fc553bd..3318b1429 100644 --- a/je_auto_control/gui/accessibility_tab.py +++ b/je_auto_control/gui/accessibility_tab.py @@ -6,7 +6,7 @@ backend gives each thread its own automation object, so the worker is safe. """ import functools -from typing import List, Optional +from typing import Any, Callable, List, Optional, Tuple from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -92,7 +92,7 @@ def dispose(self) -> None: """ release_resources(self) - def _start(self, tag: str, work) -> None: + def _start(self, tag: str, work: Callable[[], Any]) -> None: """Run ``work`` off the GUI thread as the command ``tag``; say so, or that one is still running.""" self._task.start(work, tag=tag) # False while busy: the status below is true either way self._status.setText(_t("task_running")) @@ -128,7 +128,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("a11y_refresh", self._refresh), @@ -168,7 +168,7 @@ def _on_error(self, error: object) -> None: elif tag == _CLICK and isinstance(error, AccessibilityNotAvailableError): QMessageBox.warning(self, _t("a11y_click_selected"), str(error)) - def _populate(self, elements) -> None: + def _populate(self, elements: List[AccessibilityElement]) -> None: self._table.setRowCount(len(elements)) for row, element in enumerate(elements): values = ( diff --git a/je_auto_control/gui/agent_observation_view.py b/je_auto_control/gui/agent_observation_view.py index e49cf7711..443219c13 100644 --- a/je_auto_control/gui/agent_observation_view.py +++ b/je_auto_control/gui/agent_observation_view.py @@ -89,7 +89,7 @@ def present(self, observation: dict[str, Any]) -> None: if isinstance(image, dict): self._present_image(image) - def _present_elements(self, elements: list) -> None: + def _present_elements(self, elements: list[Any]) -> None: for index, element in enumerate(elements): if not isinstance(element, dict) or element.get("index", index) != index: raise AgentTaskError("observation preview element index is ambiguous") @@ -101,7 +101,7 @@ def _present_elements(self, elements: list) -> None: value = {"selector": element["selector"], "frame": element.get("frame", "")} self._elements.setItem(index, column, QTableWidgetItem(str(value))) - def _present_image(self, image: dict) -> None: + def _present_image(self, image: dict[str, Any]) -> None: try: pixels = observation_image_bytes(image) pixmap = QPixmap() diff --git a/je_auto_control/gui/agent_transfer_view.py b/je_auto_control/gui/agent_transfer_view.py index a26169ae8..eae7b5786 100644 --- a/je_auto_control/gui/agent_transfer_view.py +++ b/je_auto_control/gui/agent_transfer_view.py @@ -20,7 +20,7 @@ def _translate(key: str) -> str: return language_wrapper.translate(key, key) -def _request(operation: str, request: dict, token: CancellationToken) -> dict: +def _request(operation: str, request: dict[str, Any], token: CancellationToken) -> dict[str, Any]: token.checkpoint() return manage_agent_transfer(operation, request) @@ -36,7 +36,7 @@ class _ViewState: generation: int = 0 submitted: int = -1 closed: bool = False - review: tuple[str, dict, dict] | None = None + review: tuple[str, dict[str, Any], dict[str, Any]] | None = None labels: list[tuple[QtWidgets.QLabel, str]] = field(default_factory=list) @@ -95,7 +95,7 @@ def detach(self) -> None: self.invalidate() self._controller.close() - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose explicit dispatch and editable preparation only through the common Actions menu.""" return [('agent_transfer_apply', self.apply), ('agent_transfer_prepare_approval', self.prepare_approval), *[('agent_transfer_example_' + name, partial(self.example, name)) for name in diff --git a/je_auto_control/gui/audit_log_tab.py b/je_auto_control/gui/audit_log_tab.py index 897d3ff32..302f09a43 100644 --- a/je_auto_control/gui/audit_log_tab.py +++ b/je_auto_control/gui/audit_log_tab.py @@ -1,6 +1,6 @@ """Audit log tab: browse and verify the tamper-evident chain.""" from datetime import datetime -from typing import List, Optional, Sequence +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple from PySide6.QtWidgets import ( QComboBox, QGroupBox, QHeaderView, QLabel, QLineEdit, @@ -84,7 +84,7 @@ def _build_layout(self) -> None: set_role(self._verify_status, "hint") root.addWidget(self._verify_status) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("audit_refresh", self._refresh), @@ -119,7 +119,7 @@ def _refresh(self) -> None: row_index, col_index, QTableWidgetItem(text), ) - def _sync_event_type_dropdown(self, all_rows: List[dict]) -> None: + def _sync_event_type_dropdown(self, all_rows: List[Dict[str, Any]]) -> None: observed = [r.get("event_type", "") for r in all_rows] choices = build_event_type_choices(observed) current = self._type_filter.currentText() @@ -173,7 +173,7 @@ def _apply_table_headers(self) -> None: ]) -def _format_row(entry: dict) -> List[str]: +def _format_row(entry: Dict[str, Any]) -> List[str]: ts = entry.get("ts", "") try: ts = datetime.fromisoformat(ts).astimezone().strftime( diff --git a/je_auto_control/gui/chatops_tab.py b/je_auto_control/gui/chatops_tab.py index 688cb6b3e..8564bb020 100644 --- a/je_auto_control/gui/chatops_tab.py +++ b/je_auto_control/gui/chatops_tab.py @@ -4,7 +4,7 @@ one at a time, as a stoppable executor run. """ import functools -from typing import Any, Optional +from typing import Any, Callable, Optional from PySide6.QtWidgets import ( QFileDialog, QFormLayout, QLabel, QLineEdit, QTextEdit, @@ -27,7 +27,7 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _dispatch(router: CommandRouter, message: str, context: dict) -> Any: +def _dispatch(router: CommandRouter, message: str, context: dict[str, Any]) -> Any: """Worker thread: route one message; the router is not touched by the GUI meanwhile.""" return router.dispatch(message, context=context) @@ -79,7 +79,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("chatops_browse_btn", self._on_browse), diff --git a/je_auto_control/gui/device_matrix_tab.py b/je_auto_control/gui/device_matrix_tab.py index 9e8229978..a0d011745 100644 --- a/je_auto_control/gui/device_matrix_tab.py +++ b/je_auto_control/gui/device_matrix_tab.py @@ -6,7 +6,7 @@ destroyed mid-run hears nothing of the result. """ import json -from typing import Optional +from typing import Any, Callable, Optional from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -88,7 +88,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("dm_run", self._on_run), @@ -120,7 +120,7 @@ def _on_run_finished(self) -> None: def _show_error(self, error: object) -> None: self._summary.setText(_t("dm_error").replace("{error}", str(error))) - def _render(self, report: dict) -> None: + def _render(self, report: dict[str, Any]) -> None: results = report["results"] self._table.setRowCount(len(results)) for row, res in enumerate(results): diff --git a/je_auto_control/gui/flakiness_tab.py b/je_auto_control/gui/flakiness_tab.py index e64a2d2a4..e93def1a6 100644 --- a/je_auto_control/gui/flakiness_tab.py +++ b/je_auto_control/gui/flakiness_tab.py @@ -3,7 +3,7 @@ Thin wrapper over :func:`je_auto_control.analyze_flakiness` — the table holds no business logic, it only renders the headless report. """ -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -17,7 +17,7 @@ from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) -from je_auto_control.utils.flakiness import analyze_flakiness +from je_auto_control.utils.flakiness import FlakyEntry, analyze_flakiness _COLUMN_KEYS = ( "flaky_col_key", "flaky_col_runs", "flaky_col_ok", "flaky_col_error", @@ -78,7 +78,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("flaky_refresh", self._refresh), @@ -102,7 +102,7 @@ def _refresh(self) -> None: else: self._status.setText(_t("flaky_summary_empty")) - def _set_row(self, row: int, entry) -> None: + def _set_row(self, row: int, entry: FlakyEntry) -> None: values = ( entry.key, str(entry.total_runs), str(entry.ok), str(entry.error), str(entry.flips), f"{entry.flip_rate:.0%}", diff --git a/je_auto_control/gui/hotkeys_tab.py b/je_auto_control/gui/hotkeys_tab.py index 9045a8574..1c9ce6fd2 100644 --- a/je_auto_control/gui/hotkeys_tab.py +++ b/je_auto_control/gui/hotkeys_tab.py @@ -1,7 +1,8 @@ """Hotkeys tab: bind global hotkeys to action JSON files.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import QTimer +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QFileDialog, QFormLayout, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, @@ -55,7 +56,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("browse", self._browse), @@ -78,7 +79,7 @@ def sync_with_engine(self) -> None: self._timer.stop() self._apply_status_label() - def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt override """Catch up with an engine started or stopped elsewhere while hidden.""" super().showEvent(event) self.sync_with_engine() diff --git a/je_auto_control/gui/inspector_tab.py b/je_auto_control/gui/inspector_tab.py index c60c93c07..bf0840541 100644 --- a/je_auto_control/gui/inspector_tab.py +++ b/je_auto_control/gui/inspector_tab.py @@ -1,5 +1,5 @@ """WebRTC inspector tab: live summary + recent stat samples.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( @@ -35,7 +35,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() self._summary_label = QLabel() - self._metric_labels: dict = {} + self._metric_labels: dict[str, QLabel] = {} self._table = QTableWidget(0, 6) self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) self._table.horizontalHeader().setSectionResizeMode( @@ -67,7 +67,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("inspector_refresh", self._refresh), @@ -120,7 +120,7 @@ def _reset(self) -> None: self._refresh() -def _format_metric_row(stats: dict) -> str: +def _format_metric_row(stats: dict[str, Optional[float]]) -> str: if not stats or stats.get("last") is None: return "-" return (f"last={stats['last']:.2f} " diff --git a/je_auto_control/gui/live_hud_tab.py b/je_auto_control/gui/live_hud_tab.py index a9293d157..4dfb832c0 100644 --- a/je_auto_control/gui/live_hud_tab.py +++ b/je_auto_control/gui/live_hud_tab.py @@ -6,6 +6,7 @@ import weakref from PySide6.QtCore import QTimer +from PySide6.QtGui import QHideEvent, QShowEvent from PySide6.QtWidgets import ( QGroupBox, QLabel, QTextEdit, QVBoxLayout, QWidget, ) @@ -101,7 +102,7 @@ def _build_layout(self) -> None: log_card.add(self._log_view, stretch=1) root.addWidget(log_card, stretch=1) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("hud_start", self._start), @@ -145,11 +146,11 @@ def _tick(self) -> None: # The HUD samples the cursor and a pixel four times a second only while # it is on screen: a closed or switched-away tab kept polling. The log # tail stays attached, so lines logged meanwhile are there on return. - def hideEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def hideEvent(self, event: QHideEvent) -> None: # noqa: N802 # reason: Qt override self._timer.stop() super().hideEvent(event) - def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt override if self._running: self._timer.start() super().showEvent(event) diff --git a/je_auto_control/gui/main_window.py b/je_auto_control/gui/main_window.py index 12135f727..0cf9fb773 100644 --- a/je_auto_control/gui/main_window.py +++ b/je_auto_control/gui/main_window.py @@ -1,6 +1,6 @@ """Top-level window: menu bar, feature navigation, tabbed workspace, themes, live language switching.""" import sys -from typing import cast +from typing import Any, cast from PySide6.QtCore import QEvent, QObject, QSettings, Qt from PySide6.QtGui import QAction, QActionGroup, QCloseEvent, QKeySequence @@ -82,7 +82,7 @@ def __init__(self, *, settings: QSettings | None = None) -> None: self._view_menu: QMenu | None = None self._actions_menu: QMenu | None = None - self._tab_actions: list = [] + self._tab_actions: list[QAction] = [] self._build_menu_bar() self.auto_control_gui_widget.tabs_changed.connect(self._rebuild_tabs_menu) self.auto_control_gui_widget.tabs_changed.connect(self._refresh_navigation) @@ -299,7 +299,7 @@ def _rebuild_tabs_menu(self) -> None: submenu.deleteLater() view_menu.clear() self._tab_actions = [] - entries_by_cat: dict = {} + entries_by_cat: dict[str, list[dict[str, Any]]] = {} for entry in self.auto_control_gui_widget.list_registered_tabs(): entries_by_cat.setdefault(entry["category"], []).append(entry) for cat_key, title_key, default in _TAB_CATEGORIES: @@ -310,7 +310,7 @@ def _rebuild_tabs_menu(self) -> None: if entries: self._add_category_submenu(view_menu, cat_key.title(), entries) - def _add_category_submenu(self, view_menu: QMenu, label: str, entries: list) -> None: + def _add_category_submenu(self, view_menu: QMenu, label: str, entries: list[dict[str, Any]]) -> None: sub = view_menu.addMenu(label) for entry in entries: action = QAction(entry["title"], sub, checkable=True) diff --git a/je_auto_control/gui/media_checks_tab.py b/je_auto_control/gui/media_checks_tab.py index f87e49606..49169e358 100644 --- a/je_auto_control/gui/media_checks_tab.py +++ b/je_auto_control/gui/media_checks_tab.py @@ -6,7 +6,7 @@ thread, one at a time. """ import functools -from typing import Any, Optional +from typing import Any, Callable, Optional from PySide6.QtWidgets import ( QCheckBox, QDoubleSpinBox, QFileDialog, QLabel, QLineEdit, @@ -28,12 +28,12 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _check_audio(options: dict) -> Any: +def _check_audio(options: dict[str, Any]) -> Any: """Worker thread: record and measure.""" return ac.assert_audio_activity(raise_on_fail=False, **options) -def _check_video(path: str, options: dict) -> Any: +def _check_video(path: str, options: dict[str, Any]) -> Any: """Worker thread: decode the file and measure.""" return ac.assert_video_changes(path, raise_on_fail=False, **options) @@ -94,7 +94,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("media_audio_run", self._on_audio), diff --git a/je_auto_control/gui/remote_desktop/frame_display.py b/je_auto_control/gui/remote_desktop/frame_display.py index f133c2605..db0749160 100644 --- a/je_auto_control/gui/remote_desktop/frame_display.py +++ b/je_auto_control/gui/remote_desktop/frame_display.py @@ -5,7 +5,7 @@ from PySide6.QtCore import QPoint, QRect, Qt, Signal from PySide6.QtGui import ( QColor, QDragEnterEvent, QDropEvent, QImage, QKeyEvent, QMouseEvent, - QPainter, QPen, QWheelEvent, + QPaintEvent, QPainter, QPen, QWheelEvent, ) from PySide6.QtWidgets import QSizePolicy, QWidget @@ -40,7 +40,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: # Remote host cursor position in *host* screen coords. ``None`` # while no CURSOR message has been received yet; the overlay is # then suppressed so we don't draw a stale arrow over the frame. - self._remote_cursor: Optional[tuple] = None + self._remote_cursor: Optional[tuple[int, int]] = None self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) self.setMouseTracking(True) self.setSizePolicy( @@ -79,7 +79,7 @@ def has_image(self) -> bool: # --- painting ------------------------------------------------------- - def paintEvent(self, _event) -> None: # noqa: N802 Qt override + def paintEvent(self, _event: QPaintEvent) -> None: # noqa: N802 Qt override painter = QPainter(self) painter.fillRect(self.rect(), Qt.GlobalColor.black) image = self._image @@ -135,7 +135,7 @@ def _fit_rect(self) -> QRect: y = (widget_h - scaled_h) // 2 return QRect(x, y, scaled_w, scaled_h) - def _to_remote(self, pos: QPoint) -> Optional[tuple]: + def _to_remote(self, pos: QPoint) -> Optional[tuple[int, int]]: rect = self._fit_rect() if not rect.isValid() or not rect.contains(pos): return None diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index 308ce9287..cf4f63c84 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -53,7 +53,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._host_op = SlowOp(self) self._pending_key = "gui_op_stopping" # The share details of the start that is out; they become _shared when it reports. - self._starting: dict = {} + self._starting: dict[str, str] = {} self._host_id_label = QLabel("---") self._host_id_label.setStyleSheet( "font-family: 'Consolas', 'Menlo', 'Courier New', monospace; " @@ -84,7 +84,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: if not self._audio_available: self._enable_audio.setEnabled(False) # What the share text quotes, taken at Start (see _copy_share_text). - self._shared: Optional[dict] = None + self._shared: Optional[dict[str, Any]] = None self._preview = _FrameDisplay() # Preview is read-only — a host watching their own stream shouldn't # trigger fake input on themselves through the local widget. diff --git a/je_auto_control/gui/remote_desktop/remote_screen_window.py b/je_auto_control/gui/remote_desktop/remote_screen_window.py index ba81229ea..7862e9191 100644 --- a/je_auto_control/gui/remote_desktop/remote_screen_window.py +++ b/je_auto_control/gui/remote_desktop/remote_screen_window.py @@ -17,8 +17,8 @@ from typing import Optional from PySide6.QtCore import Qt, Signal -from PySide6.QtGui import QImage -from PySide6.QtWidgets import QDialog, QLabel, QProgressBar, QVBoxLayout +from PySide6.QtGui import QCloseEvent, QImage +from PySide6.QtWidgets import QDialog, QLabel, QProgressBar, QVBoxLayout, QWidget from je_auto_control.gui.remote_desktop._helpers import _t from je_auto_control.gui.remote_desktop.frame_display import _FrameDisplay @@ -39,7 +39,7 @@ class RemoteScreenWindow(QDialog): annotation_event = Signal(str, int, int) closed = Signal() - def __init__(self, title: str, parent=None) -> None: + def __init__(self, title: str, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self.setWindowTitle(title) # Modeless: the operator can keep poking the control panel while @@ -127,12 +127,12 @@ def display(self) -> _FrameDisplay: # --- close handling -------------------------------------------------- - def closeEvent(self, event) -> None: # noqa: N802 Qt override + def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 Qt override self.closed.emit() super().closeEvent(event) -def make_remote_screen_window(parent=None) -> RemoteScreenWindow: +def make_remote_screen_window(parent: Optional[QWidget] = None) -> RemoteScreenWindow: """Factory that picks a sensible default title from the i18n table.""" return RemoteScreenWindow(_t("rd_remote_screen_title"), parent=parent) diff --git a/je_auto_control/gui/remote_desktop/tray_icon.py b/je_auto_control/gui/remote_desktop/tray_icon.py index e03d3eaf5..b79e5a3f5 100644 --- a/je_auto_control/gui/remote_desktop/tray_icon.py +++ b/je_auto_control/gui/remote_desktop/tray_icon.py @@ -73,7 +73,7 @@ def set_state(self, *, sessions: int) -> None: self._tray.setIcon(_build_icon(color)) self._tray.setToolTip(tip) - def _on_activated(self, reason) -> None: + def _on_activated(self, reason: QSystemTrayIcon.ActivationReason) -> None: if reason == QSystemTrayIcon.ActivationReason.Trigger: self.open_requested.emit() @@ -90,8 +90,8 @@ def hide(self) -> None: self._tray.hide() -def install_host_tray(*, on_open: Callable, on_stop: Callable, - on_quit: Callable, +def install_host_tray(*, on_open: Callable[[], None], on_stop: Callable[[], None], + on_quit: Callable[[], None], parent: Optional[QObject] = None) -> Optional[HostTrayIcon]: """Build a tray icon if the system supports it; return None otherwise.""" if not QSystemTrayIcon.isSystemTrayAvailable(): diff --git a/je_auto_control/gui/remote_desktop/viewer_screen_window.py b/je_auto_control/gui/remote_desktop/viewer_screen_window.py index 26d3ef5da..992a4ef77 100644 --- a/je_auto_control/gui/remote_desktop/viewer_screen_window.py +++ b/je_auto_control/gui/remote_desktop/viewer_screen_window.py @@ -9,8 +9,8 @@ from typing import Optional from PySide6.QtCore import Qt, Signal -from PySide6.QtGui import QImage -from PySide6.QtWidgets import QDialog, QVBoxLayout +from PySide6.QtGui import QCloseEvent, QImage +from PySide6.QtWidgets import QDialog, QVBoxLayout, QWidget from je_auto_control.gui.remote_desktop._helpers import _t from je_auto_control.gui.remote_desktop.frame_display import _FrameDisplay @@ -21,7 +21,7 @@ class ViewerScreenWindow(QDialog): closed = Signal() - def __init__(self, parent=None) -> None: + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self.setWindowTitle(_t("rd_webrtc_viewer_screen_title")) self.setModal(False) @@ -38,7 +38,7 @@ def set_image(self, image: Optional[QImage]) -> None: else: self._display.clear() - def closeEvent(self, event) -> None: # noqa: N802 Qt override + def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 Qt override self.closed.emit() super().closeEvent(event) diff --git a/je_auto_control/gui/run_history_tab.py b/je_auto_control/gui/run_history_tab.py index 48e414c2b..87966f9c2 100644 --- a/je_auto_control/gui/run_history_tab.py +++ b/je_auto_control/gui/run_history_tab.py @@ -1,10 +1,10 @@ """Run History tab: browse recorded runs, artifacts and explicit journal links.""" import datetime as _dt from pathlib import Path -from typing import List, Optional +from typing import Callable, List, Optional, Tuple from PySide6.QtCore import QTimer, Qt, QUrl -from PySide6.QtGui import QCloseEvent, QDesktopServices, QPixmap +from PySide6.QtGui import QCloseEvent, QDesktopServices, QPixmap, QResizeEvent from PySide6.QtWidgets import ( QAbstractItemView, QComboBox, QFrame, QHeaderView, QLabel, QMessageBox, QSplitter, QTableWidget, QTableWidgetItem, @@ -120,7 +120,7 @@ def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 # reason: Qt ov self.dispose() super().closeEvent(event) - def resizeEvent(self, event) -> None: + def resizeEvent(self, event: QResizeEvent) -> None: super().resizeEvent(event) self._refresh_preview() @@ -176,7 +176,7 @@ def _build_layout(self) -> None: set_role(self._count_label, "hint") root.addWidget(self._count_label) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("rh_refresh", self._refresh), @@ -220,7 +220,7 @@ def _refresh(self) -> None: self._timeline.set_records(runs) self._refresh_preview() - def _set_row(self, row: int, record) -> None: + def _set_row(self, row: int, record: RunRecord) -> None: status_key = _STATUS_LABEL_KEYS.get(record.status, record.status) status_text = _t(status_key) if record.error_text is None \ else f"{_t(status_key)}: {record.error_text}" diff --git a/je_auto_control/gui/scheduler_tab.py b/je_auto_control/gui/scheduler_tab.py index 4a1ef1c1b..de556bf7f 100644 --- a/je_auto_control/gui/scheduler_tab.py +++ b/je_auto_control/gui/scheduler_tab.py @@ -1,7 +1,8 @@ """Scheduler tab: register interval-based action JSON runs.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import QTimer +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QCheckBox, QFileDialog, QLabel, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, @@ -63,7 +64,7 @@ def sync_with_engine(self) -> None: self._timer.stop() self._apply_status() - def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt override """Catch up with an engine started or stopped elsewhere while hidden.""" super().showEvent(event) self.sync_with_engine() @@ -102,7 +103,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("browse", self._browse), diff --git a/je_auto_control/gui/script_builder/builder_tab.py b/je_auto_control/gui/script_builder/builder_tab.py index 5653c6670..4e2129bd7 100644 --- a/je_auto_control/gui/script_builder/builder_tab.py +++ b/je_auto_control/gui/script_builder/builder_tab.py @@ -15,7 +15,7 @@ import functools from contextlib import nullcontext import json -from typing import Callable, ContextManager, List, Optional, Sequence +from typing import Any, Callable, ContextManager, Dict, List, Optional, Sequence from PySide6.QtCore import Qt from PySide6.QtGui import QAction, QCloseEvent @@ -55,7 +55,7 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _run_actions(actions: list, collector: OneTimeCollector, +def _run_actions(actions: List[Any], collector: OneTimeCollector, capture: Callable[[], ContextManager[object]] = nullcontext) -> object: """Worker thread: execute the built action list, reporting each result to ``collector``. @@ -88,7 +88,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._add_btn: Optional[QToolButton] = None # The other top-level keys of a loaded {"auto_control": [...]} file, # written back on Save; None for a bare list. - self._file_extras: Optional[dict] = None + self._file_extras: Optional[Dict[str, Any]] = None self._source_path = "" self._capture = ManualRunControls() # The secrets of the last run, until they are revealed or the next run starts. diff --git a/je_auto_control/gui/selector/region_overlay.py b/je_auto_control/gui/selector/region_overlay.py index 2e4956436..973bf8387 100644 --- a/je_auto_control/gui/selector/region_overlay.py +++ b/je_auto_control/gui/selector/region_overlay.py @@ -5,10 +5,10 @@ result was still offset by the virtual desktop's origin, and Qt's logical coordinates are not the native pixels screenshots use on a scaled screen. """ -from typing import List, Optional +from typing import Any, Dict, List, Optional from PySide6.QtCore import QEventLoop, QPoint, QRect, Qt, Signal -from PySide6.QtGui import QColor, QKeyEvent, QMouseEvent, QPainter, QPen, QScreen +from PySide6.QtGui import QCloseEvent, QColor, QKeyEvent, QMouseEvent, QPaintEvent, QPainter, QPen, QScreen from PySide6.QtWidgets import QApplication, QWidget from je_auto_control.gui._screen_geometry import Region, native_region @@ -50,7 +50,7 @@ def _rect(self) -> QRect: return QRect() return QRect(self._origin, self._current).normalized() - def paintEvent(self, event) -> None: # noqa: N802 Qt override + def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 Qt override del event painter = QPainter(self) painter.fillRect(self.rect(), QColor(0, 0, 0, 90)) @@ -91,7 +91,7 @@ def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802 else: super().keyPressEvent(event) - def closeEvent(self, event) -> None: # noqa: N802 Qt override + def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 Qt override # Closed some other way (Alt+F4, the window manager): a cancel, so a # caller waiting for an answer is not left waiting. if not self._finished: @@ -118,7 +118,7 @@ def pick_region_blocking(parent: Optional[QWidget] = None) -> Optional[Region]: """ del parent overlays: List[RegionOverlay] = [RegionOverlay(screen) for screen in QApplication.screens()] - result: dict = {"region": None, "done": False} + result: Dict[str, Any] = {"region": None, "done": False} loop = QEventLoop() def finish(region: Optional[Region] = None) -> None: diff --git a/je_auto_control/gui/self_healing_tab.py b/je_auto_control/gui/self_healing_tab.py index 317abc4cf..f6fd226ef 100644 --- a/je_auto_control/gui/self_healing_tab.py +++ b/je_auto_control/gui/self_healing_tab.py @@ -4,7 +4,7 @@ audit log, or compare explicit versions on provided PNG samples without device effects. """ import json -from typing import Optional +from typing import Callable, Optional, Sequence from PySide6.QtCore import Qt from PySide6.QtGui import QCloseEvent @@ -126,7 +126,7 @@ def _build_form_group(self) -> QGroupBox: form.addRow(QLabel(), self._click_check) return group - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("self_heal_browse", self._on_browse_template), @@ -177,7 +177,7 @@ def _on_browse_template(self) -> None: if path: self._template_input.setText(path) - def _collect_inputs(self): + def _collect_inputs(self) -> Optional[tuple[Optional[str], Optional[str], float, Optional[list[int]]]]: template = self._template_input.text().strip() or None description = self._description_input.text().strip() or None if template is None and description is None: @@ -284,7 +284,7 @@ def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 # reason: Qt ov super().closeEvent(event) -def _format_coordinates(coords) -> str: +def _format_coordinates(coords: Optional[Sequence[int]]) -> str: if coords is None: return "" return f"({coords[0]}, {coords[1]})" diff --git a/je_auto_control/gui/template_candidate_panel.py b/je_auto_control/gui/template_candidate_panel.py index 6917a3aea..649d7387c 100644 --- a/je_auto_control/gui/template_candidate_panel.py +++ b/je_auto_control/gui/template_candidate_panel.py @@ -110,7 +110,7 @@ def _set_status(self, key: str, value: str = "") -> None: self._status_key, self._status_value = key, value self._status.setText(_t(key).replace("{value}", value)) - def _inputs_changed(self, *_args) -> None: + def _inputs_changed(self, *_args: object) -> None: if self._updating: return self.cancel() @@ -121,7 +121,7 @@ def _inputs_changed(self, *_args) -> None: self._details.clear() self._set_status("idle") - def _dataset_changed(self, *_args) -> None: + def _dataset_changed(self, *_args: object) -> None: if not self._updating: self.cancel() self._generation += 1 diff --git a/je_auto_control/gui/test_suite_tab.py b/je_auto_control/gui/test_suite_tab.py index 9aaf05896..d673e07d1 100644 --- a/je_auto_control/gui/test_suite_tab.py +++ b/je_auto_control/gui/test_suite_tab.py @@ -6,7 +6,7 @@ """ import functools import json -from typing import Any, Optional +from typing import Any, Callable, Optional from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -27,6 +27,7 @@ from je_auto_control.utils.quarantine import ( auto_quarantine_from_flakiness, default_quarantine_store, ) +from je_auto_control.utils.test_suite import TestSuiteResult _COLS = ("suite_col_case", "suite_col_status", "suite_col_time", "suite_col_message") @@ -91,7 +92,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("suite_load_file", self._on_load_file), @@ -104,7 +105,7 @@ def menu_actions(self) -> list: ("suite_q_clear", self._on_clear_quarantine), ] - def _parse_spec(self): + def _parse_spec(self) -> Any: return json.loads(self._spec.toPlainText() or "{}") def _on_load_file(self) -> None: @@ -145,7 +146,7 @@ def _show_run_error(self, error: object) -> None: return self._summary.setText(_t("suite_error").replace("{error}", str(error))) - def _render_result(self, result) -> None: + def _render_result(self, result: TestSuiteResult) -> None: self._table.setRowCount(len(result.cases)) for row, case in enumerate(result.cases): values = (case.name, case.status, f"{case.duration_s:.3f}s", diff --git a/je_auto_control/gui/usb_passthrough_prompt.py b/je_auto_control/gui/usb_passthrough_prompt.py index 2bbc2c236..f6074f5fa 100644 --- a/je_auto_control/gui/usb_passthrough_prompt.py +++ b/je_auto_control/gui/usb_passthrough_prompt.py @@ -22,7 +22,7 @@ from __future__ import annotations import threading -from typing import Optional +from typing import Any, Optional from PySide6.QtCore import QObject, Qt, Signal, Slot from PySide6.QtWidgets import ( @@ -123,7 +123,7 @@ def decide(self, vendor_id: str, product_id: str, *, viewer_id: Optional[str] = None, wait_timeout_s: float = 60.0) -> bool: """Worker-thread entry point. Blocks on the operator's choice.""" - result: dict = {"allow": False, "remember": False} + result: dict[str, bool] = {"allow": False, "remember": False} done = threading.Event() self._request.emit( vendor_id, product_id, serial or "", viewer_id or "", @@ -146,7 +146,7 @@ def decide(self, vendor_id: str, product_id: str, @Slot(str, str, str, str, object, object) def _show_dialog(self, vendor_id: str, product_id: str, serial: str, viewer_id: str, - result: dict, done: threading.Event) -> None: + result: dict[str, bool], done: threading.Event) -> None: dialog = UsbPassthroughPromptDialog( vendor_id=vendor_id, product_id=product_id, serial=serial or None, viewer_id=viewer_id or None, @@ -163,7 +163,7 @@ def _show_dialog(self, vendor_id: str, product_id: str, dialog.deleteLater() -def attach_prompt_to_session(session, *, +def attach_prompt_to_session(session: Any, *, acl: Optional[UsbAcl] = None, dialog_parent: Optional[QWidget] = None, ) -> PromptBridge: diff --git a/je_auto_control/gui/variables_tab.py b/je_auto_control/gui/variables_tab.py index 046f40f5f..64ab608a4 100644 --- a/je_auto_control/gui/variables_tab.py +++ b/je_auto_control/gui/variables_tab.py @@ -6,7 +6,7 @@ script that reads ``${var}`` placeholders. """ import json -from typing import Optional +from typing import Any, Callable, Optional from PySide6.QtWidgets import ( QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, @@ -89,7 +89,7 @@ def _build_layout(self) -> None: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("vars_refresh", self._refresh), @@ -110,7 +110,7 @@ def _refresh(self) -> None: ) @staticmethod - def _format_value(value) -> str: + def _format_value(value: Any) -> str: if isinstance(value, (dict, list, tuple)): try: return json.dumps(value, ensure_ascii=False) @@ -119,7 +119,7 @@ def _format_value(value) -> str: return repr(value) if isinstance(value, str) else str(value) @staticmethod - def _coerce_value(text: str): + def _coerce_value(text: str) -> Any: """Try JSON-decoding so '42' becomes int, fall back to raw string.""" stripped = text.strip() if not stripped: diff --git a/je_auto_control/gui/webhooks_tab.py b/je_auto_control/gui/webhooks_tab.py index 880fbbaad..31417b387 100644 --- a/je_auto_control/gui/webhooks_tab.py +++ b/je_auto_control/gui/webhooks_tab.py @@ -1,5 +1,5 @@ """Webhooks tab: bind HTTP requests to action scripts.""" -from typing import Optional +from typing import Callable, Optional from PySide6.QtCore import QTimer, Qt from PySide6.QtWidgets import ( @@ -115,7 +115,7 @@ def _build_layout(self) -> None: root.addWidget(Card().add(self._table, stretch=1), stretch=1) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("wh_start", self._on_start), @@ -160,7 +160,7 @@ def _on_browse(self) -> None: if path: self._script_input.setText(path) - def _selected_methods(self) -> list: + def _selected_methods(self) -> list[str]: return [m for m, c in self._method_checks.items() if c.isChecked()] def _on_register(self) -> None: diff --git a/je_auto_control/linux_wayland/_ctypes_bind.py b/je_auto_control/linux_wayland/_ctypes_bind.py index 573bf434f..55a8a8b91 100644 --- a/je_auto_control/linux_wayland/_ctypes_bind.py +++ b/je_auto_control/linux_wayland/_ctypes_bind.py @@ -15,7 +15,7 @@ #: ``(name, restype, argtypes)`` as ctypes wants them. -Prototype = Tuple[str, Any, tuple] +Prototype = Tuple[str, Any, Tuple[Any, ...]] class BoundSymbols: @@ -35,7 +35,7 @@ def __init__(self, lib: ctypes.CDLL, prototypes: Iterable[Prototype], *, # at the call site, so an argtypes tuple would be wrong here. self._fn[name] = getattr(lib, name) - def __getattr__(self, name: str): + def __getattr__(self, name: str) -> Any: try: return self._fn[name] except KeyError: diff --git a/je_auto_control/linux_wayland/_select_input.py b/je_auto_control/linux_wayland/_select_input.py index d91394417..82bb93c5c 100644 --- a/je_auto_control/linux_wayland/_select_input.py +++ b/je_auto_control/linux_wayland/_select_input.py @@ -12,16 +12,19 @@ from __future__ import annotations import os -from typing import Optional +from typing import TYPE_CHECKING, Callable, Optional from je_auto_control.linux_wayland._input_state import raise_if_input_blocked +if TYPE_CHECKING: + from je_auto_control.linux_wayland.ei_protocol import InputBackend + _ENV_OVERRIDE = "JE_AUTOCONTROL_WAYLAND_INPUT_BACKEND" _VALID = frozenset({"auto", "libei", "cli"}) -def select_input_backend(environ: Optional[dict] = None) -> str: +def select_input_backend(environ: Optional[dict[str, str]] = None) -> str: """Return one of ``"libei"`` or ``"cli"`` based on env + libei probe.""" env = environ if environ is not None else os.environ forced = (env.get(_ENV_OVERRIDE) or "auto").strip().lower() @@ -51,7 +54,7 @@ def _libei_loadable() -> bool: return False -def active_backend(): +def active_backend() -> Optional[InputBackend]: """Return a connected libei backend, or None to use the ydotool CLI. The single entry point ``keyboard`` and ``mouse`` use. It lives here @@ -82,7 +85,7 @@ def _refuse_required(error: BaseException) -> None: raise LibeiUnavailable(str(error), fallback_allowed=False) from error -def emitted(backend, send) -> bool: +def emitted(backend: InputBackend, send: Callable[..., object]) -> bool: """Run one emission on ``backend``; False means the CLI has to take it. Unclassified optional-backend misses retain their legacy auto fallback. diff --git a/je_auto_control/linux_wayland/listener.py b/je_auto_control/linux_wayland/listener.py index d2e77b260..16b4d59dd 100644 --- a/je_auto_control/linux_wayland/listener.py +++ b/je_auto_control/linux_wayland/listener.py @@ -17,8 +17,10 @@ """ from __future__ import annotations +from typing import Any, NoReturn -def check_key_press(*_args, **_kwargs): + +def check_key_press(*_args: Any, **_kwargs: Any) -> NoReturn: """Wayland clients cannot read the global key state. Raise explicitly.""" raise NotImplementedError( "Wayland forbids global key-state queries from unprivileged " @@ -30,7 +32,7 @@ def check_key_press(*_args, **_kwargs): ) -def hook_keyboard(*_args, **_kwargs): +def hook_keyboard(*_args: Any, **_kwargs: Any) -> NoReturn: """Wayland clients cannot install a global key hook.""" raise NotImplementedError( "Wayland forbids global key hooks. See check_key_press for " diff --git a/je_auto_control/linux_wayland/mouse.py b/je_auto_control/linux_wayland/mouse.py index 59b74d6e1..45037c11f 100644 --- a/je_auto_control/linux_wayland/mouse.py +++ b/je_auto_control/linux_wayland/mouse.py @@ -13,7 +13,7 @@ import subprocess # nosec B404 # reason: argv-list, no shell interpolation import time from functools import lru_cache -from typing import Mapping, Optional, Tuple +from typing import TYPE_CHECKING, Any, Mapping, Optional, Tuple from je_auto_control.linux_wayland._detect import WAYLAND_YDOTOOL, binary_path from je_auto_control.linux_wayland._layout import layout_origin @@ -23,6 +23,9 @@ from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger +if TYPE_CHECKING: + from je_auto_control.linux_wayland.ei_protocol import InputBackend + # ydotool ``click`` accepts hex bitmasks: the low nibble selects the # button (0 left, 1 right, 2 middle) and the high bits toggle the edge — @@ -56,7 +59,7 @@ def _require_ydotool() -> str: return reject_legacy_cli(path) -def _run(argv: list, *, timeout: float = 5.0) -> None: +def _run(argv: list[str], *, timeout: float = 5.0) -> None: # argv comes from a private allow-list (ydotool absolute path via # shutil.which), never user input; no shell=True. try: @@ -216,7 +219,7 @@ def _warn_about_acceleration() -> None: _warn_once(_ACCELERATION_WARNING) -def _try_libei(): +def _try_libei() -> Optional[InputBackend]: """Return a connected :class:`LibeiBackend`, or None when CLI should win.""" try: from je_auto_control.linux_wayland._select_input import active_backend @@ -368,7 +371,7 @@ def scroll(scroll_value: int, "-x", str(delta_x), "-y", str(delta_y)]) -def send_mouse_event_to_window(*_args, **_kwargs) -> None: +def send_mouse_event_to_window(*_args: Any, **_kwargs: Any) -> None: """Wayland has no per-window mouse injection.""" raise NotImplementedError( "Wayland forbids per-window mouse injection (no XSendEvent " diff --git a/je_auto_control/linux_with_x11/record/x11_linux_record.py b/je_auto_control/linux_with_x11/record/x11_linux_record.py index fd7588fe2..3048a33b7 100644 --- a/je_auto_control/linux_with_x11/record/x11_linux_record.py +++ b/je_auto_control/linux_with_x11/record/x11_linux_record.py @@ -39,9 +39,9 @@ class X11LinuxRecorder: - 將原始事件轉換成可讀的動作序列 """ - def __init__(self): - self.record_queue: Queue | None = None - self.result_queue: Queue | None = None + def __init__(self) -> None: + self.record_queue: Queue[tuple[int, int, int, int]] | None = None + self.result_queue: Queue[tuple[int, int, int, int]] | None = None @property def is_recording(self) -> bool: diff --git a/je_auto_control/utils/accessibility/element.py b/je_auto_control/utils/accessibility/element.py index fe9cf057e..f4d9e2ed7 100644 --- a/je_auto_control/utils/accessibility/element.py +++ b/je_auto_control/utils/accessibility/element.py @@ -1,6 +1,6 @@ """Shared dataclasses and exceptions for the accessibility API.""" from dataclasses import dataclass -from typing import Any, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException @@ -27,7 +27,7 @@ def center(self) -> Tuple[int, int]: left, top, width, height = self.bounds return (left + width // 2, top + height // 2) - def to_dict(self) -> dict: + def to_dict(self) -> Dict[str, Any]: return { "name": self.name, "role": self.role, "bounds": list(self.bounds), @@ -133,7 +133,7 @@ def rank_by_name(elements: List[AccessibilityElement], """ needle = (name or "").strip().lower() - def _key(element: AccessibilityElement): + def _key(element: AccessibilityElement) -> Tuple[bool, bool, int, int]: left, top, _width, _height = element.bounds # Nothing to click first: an empty rectangle sorted ahead of every # visible match on (top, left) = (0, 0). diff --git a/je_auto_control/utils/acme_v2/client.py b/je_auto_control/utils/acme_v2/client.py index 70f32532d..e7fbbb19c 100644 --- a/je_auto_control/utils/acme_v2/client.py +++ b/je_auto_control/utils/acme_v2/client.py @@ -278,7 +278,7 @@ def _signed_post(self, url: str, payload: Optional[Mapping[str, Any]], *, use_jwk: bool = False, accept: Optional[str] = None, - ) -> tuple: + ) -> tuple[int, Any, Dict[str, str]]: status, parsed, headers = self._post_once( url, payload, use_jwk=use_jwk, accept=accept, ) @@ -293,7 +293,7 @@ def _signed_post(self, url: str, def _post_once(self, url: str, payload: Optional[Mapping[str, Any]], - *, use_jwk: bool, accept: Optional[str]) -> tuple: + *, use_jwk: bool, accept: Optional[str]) -> tuple[int, Any, Dict[str, str]]: """Sign and POST once; cache the server's next Replay-Nonce.""" nonce = self._nonce or self._fresh_nonce() self._nonce = None @@ -323,7 +323,7 @@ def _http(self, method: str, url: str, *, body: Optional[bytes] = None, content_type: Optional[str] = None, accept: Optional[str] = None, - ) -> tuple: + ) -> tuple[int, Any, Dict[str, str]]: headers = {"User-Agent": _USER_AGENT} if content_type: headers["Content-Type"] = content_type diff --git a/je_auto_control/utils/action_lint/linter.py b/je_auto_control/utils/action_lint/linter.py index bff26d888..497061390 100644 --- a/je_auto_control/utils/action_lint/linter.py +++ b/je_auto_control/utils/action_lint/linter.py @@ -110,7 +110,7 @@ def _lint_item(self, idx: int, item: Any, trail: str = "") -> List[LintIssue]: for i in self._check_required(idx, name, params)] + self._lint_bodies(idx, name, params, trail) @staticmethod - def _shape_issue(item: Any) -> Optional[tuple]: + def _shape_issue(item: Any) -> Optional[tuple[str, str]]: """``(code, message)`` when ``item`` is not ``[name]`` / ``[name, params]``.""" if not isinstance(item, (list, tuple)): return "bad-shape", "action item must be a list [command_name, params]" @@ -170,7 +170,7 @@ def _check_required(self, idx: int, name: str, @staticmethod def _scan_signature(sig: inspect.Signature, params: Dict[str, Any], - ) -> tuple: + ) -> tuple[List[str], List[str], bool]: """Walk a Signature → (accepted_names, missing_required, accepts_kwargs).""" accepted: List[str] = [] missing: List[str] = [] diff --git a/je_auto_control/utils/admin/admin_client.py b/je_auto_control/utils/admin/admin_client.py index 0c1a51eb2..08d0c4942 100644 --- a/je_auto_control/utils/admin/admin_client.py +++ b/je_auto_control/utils/admin/admin_client.py @@ -16,10 +16,11 @@ import threading import time import urllib.request +from email.message import Message from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, dataclass, field from pathlib import Path -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, IO, List, Optional from je_auto_control.utils.exception.cancellation import CancellationToken, current_cancellation_token from je_auto_control.utils.json_store.json_store import load_json_or_quarantine, quarantine_file @@ -51,7 +52,8 @@ class _RefuseRedirects(urllib.request.HTTPRedirectHandler): a host redirected -- another origin, or https downgraded to http. """ - def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102 + def redirect_request(self, req: urllib.request.Request, fp: IO[bytes], code: int, msg: str, + headers: Message, newurl: str) -> None: # noqa: D102 return None @@ -159,7 +161,7 @@ def fetch_thumbnails(self, *, labels: Optional[List[str]] = None, if not targets: return {} - def grab(host: AdminHost) -> tuple: + def grab(host: AdminHost) -> tuple[str, Optional[bytes]]: try: body = self._http_get(host, "/screenshot") except (OSError, ValueError, http.client.HTTPException) as error: diff --git a/je_auto_control/utils/agent_runtime/android_scope.py b/je_auto_control/utils/agent_runtime/android_scope.py index 9df0937e2..d8a0ef629 100644 --- a/je_auto_control/utils/agent_runtime/android_scope.py +++ b/je_auto_control/utils/agent_runtime/android_scope.py @@ -3,6 +3,7 @@ import re from dataclasses import dataclass +from typing import Any from je_auto_control.utils.agent_runtime.errors import AgentTaskError @@ -59,14 +60,14 @@ def __post_init__(self) -> None: or int(activity[1]) != self.user or activity[2] != self.package): raise AgentTaskError("Android window/activity is outside its device-user/app scope") - def identity(self) -> dict: + def identity(self) -> dict[str, Any]: """Return detached scope metadata, excluding raw remote diagnostics or control text.""" return {"platform": "android", "physical_id": self.physical_id, "boot_id": self.boot_id, "package": self.package, "user": self.user, "display": 0, "window": self.window, "activity": self.activity} -def _record(value: str, pattern: re.Pattern) -> re.Match | None: +def _record(value: str, pattern: re.Pattern[str]) -> re.Match[str] | None: return pattern.fullmatch(value) if isinstance(value, str) and len(value) <= 512 else None diff --git a/je_auto_control/utils/agent_runtime/browser_retirement.py b/je_auto_control/utils/agent_runtime/browser_retirement.py index 4980917cb..2af909f80 100644 --- a/je_auto_control/utils/agent_runtime/browser_retirement.py +++ b/je_auto_control/utils/agent_runtime/browser_retirement.py @@ -9,7 +9,7 @@ _UNCONFIRMED = "browser retirement is unconfirmed" -def retirement_proof(value: Any, context_id: str | None = None) -> dict: +def retirement_proof(value: Any, context_id: str | None = None) -> dict[str, Any]: """Validate a closed proof from the already owned helper, optionally pinning its actual context.""" fields = {"contract", "input_supported", "network_retired", "context_id"} if not isinstance(value, dict) or set(value) != fields: @@ -29,7 +29,7 @@ def _require_context(identity: Any, context_id: str | None) -> None: raise AgentTaskError("browser retirement context is unconfirmed") -def refuse_browser_input(_event: dict) -> NoReturn: +def refuse_browser_input(_event: dict[str, Any]) -> NoReturn: """Fail before the owned channel can acknowledge any unexpected native input event.""" raise AgentTaskError("read-only browser cannot acknowledge input") diff --git a/je_auto_control/utils/agent_runtime/browser_transfers.py b/je_auto_control/utils/agent_runtime/browser_transfers.py index bdb152463..e2619071c 100644 --- a/je_auto_control/utils/agent_runtime/browser_transfers.py +++ b/je_auto_control/utils/agent_runtime/browser_transfers.py @@ -56,7 +56,7 @@ def _same_file(path: Path, opened: os.stat_result) -> None: raise AgentTaskError("browser upload file identity changed") -def sdk_transfer(session: Any, operation: str, arguments: dict) -> Any: +def sdk_transfer(session: Any, operation: str, arguments: dict[str, Any]) -> Any: """Use only the SDK transfer contract; no browser engine or ambient HTTP client is imported.""" if operation == "link": url = session.link(arguments["selector"], arguments["frame"]) @@ -85,10 +85,10 @@ def sdk_transfer(session: Any, operation: str, arguments: dict) -> Any: return metadata -def _receive_download(session: Any, url: str, path: Path, expected: str) -> dict: +def _receive_download(session: Any, url: str, path: Path, expected: str) -> dict[str, Any]: # Keep host authority/cancellation errors out of the foreign SDK's broad context-manager containment. failure: BaseException | None = None - result: dict = {} + result: dict[str, Any] = {} try: with session.open_download(url) as response: try: diff --git a/je_auto_control/utils/agent_runtime/cli.py b/je_auto_control/utils/agent_runtime/cli.py index 889ab6608..1ddc9a51b 100644 --- a/je_auto_control/utils/agent_runtime/cli.py +++ b/je_auto_control/utils/agent_runtime/cli.py @@ -114,13 +114,13 @@ def run(arguments: argparse.Namespace) -> dict[str, Any]: return AgentRuntimeClient().call(operation, body) -def _lookup(arguments: argparse.Namespace) -> dict: +def _lookup(arguments: argparse.Namespace) -> dict[str, Any]: if arguments.lookup_spec: return api.lookup_agent_task(arguments.idempotency_key, _read(arguments.lookup_spec)) return api.lookup_agent_task(arguments.idempotency_key) -def _draft(arguments: argparse.Namespace) -> dict: +def _draft(arguments: argparse.Namespace) -> dict[str, Any]: from je_auto_control.utils.agent_runtime.workflow_specs import draft_agent_workflow return {"draft": draft_agent_workflow(arguments.workflow, _read(arguments.config))} diff --git a/je_auto_control/utils/agent_runtime/completion_contract.py b/je_auto_control/utils/agent_runtime/completion_contract.py index e45a47855..e2fd57142 100644 --- a/je_auto_control/utils/agent_runtime/completion_contract.py +++ b/je_auto_control/utils/agent_runtime/completion_contract.py @@ -10,7 +10,8 @@ 'reviewer', 'source_owner', 'effect_owner'} -def decode_private_object(value: str, message: str, *, error_type: type[AgentTaskError] = AgentTaskError) -> dict: +def decode_private_object(value: str, message: str, *, + error_type: type[AgentTaskError] = AgentTaskError) -> dict[str, Any]: """Decode a private JSON object with a typed refusal before any task capability is selected.""" try: details = json.loads(value) @@ -21,7 +22,7 @@ def decode_private_object(value: str, message: str, *, error_type: type[AgentTas return details -def decode_completion_binding(value: str) -> dict: +def decode_completion_binding(value: str) -> dict[str, Any]: """Reject corrupt private completion markers without converting them to ordinary task admission.""" details = decode_private_object(value, 'invalid private completion binding') if set(details) != _BINDING_FIELDS: diff --git a/je_auto_control/utils/agent_runtime/dag_jobs.py b/je_auto_control/utils/agent_runtime/dag_jobs.py index 29bbf731e..0b0c1e9ad 100644 --- a/je_auto_control/utils/agent_runtime/dag_jobs.py +++ b/je_auto_control/utils/agent_runtime/dag_jobs.py @@ -17,7 +17,7 @@ _ERRORS = (AutoControlException, OSError, RuntimeError, TypeError, ValueError, LookupError) -def fence_delivery(runtime: Any, started: dict) -> None: +def fence_delivery(runtime: Any, started: dict[str, Any]) -> None: """Retire only this delivery's scheduling attempt, preserving all node delivery evidence.""" # pylint: disable-next=protected-access # reason: serialize internal retirement with public batch transitions with runtime._lock("dag:" + started["batch_id"]), runtime.store.connection(write=True) as connection: @@ -46,7 +46,7 @@ def enable(self) -> None: with self._lock: self._enabled = True - def enqueue(self, started: dict, owner: dict, actor: DeferredAuthorization) -> None: + def enqueue(self, started: dict[str, Any], owner: dict[str, Any], actor: DeferredAuthorization) -> None: """Persist one already-authorized attempt; never reset a previous delivery or node claim.""" data = {"started": started, "owner": owner, "actor": asdict(actor.context) if actor.context is not None else {}} @@ -130,7 +130,7 @@ def close(self) -> None: ("service stopped; explicit DAG review required", time.time())) -def delivery_status(runtime: Any, batch_id: str) -> dict | None: +def delivery_status(runtime: Any, batch_id: str) -> dict[str, Any] | None: """Publish bounded delivery state, withholding stored authority and coordination capabilities.""" with runtime.store.connection() as connection: if connection.execute("SELECT 1 FROM sqlite_master WHERE name='work_items'").fetchone() is None: diff --git a/je_auto_control/utils/agent_runtime/dag_service_client.py b/je_auto_control/utils/agent_runtime/dag_service_client.py index d1b11a32f..de2c29c56 100644 --- a/je_auto_control/utils/agent_runtime/dag_service_client.py +++ b/je_auto_control/utils/agent_runtime/dag_service_client.py @@ -11,7 +11,7 @@ class DagServiceClient: """Never consult a process-global connection file for a service's local managed destinations.""" - def __init__(self, runtime: Any, delivery: dict) -> None: + def __init__(self, runtime: Any, delivery: dict[str, Any]) -> None: self.runtime, self.started = runtime, delivery["started"] self.owner = DeferredAuthorization(AuthorizationContext(**delivery["owner"]) if delivery["owner"] else None) self.actor = DeferredAuthorization(AuthorizationContext(**delivery["actor"]) if delivery["actor"] else None) @@ -24,7 +24,7 @@ def check(self) -> None: if row is None or row["state"] != "running" or row["attempt"] != self.started["attempt"]: raise AgentTaskError("background DAG attempt is inactive") - def call(self, operation: str, body: dict | None = None, *, timeout: float = 30) -> dict: + def call(self, operation: str, body: dict[str, Any] | None = None, *, timeout: float = 30) -> dict[str, Any]: """Use only the closed coordinator protocol on this owning runtime.""" del timeout if operation != "dag" or not isinstance(body, dict) or set(body) != {"operation", "request"}: @@ -33,7 +33,7 @@ def call(self, operation: str, body: dict | None = None, *, timeout: float = 30) with self.actor.scope(): return self.runtime.batches.control(body["operation"], body["request"]) - def task_call(self, operation: str, body: dict, timeout: float) -> dict: + def task_call(self, operation: str, body: dict[str, Any], timeout: float) -> dict[str, Any]: """Route finite destination operations locally; owned pause remains available for retirement.""" del timeout if operation not in {"submit", "get", "lookup", "pause"}: diff --git a/je_auto_control/utils/agent_runtime/helper_owner_linux.py b/je_auto_control/utils/agent_runtime/helper_owner_linux.py index 8bb35bb8b..eaa185522 100644 --- a/je_auto_control/utils/agent_runtime/helper_owner_linux.py +++ b/je_auto_control/utils/agent_runtime/helper_owner_linux.py @@ -349,7 +349,7 @@ def _next_line(self, deadline: float, check: Callable[[], None]) -> Any: raise TimeoutError def _receive(self, request_id: str, deadline: float, check: Callable[[], None], - on_event: Callable[[dict], None] | None, operation: str) -> Any: + on_event: Callable[[dict[str, Any]], None] | None, operation: str) -> Any: try: while True: message = self._next_line(deadline, check) @@ -373,7 +373,7 @@ def _receive(self, request_id: str, deadline: float, check: Callable[[], None], def request(self, operation: str, payload: Any, *, timeout: float, check: Callable[[], None] = cancellation_checkpoint, - on_event: Callable[[dict], None] | None = None) -> Any: + on_event: Callable[[dict[str, Any]], None] | None = None) -> Any: """Validate one proposal, wait within its deadline, and retire the helper on every failed operation.""" positive(timeout, "native deadline", 3600) deadline = time.monotonic() + timeout diff --git a/je_auto_control/utils/agent_runtime/manifest_evidence.py b/je_auto_control/utils/agent_runtime/manifest_evidence.py index 1a80aa9cc..8029b2396 100644 --- a/je_auto_control/utils/agent_runtime/manifest_evidence.py +++ b/je_auto_control/utils/agent_runtime/manifest_evidence.py @@ -3,13 +3,13 @@ import json from pathlib import Path -from typing import Mapping +from typing import Any, Mapping from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.policy import TaskPolicy -def manifest_matches(clause: Mapping, policy: TaskPolicy) -> bool: +def manifest_matches(clause: Mapping[str, Any], policy: TaskPolicy) -> bool: """Require exact reviewed filenames, paths, sizes and current content digests, within read bounds.""" manifest = Path(policy.path(clause["path"])) if not manifest.is_file(): @@ -25,7 +25,7 @@ def manifest_matches(clause: Mapping, policy: TaskPolicy) -> bool: return _files_match(entries, names, clause, policy) -def _files_match(entries: list, names: list[str], clause: Mapping, policy: TaskPolicy) -> bool: +def _files_match(entries: list[Any], names: list[str], clause: Mapping[str, Any], policy: TaskPolicy) -> bool: from je_auto_control.utils.agent_runtime.workflow_files import _destination, _entry total = 0 for name, entry in zip(names, entries): @@ -40,7 +40,7 @@ def _files_match(entries: list, names: list[str], clause: Mapping, policy: TaskP return True -def validate_manifest_clause(clause: Mapping) -> None: +def validate_manifest_clause(clause: Mapping[str, Any]) -> None: """Reject incomplete or duplicate manifest filename contracts before executing a task.""" names = clause.get("names") if not isinstance(names, (tuple, list)) or not 1 <= len(names) <= 500: diff --git a/je_auto_control/utils/agent_runtime/model_tools.py b/je_auto_control/utils/agent_runtime/model_tools.py index 1c124e211..23fa8a8bb 100644 --- a/je_auto_control/utils/agent_runtime/model_tools.py +++ b/je_auto_control/utils/agent_runtime/model_tools.py @@ -17,7 +17,7 @@ ]} -def offered_tools(names: Sequence[str]) -> list[dict]: +def offered_tools(names: Sequence[str]) -> list[dict[str, Any]]: """Clone offered schemas and add a host-resolved target option only to reviewed point tools.""" from je_auto_control.utils.tool_use_schema import export_openai_tools from je_auto_control.utils.agent_runtime.commands import CATALOG @@ -51,7 +51,7 @@ def _point_schema(function: dict[str, Any]) -> None: ]}) -def referenced_proposal(name: str, arguments: dict) -> dict: +def referenced_proposal(name: str, arguments: dict[str, Any]) -> dict[str, Any]: """Separate reserved model reference data from real executor keyword arguments.""" arguments = detached(arguments) reference = arguments.pop("observed_target", None) diff --git a/je_auto_control/utils/agent_runtime/native_scope.py b/je_auto_control/utils/agent_runtime/native_scope.py index 88a2c5ca0..57357cf78 100644 --- a/je_auto_control/utils/agent_runtime/native_scope.py +++ b/je_auto_control/utils/agent_runtime/native_scope.py @@ -11,7 +11,7 @@ from je_auto_control.utils.agent_runtime.models import AgentTaskSpec -def check_pointer(hwnd: int, event: dict) -> None: +def check_pointer(hwnd: int, event: dict[str, Any]) -> None: """Require coordinates within the actual owned window; no desktop-wide fallback.""" if sys.platform != "win32": raise AgentTaskError("window-scoped pointer geometry needs a platform adapter") @@ -42,7 +42,7 @@ def _point_window(x: int, y: int) -> int | None: return int(user.GetAncestor(hit, 2) or 0) if hit else None # GA_ROOT retains owned child controls. -def check_window_arguments(arguments: dict, spec: AgentTaskSpec | None) -> None: +def check_window_arguments(arguments: dict[str, Any], spec: AgentTaskSpec | None) -> None: """Reject ambiguous or foreign explicit window selections before native dispatch.""" from je_auto_control.wrapper.auto_control_window import list_windows, window_process_id for name in ("title", "title_substring", "window_title"): diff --git a/je_auto_control/utils/agent_runtime/origin_policy.py b/je_auto_control/utils/agent_runtime/origin_policy.py index bd15c812c..2970f9a5a 100644 --- a/je_auto_control/utils/agent_runtime/origin_policy.py +++ b/je_auto_control/utils/agent_runtime/origin_policy.py @@ -64,7 +64,7 @@ def current_origin() -> str | None: return ",".join(origins) if origins else None -def origin_ceilings(retained: tuple[str, ...] | list[str] = ()) -> list[dict]: +def origin_ceilings(retained: tuple[str, ...] | list[str] = ()) -> list[dict[str, Any]]: """Read retained and current live ceilings for non-task operations without granting task authority.""" if not isinstance(retained, (tuple, list)) or len(retained) > 16: raise AgentTaskError('retained origin ceilings require at most sixteen policies') @@ -164,7 +164,7 @@ def review_origin_policies(spec: AgentTaskSpec) -> dict[str, Any]: return {"source": list(source), "current": current, "retained": retained, "unavailable": unavailable} -def _origin_record(identifier: str) -> dict: +def _origin_record(identifier: str) -> dict[str, Any]: return {"id": identifier, "roots": _read(identifier)["roots"]} @@ -177,7 +177,7 @@ def _identifiers(spec: AgentTaskSpec) -> tuple[str, ...]: return tuple(identifiers) -def _read(identifier: str) -> dict: +def _read(identifier: str) -> dict[str, Any]: path = _path(identifier) try: if path.is_symlink() or path.stat().st_size > 65536: diff --git a/je_auto_control/utils/agent_runtime/presence_channel_linux.py b/je_auto_control/utils/agent_runtime/presence_channel_linux.py index a30e804d1..5eb6d9005 100644 --- a/je_auto_control/utils/agent_runtime/presence_channel_linux.py +++ b/je_auto_control/utils/agent_runtime/presence_channel_linux.py @@ -11,7 +11,7 @@ import sys import threading import time -from typing import Generic, Iterator, TypeVar +from typing import Any, Generic, Iterator, TypeVar from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.presence_endpoint_linux import LinuxEndpoint, _EndpointCheck, _EndpointFiles @@ -318,7 +318,7 @@ def fileno(self) -> int: with self._owner.operation(_deadline(1), None) as resources: return resources.connection.fileno() - def receive(self, *, timeout: float, cancel: threading.Event | None = None) -> dict: + def receive(self, *, timeout: float, cancel: threading.Event | None = None) -> dict[str, Any]: """Receive one finite JSON object from the still-live original writer.""" deadline = _deadline(timeout) with self._owner.operation(deadline, cancel) as resources: @@ -329,7 +329,7 @@ def receive(self, *, timeout: float, cancel: threading.Event | None = None) -> d except (BlockingIOError, InterruptedError): continue - def send(self, frame: dict, *, timeout: float, cancel: threading.Event | None = None) -> None: + def send(self, frame: dict[str, Any], *, timeout: float, cancel: threading.Event | None = None) -> None: """Send exactly one packet while retaining the original live peer.""" deadline = _deadline(timeout) with self._owner.operation(deadline, cancel) as resources: diff --git a/je_auto_control/utils/agent_runtime/presence_handshake.py b/je_auto_control/utils/agent_runtime/presence_handshake.py index cc69aea3a..e79be470b 100644 --- a/je_auto_control/utils/agent_runtime/presence_handshake.py +++ b/je_auto_control/utils/agent_runtime/presence_handshake.py @@ -17,7 +17,7 @@ _PROOF = {'protocol', 'server_challenge', 'challenge', 'birth'} -def _receive(connection: Any, fields: set[str]) -> dict: +def _receive(connection: Any, fields: set[str]) -> dict[str, Any]: value = decode_frame(connection.recv_bytes(4096)) if set(value) != fields or unsigned(value.get('protocol'), 1, 1) != 1: raise AgentTaskError('physical presence handshake fields are invalid') @@ -27,7 +27,7 @@ def _receive(connection: Any, fields: set[str]) -> dict: return value -def _verify(value: dict, peer: PeerProcess, challenge: str, field: str = 'challenge') -> None: +def _verify(value: dict[str, Any], peer: PeerProcess, challenge: str, field: str = 'challenge') -> None: if value[field] != challenge or value['birth'] != peer.identity.birth or not peer.alive(): raise AgentTaskError('physical presence live peer challenge failed') diff --git a/je_auto_control/utils/agent_runtime/presence_owner.py b/je_auto_control/utils/agent_runtime/presence_owner.py index 4b3ca6066..74aa8effe 100644 --- a/je_auto_control/utils/agent_runtime/presence_owner.py +++ b/je_auto_control/utils/agent_runtime/presence_owner.py @@ -7,7 +7,7 @@ from je_auto_control.utils.agent_runtime.presence_frames import decode_frame, encode_frame, identifier -def read_request(source: Any) -> dict | None: +def read_request(source: Any) -> dict[str, Any] | None: """Require a complete bounded line before accepting any owner operation.""" line = source.readline(4097) if not line: @@ -23,7 +23,7 @@ def read_request(source: Any) -> dict | None: return request -def send_result(sink: Any, request_id: str, result: dict) -> None: +def send_result(sink: Any, request_id: str, result: dict[str, Any]) -> None: """Return only a closed JSON result over the owner's existing stream.""" _write(sink, {'id': request_id, 'result': result}) @@ -33,6 +33,6 @@ def send_error(sink: Any, request_id: str, error: BaseException) -> None: _write(sink, {'id': request_id, 'error': type(error).__name__, 'error_type': type(error).__name__}) -def _write(sink: Any, packet: dict) -> None: +def _write(sink: Any, packet: dict[str, Any]) -> None: sink.write(encode_frame(packet) + b'\n') sink.flush() diff --git a/je_auto_control/utils/agent_runtime/presence_protocol.py b/je_auto_control/utils/agent_runtime/presence_protocol.py index 23cbfaea3..81aa27ca4 100644 --- a/je_auto_control/utils/agent_runtime/presence_protocol.py +++ b/je_auto_control/utils/agent_runtime/presence_protocol.py @@ -31,7 +31,7 @@ def _outcome(self) -> str: live = {'monitoring', 'waiting_idle', 'locked'} return 'lease_lost' if isinstance(status, dict) and status.get('state') in live else 'source_lost' - def _operation(self, operation: str, body: dict) -> dict: + def _operation(self, operation: str, body: dict[str, Any]) -> dict[str, Any]: if operation == 'release': if self._issued.get(body['lease_id']) != body['generation']: raise AgentTaskError('physical presence token is not owned by this connection') @@ -40,7 +40,7 @@ def _operation(self, operation: str, body: dict) -> dict: return {'released': True} return self._source.request(operation, body) - def request(self, value: dict) -> dict: + def request(self, value: dict[str, Any]) -> dict[str, Any]: """Dispatch one sequential closed request, returning expected gate outcomes as normal data.""" with self._mutex: if self._closed: diff --git a/je_auto_control/utils/agent_runtime/presence_reader.py b/je_auto_control/utils/agent_runtime/presence_reader.py index 0c689d849..6a64f1fd4 100644 --- a/je_auto_control/utils/agent_runtime/presence_reader.py +++ b/je_auto_control/utils/agent_runtime/presence_reader.py @@ -48,8 +48,8 @@ class _Lifetime: class PresenceReader: """One permanent lease binding; only its private I/O owner touches blocking native resources.""" - def __init__(self, binding: dict, takeover: Callable[[], None], *, pipe: Any = None, - security: Any = None, endpoint: dict | None = None) -> None: + def __init__(self, binding: dict[str, Any], takeover: Callable[[], None], *, pipe: Any = None, + security: Any = None, endpoint: dict[str, Any] | None = None) -> None: self._binding = presence_body('check', binding) self._takeover = takeover if pipe is None: diff --git a/je_auto_control/utils/agent_runtime/presence_server.py b/je_auto_control/utils/agent_runtime/presence_server.py index 0bb9e6775..ecb62f138 100644 --- a/je_auto_control/utils/agent_runtime/presence_server.py +++ b/je_auto_control/utils/agent_runtime/presence_server.py @@ -41,7 +41,7 @@ def __init__(self, source_factory: Callable[[], Any] = WindowsPresenceSource, *, self._mutex = threading.RLock() self._attempted = False - def start(self) -> dict: + def start(self) -> dict[str, Any]: """Start once, only after first-instance ownership; an occupied endpoint never starts a source.""" with self._mutex: if self._attempted or self._life.stop.is_set(): @@ -67,7 +67,7 @@ def start(self) -> dict: self.close() raise - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Read coarse process-local diagnostics without starting native resources or granting a lease.""" with self._mutex: thread = self._life.acceptor diff --git a/je_auto_control/utils/agent_runtime/presence_worker.py b/je_auto_control/utils/agent_runtime/presence_worker.py index 70c2e77b5..4f3bcf83d 100644 --- a/je_auto_control/utils/agent_runtime/presence_worker.py +++ b/je_auto_control/utils/agent_runtime/presence_worker.py @@ -24,7 +24,7 @@ def __init__(self, namespace: str | None = None, *, self._channel: Any = None self._started = False - def start(self) -> dict: + def start(self) -> dict[str, Any]: """The fixed child is contained before it receives the internal source bootstrap.""" if self._started: raise AgentTaskError('physical presence source process cannot restart') @@ -45,7 +45,7 @@ def close(self) -> None: self._channel = None -def _namespace(payload: dict) -> str | None: +def _namespace(payload: dict[str, Any]) -> str | None: if set(payload) != {'namespace'}: raise AgentTaskError('physical presence source bootstrap fields are invalid') value = payload['namespace'] diff --git a/je_auto_control/utils/agent_runtime/receipts.py b/je_auto_control/utils/agent_runtime/receipts.py index 015276d1d..571bc70c7 100644 --- a/je_auto_control/utils/agent_runtime/receipts.py +++ b/je_auto_control/utils/agent_runtime/receipts.py @@ -34,7 +34,7 @@ def reconcile(store: Any, task_id: str, request: Mapping[str, Any]) -> None: _commit_review(store, task_id, value) -def _commit_review(store: Any, task_id: str, value: dict) -> None: +def _commit_review(store: Any, task_id: str, value: dict[str, Any]) -> None: identity = current_authorization() with store.connection(write=True) as connection: action = connection.execute("SELECT status,result FROM agent_actions WHERE id=? AND task_id=?", @@ -64,7 +64,7 @@ def row_report(spec: AgentTaskSpec, receipts: Sequence[Mapping[str, Any]]) -> li return [{"row": label, "status": _row_state(states)} for label, states in rows.items()] -def _step_state(action: Mapping, receipt: Mapping | None, values: Mapping) -> str: +def _step_state(action: Mapping[str, Any], receipt: Mapping[str, Any] | None, values: Mapping[str, Any]) -> str: if receipt is None: return "not_started" if receipt["status"] != "confirmed": diff --git a/je_auto_control/utils/agent_runtime/runtime.py b/je_auto_control/utils/agent_runtime/runtime.py index 8a845101d..120250588 100644 --- a/je_auto_control/utils/agent_runtime/runtime.py +++ b/je_auto_control/utils/agent_runtime/runtime.py @@ -181,7 +181,7 @@ def submit(self, spec: AgentTaskSpec | Mapping[str, Any], *, def _create_task(self, spec: AgentTaskSpec, key: str | None, event: tuple[str, str, str] | None = None, recovery: tuple[str, str, str] | None = None, - authorization: dict | RecoveryBinding | CompletionBinding | None = None, + authorization: dict[str, Any] | RecoveryBinding | CompletionBinding | None = None, submission: str | None = None) -> AgentTaskHandle: with DeferredAuthorization.capture().scope(): payload = durable_payload(spec.to_dict()) @@ -557,7 +557,7 @@ def stop_all(self) -> dict[str, Any]: errors.append({"task_id": task_id, "error": type(error).__name__}) return {"tasks": results, "requested": len(identifiers), "cleanup_errors": errors[:1000]} - def _stop_snapshots(self, identifiers: List[str]) -> dict[str, dict]: + def _stop_snapshots(self, identifiers: List[str]) -> dict[str, dict[str, Any]]: if not identifiers: return {} with self.store.connection() as connection: @@ -726,7 +726,7 @@ def prune(self, keep_days: int = 30) -> dict[str, Any]: from je_auto_control.utils.agent_runtime.retention import prune_tasks return prune_tasks(self, keep_days) - def _retained_source(self, task_id: str) -> dict: + def _retained_source(self, task_id: str) -> dict[str, Any]: """Validate private custody; exact admitted reader scopes authorize every live read separately.""" row = self.store.get(task_id) spec = AgentTaskSpec.from_dict(row["spec"]) diff --git a/je_auto_control/utils/agent_runtime/submission.py b/je_auto_control/utils/agent_runtime/submission.py index 589e46500..ab7eaadc9 100644 --- a/je_auto_control/utils/agent_runtime/submission.py +++ b/je_auto_control/utils/agent_runtime/submission.py @@ -13,9 +13,9 @@ class TaskAdmission: """Trusted store envelope keeps request identity in the same transaction as task acceptance.""" - spec: dict + spec: dict[str, Any] submitted_digest: str - dag: dict | None = None + dag: dict[str, Any] | None = None def submitted_digest(value: AgentTaskSpec | Mapping[str, Any]) -> str: @@ -24,7 +24,7 @@ def submitted_digest(value: AgentTaskSpec | Mapping[str, Any]) -> str: return hashlib.sha256(json.dumps(spec.to_dict(), sort_keys=True).encode()).hexdigest() -def submission_metadata(store: Any, identifier: str) -> dict: +def submission_metadata(store: Any, identifier: str) -> dict[str, Any]: """Expose historical request identity only; absence never invents a witness for a legacy task.""" with store.connection() as connection: row = connection.execute("SELECT s.spec_digest,a.batch_id,a.node_id,a.actor FROM agent_task_submissions s " diff --git a/je_auto_control/utils/agent_runtime/target_config.py b/je_auto_control/utils/agent_runtime/target_config.py index 9f0a54f6d..26c381edd 100644 --- a/je_auto_control/utils/agent_runtime/target_config.py +++ b/je_auto_control/utils/agent_runtime/target_config.py @@ -108,7 +108,7 @@ def _check_roots(self, spec: AgentTaskSpec) -> None: raise AgentTaskError("task roots exceed the host target profile") from error -def _settings(kind: str, value: Mapping) -> dict: +def _settings(kind: str, value: Mapping[str, Any]) -> dict[str, Any]: data = detached(value) if not isinstance(data, dict): raise AgentTaskError("target profile settings must be an object") @@ -129,7 +129,7 @@ def _settings(kind: str, value: Mapping) -> dict: return data -def _normalize_origins(data: dict) -> None: +def _normalize_origins(data: dict[str, Any]) -> None: origins = data.get("allowed_origins", []) if not isinstance(origins, list) or len(origins) > 50 or not all(isinstance(item, str) for item in origins): raise AgentTaskError("target origins must be a bounded list of strings") diff --git a/je_auto_control/utils/agent_runtime/transfer_adoption.py b/je_auto_control/utils/agent_runtime/transfer_adoption.py index 790d1b2f3..87f36624d 100644 --- a/je_auto_control/utils/agent_runtime/transfer_adoption.py +++ b/je_auto_control/utils/agent_runtime/transfer_adoption.py @@ -11,8 +11,8 @@ from je_auto_control.utils.agent_runtime.transfer_models import _canonical -def remote_successor(runtime: Any, batch: dict, node: dict, grant_id: str, - binding: dict, deadline: float, owner: Any) -> tuple[dict, list]: +def remote_successor(runtime: Any, batch: dict[str, Any], node: dict[str, Any], grant_id: str, + binding: dict[str, Any], deadline: float, owner: Any) -> tuple[dict[str, Any], list[Any]]: """Resolve the original coordinator request using its own current registered source account.""" remaining = deadline - time.monotonic() if runtime is None or remaining <= 0: diff --git a/je_auto_control/utils/agent_runtime/transfer_destination_scope.py b/je_auto_control/utils/agent_runtime/transfer_destination_scope.py index 7cfc20498..1e0a6cba2 100644 --- a/je_auto_control/utils/agent_runtime/transfer_destination_scope.py +++ b/je_auto_control/utils/agent_runtime/transfer_destination_scope.py @@ -13,8 +13,8 @@ def _directory(directory: str) -> None: raise AgentTaskError('destination directory must be an absolute text path') -def destination_scope(profile: Callable, origins: Callable, target: str, directory: str, *, - reviewed: dict | None = None, connection: Any = None) -> dict: +def destination_scope(profile: Callable[..., Any], origins: Callable[..., Any], target: str, directory: str, *, + reviewed: dict[str, Any] | None = None, connection: Any = None) -> dict[str, Any]: """Recheck host-owned scope without creating output or fabricating an ordinary agent task.""" _directory(directory) configuration = profile(target, connection=connection) diff --git a/je_auto_control/utils/agent_runtime/transfer_privacy.py b/je_auto_control/utils/agent_runtime/transfer_privacy.py index 5d196fb8c..a81955565 100644 --- a/je_auto_control/utils/agent_runtime/transfer_privacy.py +++ b/je_auto_control/utils/agent_runtime/transfer_privacy.py @@ -9,7 +9,7 @@ from je_auto_control.utils.agent_runtime.transfer_cache import private_cache_path -def _private_files(runtime: Any, actors: tuple[dict, ...]) -> tuple[Path, ...]: +def _private_files(runtime: Any, actors: tuple[dict[str, Any], ...]) -> tuple[Path, ...]: databases = (Path(runtime.store.path), private_cache_path(runtime.store.path)) files = [path for database in databases for path in (database, *(database.with_name(database.name + suffix) for suffix in ('-wal', '-shm', '-journal')))] @@ -33,7 +33,7 @@ class SourceFilePolicy: policy: Any runtime: Any - actors: tuple[dict, ...] + actors: tuple[dict[str, Any], ...] historical: tuple[Any, ...] = () @property diff --git a/je_auto_control/utils/agent_runtime/trigger_registration.py b/je_auto_control/utils/agent_runtime/trigger_registration.py index 149eaedef..6bfc5355a 100644 --- a/je_auto_control/utils/agent_runtime/trigger_registration.py +++ b/je_auto_control/utils/agent_runtime/trigger_registration.py @@ -10,8 +10,8 @@ from je_auto_control.utils.agent_runtime.trigger_config import next_due -def insert_registration(connection: Any, identifier: str, value: dict, spec: AgentTaskSpec, - config: dict, owner: dict, now: float) -> None: +def insert_registration(connection: Any, identifier: str, value: dict[str, Any], spec: AgentTaskSpec, + config: dict[str, Any], owner: dict[str, Any], now: float) -> None: """Persist a reviewed binding enabled for future notifications, never a schedule backlog.""" if connection.execute("SELECT COUNT(*) FROM agent_triggers").fetchone()[0] >= 200: raise AgentTaskError("a runtime supports at most two hundred configured task triggers") diff --git a/je_auto_control/utils/agent_runtime/workflow_desktop.py b/je_auto_control/utils/agent_runtime/workflow_desktop.py index 53e9af070..0559ce349 100644 --- a/je_auto_control/utils/agent_runtime/workflow_desktop.py +++ b/je_auto_control/utils/agent_runtime/workflow_desktop.py @@ -48,11 +48,11 @@ def _unique_control(selector: dict[str, Any]) -> None: raise AgentTaskError("workflow control is ambiguous, unavailable or disabled") -def _native_id_matches(node: Any, selector: dict) -> bool: +def _native_id_matches(node: Any, selector: dict[str, Any]) -> bool: return "automation_id" not in selector or node.native_id == selector["automation_id"] -def _matches(node: Any, process_id: int | None, filters: dict, selector: dict) -> bool: +def _matches(node: Any, process_id: int | None, filters: dict[str, Any], selector: dict[str, Any]) -> bool: from je_auto_control.utils.accessibility.element import element_matches return node.process_id == process_id and element_matches(node, **filters) and _native_id_matches(node, selector) diff --git a/je_auto_control/utils/agent_runtime/workflow_values.py b/je_auto_control/utils/agent_runtime/workflow_values.py index d02a3aa8d..4be452c86 100644 --- a/je_auto_control/utils/agent_runtime/workflow_values.py +++ b/je_auto_control/utils/agent_runtime/workflow_values.py @@ -70,7 +70,7 @@ def verified_prefix(spec: AgentTaskSpec, receipts: Sequence[Mapping[str, Any]]) return True -def _matches_action(action: Mapping, receipt: Mapping, values: Mapping) -> bool: +def _matches_action(action: Mapping[str, Any], receipt: Mapping[str, Any], values: Mapping[str, Any]) -> bool: if receipt["status"] != "confirmed" or receipt["command"] != action["tool"]: return False if not _arguments_match(action, receipt, values): @@ -81,7 +81,7 @@ def _matches_action(action: Mapping, receipt: Mapping, values: Mapping) -> bool: return not required or receipt["result"] == value -def _arguments_match(action: Mapping, receipt: Mapping, values: Mapping) -> bool: +def _arguments_match(action: Mapping[str, Any], receipt: Mapping[str, Any], values: Mapping[str, Any]) -> bool: arguments = resolve(action.get("arguments", {}), values) if action.get("reference") is None: return receipt["arguments"] == arguments diff --git a/je_auto_control/utils/chatops/slack_bot.py b/je_auto_control/utils/chatops/slack_bot.py index ca4f15456..7cce6910f 100644 --- a/je_auto_control/utils/chatops/slack_bot.py +++ b/je_auto_control/utils/chatops/slack_bot.py @@ -317,7 +317,7 @@ def post_message(self, text: str, payload["thread_ts"] = thread_ts return self._api_post("chat.postMessage", payload) - def _fetch_messages(self) -> list: + def _fetch_messages(self) -> List[Dict[str, Any]]: """Every message since ``last_seen_ts``, newest first, across pages. One page of 50 was read and ``last_seen_ts`` then moved past the @@ -329,7 +329,7 @@ def _fetch_messages(self) -> list: } if self.last_seen_ts: params["oldest"] = self.last_seen_ts - messages: list = [] + messages: List[Dict[str, Any]] = [] for _ in range(_MAX_PAGES): body = self._api_get("conversations.history", params) messages.extend(message for message in body.get("messages") or [] diff --git a/je_auto_control/utils/color_region/color_region.py b/je_auto_control/utils/color_region/color_region.py index 0da0e57ae..403a5c8bb 100644 --- a/je_auto_control/utils/color_region/color_region.py +++ b/je_auto_control/utils/color_region/color_region.py @@ -34,7 +34,7 @@ def _array_as_rgb(array: Any) -> Any: return array -def _to_rgb(source: ImageSource): +def _to_rgb(source: ImageSource) -> Any: """Load a path / ndarray / PIL image as an RGB ndarray.""" import cv2 import numpy as np @@ -47,7 +47,7 @@ def _to_rgb(source: ImageSource): return np.asarray(source.convert("RGB")) -def _grab_rgb(region: Optional[Sequence[int]]): +def _grab_rgb(region: Optional[Sequence[int]]) -> Any: import numpy as np from je_auto_control.utils.cv2_utils.region_capture import grab_screen_region return np.asarray(grab_screen_region(region).convert("RGB")) diff --git a/je_auto_control/utils/cost_telemetry/__init__.py b/je_auto_control/utils/cost_telemetry/__init__.py index 1704343f9..e220be876 100644 --- a/je_auto_control/utils/cost_telemetry/__init__.py +++ b/je_auto_control/utils/cost_telemetry/__init__.py @@ -14,6 +14,8 @@ summary = summarise_llm_costs() print(summary.total_usd, summary.by_model) """ +from typing import Iterable, Optional + from je_auto_control.utils.cost_telemetry.pricing import ( Pricing, estimate_usd as estimate_llm_usd, known_models, pricing_for, ) @@ -22,7 +24,7 @@ ) -def summarise_llm_costs(events=None) -> CostSummary: +def summarise_llm_costs(events: Optional[Iterable[CostEvent]] = None) -> CostSummary: """Summarise ``events``, or ``default_cost_store``'s recorded calls when omitted. It was an alias of ``summarise_events(events)``, whose argument is @@ -33,7 +35,8 @@ def summarise_llm_costs(events=None) -> CostSummary: def record_llm_call(*, provider: str, model: str, input_tokens: int, output_tokens: int, - label=None, run_id=None, user=None) -> CostEvent: + label: Optional[str] = None, run_id: Optional[str] = None, + user: Optional[str] = None) -> CostEvent: """Convenience wrapper around ``default_cost_store.record``.""" return default_cost_store.record( provider=provider, model=model, diff --git a/je_auto_control/utils/cv2_utils/video_recording.py b/je_auto_control/utils/cv2_utils/video_recording.py index b120613ea..8c19ecc0d 100644 --- a/je_auto_control/utils/cv2_utils/video_recording.py +++ b/je_auto_control/utils/cv2_utils/video_recording.py @@ -14,7 +14,7 @@ class RecordingThread(threading.Thread): - 使用 OpenCV VideoWriter 寫入影片檔案 """ - def __init__(self, video_name: str = "autocontrol_recording", fps: int = 20): + def __init__(self, video_name: str = "autocontrol_recording", fps: int = 20) -> None: super().__init__() autocontrol_logger.info("Init RecordingThread") self.recording_flag = True @@ -22,7 +22,7 @@ def __init__(self, video_name: str = "autocontrol_recording", fps: int = 20): self.daemon = True self.fps = fps - def set_recording_flag(self, recording_flag: bool): + def set_recording_flag(self, recording_flag: bool) -> None: """ 設定錄影旗標 Set recording flag @@ -32,14 +32,14 @@ def set_recording_flag(self, recording_flag: bool): autocontrol_logger.info(f"RecordingThread set_recording_flag: {recording_flag}") self.recording_flag = recording_flag - def stop(self): + def stop(self) -> None: """ 停止錄影 Stop recording """ self.set_recording_flag(False) - def run(self): + def run(self) -> None: """ 執行錄影迴圈 Run recording loop diff --git a/je_auto_control/utils/dag/managed_tasks.py b/je_auto_control/utils/dag/managed_tasks.py index a331943fc..ca2fee03a 100644 --- a/je_auto_control/utils/dag/managed_tasks.py +++ b/je_auto_control/utils/dag/managed_tasks.py @@ -41,7 +41,8 @@ def registered_transfer_binding(host: str) -> str: return host_fingerprint(*identity) -def registered_host_transfer(host: str, binding: str, path: str, body: dict, timeout: float) -> dict: +def registered_host_transfer(host: str, binding: str, path: str, body: dict[str, Any], + timeout: float) -> dict[str, Any]: """Use only reviewed transfer routes with fresh pre/post host and local authorization checks.""" if not isinstance(path, str) or path not in {'/agent/transfer', '/agent/transfer/peer'}: raise AgentTaskError('unavailable registered transfer route') @@ -230,7 +231,8 @@ def remote(operation: str, body: dict[str, Any], timeout: float) -> dict[str, An return remote -def _remote_json(url: str, *, body: dict | None = None, token: str, timeout: float, control: bool = False) -> dict: +def _remote_json(url: str, *, body: dict[str, Any] | None = None, token: str, timeout: float, + control: bool = False) -> dict[str, Any]: from je_auto_control.utils.agent_runtime.transport import request_json options: dict[str, Any] = {'body': body, 'token': token, 'timeout': timeout, 'control': control} if urlsplit(url).path.endswith(('/agent/transfer', '/agent/transfer/peer')): diff --git a/je_auto_control/utils/dbus_client/session_bus.py b/je_auto_control/utils/dbus_client/session_bus.py index a40250c23..d99c8e652 100644 --- a/je_auto_control/utils/dbus_client/session_bus.py +++ b/je_auto_control/utils/dbus_client/session_bus.py @@ -34,7 +34,7 @@ import struct import time import urllib.parse -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, Iterator, List, Optional, Tuple # A direct sibling import avoids the partially initialized facade's import cycle. from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption @@ -371,7 +371,7 @@ def _read_array(reader: _Reader, signature: _SignatureReader) -> Any: def _read_struct(reader: _Reader, signature: _SignatureReader, - code: str) -> tuple: + code: str) -> Tuple[Any, ...]: closing = ")" if code == "(" else "}" reader.align(8) members = [] @@ -679,7 +679,7 @@ def matches(message: Message) -> bool: return message.body -def body_pairs(signature: str, body: List[Any]): +def body_pairs(signature: str, body: List[Any]) -> Iterator[Tuple[str, Any]]: """Pair each top-level type in a signature with its argument.""" reader = _SignatureReader(signature) for value in body: diff --git a/je_auto_control/utils/deprecation.py b/je_auto_control/utils/deprecation.py index c4084c68c..35fa61d90 100644 --- a/je_auto_control/utils/deprecation.py +++ b/je_auto_control/utils/deprecation.py @@ -3,16 +3,16 @@ import functools import warnings -from typing import Callable, TypeVar, cast +from typing import Any, Callable, TypeVar, cast -F = TypeVar("F", bound=Callable) +F = TypeVar("F", bound=Callable[..., Any]) class AutoControlDeprecationWarning(FutureWarning): """A user-visible warning for an API scheduled for removal.""" -def deprecated(*, since: str, removal: str, replacement: str = ""): +def deprecated(*, since: str, removal: str, replacement: str = "") -> Callable[[F], F]: """Mark a callable deprecated with actionable lifecycle metadata.""" def decorate(func: F) -> F: message = f"{func.__qualname__} is deprecated since {since}" @@ -21,7 +21,7 @@ def decorate(func: F) -> F: message += f" Use {replacement} instead." @functools.wraps(func) - def wrapped(*args, **kwargs): + def wrapped(*args: Any, **kwargs: Any) -> Any: warnings.warn(message, AutoControlDeprecationWarning, stacklevel=2) return func(*args, **kwargs) diff --git a/je_auto_control/utils/edge_match/edge_match.py b/je_auto_control/utils/edge_match/edge_match.py index ca156658a..680435a64 100644 --- a/je_auto_control/utils/edge_match/edge_match.py +++ b/je_auto_control/utils/edge_match/edge_match.py @@ -25,12 +25,13 @@ _DEFAULT_CANNY = (50, 150) -def _edges(gray, canny: Sequence[int]): +def _edges(gray: Any, canny: Sequence[int]) -> Any: import cv2 return cv2.Canny(gray, int(canny[0]), int(canny[1])) -def _chamfer_score_map(template_gray, scene_gray, canny: Sequence[int]): +def _chamfer_score_map(template_gray: Any, scene_gray: Any, + canny: Sequence[int]) -> Tuple[Any, Tuple[int, int]]: """Return ``(score_map, (w, h))`` where higher = better edge alignment, or ``(None, _)``.""" import cv2 import numpy as np @@ -48,7 +49,7 @@ def _chamfer_score_map(template_gray, scene_gray, canny: Sequence[int]): return score_map, (template_edges.shape[1], template_edges.shape[0]) -def _best(score_map, size: Tuple[int, int], scale: float, min_score: float, +def _best(score_map: Any, size: Tuple[int, int], scale: float, min_score: float, current: Optional[Match]) -> Optional[Match]: import cv2 _, max_val, _, max_loc = cv2.minMaxLoc(score_map) diff --git a/je_auto_control/utils/element_diff/element_diff.py b/je_auto_control/utils/element_diff/element_diff.py index 03d459f4d..2a8b5cd28 100644 --- a/je_auto_control/utils/element_diff/element_diff.py +++ b/je_auto_control/utils/element_diff/element_diff.py @@ -11,7 +11,7 @@ Pure-stdlib over plain element dicts (``x`` / ``y`` / ``width`` / ``height``), so it is fully unit-testable. Imports no ``PySide6``. """ -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Set from je_auto_control.utils.element_parse import iou @@ -27,7 +27,7 @@ def match_elements(before: Sequence[Element], after: Sequence[Element], *, unmatched ``after`` element is *added*. """ after = list(after) - taken: set = set() + taken: Set[int] = set() matched: List[Dict[str, Any]] = [] removed: List[Element] = [] for element in before: @@ -75,7 +75,7 @@ def assign_stable_ids(elements: Sequence[Element], result: List[Element] = [] # Each prior id is inherited once: two elements overlapping the same # prior element both took its id, so "stable" ids repeated. - used: set = set() + used: Set[int] = set() for element in elements: available = [p for p in prior if "id" in p and int(p["id"]) not in used] match = _best_prior(element, available, float(iou_threshold)) diff --git a/je_auto_control/utils/feature_flags/feature_flags.py b/je_auto_control/utils/feature_flags/feature_flags.py index 61543528f..fd896ca0b 100644 --- a/je_auto_control/utils/feature_flags/feature_flags.py +++ b/je_auto_control/utils/feature_flags/feature_flags.py @@ -13,12 +13,12 @@ import json import os from dataclasses import dataclass, field -from typing import Any, Dict, Mapping, Optional +from typing import Any, Dict, Mapping, Optional, Tuple from je_auto_control.utils.vuln_scan.vuln_scan import version_key -def _semver(value: Any) -> tuple: +def _semver(value: Any) -> Tuple[Tuple[int, ...], int, Tuple[Tuple[int, Any], ...]]: # The digit groups alone made 1.2 < 1.2.0 and 1.0.0-rc.1 == 1.0.0. return version_key(str(value)) @@ -51,7 +51,7 @@ class Flag: default_variant: str = "" off_variant: str = "" enabled: bool = True - targeting: tuple = () + targeting: Tuple[Dict[str, Any], ...] = () fallthrough: Any = None diff --git a/je_auto_control/utils/form_fields/form_fields.py b/je_auto_control/utils/form_fields/form_fields.py index 785b8dc05..dd11776fa 100644 --- a/je_auto_control/utils/form_fields/form_fields.py +++ b/je_auto_control/utils/form_fields/form_fields.py @@ -24,7 +24,7 @@ def _overlap_1d(a0: int, a1: int, b0: int, b1: int) -> int: return max(0, min(a1, b1) - max(a0, b0)) -def _right_value(label: Box, values: Sequence[Box], max_gap: int): +def _right_value(label: Box, values: Sequence[Box], max_gap: int) -> Optional[Tuple[Box, int]]: """Nearest value to the right of ``label`` that shares a row, or ``None``.""" _, top, right, bottom = _box_bounds(label) best: Optional[Tuple[Box, int]] = None @@ -37,7 +37,7 @@ def _right_value(label: Box, values: Sequence[Box], max_gap: int): return best -def _below_value(label: Box, values: Sequence[Box], max_gap: int): +def _below_value(label: Box, values: Sequence[Box], max_gap: int) -> Optional[Tuple[Box, int]]: """Nearest value below ``label`` that shares a column, or ``None``.""" left, _, right, bottom = _box_bounds(label) best: Optional[Tuple[Box, int]] = None @@ -59,7 +59,7 @@ def _clean_label(box: Box) -> str: def _best_value(label: Box, values: Sequence[Box], directions: Sequence[str], - max_gap: int): + max_gap: int) -> Optional[Tuple[Box, int, str]]: """Pick the nearest value across the requested directions, or ``None``.""" best = None for direction in directions: diff --git a/je_auto_control/utils/generate_report/generate_html_report.py b/je_auto_control/utils/generate_report/generate_html_report.py index 551f50b27..2829dd253 100644 --- a/je_auto_control/utils/generate_report/generate_html_report.py +++ b/je_auto_control/utils/generate_report/generate_html_report.py @@ -1,5 +1,6 @@ import html from threading import Lock +from typing import Any, Dict from je_auto_control.utils.exception.exception_tags import html_generate_no_data_tag_error_message from je_auto_control.utils.exception.exceptions import AutoControlHTMLException @@ -99,7 +100,7 @@ """.strip() -def make_html_table(event_str: str, record_data: dict, table_head: str) -> str: +def make_html_table(event_str: str, record_data: Dict[str, Any], table_head: str) -> str: """ 建立單一事件的 HTML 表格 Create HTML table for a single event @@ -116,7 +117,7 @@ def make_html_table(event_str: str, record_data: dict, table_head: str) -> str: return event_str + _event_html(record_data, table_head) -def _event_html(record_data: dict, table_head: str) -> str: +def _event_html(record_data: Dict[str, Any], table_head: str) -> str: """One event's table, its recorded values escaped.""" return _event_table.format( table_head_class=table_head, diff --git a/je_auto_control/utils/hotkey/backends/windows_backend.py b/je_auto_control/utils/hotkey/backends/windows_backend.py index bcdaf1e16..3f30fcddf 100644 --- a/je_auto_control/utils/hotkey/backends/windows_backend.py +++ b/je_auto_control/utils/hotkey/backends/windows_backend.py @@ -1,5 +1,5 @@ """Windows hotkey backend: ``RegisterHotKey`` + a message-pump thread.""" -from typing import Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Set, Tuple from je_auto_control.utils.hotkey.backends.base import HotkeyBackend from je_auto_control.utils.hotkey.hotkey_daemon import ( @@ -53,7 +53,7 @@ def run_forever(self, context: BackendContext) -> None: user32.UnregisterHotKey(None, reg_id) self._registered.clear() - def _sync(self, user32, bindings: List[HotkeyBinding]) -> None: + def _sync(self, user32: Any, bindings: List[HotkeyBinding]) -> None: """Add new bindings + drop removed ones vs. ``self._registered``.""" self._drop_removed(user32, {b.binding_id for b in bindings}) for binding in bindings: @@ -69,7 +69,7 @@ def _sync(self, user32, bindings: List[HotkeyBinding]) -> None: self._registered.pop(binding.binding_id, None) self._try_register(user32, binding) - def _drop_removed(self, user32, current_ids: set) -> None: + def _drop_removed(self, user32: Any, current_ids: Set[str]) -> None: """Unregister bindings that are gone and forget their failures.""" for stale_id in [bid for bid in self._registered if bid not in current_ids]: reg_id, _combo = self._registered.pop(stale_id) @@ -77,7 +77,7 @@ def _drop_removed(self, user32, current_ids: set) -> None: for stale_id in [bid for bid in self._failed if bid not in current_ids]: del self._failed[stale_id] - def _try_register(self, user32, binding: HotkeyBinding) -> None: + def _try_register(self, user32: Any, binding: HotkeyBinding) -> None: try: modifiers, vk = parse_combo(binding.combo) except ValueError as error: diff --git a/je_auto_control/utils/hotkey/hotkey_daemon.py b/je_auto_control/utils/hotkey/hotkey_daemon.py index a27ae245e..834d6f080 100644 --- a/je_auto_control/utils/hotkey/hotkey_daemon.py +++ b/je_auto_control/utils/hotkey/hotkey_daemon.py @@ -15,7 +15,7 @@ import threading import uuid from dataclasses import dataclass, field -from typing import Callable, Dict, FrozenSet, List, Optional, Tuple +from typing import Any, Callable, Dict, FrozenSet, List, Optional, Set, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.json.json_file import read_executable_action_json @@ -72,7 +72,7 @@ def split_combo(combo: str) -> Tuple[FrozenSet[str], str]: parts = [p.strip().lower() for p in combo.split("+") if p.strip()] if not parts: raise ValueError(f"invalid hotkey combo: {combo!r}") - mods: set = set() + mods: Set[str] = set() key_part: Optional[str] = None for part in parts: if part in _MODIFIER_NAMES: @@ -140,7 +140,7 @@ class HotkeyDaemon: """Register OS-level hotkeys and run their action JSON on trigger.""" def __init__(self, - executor: Optional[Callable[[list], object]] = None) -> None: + executor: Optional[Callable[[List[Any]], object]] = None) -> None: from je_auto_control.utils.executor.action_executor import execute_action self._execute = executor or execute_action self._bindings: Dict[str, HotkeyBinding] = {} diff --git a/je_auto_control/utils/i18n_test/i18n_test.py b/je_auto_control/utils/i18n_test/i18n_test.py index e570d26c8..27945fd71 100644 --- a/je_auto_control/utils/i18n_test/i18n_test.py +++ b/je_auto_control/utils/i18n_test/i18n_test.py @@ -14,7 +14,7 @@ Imports no ``PySide6``; no third-party dependency. """ import re -from typing import Any, Dict, List +from typing import Any, Dict, List, Set # Accent map for common Latin letters (pseudo-localization). _ACCENTS = str.maketrans( @@ -69,7 +69,7 @@ def _scan(self, index: int, *, nested: bool, plural: bool) -> int: index += 1 return index - def _icu(self, head: "re.Match") -> int: + def _icu(self, head: "re.Match[str]") -> int: self._add(True, head.group(0)) plural = head.group(1) != "select" index = head.end() @@ -147,7 +147,7 @@ def check_overflow(elements: List[Any], *, return issues -def _placeholders(value: Any) -> set: +def _placeholders(value: Any) -> Set[str]: """Printf conversions and ``{argument}`` names -- not ICU case keywords, which legitimately differ between languages.""" text = str(value) diff --git a/je_auto_control/utils/llm/planner.py b/je_auto_control/utils/llm/planner.py index 1dcde70c2..a90b05589 100644 --- a/je_auto_control/utils/llm/planner.py +++ b/je_auto_control/utils/llm/planner.py @@ -43,7 +43,7 @@ def plan_actions(description: str, examples: Optional[List[Dict[str, Any]]] = None, backend: Optional[LLMBackend] = None, model: Optional[str] = None, - max_tokens: int = 2048) -> List[list]: + max_tokens: int = 2048) -> List[List[Any]]: """Translate ``description`` into a validated action list. ``examples`` is an optional list of ``{"description": ..., "actions": [...]}`` @@ -113,7 +113,7 @@ def _build_user_prompt(description: str, return "\n".join(parts) -def _parse_actions(raw: str) -> List[list]: +def _parse_actions(raw: str) -> List[List[Any]]: """Extract a JSON array from ``raw`` and ensure it's a list of lists.""" if not raw or not raw.strip(): raise LLMPlanError("LLM returned empty response") diff --git a/je_auto_control/utils/match_autothresh/match_autothresh.py b/je_auto_control/utils/match_autothresh/match_autothresh.py index b1f447204..9d61fdc1a 100644 --- a/je_auto_control/utils/match_autothresh/match_autothresh.py +++ b/je_auto_control/utils/match_autothresh/match_autothresh.py @@ -13,7 +13,7 @@ (ndarray / path / PIL); the analysis is unit-testable on synthetic arrays. OpenCV + NumPy are imported lazily. Imports no ``PySide6``. """ -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.visual_match.visual_match import ( Match, _score_map, _score_map_with_origin, @@ -22,7 +22,7 @@ ImageSource = Any -def _separability(scaled, threshold: float) -> float: +def _separability(scaled: Any, threshold: float) -> float: """Otsu separability eta = between-class variance / total variance (0..1).""" total_var = float(scaled.var()) if total_var < 1e-9: @@ -35,7 +35,7 @@ def _separability(scaled, threshold: float) -> float: return max(0.0, min(1.0, between / total_var)) -def _otsu_on_scores(score_map): +def _otsu_on_scores(score_map: Any) -> Tuple[float, float]: """Return ``(threshold_in_score_units, separability)`` for a correlation surface.""" import cv2 import numpy as np @@ -66,7 +66,7 @@ def auto_threshold(template: ImageSource, *, haystack: Optional[ImageSource] = N "n_above": int(np.count_nonzero(score_map >= threshold))} -def _blob_peaks(score_map, mask): +def _blob_peaks(score_map: Any, mask: Any) -> List[Tuple[int, int, float]]: """``(x, y, score)`` of the highest score inside each connected blob. Searched within the blob itself: its bounding box can hold another blob, diff --git a/je_auto_control/utils/match_trust/match_trust.py b/je_auto_control/utils/match_trust/match_trust.py index 1534605e7..0beb5beed 100644 --- a/je_auto_control/utils/match_trust/match_trust.py +++ b/je_auto_control/utils/match_trust/match_trust.py @@ -14,7 +14,7 @@ NumPy are imported lazily. Imports no ``PySide6``. """ from dataclasses import asdict, dataclass -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.visual_match.visual_match import ( _contain_cv2_error, _score_map_with_origin, @@ -56,7 +56,8 @@ def _safe_psr(value: float) -> Optional[float]: return round(value, 4) if math.isfinite(value) else None -def _peak_stats(score_map, exclude_radius: int, rebase: bool = False): +def _peak_stats(score_map: Any, exclude_radius: int, rebase: bool = False, + ) -> Tuple[Tuple[int, int], float, float, float, float]: """Return ``(loc, best, second, peak_ratio, psr)`` for one correlation surface. With ``rebase`` (``ccorr_normed``) the ratio is taken above the surface's @@ -89,7 +90,7 @@ def _is_ccorr(method: str) -> bool: return str(method).lower().startswith("ccorr") -def _default_radius(template_shape, exclude_radius: Optional[int]) -> int: +def _default_radius(template_shape: Sequence[int], exclude_radius: Optional[int]) -> int: """Pick the peak-exclusion radius: caller value, or a quarter of the smaller side.""" if exclude_radius: return int(exclude_radius) diff --git a/je_auto_control/utils/mcp_server/_call_authority.py b/je_auto_control/utils/mcp_server/_call_authority.py index 901ee527d..9f6aef04f 100644 --- a/je_auto_control/utils/mcp_server/_call_authority.py +++ b/je_auto_control/utils/mcp_server/_call_authority.py @@ -10,7 +10,7 @@ @contextmanager -def invocation_authority(tool: Any, arguments: dict, context: Any) -> Iterator[None]: +def invocation_authority(tool: Any, arguments: dict[str, Any], context: Any) -> Iterator[None]: """Refresh an authenticated owner or derive a restricted session principal before any wrapper runs.""" caller = current_authorization() session = getattr(context, "session_id", "") @@ -22,7 +22,7 @@ def invocation_authority(tool: Any, arguments: dict, context: Any) -> Iterator[N yield -def _require(identity: AuthorizationContext, tool: Any, arguments: dict) -> None: +def _require(identity: AuthorizationContext, tool: Any, arguments: dict[str, Any]) -> None: for needed in capabilities_for_tool_call(tool.name, tool.annotations.read_only, arguments): if not identity.allows(needed): raise AuthorizationError(f"{tool.name} requires {needed}", capability=needed) diff --git a/je_auto_control/utils/mcp_server/fake_backend.py b/je_auto_control/utils/mcp_server/fake_backend.py index fbbae80aa..b1f7788ae 100644 --- a/je_auto_control/utils/mcp_server/fake_backend.py +++ b/je_auto_control/utils/mcp_server/fake_backend.py @@ -96,19 +96,19 @@ def _fake_screen_size() -> Tuple[int, int]: return _STATE.screen_size -def _fake_write(text: str, *_args, **_kwargs) -> str: +def _fake_write(text: str, *_args: Any, **_kwargs: Any) -> str: with _STATE_LOCK: _STATE.typed_text.append(text) return text -def _fake_type_keyboard(keycode: Any, *_args, **_kwargs) -> str: +def _fake_type_keyboard(keycode: Any, *_args: Any, **_kwargs: Any) -> str: with _STATE_LOCK: _STATE.keys_pressed.append(keycode) return str(keycode) -def _fake_hotkey(keys: List[Any], *_args, **_kwargs) -> Tuple[str, str]: +def _fake_hotkey(keys: List[Any], *_args: Any, **_kwargs: Any) -> Tuple[str, str]: joined = ",".join(str(k) for k in keys) with _STATE_LOCK: _STATE.keys_pressed.append(("hotkey", joined)) diff --git a/je_auto_control/utils/mcp_server/http_transport.py b/je_auto_control/utils/mcp_server/http_transport.py index f66895b43..fe965eba8 100644 --- a/je_auto_control/utils/mcp_server/http_transport.py +++ b/je_auto_control/utils/mcp_server/http_transport.py @@ -104,7 +104,8 @@ def _forget_if_dropped(bridge: "MCPServer", session: Optional[HttpSession]) -> N bridge.forget_connection(session.id) -def _notifier_for(writer: Optional[Callable[[str], None]]): +def _notifier_for(writer: Optional[Callable[[str], None]], + ) -> Optional[Callable[[str, Dict[str, Any]], None]]: """Wrap a raw writer as a (method, params) notifier, or ``None``.""" if writer is None: return None @@ -124,7 +125,7 @@ class _MCPHttpHandler(HttpResponseMixin, BaseHTTPRequestHandler): timeout = _REQUEST_TIMEOUT # Suppress default stderr access logs — route through project logger. - def log_message(self, format, *args) -> None: # noqa: A002 # pylint: disable=redefined-builtin # reason: stdlib override + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 # pylint: disable=redefined-builtin # reason: stdlib override autocontrol_logger.info("mcp-http %s - %s", self.address_string(), log_safe(format % args)) diff --git a/je_auto_control/utils/mcp_server/plugin_watcher.py b/je_auto_control/utils/mcp_server/plugin_watcher.py index 1f95efa3b..5fc047208 100644 --- a/je_auto_control/utils/mcp_server/plugin_watcher.py +++ b/je_auto_control/utils/mcp_server/plugin_watcher.py @@ -8,7 +8,7 @@ """ import os import threading -from typing import Any, Dict, List, Optional, Set +from typing import Any, Dict, Iterable, List, Optional, Set, Tuple from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.mcp_server.tools.plugin_tools import ( @@ -27,7 +27,7 @@ def __init__(self, server: Any, directory: str, self._stop = threading.Event() self._thread: Optional[threading.Thread] = None # path → (mtime, [tool_names]) - self._known: Dict[str, tuple] = {} + self._known: Dict[str, Tuple[float, List[str]]] = {} # path -> {tool name: tool} for every file that built successfully. self._defined: Dict[str, Dict[str, Any]] = {} @@ -115,7 +115,7 @@ def _reload_file(self, path: str, mtime: float) -> None: len(registered), ) - def _build_tools(self, path: str, previous: Optional[tuple], + def _build_tools(self, path: str, previous: Optional[Tuple[float, List[str]]], mtime: float) -> Optional[List[Any]]: """Load ``path`` and build its tools, or ``None`` on any failure. @@ -139,7 +139,7 @@ def _build_tools(self, path: str, previous: Optional[tuple], self._known[path] = (mtime, previous[1] if previous else []) return None - def _release(self, path: str, names) -> None: + def _release(self, path: str, names: Iterable[str]) -> None: """Drop ``path``'s claim on ``names``. A tool another watched file still defines is handed to that file's diff --git a/je_auto_control/utils/mcp_server/tools/plugin_tools.py b/je_auto_control/utils/mcp_server/tools/plugin_tools.py index 1d42b3c36..ec23ffd90 100644 --- a/je_auto_control/utils/mcp_server/tools/plugin_tools.py +++ b/je_auto_control/utils/mcp_server/tools/plugin_tools.py @@ -16,13 +16,16 @@ attribute that raises) leaves the tool mutating. """ import inspect -from typing import Any, Callable, Dict, List +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.mcp_server.tools._base import ( DESTRUCTIVE, MCPTool, MCPToolAnnotations, schema, ) +if TYPE_CHECKING: + from je_auto_control.utils.mcp_server.server import MCPServer + #: Attribute a plugin sets to ``True`` on a callable to declare it read-only. PLUGIN_READ_ONLY_ATTRIBUTE = "mcp_read_only" @@ -94,7 +97,7 @@ def make_plugin_tool(name: str, ) -def register_plugin_tools(server, commands: Dict[str, Callable[..., Any]] +def register_plugin_tools(server: "MCPServer", commands: Dict[str, Callable[..., Any]] ) -> List[str]: """Wrap each entry in ``commands`` and add it to ``server``. @@ -117,7 +120,7 @@ def register_plugin_tools(server, commands: Dict[str, Callable[..., Any]] def _properties_from_signature(handler: Callable[..., Any] - ) -> tuple: + ) -> Tuple[Dict[str, Any], List[str]]: """Return (properties, required) derived from the callable signature.""" try: signature = inspect.signature(handler) diff --git a/je_auto_control/utils/media_assert/media.py b/je_auto_control/utils/media_assert/media.py index 1beade52c..7a9d1b37e 100644 --- a/je_auto_control/utils/media_assert/media.py +++ b/je_auto_control/utils/media_assert/media.py @@ -18,7 +18,7 @@ import math import os from dataclasses import asdict, dataclass -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.exception.exceptions import ( AutoControlAssertionException, @@ -144,7 +144,7 @@ def _segment_motion(video_path: str, start_s: float, capture.release() -def _clipped(region: Sequence[int], frame) -> Tuple[int, int, int, int]: +def _clipped(region: Sequence[int], frame: Any) -> Tuple[int, int, int, int]: """``region`` (x1, y1, x2, y2) clipped to ``frame``; ``ValueError`` if nothing is left. An off-frame, negative or zero-width region sliced an empty frame, and @@ -159,7 +159,7 @@ def _clipped(region: Sequence[int], frame) -> Tuple[int, int, int, int]: return x1, y1, x2, y2 -def _sum_frame_diffs(capture, cv2, start_frame: int, end_frame: Optional[int], +def _sum_frame_diffs(capture: Any, cv2: Any, start_frame: int, end_frame: Optional[int], region: Optional[Sequence[int]]) -> Tuple[int, float]: """Read frames until ``end_frame`` or the end, keeping only the previous one. @@ -200,7 +200,7 @@ def video_segment_motion(video_path: str, return total / (count - 1) -def _contained(function, *args): +def _contained(function: Callable[..., Any], *args: Any) -> Any: """Call ``function``, with OpenCV's ``cv2.error`` as a framework error the executor records.""" from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error return _contain_cv2_error(function)(*args) diff --git a/je_auto_control/utils/ocr/backends/tesseract_backend.py b/je_auto_control/utils/ocr/backends/tesseract_backend.py index fb83a86ce..8875aa0f6 100644 --- a/je_auto_control/utils/ocr/backends/tesseract_backend.py +++ b/je_auto_control/utils/ocr/backends/tesseract_backend.py @@ -6,15 +6,18 @@ from __future__ import annotations from subprocess import SubprocessError # nosec B404 # reason: exception type only -from typing import List +from typing import TYPE_CHECKING, Any, List from je_auto_control.utils.ocr.backends.base import OCRBackendNotAvailableError +if TYPE_CHECKING: + from je_auto_control.utils.ocr.ocr_engine import TextMatch + _pytesseract = None -def _load(): +def _load() -> Any: global _pytesseract if _pytesseract is not None: return _pytesseract @@ -94,8 +97,8 @@ def languages(self) -> List[str]: raise OCRBackendNotAvailableError( f"Tesseract cannot list its languages: {error!r}") from error - def image_to_matches(self, image, lang: str, - min_confidence: float) -> List: + def image_to_matches(self, image: Any, lang: str, + min_confidence: float) -> List[TextMatch]: # Import inside to avoid circular import at module load. from je_auto_control.utils.ocr.ocr_engine import TextMatch diff --git a/je_auto_control/utils/ocr/ocr_engine.py b/je_auto_control/utils/ocr/ocr_engine.py index 2c42fa800..51754e5a4 100644 --- a/je_auto_control/utils/ocr/ocr_engine.py +++ b/je_auto_control/utils/ocr/ocr_engine.py @@ -12,7 +12,7 @@ import re import time from dataclasses import dataclass -from typing import List, Optional, Pattern, Sequence, Tuple +from typing import Any, List, Optional, Pattern, Sequence, Tuple from je_auto_control.utils.exception.exceptions import AutoControlActionException from je_auto_control.utils.executor.run_control import pause @@ -28,7 +28,7 @@ _image_grab = None -def _load_image_grab(): +def _load_image_grab() -> Any: """Cache the platform's ``ImageGrab``-shaped grabber. Not Pillow directly: under Wayland the screen has to come from the @@ -77,7 +77,7 @@ def set_tesseract_cmd(path: str) -> None: backend.set_cmd(path) -def _grab(region: Optional[Sequence[int]]): +def _grab(region: Optional[Sequence[int]]) -> Tuple[Any, int, int]: """Capture in mouse-coordinate space; returns ``(image, offset_x, offset_y)``. Delegated to :func:`monitor_layout.grab_logical` so the OCR and template diff --git a/je_auto_control/utils/package_manager/package_manager_class.py b/je_auto_control/utils/package_manager/package_manager_class.py index ee66731a8..14e70a9d9 100644 --- a/je_auto_control/utils/package_manager/package_manager_class.py +++ b/je_auto_control/utils/package_manager/package_manager_class.py @@ -4,11 +4,15 @@ from importlib.util import find_spec from inspect import getmembers, isfunction, isbuiltin, isclass from types import ModuleType -from typing import Optional +from typing import TYPE_CHECKING, Any, Callable, Optional from je_auto_control.utils.exception.exceptions import AutoControlExecuteActionException from je_auto_control.utils.logging.logging_instance import autocontrol_logger +if TYPE_CHECKING: + from je_auto_control.utils.callback.callback_function_executor import CallbackFunctionExecutor + from je_auto_control.utils.executor.action_executor import Executor + #: One name of a dotted module name. Each part is matched on its own, so no #: pattern here repeats a group that itself repeats. _PACKAGE_PART_RE = re.compile(r"[A-Za-z_]\w*") @@ -49,10 +53,10 @@ class PackageManager: - 將套件中的函式/類別加入到 Executor 或 CallbackExecutor 的事件字典 """ - def __init__(self): + def __init__(self) -> None: self.installed_package_dict: dict[str, ModuleType] = {} - self.executor = None - self.callback_executor = None + self.executor: Optional["Executor"] = None + self.callback_executor: Optional["CallbackFunctionExecutor"] = None # Package gate (workspace X-12). False (the default) = only ``allowed_packages``; # True = any package. The allowlist starts from JE_AUTOCONTROL_ALLOWED_PACKAGES. self.allow_arbitrary_packages: bool = False @@ -156,7 +160,8 @@ def add_package_to_callback_executor(self, package: str) -> None: self._check_allowed(package) self.add_package_to_target(package, self.callback_executor) - def get_member(self, package: str, predicate, target) -> None: + def get_member(self, package: str, predicate: Callable[[Any], bool], + target: "Optional[Executor | CallbackFunctionExecutor]") -> None: """ 取得套件成員並加入事件字典 Get package members and add to event_dict @@ -174,7 +179,7 @@ def get_member(self, package: str, predicate, target) -> None: else: autocontrol_logger.error("Executor error %r", self.executor) - def add_package_to_target(self, package: str, target) -> None: + def add_package_to_target(self, package: str, target: "Optional[Executor | CallbackFunctionExecutor]") -> None: """ 將套件所有成員加入目標事件字典 Add all package members to target event_dict diff --git a/je_auto_control/utils/path_guard/path_guard.py b/je_auto_control/utils/path_guard/path_guard.py index 411788818..89707a606 100644 --- a/je_auto_control/utils/path_guard/path_guard.py +++ b/je_auto_control/utils/path_guard/path_guard.py @@ -45,8 +45,8 @@ def default_allowed_roots() -> List[Path]: return roots -def validate_path(raw: os.PathLike | str, *, - allowed_roots: Optional[Iterable[os.PathLike | str]] = None, +def validate_path(raw: os.PathLike[str] | str, *, + allowed_roots: Optional[Iterable[os.PathLike[str] | str]] = None, allowed_suffixes: Optional[Sequence[str]] = None, must_exist: bool = False) -> Path: """Return ``raw`` canonicalised, or raise :class:`PathNotAllowedError`. @@ -81,7 +81,7 @@ def _home() -> Path: raise PathNotAllowedError(f"no home directory: {error}") from error -def _canonical(value: os.PathLike | str) -> Path: +def _canonical(value: os.PathLike[str] | str) -> Path: try: return Path(os.path.realpath(Path(value).expanduser())) except RuntimeError as error: diff --git a/je_auto_control/utils/process_mining/process_mining.py b/je_auto_control/utils/process_mining/process_mining.py index aea5f67a1..05ca2fab5 100644 --- a/je_auto_control/utils/process_mining/process_mining.py +++ b/je_auto_control/utils/process_mining/process_mining.py @@ -52,12 +52,12 @@ def _command_names(actions: Sequence[Any]) -> List[str]: return [_command_name(action) for action in actions] -def _non_overlapping_counts(names: List[str], length: int) -> Counter: +def _non_overlapping_counts(names: List[str], length: int) -> Counter[Tuple[str, ...]]: """How often each n-gram repeats without overlapping itself. Counting every window made "A A A A" three repetitions of "A A". """ - counter: Counter = Counter() + counter: Counter[Tuple[str, ...]] = Counter() next_free: Dict[Tuple[str, ...], int] = {} for start in range(len(names) - length + 1): gram = tuple(names[start:start + length]) @@ -95,7 +95,7 @@ def find_repeated_sequences(actions: Sequence[Any], *, min_len: int = 2, def directly_follows(actions: Sequence[Any]) -> Dict[Tuple[str, str], int]: """Return the directly-follows edge counts of the command flow.""" names = _command_names(actions) - edges: Counter = Counter( + edges: Counter[Tuple[str, str]] = Counter( (names[i], names[i + 1]) for i in range(len(names) - 1)) return dict(edges) diff --git a/je_auto_control/utils/project/template/template_keyword.py b/je_auto_control/utils/project/template/template_keyword.py index d266e26a4..a83c68926 100644 --- a/je_auto_control/utils/project/template/template_keyword.py +++ b/je_auto_control/utils/project/template/template_keyword.py @@ -1,4 +1,6 @@ -template_keyword_1: list = [ +from typing import Any, List + +template_keyword_1: List[List[Any]] = [ ["AC_set_record_enable", [True]], ["AC_write", {"write_string": "Hello World"}], ["AC_type_keyboard", {"keycode": "return"}], @@ -21,7 +23,7 @@ ["AC_type_keyboard", {"keycode": "return"}] ] -template_keyword_2: list = [ +template_keyword_2: List[List[Any]] = [ ["AC_set_record_enable", [True]], ["AC_write", {"write_string": "in this keyword file we will change the mouse position"}], ["AC_type_keyboard", {"keycode": "return"}], diff --git a/je_auto_control/utils/pytest_plugin/bdd_steps.py b/je_auto_control/utils/pytest_plugin/bdd_steps.py index 94139dfc9..63d76035c 100644 --- a/je_auto_control/utils/pytest_plugin/bdd_steps.py +++ b/je_auto_control/utils/pytest_plugin/bdd_steps.py @@ -47,7 +47,7 @@ def when_press_key(keycode: str) -> None: keyword_press_key(keycode) -def when_click_image(path: str) -> tuple: +def when_click_image(path: str) -> tuple[int, int]: """``When I click on image ""`` — locate + click.""" return keyword_click_image(path) @@ -59,12 +59,12 @@ def when_take_screenshot(path: str) -> str: # === Then ================================================================== -def then_see_image(path: str, timeout: float = 10.0) -> tuple: +def then_see_image(path: str, timeout: float = 10.0) -> tuple[int, int]: """``Then I see image ""`` — waits up to ``timeout`` seconds.""" return keyword_wait_for_image(path, timeout=timeout) -def then_see_text(text: str, timeout: float = 10.0) -> tuple: +def then_see_text(text: str, timeout: float = 10.0) -> tuple[int, int]: """``Then I see text ""`` — OCR wait.""" return keyword_wait_for_text(text, timeout=timeout) diff --git a/je_auto_control/utils/pytest_plugin/keywords.py b/je_auto_control/utils/pytest_plugin/keywords.py index 20a25b980..332d30c72 100644 --- a/je_auto_control/utils/pytest_plugin/keywords.py +++ b/je_auto_control/utils/pytest_plugin/keywords.py @@ -6,7 +6,7 @@ """ from __future__ import annotations -from typing import Optional, Tuple +from typing import List, Optional, Tuple from je_auto_control.utils.timeouts import deadline_after @@ -35,7 +35,7 @@ def keyword_press_key(keycode: str) -> None: def keyword_screenshot(path: str, - region: Optional[list] = None) -> str: + region: Optional[List[int]] = None) -> str: """Capture the screen (or ``region``) to ``path``; returns the path.""" from je_auto_control.wrapper.auto_control_screen import screenshot screenshot(file_path=path, screen_region=region) @@ -75,7 +75,7 @@ def keyword_wait_for_image(image_path: str, def keyword_wait_for_text(text: str, timeout: float = 10.0, - region: Optional[list] = None) -> Tuple[int, int]: + region: Optional[List[int]] = None) -> Tuple[int, int]: """Block until ``text`` is rendered on screen via OCR.""" from je_auto_control.utils.ocr.ocr_engine import wait_for_text return wait_for_text(text, timeout=float(timeout), region=region) diff --git a/je_auto_control/utils/reading_flow/reading_flow.py b/je_auto_control/utils/reading_flow/reading_flow.py index d9f0316b7..f0210dff6 100644 --- a/je_auto_control/utils/reading_flow/reading_flow.py +++ b/je_auto_control/utils/reading_flow/reading_flow.py @@ -49,7 +49,7 @@ def _center_on(box: Box, axis: str) -> float: return (low + high) / 2.0 -def _widest_gap(boxes: Sequence[Box], axis: str, min_gap: int): +def _widest_gap(boxes: Sequence[Box], axis: str, min_gap: int) -> Optional[Tuple[float, float]]: """Return ``(position, width)`` of the widest whitespace gap on ``axis``, or ``None``.""" spans = sorted(_axis_bounds(box, axis) for box in boxes) best_pos: Optional[float] = None @@ -65,7 +65,7 @@ def _widest_gap(boxes: Sequence[Box], axis: str, min_gap: int): return None -def _choose_axis(boxes: Sequence[Box], min_gap: int): +def _choose_axis(boxes: Sequence[Box], min_gap: int) -> Optional[Tuple[str, float]]: """Return ``(axis, position)`` of the widest gap across both axes, or ``None``.""" candidates = [] for axis in ("x", "y"): diff --git a/je_auto_control/utils/remote_desktop/audit_log.py b/je_auto_control/utils/remote_desktop/audit_log.py index 3722c0694..7be618699 100644 --- a/je_auto_control/utils/remote_desktop/audit_log.py +++ b/je_auto_control/utils/remote_desktop/audit_log.py @@ -24,7 +24,7 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -236,7 +236,7 @@ def _maybe_prune_locked(self) -> None: def query(self, *, event_type: Optional[str] = None, host_id: Optional[str] = None, - limit: int = 500) -> List[dict]: + limit: int = 500) -> List[Dict[str, Any]]: sql, args = _build_query_sql( event_type=event_type, host_id=host_id, limit=int(limit), ) @@ -324,7 +324,7 @@ def _compute_row_hash(prev_hash: Optional[str], ts: str, event_type: str, def _build_query_sql(*, event_type: Optional[str], host_id: Optional[str], - limit: int) -> Tuple[str, list]: + limit: int) -> Tuple[str, List[Any]]: """Return a static SQL string + bound args for an audit-log query. The SQL is a single fixed template; optional filters are toggled @@ -332,7 +332,7 @@ def _build_query_sql(*, event_type: Optional[str], host_id: Optional[str], literal-only means there is no string concatenation for static analysers to mistake for SQL injection. """ - args: list = [event_type, event_type, host_id, host_id, int(limit)] + args: List[Any] = [event_type, event_type, host_id, host_id, int(limit)] return _QUERY_SQL, args diff --git a/je_auto_control/utils/remote_desktop/fingerprint.py b/je_auto_control/utils/remote_desktop/fingerprint.py index c3d1321db..e1ad064ff 100644 --- a/je_auto_control/utils/remote_desktop/fingerprint.py +++ b/je_auto_control/utils/remote_desktop/fingerprint.py @@ -20,7 +20,7 @@ import threading from datetime import datetime, timezone from pathlib import Path -from typing import Dict, Optional +from typing import Any, Dict, Optional from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.json_store.json_store import ( @@ -73,7 +73,7 @@ class KnownHosts: def __init__(self, path: Optional[Path] = None) -> None: self._path = (Path(path) if path is not None else _known_hosts_path()) self._lock = threading.Lock() - self._entries: Dict[str, dict] = {} + self._entries: Dict[str, Dict[str, Optional[str]]] = {} self._load() def _load(self) -> None: @@ -94,7 +94,7 @@ def _load(self) -> None: self._entries[host_id] = entry @staticmethod - def _normalise_entry(value) -> Optional[dict]: + def _normalise_entry(value: Any) -> Optional[Dict[str, Optional[str]]]: """Coerce a stored known-hosts value into an entry, or ``None``.""" if isinstance(value, str): return {"app_fp": value, "dtls_fp": None, "last_seen": None} @@ -166,7 +166,7 @@ def forget(self, host_id: str) -> bool: self._save() return removed - def list_entries(self) -> Dict[str, dict]: + def list_entries(self) -> Dict[str, Dict[str, Optional[str]]]: with self._lock: return {hid: dict(entry) for hid, entry in self._entries.items()} diff --git a/je_auto_control/utils/remote_desktop/host_access.py b/je_auto_control/utils/remote_desktop/host_access.py index 7906b7eac..3d561d037 100644 --- a/je_auto_control/utils/remote_desktop/host_access.py +++ b/je_auto_control/utils/remote_desktop/host_access.py @@ -9,7 +9,7 @@ """ import time from dataclasses import dataclass -from typing import Any, Callable, List, Optional, Sequence +from typing import Any, Callable, Iterator, List, Optional, Sequence, Tuple from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -26,7 +26,7 @@ class PendingViewer: * ``"view_only"`` → admit, but drop incoming INPUT messages * ``False`` / ``None`` / etc. → reject """ - address: tuple + address: Tuple[Any, ...] host_id: str transport: str = "tcp" @@ -52,7 +52,7 @@ def _interpret_approval(result: Any) -> str: _AUTH_TIMEOUT_S = 60.0 -def _candidate_totp_codes(secret: str): +def _candidate_totp_codes(secret: str) -> Iterator[str]: """Yield TOTP codes within ±1 step of the current 30-second window.""" from je_auto_control.utils.remote_desktop.totp import generate_code now = time.time() diff --git a/je_auto_control/utils/remote_desktop/host_client.py b/je_auto_control/utils/remote_desktop/host_client.py index 2c1597c4e..66326611a 100644 --- a/je_auto_control/utils/remote_desktop/host_client.py +++ b/je_auto_control/utils/remote_desktop/host_client.py @@ -10,7 +10,7 @@ import collections import json import threading -from typing import TYPE_CHECKING, Deque, NoReturn, Optional +from typing import TYPE_CHECKING, Deque, NoReturn, Optional, Any, Set, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption @@ -52,7 +52,7 @@ class _ClientHandler: _AUDIO_QUEUE_MAXLEN = 50 # ~2.5 s of buffered chunks at 50 ms each def __init__(self, host: "RemoteDesktopHost", - channel: MessageChannel, address) -> None: + channel: MessageChannel, address: Tuple[Any, ...]) -> None: self._host = host self._channel = channel self._address = address @@ -71,14 +71,14 @@ def __init__(self, host: "RemoteDesktopHost", self.clipboard_guard = ClipboardEchoGuard() # Transfers this viewer began: aborted if it disconnects mid-file, # which used to leave the .part file and its open handle behind. - self._transfer_ids: set = set() + self._transfer_ids: Set[str] = set() # Phase 5.3: per-client permission set by the approval callback. # Default is full control so legacy callers (no callback) keep # the prior behaviour. self.permission = PERMISSION_FULL @property - def address(self): + def address(self) -> Tuple[Any, ...]: return self._address def start(self) -> None: diff --git a/je_auto_control/utils/remote_desktop/protocol.py b/je_auto_control/utils/remote_desktop/protocol.py index 7213bce93..56d249eb4 100644 --- a/je_auto_control/utils/remote_desktop/protocol.py +++ b/je_auto_control/utils/remote_desktop/protocol.py @@ -6,6 +6,7 @@ and high-level semantics live in :mod:`auth`, :mod:`host`, :mod:`viewer`. """ import enum +import socket import struct from typing import Tuple @@ -77,7 +78,7 @@ def decode_frame_header(header: bytes) -> Tuple[MessageType, int]: raise ProtocolError(f"unknown message type 0x{type_byte:02x}") from error -def read_exact(sock, length: int) -> bytes: +def read_exact(sock: socket.socket, length: int) -> bytes: """Read exactly ``length`` bytes from ``sock`` or raise ConnectionError.""" chunks = [] remaining = length @@ -90,7 +91,7 @@ def read_exact(sock, length: int) -> bytes: return b"".join(chunks) -def read_message(sock) -> Tuple[MessageType, bytes]: +def read_message(sock: socket.socket) -> Tuple[MessageType, bytes]: """Read one full ``(type, payload)`` message from ``sock``.""" header = read_exact(sock, HEADER_SIZE) msg_type, length = decode_frame_header(header) diff --git a/je_auto_control/utils/remote_desktop/registry.py b/je_auto_control/utils/remote_desktop/registry.py index 6636ddd33..1f160336a 100644 --- a/je_auto_control/utils/remote_desktop/registry.py +++ b/je_auto_control/utils/remote_desktop/registry.py @@ -34,7 +34,7 @@ import itertools import ssl import threading -from typing import Any, Callable, Dict, NamedTuple, Optional, Sequence +from typing import Any, Callable, Dict, NamedTuple, Optional, Sequence, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -79,7 +79,7 @@ class _Claim(NamedTuple): on_displaced: Optional[DisplacedCallback] -def _load_webrtc_classes(): +def _load_webrtc_classes() -> Tuple[Any, Any, Any]: """Lazy import — aiortc/av are optional extras; absent ⇒ (None, None, None).""" try: from je_auto_control.utils.remote_desktop.webrtc_host import ( @@ -459,7 +459,7 @@ def ws_send_input(self, action: Dict[str, Any]) -> Dict[str, Any]: # ------------------------------------------------------------------ @staticmethod - def _require_webrtc(): + def _require_webrtc() -> Tuple[Any, Any, Any]: host_cls, viewer_cls, config_cls = _load_webrtc_classes() if host_cls is None: raise RuntimeError( @@ -563,7 +563,7 @@ def webrtc_viewer_status(self) -> Dict[str, Any]: "authenticated": getattr(viewer, "authenticated", False), } - def webrtc_usb_client(self): + def webrtc_usb_client(self) -> Any: """Return the live WebRTC viewer's USB passthrough client, or None. The viewer exposes ``usb_client()`` once the host has opened the diff --git a/je_auto_control/utils/remote_desktop/session_recorder.py b/je_auto_control/utils/remote_desktop/session_recorder.py index 512eaf4c3..c1b07c343 100644 --- a/je_auto_control/utils/remote_desktop/session_recorder.py +++ b/je_auto_control/utils/remote_desktop/session_recorder.py @@ -36,7 +36,7 @@ } -def preset_for_path(path) -> dict: +def preset_for_path(path: str | Path) -> dict[str, str]: """Return codec defaults for a path's extension, or empty dict.""" suffix = str(path).rsplit(".", 1)[-1].lower() return _FORMAT_PRESETS.get(suffix, {}) @@ -63,7 +63,7 @@ def __init__(self, output_path: str, *, self._close_attempted = False self._failures: tuple[str, ...] = () - def _open(self, frame) -> Tuple[ + def _open(self, frame: av.VideoFrame) -> Tuple[ "av.container.OutputContainer", "av.video.stream.VideoStream", ]: """Return the open (container, stream) pair, creating it on first use.""" @@ -91,7 +91,7 @@ def _open(self, frame) -> Tuple[ ) return container, stream - def write_frame(self, frame) -> None: + def write_frame(self, frame: av.VideoFrame) -> None: """Encode one ``av.VideoFrame``; lazy-init the container.""" if self._closed: return diff --git a/je_auto_control/utils/remote_desktop/transport.py b/je_auto_control/utils/remote_desktop/transport.py index e526ebfd2..0e1dbbf9c 100644 --- a/je_auto_control/utils/remote_desktop/transport.py +++ b/je_auto_control/utils/remote_desktop/transport.py @@ -8,7 +8,7 @@ """ import socket import threading -from typing import Tuple +from typing import Optional, Tuple from je_auto_control.utils.remote_desktop.protocol import ( HEADER_SIZE, MessageType, ProtocolError, @@ -30,7 +30,7 @@ def send_typed(self, message_type: MessageType, payload: bytes) -> None: def read_typed(self) -> Tuple[MessageType, bytes]: raise NotImplementedError - def settimeout(self, timeout) -> None: + def settimeout(self, timeout: Optional[float]) -> None: raise NotImplementedError def close(self) -> None: @@ -52,7 +52,7 @@ def send_typed(self, message_type: MessageType, payload: bytes) -> None: def read_typed(self) -> Tuple[MessageType, bytes]: return read_message(self._sock) - def settimeout(self, timeout) -> None: + def settimeout(self, timeout: Optional[float]) -> None: self._sock.settimeout(timeout) def close(self) -> None: @@ -104,7 +104,7 @@ def read_typed(self) -> Tuple[MessageType, bytes]: ) return msg_type, body - def settimeout(self, timeout) -> None: + def settimeout(self, timeout: Optional[float]) -> None: self._sock.settimeout(timeout) def close(self) -> None: diff --git a/je_auto_control/utils/remote_desktop/trust_list.py b/je_auto_control/utils/remote_desktop/trust_list.py index 3804ab467..e0cf8841e 100644 --- a/je_auto_control/utils/remote_desktop/trust_list.py +++ b/je_auto_control/utils/remote_desktop/trust_list.py @@ -20,7 +20,7 @@ import threading from datetime import datetime, timezone from pathlib import Path -from typing import Dict, List, Optional +from typing import Any, Dict, List, Optional from je_auto_control.utils.json_store.json_store import ( atomic_write_text, load_json_or_quarantine, quarantine_file, @@ -42,7 +42,7 @@ class TrustList: def __init__(self, path: Optional[Path] = None) -> None: self._path = Path(path) if path is not None else default_trust_list_path() self._lock = threading.Lock() - self._entries: Dict[str, dict] = {} + self._entries: Dict[str, Dict[str, Any]] = {} self._load() # --- persistence -------------------------------------------------------- @@ -118,7 +118,7 @@ def clear(self) -> None: self._entries.clear() self._save() - def list_entries(self) -> List[dict]: + def list_entries(self) -> List[Dict[str, Any]]: with self._lock: return [dict(entry) for entry in self._entries.values()] diff --git a/je_auto_control/utils/remote_desktop/viewer.py b/je_auto_control/utils/remote_desktop/viewer.py index 5d96ee639..3895aa19f 100644 --- a/je_auto_control/utils/remote_desktop/viewer.py +++ b/je_auto_control/utils/remote_desktop/viewer.py @@ -5,6 +5,7 @@ import ssl import threading import time as _time_module +from types import TracebackType from typing import Any, Callable, Deque, Dict, Mapping, Optional, Tuple from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption @@ -15,7 +16,7 @@ encode_text, ) from je_auto_control.utils.remote_desktop.file_transfer import ( - FileReceiver, FileTransferError, default_download_dir, send_file, + FileReceiver, FileSendResult, FileTransferError, ProgressCallback, default_download_dir, send_file, ) from je_auto_control.utils.remote_desktop.host_id import validate_host_id from je_auto_control.utils.remote_desktop.input_send_queue import ( @@ -398,7 +399,8 @@ def _ensure_file_receiver(self) -> FileReceiver: return self._file_receiver def send_file(self, source_path: str, dest_path: str, - on_progress=None, *, cancelled=None): + on_progress: Optional[ProgressCallback] = None, *, + cancelled: Optional[Callable[[], bool]] = None) -> FileSendResult: """Stream ``source_path`` to ``dest_path`` on the host. Returns the :class:`FileSendResult`. Synchronous: callers wanting @@ -455,7 +457,8 @@ def __enter__(self) -> "RemoteDesktopViewer": self.connect() return self - def __exit__(self, exc_type, exc, tb) -> None: + def __exit__(self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], + tb: Optional[TracebackType]) -> None: self.disconnect() # internals ---------------------------------------------------------- diff --git a/je_auto_control/utils/remote_desktop/webrtc_mic.py b/je_auto_control/utils/remote_desktop/webrtc_mic.py index 69e7d4770..c9021e502 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_mic.py +++ b/je_auto_control/utils/remote_desktop/webrtc_mic.py @@ -15,7 +15,7 @@ from __future__ import annotations import threading -from typing import Optional +from typing import Any, Optional from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -33,7 +33,7 @@ class MicUplinkSender: """Viewer side: stream microphone PCM to the host via a DataChannel.""" - def __init__(self, channel, *, + def __init__(self, channel: Any, *, sample_rate: int = _DEFAULT_SAMPLE_RATE, channels: int = _DEFAULT_CHANNELS, block_frames: int = _DEFAULT_BLOCK_FRAMES, @@ -177,7 +177,7 @@ def stop(self) -> None: def is_running(self) -> bool: return self._player is not None and bool(self._player.is_running) - def on_chunk(self, chunk) -> None: + def on_chunk(self, chunk: object) -> None: """Feed a PCM chunk into the player. Tolerates non-bytes silently.""" if not isinstance(chunk, (bytes, bytearray, memoryview)): return diff --git a/je_auto_control/utils/rich_clipboard/rich_clipboard.py b/je_auto_control/utils/rich_clipboard/rich_clipboard.py index 0efa591cd..2ca76e4d6 100644 --- a/je_auto_control/utils/rich_clipboard/rich_clipboard.py +++ b/je_auto_control/utils/rich_clipboard/rich_clipboard.py @@ -50,7 +50,7 @@ def _header_offset(text: str, name: str) -> Optional[int]: return int(match.group(1)) if match else None -def parse_cf_html(blob) -> str: +def parse_cf_html(blob: bytes | bytearray | str) -> str: """Extract the HTML fragment from a ``CF_HTML`` payload (bytes or str). Prefers the ``StartFragment`` / ``EndFragment`` comment markers, falling back to @@ -92,7 +92,7 @@ def get_clipboard_html() -> Optional[str]: return parse_cf_html(blob) if blob is not None else None -def _html_format_id(): +def _html_format_id() -> int: from je_auto_control.utils.clipboard.win32_clipboard_api import register_format return register_format(_HTML_FORMAT_NAME) diff --git a/je_auto_control/utils/sbom/sbom.py b/je_auto_control/utils/sbom/sbom.py index 7a634f8d9..209d19277 100644 --- a/je_auto_control/utils/sbom/sbom.py +++ b/je_auto_control/utils/sbom/sbom.py @@ -14,7 +14,7 @@ import re from importlib import metadata from pathlib import Path -from typing import Any, Dict, List, Optional, Set +from typing import Any, Dict, Iterator, List, Optional, Set _SCHEMA = "https://cyclonedx.org/schema/bom-1.6.schema.json" _BOM_FORMAT = "CycloneDX" @@ -68,7 +68,7 @@ def _component(dist: "metadata.Distribution") -> Dict[str, Any]: return component -def _iter_distributions(root: Optional[str]): +def _iter_distributions(root: Optional[str]) -> Iterator[metadata.Distribution]: """Yield distributions that have metadata: all installed, or the closure of ``root``.""" if root is None: yield from (dist for dist in metadata.distributions() if _name(dist) is not None) @@ -76,7 +76,7 @@ def _iter_distributions(root: Optional[str]): yield from _closure(root) -def _closure(root: str): +def _closure(root: str) -> Iterator[metadata.Distribution]: """Yield ``root`` and every distribution it requires here, each once.""" seen: Set[str] = set() queue = [root] diff --git a/je_auto_control/utils/shape_locator/shape_locator.py b/je_auto_control/utils/shape_locator/shape_locator.py index 2bad1963a..49ec7eca4 100644 --- a/je_auto_control/utils/shape_locator/shape_locator.py +++ b/je_auto_control/utils/shape_locator/shape_locator.py @@ -24,7 +24,7 @@ _CANNY_HIGH = 150 -def _contours(gray): +def _contours(gray: Any) -> Any: """Canny edges (dilated to close gaps) -> external contours, version-agnostic.""" import cv2 edges = cv2.Canny(gray, _CANNY_LOW, _CANNY_HIGH) @@ -34,7 +34,7 @@ def _contours(gray): return found[0] if len(found) == 2 else found[1] -def _box(contour) -> Dict[str, Any]: +def _box(contour: Any) -> Dict[str, Any]: """Bounding box of one contour as ``{x,y,width,height,area,center,aspect}``.""" import cv2 x, y, width, height = cv2.boundingRect(contour) @@ -57,7 +57,7 @@ def _passes(box: Dict[str, Any], min_area: int, max_area: Optional[int], return True -def _is_rectangle(contour, epsilon: float) -> bool: +def _is_rectangle(contour: Any, epsilon: float) -> bool: """True when the contour approximates to a convex 4-gon (a rectangle).""" import cv2 perimeter = cv2.arcLength(contour, True) diff --git a/je_auto_control/utils/soft_assert/soft_assert.py b/je_auto_control/utils/soft_assert/soft_assert.py index 4e230dc2a..388d217ce 100644 --- a/je_auto_control/utils/soft_assert/soft_assert.py +++ b/je_auto_control/utils/soft_assert/soft_assert.py @@ -8,7 +8,8 @@ Pure-stdlib context manager; imports no ``PySide6``. """ -from typing import Any, List, Literal +from types import TracebackType +from typing import Any, List, Literal, Optional, Tuple from je_auto_control.utils.exception.exceptions import ( AutoControlActionException, AutoControlAssertionException, @@ -28,8 +29,8 @@ class SoftAssertionsFailed(AutoControlAssertionException, AutoControlActionExcep class SoftAssertions: """A scope that records pass/fail checks and raises the aggregate on exit.""" - def __init__(self, raise_on_exit: bool = True): - self._results: List[tuple] = [] + def __init__(self, raise_on_exit: bool = True) -> None: + self._results: List[Tuple[bool, str]] = [] self._raise_on_exit = bool(raise_on_exit) def check(self, condition: Any, message: str = "") -> bool: @@ -64,7 +65,8 @@ def assert_all(self) -> None: def __enter__(self) -> "SoftAssertions": return self - def __exit__(self, exc_type, exc, _tb) -> Literal[False]: + def __exit__(self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], + _tb: Optional[TracebackType]) -> Literal[False]: if exc_type is None and self._raise_on_exit: self.assert_all() elif exc is not None and self.failures and hasattr(exc, "add_note"): diff --git a/je_auto_control/utils/test_record/record_test_class.py b/je_auto_control/utils/test_record/record_test_class.py index 3f197f0d7..3f1786f11 100644 --- a/je_auto_control/utils/test_record/record_test_class.py +++ b/je_auto_control/utils/test_record/record_test_class.py @@ -1,5 +1,5 @@ import datetime -from typing import Optional +from typing import Any, Optional from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.logging.secret_scope import scrub_secret_data, scrub_secret_text from je_auto_control.utils.executor.action_redaction import redact_actions @@ -13,7 +13,7 @@ class TestRecord: - 儲存測試紀錄清單 """ - def __init__(self, init_record: bool = False): + def __init__(self, init_record: bool = False) -> None: """ 初始化 TestRecord Initialize TestRecord @@ -21,7 +21,7 @@ def __init__(self, init_record: bool = False): :param init_record: 是否啟用紀錄 Flag to enable recording """ self.init_record: bool = init_record - self.test_record_list: list[dict] = [] + self.test_record_list: list[dict[str, Any]] = [] def clean_record(self) -> None: """ @@ -45,7 +45,7 @@ def set_record_enable(self, set_enable: bool = True) -> None: test_record_instance = TestRecord() -def record_action_to_list(function_name: str, local_param, +def record_action_to_list(function_name: str, local_param: Any, program_exception: Optional[str] = None) -> None: """ 將動作紀錄加入清單 diff --git a/je_auto_control/utils/test_select/test_select.py b/je_auto_control/utils/test_select/test_select.py index 72f1374e1..cc169ee07 100644 --- a/je_auto_control/utils/test_select/test_select.py +++ b/je_auto_control/utils/test_select/test_select.py @@ -17,7 +17,10 @@ A flow that has never run scores ``0.8`` — untested means risky. """ import time -from typing import Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +if TYPE_CHECKING: + from je_auto_control.utils.run_history import HistoryStore _WEIGHT_FAILURE = 0.5 _WEIGHT_LAST_FAILED = 0.2 @@ -28,7 +31,7 @@ _SECONDS_PER_DAY = 86400.0 -def _open_store(history_path: Optional[str]): +def _open_store(history_path: Optional[str]) -> Tuple["HistoryStore", bool]: """Return ``(store, owned)``; ``owned`` stores must be closed by caller.""" from je_auto_control.utils.run_history import ( HistoryStore, default_history_store) @@ -52,7 +55,7 @@ def _runs_by_flow(store: Any, flows: List[str], limit: int) -> Dict[str, List[An for flow in flows} -def _flaky(chrono: List[str]) -> tuple: +def _flaky(chrono: List[str]) -> Tuple[float, int]: """Return ``(flaky_rate, transition_count)`` over a status sequence.""" if len(chrono) < 2: return 0.0, 0 diff --git a/je_auto_control/utils/text_diff/text_diff.py b/je_auto_control/utils/text_diff/text_diff.py index 8d0eaeb56..b62f5f619 100644 --- a/je_auto_control/utils/text_diff/text_diff.py +++ b/je_auto_control/utils/text_diff/text_diff.py @@ -104,7 +104,7 @@ def _read_hunk(lines: List[str], index: int, old_left: int, return body, index -def _hunk_start(match: "re.Match") -> int: +def _hunk_start(match: "re.Match[str]") -> int: """0-based source line the hunk starts at. ``-N,0`` (a pure insertion, from ``-U0`` diffs) means "after line N", @@ -145,7 +145,7 @@ def _changes(base: List[str], side: List[str]) -> List[Tuple[int, int, List[str] for tag, i1, i2, j1, j2 in matcher.get_opcodes() if tag != "equal"] -def _overlap(ours: List[Tuple], theirs: List[Tuple]) -> bool: +def _overlap(ours: List[Tuple[int, int, List[str]]], theirs: List[Tuple[int, int, List[str]]]) -> bool: """Whether two change lists touch the same base lines. Two insertions at the same point overlap too: which goes first is a diff --git a/je_auto_control/utils/text_regions/text_regions.py b/je_auto_control/utils/text_regions/text_regions.py index d5dc8d6e2..72b723337 100644 --- a/je_auto_control/utils/text_regions/text_regions.py +++ b/je_auto_control/utils/text_regions/text_regions.py @@ -28,7 +28,7 @@ def _box_dict(rect: Rect) -> Dict[str, Any]: "area": width * height, "center": [x + width // 2, y + height // 2]} -def _accept(rect: Rect, shape, min_area: int, max_area: Optional[int], +def _accept(rect: Rect, shape: Sequence[int], min_area: int, max_area: Optional[int], max_aspect: float) -> bool: """Whether an MSER box looks like text (size / aspect, not the whole frame).""" _x, _y, width, height = rect @@ -50,7 +50,7 @@ def _accept(rect: Rect, shape, min_area: int, max_area: Optional[int], {}, {"min_diversity": 0.01}, {"delta": 1, "min_diversity": 0.0}) -def _detect_regions(gray): +def _detect_regions(gray: Any) -> Any: """Return MSER point sets, relaxing diversity pruning if none found.""" import cv2 regions = () @@ -64,7 +64,7 @@ def _detect_regions(gray): return regions -def _filtered_boxes(gray, min_area: int, max_area: Optional[int], +def _filtered_boxes(gray: Any, min_area: int, max_area: Optional[int], max_aspect: float) -> List[Rect]: """Return de-duplicated MSER bounding boxes passing the size / aspect filters.""" import cv2 diff --git a/je_auto_control/utils/text_similarity/text_similarity.py b/je_auto_control/utils/text_similarity/text_similarity.py index 80f4051e1..2aabf65c3 100644 --- a/je_auto_control/utils/text_similarity/text_similarity.py +++ b/je_auto_control/utils/text_similarity/text_similarity.py @@ -8,7 +8,7 @@ Pure standard library; imports no ``PySide6``. Every function is pure (two strings in, number out), so it is fully deterministic in CI. """ -from typing import Set +from typing import List, Set, Tuple _METRICS = ("levenshtein", "damerau_levenshtein", "jaro", "jaro_winkler", "jaccard", "dice") @@ -33,7 +33,7 @@ def levenshtein(a: str, b: str) -> int: return previous[-1] -def _osa_cell(d, a, b, i, j): +def _osa_cell(d: List[List[int]], a: str, b: str, i: int, j: int) -> int: cost = 0 if a[i - 1] == b[j - 1] else 1 value = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost) if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]: @@ -59,7 +59,7 @@ def damerau_levenshtein(a: str, b: str) -> int: return d[-1][-1] -def _match_flags(a: str, b: str, max_dist: int): +def _match_flags(a: str, b: str, max_dist: int) -> Tuple[List[bool], List[bool], int]: a_match = [False] * len(a) b_match = [False] * len(b) matches = 0 @@ -74,7 +74,7 @@ def _match_flags(a: str, b: str, max_dist: int): return a_match, b_match, matches -def _transpositions(a: str, b: str, a_match, b_match) -> int: +def _transpositions(a: str, b: str, a_match: List[bool], b_match: List[bool]) -> int: transposed = 0 k = 0 for i, flag in enumerate(a_match): diff --git a/je_auto_control/utils/time_travel/player.py b/je_auto_control/utils/time_travel/player.py index c7acdfbbe..3a47352f7 100644 --- a/je_auto_control/utils/time_travel/player.py +++ b/je_auto_control/utils/time_travel/player.py @@ -57,7 +57,7 @@ class TimelineSnapshot: relative_time_s: float -def load_action_log(path) -> List[ActionEvent]: +def load_action_log(path: str | os.PathLike[str]) -> List[ActionEvent]: """Load a ``actions.jsonl`` file (one JSON object per line).""" target = Path(os.path.expanduser(str(path))) events: List[ActionEvent] = [] @@ -76,7 +76,7 @@ def load_action_log(path) -> List[ActionEvent]: return sorted(events, key=lambda e: e.timestamp) -def save_action_log(events: Sequence[ActionEvent], path) -> Path: +def save_action_log(events: Sequence[ActionEvent], path: str | os.PathLike[str]) -> Path: """Write events as ``actions.jsonl`` — one JSON object per line.""" target = Path(os.path.expanduser(str(path))) target.parent.mkdir(parents=True, exist_ok=True) @@ -99,7 +99,7 @@ class TimelinePlayer: returns empty slices in that case. """ - def __init__(self, recording_dir) -> None: + def __init__(self, recording_dir: str | os.PathLike[str]) -> None: self._dir = Path(os.path.expanduser(str(recording_dir))) self._frames: List[FrameRef] = [] self._actions: List[ActionEvent] = [] diff --git a/je_auto_control/utils/tls_acme/renewal.py b/je_auto_control/utils/tls_acme/renewal.py index bab212b10..78b5838b6 100644 --- a/je_auto_control/utils/tls_acme/renewal.py +++ b/je_auto_control/utils/tls_acme/renewal.py @@ -16,7 +16,7 @@ _DEFAULT_CHECK_INTERVAL_S = 60 * 60 # one hour -def renewal_due(certificate_path, +def renewal_due(certificate_path: str | os.PathLike[str], *, now: Optional[datetime] = None, threshold: timedelta = _DEFAULT_THRESHOLD) -> bool: """Return ``True`` when the cert at ``certificate_path`` should be renewed. @@ -49,7 +49,7 @@ class RenewalScheduler: answer "is it time yet?" and call the renew hook. """ - def __init__(self, certificate_path, + def __init__(self, certificate_path: str | os.PathLike[str], renew: Callable[[], None], *, threshold: timedelta = _DEFAULT_THRESHOLD, check_interval_s: float = _DEFAULT_CHECK_INTERVAL_S, diff --git a/je_auto_control/utils/usb/passthrough/iokit_backend.py b/je_auto_control/utils/usb/passthrough/iokit_backend.py index 3aa44b6d8..8193df58d 100644 --- a/je_auto_control/utils/usb/passthrough/iokit_backend.py +++ b/je_auto_control/utils/usb/passthrough/iokit_backend.py @@ -30,7 +30,7 @@ import ctypes import platform -from typing import List, Optional +from typing import List, Optional, Tuple from je_auto_control.utils.usb.passthrough.backend import ( BackendDevice, LibusbBackend, UsbBackend, UsbHandle, @@ -45,7 +45,7 @@ _STRING_BUFFER_BYTES = 512 -def _load_frameworks(): +def _load_frameworks() -> Tuple[ctypes.CDLL, ctypes.CDLL]: """Load + bind IOKit and CoreFoundation; raise RuntimeError on failure.""" try: iokit = ctypes.cdll.LoadLibrary(_IOKIT_PATH) @@ -175,7 +175,7 @@ def _read_device(iokit: ctypes.CDLL, core: ctypes.CDLL, def _property_ref(iokit: ctypes.CDLL, core: ctypes.CDLL, - service: int, key_name: str): + service: int, key_name: str) -> Optional[int]: key = core.CFStringCreateWithCString( None, key_name.encode("utf-8"), _K_CFSTRING_UTF8, ) diff --git a/je_auto_control/utils/usbip/server.py b/je_auto_control/utils/usbip/server.py index 6a9810399..81ce36904 100644 --- a/je_auto_control/utils/usbip/server.py +++ b/je_auto_control/utils/usbip/server.py @@ -50,7 +50,7 @@ def __init__(self, backend: UrbBackend, *, self._listen_sock: Optional[socket.socket] = None self._accept_thread: Optional[threading.Thread] = None self._stop = threading.Event() - self._workers: list = [] + self._workers: list[threading.Thread] = [] @property def port(self) -> int: @@ -281,7 +281,7 @@ def _serve_cmd_submit(self, sock: socket.socket, def _recv_exact(sock: socket.socket, n: int) -> bytes: """Block until ``n`` bytes are received or the peer hangs up.""" - chunks: list = [] + chunks: list[bytes] = [] remaining = n while remaining > 0: chunk = sock.recv(remaining) diff --git a/je_auto_control/utils/vision/backends/__init__.py b/je_auto_control/utils/vision/backends/__init__.py index a357bf5a0..93ef711fc 100644 --- a/je_auto_control/utils/vision/backends/__init__.py +++ b/je_auto_control/utils/vision/backends/__init__.py @@ -1,6 +1,6 @@ """VLM backend factory.""" import os -from typing import Optional +from typing import Optional, Tuple from je_auto_control.utils.vision.backends.base import ( VLMBackend, VLMNotAvailableError, @@ -38,7 +38,7 @@ def _build_backend() -> VLMBackend: ) -def _preference_order(preferred: str): +def _preference_order(preferred: str) -> Tuple[str, str]: if preferred == "anthropic": return ("anthropic", "openai") if preferred == "openai": @@ -50,7 +50,7 @@ def _preference_order(preferred: str): return ("anthropic", "openai") -def _try_build(name: str): +def _try_build(name: str) -> Optional[VLMBackend]: if name == "anthropic": from je_auto_control.utils.vision.backends.anthropic_backend import ( AnthropicVLMBackend, diff --git a/je_auto_control/utils/webrunner_bridge/bridge.py b/je_auto_control/utils/webrunner_bridge/bridge.py index 8a70daeb3..cd3683f02 100644 --- a/je_auto_control/utils/webrunner_bridge/bridge.py +++ b/je_auto_control/utils/webrunner_bridge/bridge.py @@ -3,7 +3,7 @@ import importlib.util import inspect -from typing import Any, Callable, List, Mapping, Optional, Sequence +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence from je_auto_control.utils.exception.exceptions import AutoControlException @@ -30,7 +30,7 @@ def is_webrunner_available() -> bool: return False -def _executor(): +def _executor() -> Any: try: from je_web_runner.utils.executor.action_executor import executor except ImportError as exc: # pragma: no cover - optional dep @@ -38,7 +38,7 @@ def _executor(): return executor -def _execute_one() -> Optional[Callable[[list], Any]]: +def _execute_one() -> Optional[Callable[[List[Any]], Any]]: """WebRunner's ``execute_one``, or None on a release that predates it.""" try: from je_web_runner.utils.executor.action_executor import execute_one @@ -47,7 +47,7 @@ def _execute_one() -> Optional[Callable[[list], Any]]: return execute_one -def _call(name: str, callable_obj: Callable[..., Any], params: dict) -> Any: +def _call(name: str, callable_obj: Callable[..., Any], params: Dict[str, Any]) -> Any: """Run the command through ``execute_one`` when WebRunner has it, else directly. ``execute_one`` applies WebRunner's command gates, retry policy and failure diff --git a/je_auto_control/utils/window_capture/window_capture.py b/je_auto_control/utils/window_capture/window_capture.py index 8a5a6d82f..a62d3395a 100644 --- a/je_auto_control/utils/window_capture/window_capture.py +++ b/je_auto_control/utils/window_capture/window_capture.py @@ -23,7 +23,10 @@ import math import sys from pathlib import Path -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Set, Tuple + +if TYPE_CHECKING: + from je_auto_control.utils.window_layout.window_layout import WindowRect Rect = Tuple[int, int, int, int] GeometryProvider = Callable[[str], Optional[Rect]] @@ -220,7 +223,7 @@ def _exact_title_mover() -> LayoutMover: window's title contained -- and every duplicate title -- moved the same first window, leaving the others where they were. """ - used: set = set() + used: Set[int] = set() def move(title: str, x: int, y: int, width: int, height: int, maximize: bool = False) -> bool: if sys.platform != "win32": @@ -341,7 +344,7 @@ def snap_window(title: str, position: str = "left", *, return (mover or _default_mover)(title, x, y, w, h) -def _move_into(titles: List[str], rects, move: WindowMover) -> int: +def _move_into(titles: List[str], rects: Sequence["WindowRect"], move: WindowMover) -> int: """Move each title to the matching rectangle; return the number moved.""" moved = 0 for title, rect in zip(titles, rects): diff --git a/je_auto_control/utils/xml/change_xml_structure/change_xml_structure.py b/je_auto_control/utils/xml/change_xml_structure/change_xml_structure.py index e4c578084..c0895c60c 100644 --- a/je_auto_control/utils/xml/change_xml_structure/change_xml_structure.py +++ b/je_auto_control/utils/xml/change_xml_structure/change_xml_structure.py @@ -2,7 +2,7 @@ from collections import defaultdict from defusedxml import ElementTree as DefusedET # nosec B405 # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml # reason: defusedxml is the safe replacement from xml.etree import ElementTree # nosec B405 # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml # reason: only used to construct trees, not to parse untrusted data -from typing import Any, Dict +from typing import Any, Dict, List # Characters XML 1.0 cannot hold at all, not even as a character reference: # the C0 controls except tab / LF / CR, the surrogates, and U+FFFE / U+FFFF. @@ -30,7 +30,7 @@ def xml_safe_text(text: str) -> str: return _XML_INVALID.sub("\ufffd", text) -def _initial_body(children: list, element: ElementTree.Element) -> Any: +def _initial_body(children: List[ElementTree.Element], element: ElementTree.Element) -> Any: """Pick the starting body form: dict from children, empty dict, or None.""" if children: return _children_to_dict(children) @@ -39,9 +39,9 @@ def _initial_body(children: list, element: ElementTree.Element) -> Any: return None -def _children_to_dict(children: list) -> Dict[str, Any]: +def _children_to_dict(children: List[ElementTree.Element]) -> Dict[str, Any]: """Collapse children into ``{tag: value | [values]}`` form.""" - grouped: Dict[str, list] = defaultdict(list) + grouped: Dict[str, List[Any]] = defaultdict(list) for child_dict in (elements_tree_to_dict(c) for c in children): for key, value in child_dict.items(): grouped[key].append(value) diff --git a/je_auto_control/utils/xml/xml_file/xml_file.py b/je_auto_control/utils/xml/xml_file/xml_file.py index fdc75254c..3d27f3e63 100644 --- a/je_auto_control/utils/xml/xml_file/xml_file.py +++ b/je_auto_control/utils/xml/xml_file/xml_file.py @@ -11,6 +11,7 @@ ) from xml.etree import ElementTree # nosec B405 # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml # reason: only used to construct trees, not to parse untrusted data from xml.etree.ElementTree import ParseError # nosec B405 # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml # reason: exception type used for catching only +from typing import Any from je_auto_control.utils.exception.exception_tags import ( cant_read_xml_error_message, xml_type_error_message, @@ -40,7 +41,7 @@ class XMLParser: - 可輸出 XML 檔案 """ - def __init__(self, xml_string: str, xml_type: str = "string"): + def __init__(self, xml_string: str, xml_type: str = "string") -> None: """ Initialize XMLParser. 初始化 XMLParser @@ -62,7 +63,7 @@ def __init__(self, xml_string: str, xml_type: str = "string"): else: self.xml_parser_from_file() - def xml_parser_from_string(self, **kwargs) -> ElementTree.Element: + def xml_parser_from_string(self, **kwargs: Any) -> ElementTree.Element: """ Parse XML from string. 從字串解析 XML @@ -75,7 +76,7 @@ def xml_parser_from_string(self, **kwargs) -> ElementTree.Element: raise XMLException(f"{cant_read_xml_error_message}: {repr(error)}") from error return self.xml_root - def xml_parser_from_file(self, **kwargs) -> ElementTree.Element: + def xml_parser_from_file(self, **kwargs: Any) -> ElementTree.Element: """ Parse XML from file. 從檔案解析 XML diff --git a/je_auto_control/windows/core/utils/win32_ctype_input.py b/je_auto_control/windows/core/utils/win32_ctype_input.py index eb05804da..ed2058c07 100644 --- a/je_auto_control/windows/core/utils/win32_ctype_input.py +++ b/je_auto_control/windows/core/utils/win32_ctype_input.py @@ -8,7 +8,7 @@ import ctypes from ctypes import wintypes -from typing import Any +from typing import Any, Tuple from je_auto_control.windows.core.utils.win32_vk import WIN32_EventF_UNICODE, WIN32_VkToVSC # Annotated: on a non-Windows target mypy 2.4 treats this module as unreachable @@ -36,7 +36,7 @@ class KeyboardInput(ctypes.Structure): ("time", wintypes.DWORD), ("dwExtraInfo", ctypes.c_void_p)) - def __init__(self, *args, **kwds): + def __init__(self, *args: Any, **kwds: Any) -> None: super(KeyboardInput, self).__init__(*args, **kwds) if not self.dwFlags & WIN32_EventF_UNICODE: self.wScan = user32.MapVirtualKeyExW(self.wVk, WIN32_VkToVSC, 0) @@ -59,7 +59,7 @@ class INPUTUnion(ctypes.Union): ("_input", INPUTUnion)) -def _check_count(result, func, args) -> list: +def _check_count(result: Any, func: Any, args: Tuple[Any, ...]) -> Tuple[Any, ...]: if result == 0: raise ctypes.WinError(ctypes.get_last_error()) # type: ignore[attr-defined] # reason: win32-only ctypes return args diff --git a/je_auto_control/windows/mouse/win32_ctype_mouse_control.py b/je_auto_control/windows/mouse/win32_ctype_mouse_control.py index 463c5339a..464afc08a 100644 --- a/je_auto_control/windows/mouse/win32_ctype_mouse_control.py +++ b/je_auto_control/windows/mouse/win32_ctype_mouse_control.py @@ -1,5 +1,5 @@ import sys -from typing import Tuple, Optional +from typing import Tuple, Optional, Dict from ctypes import windll # type: ignore[attr-defined] # reason: win32-only ctypes from je_auto_control.utils.exception.exception_tags import windows_import_error_message from je_auto_control.utils.exception.exceptions import AutoControlException @@ -49,7 +49,7 @@ # Map a button tuple to (down_msg, down_wparam, up_msg, up_wparam). The X # buttons pack the button id into the wParam high word, per WM_XBUTTON*. -_WINDOW_MESSAGE_TABLE: dict = { +_WINDOW_MESSAGE_TABLE: Dict[Tuple[int, int, int], Tuple[int, int, int, int]] = { win32_mouse_left: (WM_LBUTTONDOWN, MK_LBUTTON, WM_LBUTTONUP, 0), win32_mouse_right: (WM_RBUTTONDOWN, MK_RBUTTON, WM_RBUTTONUP, 0), win32_mouse_middle: (WM_MBUTTONDOWN, MK_MBUTTON, WM_MBUTTONUP, 0), @@ -201,8 +201,8 @@ def _resolve_window_messages( return (down_msg, down_wparam), (up_msg, up_wparam) -def send_mouse_event_to_window(window, mouse_keycode: Tuple[int, int, int], - x: int = 0, y: int = 0): +def send_mouse_event_to_window(window: int, mouse_keycode: Tuple[int, int, int], + x: int = 0, y: int = 0) -> None: """ 將滑鼠事件送到指定視窗 Send mouse event to a specific window diff --git a/je_auto_control/wrapper/auto_control_image.py b/je_auto_control/wrapper/auto_control_image.py index 23ccc5087..d1c53be2c 100644 --- a/je_auto_control/wrapper/auto_control_image.py +++ b/je_auto_control/wrapper/auto_control_image.py @@ -1,4 +1,4 @@ -from typing import List, Tuple +from typing import Any, List, Tuple from je_auto_control.utils.cv2_utils import template_detection from je_auto_control.utils.exception.cancellation import cancellation_checkpoint @@ -9,7 +9,7 @@ from je_auto_control.wrapper.auto_control_mouse import click_mouse, set_mouse_position -def locate_all_image(image, detect_threshold: float = 1.0, +def locate_all_image(image: Any, detect_threshold: float = 1.0, draw_image: bool = False) -> List[List[int]]: """ 找出螢幕上所有符合的影像位置 @@ -33,7 +33,7 @@ def locate_all_image(image, detect_threshold: float = 1.0, raise -def locate_image_center(image, detect_threshold: float = 1.0, +def locate_image_center(image: Any, detect_threshold: float = 1.0, draw_image: bool = False) -> Tuple[int, int]: """ 找出單一影像並回傳中心座標 @@ -59,7 +59,7 @@ def locate_image_center(image, detect_threshold: float = 1.0, raise -def locate_and_click(image, mouse_keycode: int | str, +def locate_and_click(image: Any, mouse_keycode: int | str, detect_threshold: float = 1.0, draw_image: bool = False) -> Tuple[int, int]: """ diff --git a/je_auto_control/wrapper/auto_control_record.py b/je_auto_control/wrapper/auto_control_record.py index efca02f0e..0cdc529a1 100644 --- a/je_auto_control/wrapper/auto_control_record.py +++ b/je_auto_control/wrapper/auto_control_record.py @@ -9,7 +9,7 @@ """ import os import threading -from typing import Optional +from typing import Any, Dict, List, Optional from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.exception.exceptions import AutoControlJsonActionException @@ -37,7 +37,7 @@ def record() -> bool: return False -def stop_record() -> list: +def stop_record() -> List[List[Any]]: """ stop current record @@ -68,7 +68,7 @@ def stop_record() -> list: return [] -def stop_record_timeline() -> list: +def stop_record_timeline() -> List[Dict[str, Any]]: """ 停止錄製並回傳含放開、滾輪與間隔時間的完整事件 Stop recording and return press *and* release, wheel, and ``delta_ms`` @@ -98,7 +98,7 @@ def stop_record_timeline() -> list: def record_to_json(output_path: str, *, stop_event: threading.Event, - timeout: Optional[float] = None) -> list: + timeout: Optional[float] = None) -> List[List[Any]]: """ Record input until ``stop_event`` is set (or ``timeout``), saving to JSON. diff --git a/je_auto_control/wrapper/auto_control_screen.py b/je_auto_control/wrapper/auto_control_screen.py index 93ed0491c..59805fa63 100644 --- a/je_auto_control/wrapper/auto_control_screen.py +++ b/je_auto_control/wrapper/auto_control_screen.py @@ -1,5 +1,5 @@ import sys -from typing import Any, Optional, Tuple +from typing import Any, List, Optional, Tuple from je_auto_control.utils.cv2_utils.optional import require_cv2 from je_auto_control.utils.cv2_utils.screenshot import pil_screenshot @@ -31,7 +31,7 @@ def screen_size() -> Tuple[int, int]: def screenshot(file_path: Optional[str] = None, - screen_region: Optional[list] = None) -> Any: + screen_region: Optional[List[int]] = None) -> Any: """ use to capture current screen 擷取當前螢幕畫面 @@ -78,7 +78,7 @@ def screenshot(file_path: Optional[str] = None, raise -def get_pixel(x: int, y: int, hwnd=None): +def get_pixel(x: int, y: int, hwnd: Optional[int] = None) -> Tuple[int, int, int]: """ 取得指定座標的像素顏色 Get pixel color at given coordinates diff --git a/pyproject.toml b/pyproject.toml index 5bd07a982..febcf2d3d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -360,6 +360,7 @@ module = [ "je_auto_control._export_bindings", "je_auto_control._lazy_exports", "je_auto_control.android", + "je_auto_control.android.adb_client", "je_auto_control.android.apps", "je_auto_control.android.find", "je_auto_control.android.input", @@ -386,20 +387,29 @@ module = [ "je_auto_control.gui._validators", "je_auto_control.gui._weak_call", "je_auto_control.gui._worker_thread", + "je_auto_control.gui.accessibility_tab", "je_auto_control.gui.adaptive", "je_auto_control.gui.adaptive.*", "je_auto_control.gui.adaptive_window", + "je_auto_control.gui.agent_observation_view", + "je_auto_control.gui.agent_transfer_view", "je_auto_control.gui.assertions_tab", + "je_auto_control.gui.audit_log_tab", + "je_auto_control.gui.chatops_tab", "je_auto_control.gui.config_sync_tab", "je_auto_control.gui.config_sync_worker", "je_auto_control.gui.data_source_tab", + "je_auto_control.gui.device_matrix_tab", "je_auto_control.gui.diagnostics_capabilities", "je_auto_control.gui.diagnostics_tab", "je_auto_control.gui.email_triggers_tab", "je_auto_control.gui.failed_stops_view", + "je_auto_control.gui.flakiness_tab", "je_auto_control.gui.flow_editor", "je_auto_control.gui.healing_evaluation_panel", "je_auto_control.gui.healing_evaluation_worker", + "je_auto_control.gui.hotkeys_tab", + "je_auto_control.gui.inspector_tab", "je_auto_control.gui.journal_browser", "je_auto_control.gui.journal_browser_worker", "je_auto_control.gui.journal_candidate_dialog", @@ -410,9 +420,12 @@ module = [ "je_auto_control.gui.language_wrapper.japanese", "je_auto_control.gui.language_wrapper.simplified_chinese", "je_auto_control.gui.language_wrapper.traditional_chinese", + "je_auto_control.gui.live_hud_tab", "je_auto_control.gui.main_widget", + "je_auto_control.gui.main_window", "je_auto_control.gui.manual_run_controls", "je_auto_control.gui.mcp_discovery_view", + "je_auto_control.gui.media_checks_tab", "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", "je_auto_control.gui.plugins_tab", @@ -428,13 +441,18 @@ module = [ "je_auto_control.gui.remote_desktop.connection_recent", "je_auto_control.gui.remote_desktop.folder_sync_controls", "je_auto_control.gui.remote_desktop.folder_sync_io", + "je_auto_control.gui.remote_desktop.frame_display", + "je_auto_control.gui.remote_desktop.host_panel", + "je_auto_control.gui.remote_desktop.remote_screen_window", "je_auto_control.gui.remote_desktop.sparkline", "je_auto_control.gui.remote_desktop.tab", + "je_auto_control.gui.remote_desktop.tray_icon", "je_auto_control.gui.remote_desktop.trusted_group", "je_auto_control.gui.remote_desktop.view_approvals", "je_auto_control.gui.remote_desktop.view_frames", "je_auto_control.gui.remote_desktop.view_lifetime", "je_auto_control.gui.remote_desktop.view_upload", + "je_auto_control.gui.remote_desktop.viewer_screen_window", "je_auto_control.gui.remote_desktop.webrtc_host_connection", "je_auto_control.gui.remote_desktop.webrtc_host_media", "je_auto_control.gui.remote_desktop.webrtc_host_sessions", @@ -449,22 +467,30 @@ module = [ "je_auto_control.gui.remote_desktop.webrtc_viewer_ui", "je_auto_control.gui.remote_desktop_tab", "je_auto_control.gui.rest_api_tab", + "je_auto_control.gui.run_history_tab", "je_auto_control.gui.run_history_timeline", + "je_auto_control.gui.scheduler_tab", "je_auto_control.gui.script_builder", + "je_auto_control.gui.script_builder.builder_tab", "je_auto_control.gui.script_builder.command_schema", "je_auto_control.gui.script_builder.one_time_dialog", "je_auto_control.gui.script_builder.step_form_view", "je_auto_control.gui.script_builder.step_list_view", "je_auto_control.gui.secrets_tab", "je_auto_control.gui.selector", - "je_auto_control.gui.selector.region_selector", - "je_auto_control.gui.selector.template_cropper", + "je_auto_control.gui.selector.*", + "je_auto_control.gui.self_healing_tab", "je_auto_control.gui.tab_registry", "je_auto_control.gui.tab_task_controller", "je_auto_control.gui.task_controller", + "je_auto_control.gui.template_candidate_panel", "je_auto_control.gui.template_candidate_worker", + "je_auto_control.gui.test_suite_tab", "je_auto_control.gui.theme", "je_auto_control.gui.trace_replay_tab", + "je_auto_control.gui.usb_passthrough_prompt", + "je_auto_control.gui.variables_tab", + "je_auto_control.gui.webhooks_tab", "je_auto_control.gui.webrunner_tab", "je_auto_control.gui.window_tab", "je_auto_control.gui.workspace", @@ -477,10 +503,12 @@ module = [ "je_auto_control.ios.screen", "je_auto_control.ios.session", "je_auto_control.linux_wayland", + "je_auto_control.linux_wayland._ctypes_bind", "je_auto_control.linux_wayland._dbus_client", "je_auto_control.linux_wayland._detect", "je_auto_control.linux_wayland._input_state", "je_auto_control.linux_wayland._layout", + "je_auto_control.linux_wayland._select_input", "je_auto_control.linux_wayland._ydotool_cli", "je_auto_control.linux_wayland.capture", "je_auto_control.linux_wayland.ei_default", @@ -490,6 +518,8 @@ module = [ "je_auto_control.linux_wayland.global_shortcuts", "je_auto_control.linux_wayland.input_events", "je_auto_control.linux_wayland.keymap", + "je_auto_control.linux_wayland.listener", + "je_auto_control.linux_wayland.mouse", "je_auto_control.linux_wayland.oeffis", "je_auto_control.linux_wayland.portal", "je_auto_control.linux_wayland.record", @@ -503,6 +533,7 @@ module = [ "je_auto_control.linux_with_x11.mouse", "je_auto_control.linux_with_x11.mouse.*", "je_auto_control.linux_with_x11.record", + "je_auto_control.linux_with_x11.record.*", "je_auto_control.linux_with_x11.screen", "je_auto_control.linux_with_x11.screen.*", "je_auto_control.linux_with_x11.uinput", @@ -523,10 +554,11 @@ module = [ "je_auto_control.utils.accessibility.backends.null_backend", "je_auto_control.utils.accessibility.backends.windows_automation", "je_auto_control.utils.accessibility.backends.windows_events", + "je_auto_control.utils.accessibility.element", "je_auto_control.utils.accessibility.recorder", "je_auto_control.utils.accessibility.tree", "je_auto_control.utils.acme_v2", - "je_auto_control.utils.acme_v2.jws", + "je_auto_control.utils.acme_v2.*", "je_auto_control.utils.act_in_view", "je_auto_control.utils.act_in_view.*", "je_auto_control.utils.act_modes", @@ -538,14 +570,14 @@ module = [ "je_auto_control.utils.action_journal", "je_auto_control.utils.action_journal.*", "je_auto_control.utils.action_lint", - "je_auto_control.utils.action_lint.__main__", - "je_auto_control.utils.action_lint.schema", + "je_auto_control.utils.action_lint.*", "je_auto_control.utils.action_signing", "je_auto_control.utils.action_signing.*", "je_auto_control.utils.actionability", "je_auto_control.utils.adaptive_timeout", "je_auto_control.utils.adaptive_timeout.*", "je_auto_control.utils.admin", + "je_auto_control.utils.admin.*", "je_auto_control.utils.agent", "je_auto_control.utils.agent.backends", "je_auto_control.utils.agent.backends.*", @@ -564,18 +596,25 @@ module = [ "je_auto_control.utils.agent_runtime.android_geometry", "je_auto_control.utils.agent_runtime.android_input_evidence", "je_auto_control.utils.agent_runtime.android_input_windows", + "je_auto_control.utils.agent_runtime.android_scope", "je_auto_control.utils.agent_runtime.android_session", "je_auto_control.utils.agent_runtime.android_transport", "je_auto_control.utils.agent_runtime.api", "je_auto_control.utils.agent_runtime.browser_environment", "je_auto_control.utils.agent_runtime.browser_readonly_scope", + "je_auto_control.utils.agent_runtime.browser_retirement", + "je_auto_control.utils.agent_runtime.browser_transfers", "je_auto_control.utils.agent_runtime.browser_validation", "je_auto_control.utils.agent_runtime.budget_clock", + "je_auto_control.utils.agent_runtime.cli", "je_auto_control.utils.agent_runtime.client", "je_auto_control.utils.agent_runtime.commands", + "je_auto_control.utils.agent_runtime.completion_contract", "je_auto_control.utils.agent_runtime.context", "je_auto_control.utils.agent_runtime.control_admission", + "je_auto_control.utils.agent_runtime.dag_jobs", "je_auto_control.utils.agent_runtime.dag_retention", + "je_auto_control.utils.agent_runtime.dag_service_client", "je_auto_control.utils.agent_runtime.delegation", "je_auto_control.utils.agent_runtime.dialog_scope", "je_auto_control.utils.agent_runtime.document_launch", @@ -584,14 +623,19 @@ module = [ "je_auto_control.utils.agent_runtime.file_dialog_scope", "je_auto_control.utils.agent_runtime.file_target", "je_auto_control.utils.agent_runtime.helper_environment", + "je_auto_control.utils.agent_runtime.helper_owner_linux", "je_auto_control.utils.agent_runtime.images", "je_auto_control.utils.agent_runtime.jobs", "je_auto_control.utils.agent_runtime.local_evidence", + "je_auto_control.utils.agent_runtime.manifest_evidence", + "je_auto_control.utils.agent_runtime.model_tools", "je_auto_control.utils.agent_runtime.models", "je_auto_control.utils.agent_runtime.native_control", "je_auto_control.utils.agent_runtime.native_job", "je_auto_control.utils.agent_runtime.native_recovery", + "je_auto_control.utils.agent_runtime.native_scope", "je_auto_control.utils.agent_runtime.ollama", + "je_auto_control.utils.agent_runtime.origin_policy", "je_auto_control.utils.agent_runtime.owned_channel_factory", "je_auto_control.utils.agent_runtime.owner_service_nested", "je_auto_control.utils.agent_runtime.owner_service_wire", @@ -599,36 +643,53 @@ module = [ "je_auto_control.utils.agent_runtime.parent_watch", "je_auto_control.utils.agent_runtime.path_identity", "je_auto_control.utils.agent_runtime.policy", + "je_auto_control.utils.agent_runtime.presence_channel_linux", "je_auto_control.utils.agent_runtime.presence_endpoint_linux", + "je_auto_control.utils.agent_runtime.presence_handshake", "je_auto_control.utils.agent_runtime.presence_messages_linux", "je_auto_control.utils.agent_runtime.presence_native_types", + "je_auto_control.utils.agent_runtime.presence_owner", "je_auto_control.utils.agent_runtime.presence_peer_linux", "je_auto_control.utils.agent_runtime.presence_pipe_linux", "je_auto_control.utils.agent_runtime.presence_pipe_windows", "je_auto_control.utils.agent_runtime.presence_platform", + "je_auto_control.utils.agent_runtime.presence_protocol", "je_auto_control.utils.agent_runtime.presence_quartz", + "je_auto_control.utils.agent_runtime.presence_reader", "je_auto_control.utils.agent_runtime.presence_security_windows", + "je_auto_control.utils.agent_runtime.presence_server", "je_auto_control.utils.agent_runtime.presence_session_windows", "je_auto_control.utils.agent_runtime.presence_win32", + "je_auto_control.utils.agent_runtime.presence_worker", "je_auto_control.utils.agent_runtime.presence_x11", "je_auto_control.utils.agent_runtime.readiness", + "je_auto_control.utils.agent_runtime.receipts", "je_auto_control.utils.agent_runtime.resume_gate", "je_auto_control.utils.agent_runtime.retention", + "je_auto_control.utils.agent_runtime.runtime", "je_auto_control.utils.agent_runtime.runtime_lock", "je_auto_control.utils.agent_runtime.service", + "je_auto_control.utils.agent_runtime.submission", + "je_auto_control.utils.agent_runtime.target_config", "je_auto_control.utils.agent_runtime.target_continuity", "je_auto_control.utils.agent_runtime.target_factory", + "je_auto_control.utils.agent_runtime.transfer_adoption", "je_auto_control.utils.agent_runtime.transfer_cache", + "je_auto_control.utils.agent_runtime.transfer_destination_scope", "je_auto_control.utils.agent_runtime.transfer_files", "je_auto_control.utils.agent_runtime.transfer_import_jobs", "je_auto_control.utils.agent_runtime.transfer_models", "je_auto_control.utils.agent_runtime.transfer_operations", + "je_auto_control.utils.agent_runtime.transfer_privacy", "je_auto_control.utils.agent_runtime.transfer_records", "je_auto_control.utils.agent_runtime.transport", "je_auto_control.utils.agent_runtime.trigger_history", + "je_auto_control.utils.agent_runtime.trigger_registration", "je_auto_control.utils.agent_runtime.window_pixels", "je_auto_control.utils.agent_runtime.wire_data", + "je_auto_control.utils.agent_runtime.workflow_desktop", "je_auto_control.utils.agent_runtime.workflow_files", + "je_auto_control.utils.agent_runtime.workflow_values", "je_auto_control.utils.agent_runtime.workflow_wait", "je_auto_control.utils.agent_runtime.workspace_scope", "je_auto_control.utils.agent_trace", @@ -673,8 +734,7 @@ module = [ "je_auto_control.utils.chaos", "je_auto_control.utils.chaos.*", "je_auto_control.utils.chatops", - "je_auto_control.utils.chatops.handlers", - "je_auto_control.utils.chatops.router", + "je_auto_control.utils.chatops.*", "je_auto_control.utils.checkpoint", "je_auto_control.utils.checkpoint.*", "je_auto_control.utils.checksum", @@ -729,8 +789,8 @@ module = [ "je_auto_control.utils.cookie_jar.*", "je_auto_control.utils.coordinate_space", "je_auto_control.utils.coordinate_space.*", - "je_auto_control.utils.cost_telemetry.pricing", - "je_auto_control.utils.cost_telemetry.store", + "je_auto_control.utils.cost_telemetry", + "je_auto_control.utils.cost_telemetry.*", "je_auto_control.utils.critic_features", "je_auto_control.utils.critic_features.*", "je_auto_control.utils.critical_exit", @@ -747,10 +807,12 @@ module = [ "je_auto_control.utils.cv2_utils.screen_grabber", "je_auto_control.utils.cv2_utils.screenshot", "je_auto_control.utils.cv2_utils.template_detection", + "je_auto_control.utils.cv2_utils.video_recording", "je_auto_control.utils.cvd_simulate", "je_auto_control.utils.cvd_simulate.*", "je_auto_control.utils.dag", "je_auto_control.utils.dag.graph", + "je_auto_control.utils.dag.managed_tasks", "je_auto_control.utils.dag.task_contract", "je_auto_control.utils.data_drift", "je_auto_control.utils.data_drift.*", @@ -763,11 +825,12 @@ module = [ "je_auto_control.utils.dataset_diff", "je_auto_control.utils.dataset_diff.*", "je_auto_control.utils.dbus_client", - "je_auto_control.utils.dbus_client.cancellable_io", + "je_auto_control.utils.dbus_client.*", "je_auto_control.utils.decision_table", "je_auto_control.utils.decision_table.*", "je_auto_control.utils.dedup_window", "je_auto_control.utils.dedup_window.*", + "je_auto_control.utils.deprecation", "je_auto_control.utils.deterministic", "je_auto_control.utils.deterministic.*", "je_auto_control.utils.device_matrix", @@ -781,6 +844,7 @@ module = [ "je_auto_control.utils.egress", "je_auto_control.utils.egress.*", "je_auto_control.utils.element_diff", + "je_auto_control.utils.element_diff.*", "je_auto_control.utils.element_parse", "je_auto_control.utils.element_parse.*", "je_auto_control.utils.element_proposal", @@ -814,6 +878,7 @@ module = [ "je_auto_control.utils.failure_signature", "je_auto_control.utils.failure_signature.*", "je_auto_control.utils.feature_flags", + "je_auto_control.utils.feature_flags.*", "je_auto_control.utils.feature_match", "je_auto_control.utils.field_entry", "je_auto_control.utils.field_entry.*", @@ -834,13 +899,12 @@ module = [ "je_auto_control.utils.focus_order", "je_auto_control.utils.focus_order.*", "je_auto_control.utils.form_fields", + "je_auto_control.utils.form_fields.*", "je_auto_control.utils.fuzzy", "je_auto_control.utils.fuzzy.*", "je_auto_control.utils.gamepad", "je_auto_control.utils.generate_report", - "je_auto_control.utils.generate_report.generate_json_report", - "je_auto_control.utils.generate_report.generate_xml_report", - "je_auto_control.utils.generate_report.report_path", + "je_auto_control.utils.generate_report.*", "je_auto_control.utils.gettext_catalog", "je_auto_control.utils.gettext_catalog.*", "je_auto_control.utils.governance", @@ -856,6 +920,8 @@ module = [ "je_auto_control.utils.hotkey", "je_auto_control.utils.hotkey.backends", "je_auto_control.utils.hotkey.backends.base", + "je_auto_control.utils.hotkey.backends.windows_backend", + "je_auto_control.utils.hotkey.hotkey_daemon", "je_auto_control.utils.hsv_segment", "je_auto_control.utils.http_cassette", "je_auto_control.utils.http_cassette.*", @@ -870,6 +936,7 @@ module = [ "je_auto_control.utils.humanize", "je_auto_control.utils.humanize.*", "je_auto_control.utils.i18n_test", + "je_auto_control.utils.i18n_test.*", "je_auto_control.utils.icon_classify", "je_auto_control.utils.icon_classify.*", "je_auto_control.utils.idempotency", @@ -912,8 +979,7 @@ module = [ "je_auto_control.utils.list_format", "je_auto_control.utils.list_format.*", "je_auto_control.utils.llm", - "je_auto_control.utils.llm.backends", - "je_auto_control.utils.llm.backends.*", + "je_auto_control.utils.llm.*", "je_auto_control.utils.locale_collation", "je_auto_control.utils.locale_collation.*", "je_auto_control.utils.locale_parse", @@ -940,6 +1006,7 @@ module = [ "je_auto_control.utils.mcp_server.__main__", "je_auto_control.utils.mcp_server._argument_policy", "je_auto_control.utils.mcp_server._authz", + "je_auto_control.utils.mcp_server._call_authority", "je_auto_control.utils.mcp_server._call_run", "je_auto_control.utils.mcp_server._client_requests", "je_auto_control.utils.mcp_server._disclosure_server", @@ -957,8 +1024,11 @@ module = [ "je_auto_control.utils.mcp_server.context", "je_auto_control.utils.mcp_server.disclosure", "je_auto_control.utils.mcp_server.discovery", + "je_auto_control.utils.mcp_server.fake_backend", "je_auto_control.utils.mcp_server.http_sessions", + "je_auto_control.utils.mcp_server.http_transport", "je_auto_control.utils.mcp_server.log_bridge", + "je_auto_control.utils.mcp_server.plugin_watcher", "je_auto_control.utils.mcp_server.prompts", "je_auto_control.utils.mcp_server.rate_limit", "je_auto_control.utils.mcp_server.resources", @@ -988,7 +1058,9 @@ module = [ "je_auto_control.utils.mcp_server.tools._readonly", "je_auto_control.utils.mcp_server.tools._template_candidates", "je_auto_control.utils.mcp_server.tools._validation", + "je_auto_control.utils.mcp_server.tools.plugin_tools", "je_auto_control.utils.media_assert", + "je_auto_control.utils.media_assert.*", "je_auto_control.utils.message_format", "je_auto_control.utils.modifier_state", "je_auto_control.utils.modifier_state.*", @@ -1019,6 +1091,8 @@ module = [ "je_auto_control.utils.ocr", "je_auto_control.utils.ocr.backends", "je_auto_control.utils.ocr.backends.base", + "je_auto_control.utils.ocr.backends.tesseract_backend", + "je_auto_control.utils.ocr.ocr_engine", "je_auto_control.utils.ocr.structure", "je_auto_control.utils.ocr.tesseract_setup", "je_auto_control.utils.ocr.text_span", @@ -1033,8 +1107,9 @@ module = [ "je_auto_control.utils.outbox", "je_auto_control.utils.outbox.*", "je_auto_control.utils.package_manager", + "je_auto_control.utils.package_manager.*", "je_auto_control.utils.path_guard", - "je_auto_control.utils.path_guard.policy", + "je_auto_control.utils.path_guard.*", "je_auto_control.utils.pdf", "je_auto_control.utils.pdf.*", "je_auto_control.utils.percentiles", @@ -1055,16 +1130,15 @@ module = [ "je_auto_control.utils.process_memory", "je_auto_control.utils.process_memory.*", "je_auto_control.utils.process_mining", + "je_auto_control.utils.process_mining.*", "je_auto_control.utils.profiler", "je_auto_control.utils.profiler.*", "je_auto_control.utils.project", - "je_auto_control.utils.project.create_project_structure", - "je_auto_control.utils.project.template", - "je_auto_control.utils.project.template.template_executor", + "je_auto_control.utils.project.*", "je_auto_control.utils.provenance", "je_auto_control.utils.provenance.*", "je_auto_control.utils.pytest_plugin", - "je_auto_control.utils.pytest_plugin.plugin", + "je_auto_control.utils.pytest_plugin.*", "je_auto_control.utils.qr", "je_auto_control.utils.qr.*", "je_auto_control.utils.quarantine", @@ -1075,6 +1149,7 @@ module = [ "je_auto_control.utils.readability", "je_auto_control.utils.readability.*", "je_auto_control.utils.reading_flow", + "je_auto_control.utils.reading_flow.*", "je_auto_control.utils.recording_edit", "je_auto_control.utils.recurrence", "je_auto_control.utils.recurrence.*", @@ -1088,6 +1163,7 @@ module = [ "je_auto_control.utils.remote_desktop._optional.*", "je_auto_control.utils.remote_desktop.adaptive_bitrate", "je_auto_control.utils.remote_desktop.audio_retirement", + "je_auto_control.utils.remote_desktop.audit_log", "je_auto_control.utils.remote_desktop.auth", "je_auto_control.utils.remote_desktop.clipboard_delivery", "je_auto_control.utils.remote_desktop.clipboard_sync", @@ -1095,7 +1171,10 @@ module = [ "je_auto_control.utils.remote_desktop.file_receipts", "je_auto_control.utils.remote_desktop.file_sync", "je_auto_control.utils.remote_desktop.file_transfer", + "je_auto_control.utils.remote_desktop.fingerprint", + "je_auto_control.utils.remote_desktop.host_access", "je_auto_control.utils.remote_desktop.host_capture", + "je_auto_control.utils.remote_desktop.host_client", "je_auto_control.utils.remote_desktop.host_id", "je_auto_control.utils.remote_desktop.input_dispatch", "je_auto_control.utils.remote_desktop.input_send_queue", @@ -1104,14 +1183,20 @@ module = [ "je_auto_control.utils.remote_desktop.media_retirement", "je_auto_control.utils.remote_desktop.permissions", "je_auto_control.utils.remote_desktop.presence", + "je_auto_control.utils.remote_desktop.protocol", "je_auto_control.utils.remote_desktop.rate_limit", + "je_auto_control.utils.remote_desktop.registry", "je_auto_control.utils.remote_desktop.relay", "je_auto_control.utils.remote_desktop.resume_tokens", "je_auto_control.utils.remote_desktop.session_actions", "je_auto_control.utils.remote_desktop.session_quality_cache", + "je_auto_control.utils.remote_desktop.session_recorder", "je_auto_control.utils.remote_desktop.totp", + "je_auto_control.utils.remote_desktop.transport", + "je_auto_control.utils.remote_desktop.trust_list", "je_auto_control.utils.remote_desktop.turn_config", "je_auto_control.utils.remote_desktop.video_codec", + "je_auto_control.utils.remote_desktop.viewer", "je_auto_control.utils.remote_desktop.viewer_id", "je_auto_control.utils.remote_desktop.wake_on_lan", "je_auto_control.utils.remote_desktop.webrtc_file_callbacks", @@ -1122,6 +1207,7 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_host_auth", "je_auto_control.utils.remote_desktop.webrtc_inspector", "je_auto_control.utils.remote_desktop.webrtc_media_owners", + "je_auto_control.utils.remote_desktop.webrtc_mic", "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", "je_auto_control.utils.remote_desktop.webrtc_retirement", "je_auto_control.utils.remote_desktop.ws_host", @@ -1139,6 +1225,7 @@ module = [ "je_auto_control.utils.retry_budget", "je_auto_control.utils.retry_budget.*", "je_auto_control.utils.rich_clipboard", + "je_auto_control.utils.rich_clipboard.*", "je_auto_control.utils.rotated_match", "je_auto_control.utils.run_diff", "je_auto_control.utils.run_history", @@ -1149,6 +1236,7 @@ module = [ "je_auto_control.utils.sarif", "je_auto_control.utils.sarif.*", "je_auto_control.utils.sbom", + "je_auto_control.utils.sbom.*", "je_auto_control.utils.scale_detect", "je_auto_control.utils.scheduler", "je_auto_control.utils.scheduler.*", @@ -1196,6 +1284,7 @@ module = [ "je_auto_control.utils.socket_server", "je_auto_control.utils.socket_server.*", "je_auto_control.utils.soft_assert", + "je_auto_control.utils.soft_assert.*", "je_auto_control.utils.sql", "je_auto_control.utils.sql.*", "je_auto_control.utils.sqlite_support", @@ -1223,7 +1312,9 @@ module = [ "je_auto_control.utils.test_data", "je_auto_control.utils.test_data.*", "je_auto_control.utils.test_record", + "je_auto_control.utils.test_record.*", "je_auto_control.utils.test_select", + "je_auto_control.utils.test_select.*", "je_auto_control.utils.test_shard", "je_auto_control.utils.test_shard.*", "je_auto_control.utils.test_suite", @@ -1231,23 +1322,24 @@ module = [ "je_auto_control.utils.text_blocks", "je_auto_control.utils.text_blocks.*", "je_auto_control.utils.text_diff", + "je_auto_control.utils.text_diff.*", "je_auto_control.utils.text_normalize", "je_auto_control.utils.text_normalize.*", "je_auto_control.utils.text_regions", "je_auto_control.utils.text_similarity", + "je_auto_control.utils.text_similarity.*", "je_auto_control.utils.text_unicode", "je_auto_control.utils.text_unicode.*", "je_auto_control.utils.theme_normalize", "je_auto_control.utils.theme_normalize.*", "je_auto_control.utils.thread_bound", "je_auto_control.utils.time_travel", - "je_auto_control.utils.time_travel.controller", + "je_auto_control.utils.time_travel.*", "je_auto_control.utils.timeouts", "je_auto_control.utils.timeseries", "je_auto_control.utils.timeseries.*", "je_auto_control.utils.tls_acme", - "je_auto_control.utils.tls_acme.challenge", - "je_auto_control.utils.tls_acme.keys", + "je_auto_control.utils.tls_acme.*", "je_auto_control.utils.tool_use_schema", "je_auto_control.utils.trace_context", "je_auto_control.utils.trace_context.*", @@ -1272,6 +1364,7 @@ module = [ "je_auto_control.utils.usb.passthrough.commands", "je_auto_control.utils.usb.passthrough.descriptor", "je_auto_control.utils.usb.passthrough.flags", + "je_auto_control.utils.usb.passthrough.iokit_backend", "je_auto_control.utils.usb.passthrough.key_provider", "je_auto_control.utils.usb.passthrough.loopback", "je_auto_control.utils.usb.passthrough.protocol", @@ -1284,6 +1377,7 @@ module = [ "je_auto_control.utils.usbip", "je_auto_control.utils.usbip.backend", "je_auto_control.utils.usbip.protocol", + "je_auto_control.utils.usbip.server", "je_auto_control.utils.verify_field", "je_auto_control.utils.verify_field.*", "je_auto_control.utils.vex", @@ -1293,6 +1387,7 @@ module = [ "je_auto_control.utils.virtualized", "je_auto_control.utils.virtualized.*", "je_auto_control.utils.vision", + "je_auto_control.utils.vision.backends", "je_auto_control.utils.vision.backends._parse", "je_auto_control.utils.vision.backends.base", "je_auto_control.utils.vision.backends.null_backend", @@ -1309,7 +1404,9 @@ module = [ "je_auto_control.utils.watcher", "je_auto_control.utils.watcher.*", "je_auto_control.utils.webrunner_bridge", + "je_auto_control.utils.webrunner_bridge.*", "je_auto_control.utils.window_capture", + "je_auto_control.utils.window_capture.*", "je_auto_control.utils.window_geometry", "je_auto_control.utils.window_geometry.*", "je_auto_control.utils.window_layout", @@ -1319,20 +1416,17 @@ module = [ "je_auto_control.utils.work_queue", "je_auto_control.utils.work_queue.*", "je_auto_control.utils.xml", - "je_auto_control.utils.xml.change_xml_structure", - "je_auto_control.utils.xml.xml_file", + "je_auto_control.utils.xml.*", "je_auto_control.windows", "je_auto_control.windows.core", - "je_auto_control.windows.core.utils", - "je_auto_control.windows.core.utils.win32_keypress_check", - "je_auto_control.windows.core.utils.win32_layout_vk", - "je_auto_control.windows.core.utils.win32_vk", + "je_auto_control.windows.core.*", "je_auto_control.windows.interception", "je_auto_control.windows.interception.*", "je_auto_control.windows.keyboard", "je_auto_control.windows.keyboard.*", "je_auto_control.windows.message", "je_auto_control.windows.mouse", + "je_auto_control.windows.mouse.*", "je_auto_control.windows.record", "je_auto_control.windows.record.win32_record", "je_auto_control.windows.screen", @@ -1345,7 +1439,10 @@ module = [ "je_auto_control.wrapper._platform_osx", "je_auto_control.wrapper._platform_wayland", "je_auto_control.wrapper._platform_windows", + "je_auto_control.wrapper.auto_control_image", "je_auto_control.wrapper.auto_control_mouse", + "je_auto_control.wrapper.auto_control_record", + "je_auto_control.wrapper.auto_control_screen", "je_auto_control.wrapper.auto_control_window", "je_auto_control.wrapper.capabilities", "je_auto_control.wrapper.device_context", diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index 2bf8b840e..3c24e1dd6 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -5,21 +5,13 @@ # (which may not grow). Each is debt, not an exemption: this list may only # shrink. Move a module into the strict block once mypy passes it there, and # delete its line. -je_auto_control.gui.agent_observation_view je_auto_control.gui.agent_tasks_tab -je_auto_control.gui.agent_transfer_view -je_auto_control.gui.template_candidate_panel je_auto_control.utils.agent_runtime.android_adapter je_auto_control.utils.agent_runtime.android_hierarchy -je_auto_control.utils.agent_runtime.android_scope je_auto_control.utils.agent_runtime.browser_commands -je_auto_control.utils.agent_runtime.browser_retirement je_auto_control.utils.agent_runtime.browser_target -je_auto_control.utils.agent_runtime.browser_transfers je_auto_control.utils.agent_runtime.browser_verification je_auto_control.utils.agent_runtime.browser_workflows -je_auto_control.utils.agent_runtime.cli -je_auto_control.utils.agent_runtime.completion_contract je_auto_control.utils.agent_runtime.completion_recovery je_auto_control.utils.agent_runtime.dag_admission je_auto_control.utils.agent_runtime.dag_batch_recording @@ -27,41 +19,26 @@ je_auto_control.utils.agent_runtime.dag_batches je_auto_control.utils.agent_runtime.dag_continuation je_auto_control.utils.agent_runtime.dag_continuation_evidence je_auto_control.utils.agent_runtime.dag_continuation_plan -je_auto_control.utils.agent_runtime.dag_jobs je_auto_control.utils.agent_runtime.dag_local -je_auto_control.utils.agent_runtime.dag_service_client je_auto_control.utils.agent_runtime.dag_transfer_checks je_auto_control.utils.agent_runtime.dag_transfer_stop je_auto_control.utils.agent_runtime.evidence je_auto_control.utils.agent_runtime.evidence_handoff je_auto_control.utils.agent_runtime.handoff_records -je_auto_control.utils.agent_runtime.helper_owner_linux je_auto_control.utils.agent_runtime.input_journal je_auto_control.utils.agent_runtime.input_ledger -je_auto_control.utils.agent_runtime.manifest_evidence -je_auto_control.utils.agent_runtime.model_tools je_auto_control.utils.agent_runtime.native_channel -je_auto_control.utils.agent_runtime.native_scope je_auto_control.utils.agent_runtime.native_target je_auto_control.utils.agent_runtime.native_worker je_auto_control.utils.agent_runtime.observation_refs -je_auto_control.utils.agent_runtime.origin_policy je_auto_control.utils.agent_runtime.presence_broker -je_auto_control.utils.agent_runtime.presence_channel_linux je_auto_control.utils.agent_runtime.presence_frames -je_auto_control.utils.agent_runtime.presence_handshake je_auto_control.utils.agent_runtime.presence_host -je_auto_control.utils.agent_runtime.presence_owner je_auto_control.utils.agent_runtime.presence_pool -je_auto_control.utils.agent_runtime.presence_protocol -je_auto_control.utils.agent_runtime.presence_reader -je_auto_control.utils.agent_runtime.presence_server je_auto_control.utils.agent_runtime.presence_state je_auto_control.utils.agent_runtime.presence_windows -je_auto_control.utils.agent_runtime.presence_worker je_auto_control.utils.agent_runtime.readonly_target je_auto_control.utils.agent_runtime.readonly_worker -je_auto_control.utils.agent_runtime.receipts je_auto_control.utils.agent_runtime.recovery_authorization je_auto_control.utils.agent_runtime.remote_effect je_auto_control.utils.agent_runtime.remote_journal @@ -72,15 +49,12 @@ je_auto_control.utils.agent_runtime.retained_browser_runtime je_auto_control.utils.agent_runtime.retained_browser_target je_auto_control.utils.agent_runtime.routes je_auto_control.utils.agent_runtime.runner -je_auto_control.utils.agent_runtime.runtime je_auto_control.utils.agent_runtime.skill_completion je_auto_control.utils.agent_runtime.skill_execution je_auto_control.utils.agent_runtime.skill_parameters je_auto_control.utils.agent_runtime.skill_reauthorization je_auto_control.utils.agent_runtime.skill_recording je_auto_control.utils.agent_runtime.store -je_auto_control.utils.agent_runtime.submission -je_auto_control.utils.agent_runtime.target_config je_auto_control.utils.agent_runtime.target_profiles je_auto_control.utils.agent_runtime.targets je_auto_control.utils.agent_runtime.task_authority @@ -88,8 +62,6 @@ je_auto_control.utils.agent_runtime.task_handoff je_auto_control.utils.agent_runtime.task_recovery je_auto_control.utils.agent_runtime.task_skills je_auto_control.utils.agent_runtime.task_triggers -je_auto_control.utils.agent_runtime.transfer_adoption -je_auto_control.utils.agent_runtime.transfer_destination_scope je_auto_control.utils.agent_runtime.transfer_evidence je_auto_control.utils.agent_runtime.transfer_evidence_contract je_auto_control.utils.agent_runtime.transfer_evidence_management @@ -100,7 +72,6 @@ je_auto_control.utils.agent_runtime.transfer_import_files je_auto_control.utils.agent_runtime.transfer_import_ledger je_auto_control.utils.agent_runtime.transfer_lineage je_auto_control.utils.agent_runtime.transfer_management -je_auto_control.utils.agent_runtime.transfer_privacy je_auto_control.utils.agent_runtime.transfer_protocol je_auto_control.utils.agent_runtime.transfer_routing je_auto_control.utils.agent_runtime.transfer_selection @@ -109,14 +80,9 @@ je_auto_control.utils.agent_runtime.transfer_staging je_auto_control.utils.agent_runtime.transfer_transport je_auto_control.utils.agent_runtime.trigger_config je_auto_control.utils.agent_runtime.trigger_reauthorization -je_auto_control.utils.agent_runtime.trigger_registration je_auto_control.utils.agent_runtime.verification -je_auto_control.utils.agent_runtime.workflow_desktop je_auto_control.utils.agent_runtime.workflow_specs -je_auto_control.utils.agent_runtime.workflow_values je_auto_control.utils.dag.batch_contract je_auto_control.utils.dag.batch_execution je_auto_control.utils.dag.inspection -je_auto_control.utils.dag.managed_tasks -je_auto_control.utils.mcp_server._call_authority je_auto_control.utils.mcp_server.tools._discovery diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 47e4b9372..e29aa4fc0 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -13,114 +13,68 @@ # * A deleted or renamed module loses its line in the same change; a module # written later under the same name is new and therefore strict. # -je_auto_control.android.adb_client je_auto_control.android.client je_auto_control.gui._auto_click_tab je_auto_control.gui._record_tab je_auto_control.gui._script_tab je_auto_control.gui.a11y_audit_tab -je_auto_control.gui.accessibility_tab je_auto_control.gui.admin_console_tab -je_auto_control.gui.audit_log_tab -je_auto_control.gui.chatops_tab je_auto_control.gui.computer_use_tab je_auto_control.gui.dag_tab -je_auto_control.gui.device_matrix_tab -je_auto_control.gui.flakiness_tab je_auto_control.gui.flow_editor.layout je_auto_control.gui.flow_editor.scene je_auto_control.gui.flow_editor.tab -je_auto_control.gui.hotkeys_tab -je_auto_control.gui.inspector_tab je_auto_control.gui.language_wrapper.multi_language_wrapper -je_auto_control.gui.live_hud_tab je_auto_control.gui.llm_planner_tab -je_auto_control.gui.main_window -je_auto_control.gui.media_checks_tab je_auto_control.gui.ocr_tab je_auto_control.gui.recording_editor_tab je_auto_control.gui.remote_desktop._helpers je_auto_control.gui.remote_desktop.annotation_overlay je_auto_control.gui.remote_desktop.connection_screen -je_auto_control.gui.remote_desktop.frame_display -je_auto_control.gui.remote_desktop.host_panel -je_auto_control.gui.remote_desktop.remote_screen_window -je_auto_control.gui.remote_desktop.tray_icon je_auto_control.gui.remote_desktop.viewer_panel -je_auto_control.gui.remote_desktop.viewer_screen_window je_auto_control.gui.remote_desktop.webrtc_dialogs je_auto_control.gui.remote_desktop.webrtc_known_hosts je_auto_control.gui.remote_desktop.webrtc_panel je_auto_control.gui.remote_desktop.webrtc_workers -je_auto_control.gui.run_history_tab -je_auto_control.gui.scheduler_tab -je_auto_control.gui.script_builder.builder_tab je_auto_control.gui.script_builder.step_model -je_auto_control.gui.selector.region_overlay -je_auto_control.gui.self_healing_tab -je_auto_control.gui.test_suite_tab je_auto_control.gui.triggers_tab je_auto_control.gui.usb_browser_tab je_auto_control.gui.usb_devices_tab je_auto_control.gui.usb_passthrough_panel -je_auto_control.gui.usb_passthrough_prompt -je_auto_control.gui.variables_tab je_auto_control.gui.vlm_tab -je_auto_control.gui.webhooks_tab je_auto_control.ios.client -je_auto_control.linux_wayland._ctypes_bind -je_auto_control.linux_wayland._select_input je_auto_control.linux_wayland.keyboard je_auto_control.linux_wayland.libei -je_auto_control.linux_wayland.listener -je_auto_control.linux_wayland.mouse je_auto_control.linux_with_x11.listener.x11_linux_listener -je_auto_control.linux_with_x11.record.x11_linux_record je_auto_control.utils.accessibility.accessibility_api je_auto_control.utils.accessibility.backends.macos_backend je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.accessibility.backends.windows_query je_auto_control.utils.accessibility.backends.windows_reads je_auto_control.utils.accessibility.backends.windows_state -je_auto_control.utils.accessibility.element -je_auto_control.utils.acme_v2.client -je_auto_control.utils.action_lint.linter je_auto_control.utils.actionability.actionability -je_auto_control.utils.admin.admin_client je_auto_control.utils.agent.agent_loop je_auto_control.utils.barcode.barcode je_auto_control.utils.callback.callback_function_executor -je_auto_control.utils.chatops.slack_bot je_auto_control.utils.clipboard.clipboard je_auto_control.utils.codegen.codegen je_auto_control.utils.color_match.color_match je_auto_control.utils.color_region.color_region -je_auto_control.utils.cost_telemetry je_auto_control.utils.cv2_utils.screen_record -je_auto_control.utils.cv2_utils.video_recording je_auto_control.utils.dag.runner -je_auto_control.utils.dbus_client.session_bus -je_auto_control.utils.deprecation je_auto_control.utils.edge_lines.edge_lines je_auto_control.utils.edge_match.edge_match -je_auto_control.utils.element_diff.element_diff je_auto_control.utils.executor.action_executor je_auto_control.utils.executor.action_schema je_auto_control.utils.executor.flow_control -je_auto_control.utils.feature_flags.feature_flags je_auto_control.utils.feature_match.feature_match -je_auto_control.utils.form_fields.form_fields je_auto_control.utils.gamepad._facade -je_auto_control.utils.generate_report.generate_html_report je_auto_control.utils.grid_locator.grid_locator je_auto_control.utils.grounding_consensus.grounding_consensus je_auto_control.utils.hotkey.backends.linux_backend je_auto_control.utils.hotkey.backends.macos_backend -je_auto_control.utils.hotkey.backends.windows_backend -je_auto_control.utils.hotkey.hotkey_daemon je_auto_control.utils.hsv_segment.hsv_segment je_auto_control.utils.http_client.http_client -je_auto_control.utils.i18n_test.i18n_test je_auto_control.utils.image_quality.image_quality je_auto_control.utils.img_histogram.img_histogram je_auto_control.utils.input_macro.input_macro @@ -128,115 +82,68 @@ je_auto_control.utils.input_macro.recorder_base je_auto_control.utils.json_contract.json_contract je_auto_control.utils.json_patch.json_patch je_auto_control.utils.json_schema.json_schema -je_auto_control.utils.llm.planner je_auto_control.utils.logging.logging_instance je_auto_control.utils.match_autothresh.match_autothresh je_auto_control.utils.match_ensemble.match_ensemble je_auto_control.utils.match_stability.match_stability je_auto_control.utils.match_trust.match_trust -je_auto_control.utils.mcp_server.fake_backend -je_auto_control.utils.mcp_server.http_transport -je_auto_control.utils.mcp_server.plugin_watcher je_auto_control.utils.mcp_server.server je_auto_control.utils.mcp_server.tools._handlers je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations je_auto_control.utils.mcp_server.tools._handlers_system -je_auto_control.utils.mcp_server.tools.plugin_tools -je_auto_control.utils.media_assert.media je_auto_control.utils.message_format.message_format je_auto_control.utils.motion_regions.motion_regions je_auto_control.utils.observability.tracing je_auto_control.utils.ocr.backends.easyocr_backend je_auto_control.utils.ocr.backends.paddleocr_backend -je_auto_control.utils.ocr.backends.tesseract_backend -je_auto_control.utils.ocr.ocr_engine -je_auto_control.utils.package_manager.package_manager_class -je_auto_control.utils.path_guard.path_guard je_auto_control.utils.perceptual_diff.perceptual_diff je_auto_control.utils.postcondition.postcondition je_auto_control.utils.preprocess.preprocess -je_auto_control.utils.process_mining.process_mining -je_auto_control.utils.project.template.template_keyword -je_auto_control.utils.pytest_plugin.bdd_steps -je_auto_control.utils.pytest_plugin.keywords je_auto_control.utils.rate_limit.rate_limit -je_auto_control.utils.reading_flow.reading_flow je_auto_control.utils.recording_edit.editor je_auto_control.utils.remote_desktop.address_book je_auto_control.utils.remote_desktop.audio -je_auto_control.utils.remote_desktop.audit_log -je_auto_control.utils.remote_desktop.fingerprint je_auto_control.utils.remote_desktop.host -je_auto_control.utils.remote_desktop.host_access -je_auto_control.utils.remote_desktop.host_client je_auto_control.utils.remote_desktop.host_service je_auto_control.utils.remote_desktop.hw_codec je_auto_control.utils.remote_desktop.lan_discovery je_auto_control.utils.remote_desktop.multi_viewer -je_auto_control.utils.remote_desktop.protocol -je_auto_control.utils.remote_desktop.registry -je_auto_control.utils.remote_desktop.session_recorder je_auto_control.utils.remote_desktop.signaling_client je_auto_control.utils.remote_desktop.signaling_server -je_auto_control.utils.remote_desktop.transport -je_auto_control.utils.remote_desktop.trust_list -je_auto_control.utils.remote_desktop.viewer je_auto_control.utils.remote_desktop.webrtc_audio je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host je_auto_control.utils.remote_desktop.webrtc_host_media -je_auto_control.utils.remote_desktop.webrtc_mic je_auto_control.utils.remote_desktop.webrtc_stats je_auto_control.utils.remote_desktop.webrtc_transport je_auto_control.utils.remote_desktop.webrtc_viewer je_auto_control.utils.rest_api.rest_server -je_auto_control.utils.rich_clipboard.rich_clipboard je_auto_control.utils.rotated_match.rotated_match je_auto_control.utils.run_diff.run_diff je_auto_control.utils.saliency.saliency -je_auto_control.utils.sbom.sbom je_auto_control.utils.scale_detect.scale_detect je_auto_control.utils.schema_compat.schema_compat je_auto_control.utils.screen_state.screen_state je_auto_control.utils.secrets.secret_store je_auto_control.utils.shape_locator.shape_locator je_auto_control.utils.shell_process.shell_exec -je_auto_control.utils.soft_assert.soft_assert je_auto_control.utils.ssim.ssim je_auto_control.utils.subpixel_match.subpixel_match je_auto_control.utils.table_grid_fill.table_grid_fill -je_auto_control.utils.test_record.record_test_class -je_auto_control.utils.test_select.test_select -je_auto_control.utils.text_diff.text_diff je_auto_control.utils.text_regions.text_regions -je_auto_control.utils.text_similarity.text_similarity -je_auto_control.utils.time_travel.player -je_auto_control.utils.tls_acme.renewal je_auto_control.utils.tool_use_schema.schema je_auto_control.utils.triggers.email_trigger je_auto_control.utils.triggers.webhook_server je_auto_control.utils.usb.passthrough.acl -je_auto_control.utils.usb.passthrough.iokit_backend je_auto_control.utils.usbip.libusb_backend -je_auto_control.utils.usbip.server -je_auto_control.utils.vision.backends je_auto_control.utils.vision.backends.anthropic_backend je_auto_control.utils.vision.backends.openai_backend je_auto_control.utils.visual_match.visual_match je_auto_control.utils.visual_regression.compare -je_auto_control.utils.webrunner_bridge.bridge -je_auto_control.utils.window_capture.window_capture -je_auto_control.utils.xml.change_xml_structure.change_xml_structure -je_auto_control.utils.xml.xml_file.xml_file -je_auto_control.windows.core.utils.win32_ctype_input je_auto_control.windows.message.window_message -je_auto_control.windows.mouse.win32_ctype_mouse_control je_auto_control.windows.record.win32_input_hook -je_auto_control.wrapper.auto_control_image je_auto_control.wrapper.auto_control_keyboard -je_auto_control.wrapper.auto_control_record -je_auto_control.wrapper.auto_control_screen je_auto_control.wrapper.backend_contract je_auto_control.wrapper.window_backends.macos_backend je_auto_control.wrapper.window_backends.x11_backend From bba080641ae62756cf425e895112dc80ce6cfbea Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 13:05:36 +0800 Subject: [PATCH 125/161] Annotate 89 modules and hold 83 more to the strict typing tier These had four to six missing annotations or bare generics each. The image modules that alias ImageSource to Any, and vlm_tab whose correct annotation exposes a real mismatch, stay listed. --- Progress.md | 2 +- architecture_explore.md | 110 ++++++++-------- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/_auto_click_tab.py | 12 +- je_auto_control/gui/_script_tab.py | 8 +- je_auto_control/gui/a11y_audit_tab.py | 12 +- je_auto_control/gui/admin_console_tab.py | 12 +- je_auto_control/gui/computer_use_tab.py | 10 +- je_auto_control/gui/flow_editor/scene.py | 16 +-- je_auto_control/gui/flow_editor/tab.py | 10 +- .../multi_language_wrapper.py | 12 +- je_auto_control/gui/llm_planner_tab.py | 12 +- je_auto_control/gui/ocr_tab.py | 15 ++- je_auto_control/gui/recording_editor_tab.py | 14 +- .../gui/remote_desktop/_helpers.py | 10 +- .../gui/remote_desktop/viewer_panel.py | 10 +- .../gui/remote_desktop/webrtc_panel.py | 13 +- .../gui/remote_desktop/webrtc_workers.py | 18 +-- .../gui/script_builder/step_model.py | 8 +- je_auto_control/gui/usb_browser_tab.py | 10 +- je_auto_control/gui/usb_devices_tab.py | 13 +- je_auto_control/gui/usb_passthrough_panel.py | 15 ++- je_auto_control/linux_wayland/keyboard.py | 13 +- .../accessibility/backends/macos_backend.py | 10 +- .../accessibility/backends/windows_state.py | 10 +- je_auto_control/utils/agent/agent_loop.py | 11 +- .../utils/agent_runtime/android_adapter.py | 12 +- .../utils/agent_runtime/browser_commands.py | 8 +- .../agent_runtime/browser_verification.py | 8 +- .../utils/agent_runtime/dag_admission.py | 8 +- .../agent_runtime/dag_batch_recording.py | 10 +- .../utils/agent_runtime/dag_local.py | 11 +- .../utils/agent_runtime/evidence.py | 8 +- .../utils/agent_runtime/input_journal.py | 8 +- .../utils/agent_runtime/native_channel.py | 9 +- .../utils/agent_runtime/presence_broker.py | 8 +- .../utils/agent_runtime/presence_host.py | 10 +- .../utils/agent_runtime/presence_state.py | 10 +- .../utils/agent_runtime/readonly_target.py | 8 +- .../utils/agent_runtime/readonly_worker.py | 10 +- .../agent_runtime/recovery_authorization.py | 12 +- .../utils/agent_runtime/remote_effect.py | 10 +- .../utils/agent_runtime/remote_target.py | 10 +- .../agent_runtime/retained_browser_runtime.py | 8 +- je_auto_control/utils/agent_runtime/runner.py | 9 +- .../utils/agent_runtime/skill_parameters.py | 8 +- .../agent_runtime/skill_reauthorization.py | 14 +- .../utils/agent_runtime/targets.py | 10 +- .../utils/agent_runtime/task_handoff.py | 13 +- .../transfer_evidence_management.py | 12 +- .../agent_runtime/transfer_import_contract.py | 8 +- .../agent_runtime/transfer_import_ledger.py | 8 +- .../agent_runtime/transfer_management.py | 12 +- .../utils/agent_runtime/transfer_protocol.py | 10 +- .../utils/agent_runtime/trigger_config.py | 10 +- je_auto_control/utils/clipboard/clipboard.py | 10 +- .../utils/color_match/color_match.py | 8 +- .../utils/cv2_utils/screen_record.py | 9 +- je_auto_control/utils/dag/batch_contract.py | 10 +- je_auto_control/utils/dag/batch_execution.py | 13 +- je_auto_control/utils/dag/inspection.py | 8 +- je_auto_control/utils/dag/runner.py | 8 +- .../utils/executor/action_schema.py | 10 +- .../utils/feature_match/feature_match.py | 16 ++- je_auto_control/utils/gamepad/_facade.py | 16 ++- .../utils/hotkey/backends/macos_backend.py | 12 +- .../utils/hsv_segment/hsv_segment.py | 10 +- .../utils/http_client/http_client.py | 14 +- .../utils/json_contract/json_contract.py | 8 +- .../utils/json_patch/json_patch.py | 8 +- je_auto_control/utils/mcp_server/server.py | 15 ++- .../utils/mcp_server/tools/_discovery.py | 13 +- .../utils/observability/tracing.py | 10 +- .../utils/ocr/backends/easyocr_backend.py | 13 +- .../utils/ocr/backends/paddleocr_backend.py | 15 ++- .../utils/postcondition/postcondition.py | 10 +- .../utils/rate_limit/rate_limit.py | 10 +- je_auto_control/utils/remote_desktop/audio.py | 10 +- .../utils/remote_desktop/signaling_client.py | 10 +- .../utils/remote_desktop/webrtc_audio.py | 10 +- .../utils/remote_desktop/webrtc_host_media.py | 11 +- je_auto_control/utils/rest_api/rest_server.py | 10 +- .../utils/rotated_match/rotated_match.py | 14 +- je_auto_control/utils/run_diff/run_diff.py | 10 +- je_auto_control/utils/saliency/saliency.py | 10 +- .../utils/schema_compat/schema_compat.py | 14 +- .../utils/screen_state/screen_state.py | 12 +- je_auto_control/utils/ssim/ssim.py | 14 +- .../utils/triggers/webhook_server.py | 8 +- je_auto_control/utils/usbip/libusb_backend.py | 8 +- .../utils/visual_regression/compare.py | 8 +- .../windows/message/window_message.py | 12 +- pyproject.toml | 123 +++++++++++------- test/verify/typing_not_yet_strict.txt | 33 ----- test/verify/typing_strict_baseline.txt | 50 ------- 96 files changed, 648 insertions(+), 642 deletions(-) diff --git a/Progress.md b/Progress.md index eba9b9335..6993a2980 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~07,共 1,309 個)。仍缺:`test/verify/typing_strict_baseline.txt` 134 個與 `typing_not_yet_strict.txt` 81 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台約 2,050 個錯誤,集中在 198 個檔案;其中 18 個影像/定位模組只差模組層級的 `ImageSource = Any` 之類的別名,要先定一個共用型別;另有 11 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)),以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~08,共 1,392 個)。仍缺:`test/verify/typing_strict_baseline.txt` 84 個與 `typing_not_yet_strict.txt` 48 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台約 1,600 個錯誤,集中在 109 個檔案,大多是每檔 7 個以上,最多的是 MCP handler 模組與 `action_executor.py`;其中 24 個影像/定位模組只差模組層級的 `ImageSource = Any` 之類的別名,要先定一個共用型別;另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`)),以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index ef4700c84..4421ea024 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,544 | -| 程式碼總行數 | 237,739 | +| 程式碼總行數 | 237,784 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -248,7 +248,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `uinput/keyboard.py` | 44 | uinput 鍵盤後端,介面與 X11 版一致。 | | `uinput/mouse.py` | 130 | uinput 滑鼠後端。 | -#### Linux Wayland(`linux_wayland/`,24 檔/4,445 行) +#### Linux Wayland(`linux_wayland/`,24 檔/4,448 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -266,7 +266,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `ei_transport.py` | 255 | 共用 owned channel 的 EI 客戶端;期限、取消、ACK 鎖內驗證與失敗保留。 | | `ei_default.py` | 121 | 預設 EI 客戶端快取、被動診斷與明確重設。 | | `mouse.py` | 390 | 滑鼠後端:移動、按鈕與捲動都 libei 優先,僅選用缺席時退回 ydotool;權限/裝置拒絕不重送;送往 libei 時垂直捲動軸取負(kernel `REL_WHEEL` 與 `wl_pointer` 正負號相反)。退到 ydotool 的絕對移動會先減掉版面原點(`--absolute` 是相對於版面左上角,不是版面座標的 `(0, 0)`),並依 `pointer_accel_mode()` 處理指標加速度——倍率讀不回來,只有操作者知道,所以由 `JE_AUTOCONTROL_WAYLAND_POINTER_ACCEL` 宣告:未設定=每個行程警告一次後照送、`flat`=已關掉加速度故靜靜送出、`strict`=拒絕這次移動。 | -| `keyboard.py` | 206 | 鍵盤後端:按鍵/組合鍵 libei 優先,權限拒絕不改走 CLI;中斷時逐一釋放原後端已按下的鍵。文字仍用 wtype。 | +| `keyboard.py` | 209 | 鍵盤後端:按鍵/組合鍵 libei 優先,權限拒絕不改走 CLI;中斷時逐一釋放原後端已按下的鍵。文字仍用 wtype。 | | `keymap.py` | 155 | 友善鍵名 → evdev key code。 | | `capture.py` | 250 | 擷取分層:操作者自訂指令 → grim → gnome-screenshot → spectacle → portal。 | | `portal.py` | 234 | `org.freedesktop.portal.Screenshot` 最後備援,直接講 D-Bus;未完成請求在原始 bus 上限時 Request.Close,保留原始控制,已完成 Response 不重複關閉。只需 session bus,不需 gdbus。 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,556 行。 +> 25 個套件、約 19,557 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -300,7 +300,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/action_signing/` | 1,082 | action 檔 HMAC-SHA256 簽章與 Fernet 加密,`execute_files` 會強制驗簽 | | `utils/checkpoint/` | 129 | 流程檢查點與續跑,讓長 action list 具持久性 | | `utils/codegen/` | 1,363 | 由 action list 或結構化日誌產生 pytest/Python/Robot 候選;來源清單、靜態/乾跑驗證與原子 ZIP 審閱匯出。 | -| `utils/dag/` | 1,354 | 跨主機動作/受管任務 DAG;權限及停止傳遞、目的地完成/釋放驗證、去重與未知結果審閱 | +| `utils/dag/` | 1,355 | 跨主機動作/受管任務 DAG;權限及停止傳遞、目的地完成/釋放驗證、去重與未知結果審閱 | | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | @@ -364,7 +364,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.4 輸入模擬與動作品質 -> 22 個套件、約 2,981 行。 +> 22 個套件、約 2,983 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -375,7 +375,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/actionability/` | 194 | 動作前就緒閘門(可見 + 穩定 + 啟用 + 未被遮擋) | | `utils/ensure_state/` | 74 | 冪等地把控制項/設定帶到期望狀態 | | `utils/field_entry/` | 79 | 清空再輸入的欄位填寫慣用法(Playwright `fill`) | -| `utils/gamepad/` | 333 | 虛擬遊戲手把後端(Windows ViGEmBus 驅動) | +| `utils/gamepad/` | 335 | 虛擬遊戲手把後端(Windows ViGEmBus 驅動) | | `utils/humanize/` | 191 | 擬人輸入:貝茲曲線滑鼠路徑 + 抖動打字節奏 | | `utils/ime_state/` | 150 | 讀取即時 IME 組字/轉換狀態,確保 CJK 輸入安全 | | `utils/key_hold/` | 117 | 按住按鍵一段時間,或以固定頻率自動重複 | @@ -393,7 +393,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,564 行。 +> 37 個套件、約 6,571 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -403,10 +403,10 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/color_region/` | 107 | 以顏色定位畫面區域(遮罩 + 連通元件) | | `utils/color_stats/` | 103 | 區域顏色統計:平均色與主色 | | `utils/coordinate_space/` | 93 | 模型網格座標與實體像素之間的座標空間對映 | -| `utils/cv2_utils/` | 1,090 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | +| `utils/cv2_utils/` | 1,091 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | | `utils/edge_lines/` | 131 | 以 Hough 轉換偵測線條/格線/分隔線 | | `utils/edge_match/` | 116 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | -| `utils/feature_match/` | 143 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | +| `utils/feature_match/` | 147 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | | `utils/hsv_segment/` | 104 | HSV 色彩空間分割(抗光照的顏色遮罩 + blob 框) | | `utils/icon_classify/` | 151 | 從像素形狀判斷一個框是哪一類元件 | | `utils/image_dedup/` | 100 | 感知雜湊影像去重(Pillow aHash/dHash) | @@ -422,7 +422,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/perceptual_diff/` | 202 | 感知式(YIQ)影像差異,抑制反鋸齒邊緣誤報 | | `utils/preprocess/` | 276 | OCR/比對前的影像前處理(灰階、二值化、去傾斜…) | | `utils/qr/` | 59 | 從影像或螢幕區域解碼 QR code(OpenCV) | -| `utils/rotated_match/` | 201 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | +| `utils/rotated_match/` | 203 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | | `utils/saliency/` | 114 | 頻譜殘差視覺顯著性:顯著圖與排序後的顯著區域 | | `utils/scale_detect/` | 105 | 偵測樣板實際渲染的顯示縮放/視覺 DPI | | `utils/screen_grid/` | 146 | 供 VLM 接地用的粗粒度標號網格(點 ↔ 格對映) | @@ -437,7 +437,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.6 OCR 與文字理解 -> 19 個套件、約 3,823 行。 +> 19 個套件、約 3,829 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -450,7 +450,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/guardrail/` | 117 | 針對畫面/OCR 文字的啟發式 prompt-injection 防護 | | `utils/heading_segment/` | 71 | 判定 OCR 行是標題或內文,建出文件大綱 | | `utils/near_dup/` | 108 | 近似重複文字偵測(SimHash/MinHash) | -| `utils/ocr/` | 1,387 | OCR 引擎門面 + 三個後端(Tesseract/EasyOCR/PaddleOCR)、版面結構化與跨詞比對(`text_span`)、Tesseract 的尋找/設定/健康檢查(`tesseract_setup`) | +| `utils/ocr/` | 1,393 | OCR 引擎門面 + 三個後端(Tesseract/EasyOCR/PaddleOCR)、版面結構化與跨詞比對(`text_span`)、Tesseract 的尋找/設定/健康檢查(`tesseract_setup`) | | `utils/pii_text/` | 141 | 自由文字中的 PII 偵測與遮蔽(email/電話/SSN/卡號/IP/IBAN) | | `utils/readability/` | 140 | 可讀性評分(Flesch、Flesch-Kincaid、Gunning Fog、SMOG、ARI) | | `utils/reading_flow/` | 165 | 以遞迴 XY-cut 推導欄位感知的閱讀順序 | @@ -516,13 +516,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,967 行。 +> 14 個套件、約 52,980 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | -| `utils/agent/` | 2,253 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,973 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent/` | 2,254 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | +| `utils/agent_runtime/` | 25,979 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -530,21 +530,21 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,235 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,241 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 666 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,238 行。 +> 6 個套件、約 32,239 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,910 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,911 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,579 行。 +> 24 個套件、約 7,585 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -572,7 +572,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/email_send/` | 118 | SMTP 寄信(email 觸發器的發送端搭檔) | | `utils/events/` | 106 | 對外 CloudEvents 發送(執行生命週期事件) | | `utils/http_cassette/` | 200 | 錄製/重播 HTTP 互動,做離線決定性 API 測試 | -| `utils/http_client/` | 272 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | +| `utils/http_client/` | 276 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | | `utils/http_conditional/` | 148 | 條件式 HTTP 請求與快取驗證器 | | `utils/http_content/` | 158 | HTTP 內容協商與回應解壓縮 | | `utils/http_problem/` | 122 | RFC 9457 problem+json 解析 | @@ -584,7 +584,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/otp/` | 37 | TOTP 一次性密碼產生(自動化 2FA 登入) | | `utils/outbox/` | 107 | 交易式 outbox,保證至少一次的事件投遞 | | `utils/pytest_plugin/` | 283 | pytest 外掛 + BDD step library(`pytest11` entry point) | -| `utils/rest_api/` | 2,226 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | +| `utils/rest_api/` | 2,228 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | | `utils/socket_server/` | 164 | 執行 action JSON 的執行緒式 TCP 指令伺服器(預設綁 127.0.0.1) | | `utils/sse_client/` | 142 | Server-Sent Events 用戶端解析 | | `utils/tls_acme/` | 475 | TLS 自動化:HTTP-01 挑戰伺服器、金鑰/CSR、自動續期 | @@ -756,7 +756,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,235 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,241 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -777,7 +777,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `_disclosure_server.py` | 170 | Bind tool availability to transport lifetimes while retaining the existing dispatcher gates. | | `stdio.py` | 23 | Lazy stdio entry point with optional host-configured tool availability. | | `discovery.py` | 141 | Bounded, authority-filtered tool summaries and detached schemas from one registry snapshot. | -| `tools/_discovery.py` | 70 | Small discovery tools query the active server registry instead of constructing another catalogue. | +| `tools/_discovery.py` | 73 | Small discovery tools query the active server registry instead of constructing another catalogue. | | `tools/_capabilities.py` | 29 | 唯讀能力 MCP schema 與共用 headless adapter;拒絕外部 context/授權資料。 | | `tools/_diagnostics.py` | 51 | 主動唯讀診斷 MCP;共用 report、request-owned 取消與進度,拒絕外部 token/授權資料。 | | `tools/_handlers_scheduling.py` | 200 | 同一種 adapter,排程主題:排程器、觸發器、熱鍵常駐。 | @@ -790,7 +790,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers_vision_executor.py` | 564 | 70 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_locators.py` | 436 | 同一種 adapter,定位主題:無障礙樹、智慧等待、自我修復、螢幕觀察、座標空間、視覺與 OCR、影像去重、元件倉庫、A/B 定位。 | | `tools/_handlers_operations.py` | 656 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | -| `server.py` | 627 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、resource/prompt 處理器;`tools/call` 的准入、執行與稽核在 `_tool_calls.py`;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | +| `server.py` | 630 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、resource/prompt 處理器;`tools/call` 的准入、執行與稽核在 `_tool_calls.py`;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | | `_tool_calls.py` | 179 | `tools/call` 路徑(`ToolCallMixin`):請求、RBAC、揭露目錄、schema、參數政策、限流與破壞性確認的准入,以 `ToolCallContext` 執行、寫稽核並轉成結果;失敗截圖在呼叫時才向 `server` 取 `_capture_error_screenshot`。 | | `http_transport.py` | 623 | MCP 的 HTTP 傳輸;宣告 2026-07-28 的請求走 `_http_stateless.py` 的標頭規則,不發 session。 | | `_http_stateless.py` | 185 | MCP 2026-07-28 在 Streamable HTTP 上的規則:`MCP-Protocol-Version`/`Mcp-Method`/`Mcp-Name` 必須與 body 相符(`=?base64?…?=` 先解碼),不符是 400+`HeaderMismatch`;版本與中繼資料錯誤 400、未知方法 404。純函式,由 `http_transport.py` 回覆。 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,910 行/77 檔) +#### `utils/remote_desktop/`(16,911 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -861,7 +861,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | | `lan_discovery.py` | 387 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | -| `webrtc_host_media.py` | 257 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | +| `webrtc_host_media.py` | 258 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | | `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | @@ -906,11 +906,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `usbip/libusb_backend.py` | 224 | 以 PyUSB/libusb 執行 URB 的正式後端。 | | `usbip/backend.py` | 87 | 可插拔 URB 執行後端。 | -#### `utils/rest_api/`(2,226 行) +#### `utils/rest_api/`(2,228 行) | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `rest_server.py` | 711 | HTTP 前端主體;相容 check-only gate,RBAC 必須帶使用者身分。 | +| `rest_server.py` | 713 | HTTP 前端主體;相容 check-only gate,RBAC 必須帶使用者身分。 | | `rest_handlers.py` | 539 | 端點實作。 | | `rest_openapi.py` | 503 | 走訪路由表產生 OpenAPI 3.1 規格。 | | `rest_auth.py` | 227 | Bearer token 驗證 + 逐 client 限流閘門。 | @@ -918,7 +918,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rest_registry.py` | 91 | 保存執行中 REST 伺服器的行程級單例,狀態包含 RBAC 模式並隱去停用的共用 token。 | | `__main__.py` | 66 | `python -m je_auto_control.utils.rest_api` 進入點。 | -#### `utils/cv2_utils/`(1,090 行)— 擷取、影像與共用定位 frame +#### `utils/cv2_utils/`(1,091 行)— 擷取、影像與共用定位 frame | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -930,7 +930,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cv2_utils/optional.py` | 39 | Name the missing image-stack wheel instead of raising ``ModuleNotFoundError``. | | `utils/cv2_utils/region_capture.py` | 64 | Capture a ``[left, top, right, bottom]`` screen region on whichever monitor holds it. | | `utils/cv2_utils/screen_grabber.py` | 229 | One place that decides how this platform's pixels are read. | -| `utils/cv2_utils/screen_record.py` | 124 | Internal image/capture utilities. | +| `utils/cv2_utils/screen_record.py` | 125 | Internal image/capture utilities. | | `utils/cv2_utils/screenshot.py` | 95 | Internal image/capture utilities. | | `utils/cv2_utils/template_detection.py` | 182 | Locate a template image on screen, in the coordinates the mouse takes. | | `utils/cv2_utils/video_recording.py` | 76 | Internal image/capture utilities. | @@ -1045,7 +1045,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,973 行/182 檔) +#### `utils/agent_runtime/`(25,979 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1089,7 +1089,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `dag_continuation_evidence.py` | 169 | Bounded read-only destination evidence for explicit whole-batch continuation decisions. | | `dag_continuation_plan.py` | 89 | Explicit per-node decisions preserve graph scope and never reset a possible delivery claim. | | `dag_jobs.py` | 140 | Service-owned durable DAG deliveries never replay an interrupted coordinator attempt. | -| `dag_local.py` | 97 | Closed local-node transport admits claimed DAG work under the original owner's authority. | +| `dag_local.py` | 98 | Closed local-node transport admits claimed DAG work under the original owner's authority. | | `dag_retention.py` | 127 | Expire settled DAG records while retaining unresolved input and referenced recovery evidence. | | `dag_service_client.py` | 53 | Runtime-bound batch coordination and destination calls refresh both approving and original owners. | | `delegation.py` | 43 | Short-lived, authenticated principal forwarding across the local service boundary. | @@ -1112,7 +1112,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `manifest_evidence.py` | 51 | Independently re-read archive manifests and their scoped files at task completion. | | `model_tools.py` | 65 | Local-model schemas expose observation references without changing legacy executor signatures. | | `models.py` | 214 | Detached JSON contracts for managed computer tasks and their evidence. | -| `native_channel.py` | 278 | Bounded JSON IPC to an owned helper, with cancellable writes, replies and retirement. | +| `native_channel.py` | 279 | Bounded JSON IPC to an owned helper, with cancellable writes, replies and retirement. | | `native_control.py` | 59 | Generation-bound negative-only takeover notices with retained coarse cleanup failure diagnostics. | | `native_job.py` | 170 | Own a Windows helper process tree through a kill-on-close Job Object. | | `native_recovery.py` | 36 | Host-only input recovery checks never replay persisted keys or signal persisted PIDs. | @@ -1166,7 +1166,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `remote_worker.py` | 213 | Owned remote SDK worker with closed RPC, refreshed authority and ACK-gated finite effects. | | `retention.py` | 71 | Thirty-day cleanup of stopped tasks and exclusively owned runtime artifacts. | | `routes.py` | 165 | Authenticated REST adapters for the runtime explicitly owned by a server. | -| `runner.py` | 117 | Autonomous skill/local-model driver over exactly the external task operations. | +| `runner.py` | 118 | Autonomous skill/local-model driver over exactly the external task operations. | | `retained_browser.py` | 148 | Bounded effect-task ownership of actual permanently read-only browser helper processes. | | `retained_browser_runtime.py` | 91 | Connect actual browser retirement to existing runtime leases and private completion bindings. | | `retained_browser_target.py` | 98 | Closed transient read borrowers; the runtime collection owns the original helper lifetime. | @@ -1176,7 +1176,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `skill_completion.py` | 120 | Private read-only evidence for skill recording and publication preserves original workflow identity. | | `skill_execution.py` | 110 | Exact original skill effects across real reviewed recovery, without granting input or replacing trials. | | `skill_parameters.py` | 110 | Explicit typed parameter slots modify data values without widening a skill's authority. | -| `skill_reauthorization.py` | 105 | Review origin renewal into a new immutable candidate without inheriting skill publication. | +| `skill_reauthorization.py` | 107 | Review origin renewal into a new immutable candidate without inheriting skill publication. | | `skill_recording.py` | 105 | Semantic skill drafts retain verified actions, original scope and independent completion evidence. | | `store.py` | 431 | Transactional task metadata, durable action receipts and input ownership. | | `submission.py` | 40 | Admission witnesses bind tagged DAG requests before live scope normalization, without granting authority. | @@ -1186,7 +1186,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `target_profiles.py` | 205 | Durable target profiles, live controls and explicit dependency diagnostics separate from native evidence. | | `targets.py` | 193 | Explicit target adapters; native imports occur only during requested operations. | | `task_authority.py` | 316 | Trusted source-owner recovery admission and live owner/reviewer authority checks. | -| `task_handoff.py` | 81 | Real non-DAG source identity for explicit completion evidence, without fabricated admission. | +| `task_handoff.py` | 82 | Real non-DAG source identity for explicit completion evidence, without fabricated admission. | | `task_recovery.py` | 484 | Review stopped tasks and create one explicitly approved successor without replay. | | `task_skills.py` | 373 | Immutable managed skill candidates require a verified trial and explicit version publication. | | `task_triggers.py` | 271 | Durable preauthorized task bindings with owner refresh, bounded backlog and event deduplication. | @@ -1233,13 +1233,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `transfer_evidence_contract.py` | 108 | Closed portable completion envelopes carry hashes and finite verification, never local authority. | | `transfer_operations.py` | 7 | Closed management names shared by public transfer surfaces, without peer-read operations. | -#### `utils/dag/`(1,354 行/8 檔) +#### `utils/dag/`(1,355 行/8 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `__init__.py` | 33 | Cross-host DAG orchestrator. | | `batch_contract.py` | 77 | Canonical whole-graph identities and destination-only tags for durable managed batches. | -| `batch_execution.py` | 95 | Initial execution of a registered graph with durable pre-delivery claims and verified receipts. | +| `batch_execution.py` | 96 | Initial execution of a registered graph with durable pre-delivery claims and verified receipts. | | `graph.py` | 168 | DAG types: nodes, definition, topological ordering, cycle detection. | | `inspection.py` | 166 | Inspect keyed DAG requests without submitting work or granting continuation. | | `managed_tasks.py` | 348 | Bounded task and artifact transports preserve registered-host authority and completion contracts. | @@ -1364,7 +1364,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | | vlm | `vlm_tab.py` | 150 | 用文字描述 UI 元素,交由模型定位。 | | self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 952 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | -| ocr_reader | `ocr_tab.py` | 192 | 傾印區域文字或以 regex 搜尋。 | +| ocr_reader | `ocr_tab.py` | 193 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | | live_hud | `live_hud_tab.py` | 156 | 即時 HUD:滑鼠位置、游標下像素色、log tail。 | | llm_planner | `llm_planner_tab.py` | 196 | 自然語言描述 → 預覽 → 執行。 | @@ -1391,15 +1391,15 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,564 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,567 | 見下。 | | presence | `presence_tab.py` | 171 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | -| usb_devices | `usb_devices_tab.py` | 175 | 唯讀列舉 + 熱插拔監看控制。 | +| usb_devices | `usb_devices_tab.py` | 176 | 唯讀列舉 + 熱插拔監看控制。 | | usb_browser | `usb_browser_tab.py` | 277 | 檢視端 USB 裝置瀏覽器。 | -| usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 778 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | +| usb_share | `usb_passthrough_panel.py` + `usb_passthrough_prompt.py` | 779 | AnyDesk 風格 USB 直通面板與主機端 ACL 授權對話框。 | | diagnostics | `diagnostics_tab.py` | 242 | Actions 提供被動快照、背景主動診斷與停止;四語進度/重試、關閉後結果隔離;不自動取得授權。 | | report | `_report_tab.py` | 106 | 產生 HTML/JSON/XML 報表。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,564 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,567 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1420,7 +1420,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `folder_sync_controls.py` | 72 | Translate the existing folder toggle into owned start, reconnect handoff and explicit baseline reset. | | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | | `webrtc_panel_state.py` | 165 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | -| `webrtc_panel.py` | 422 | WebRTC 子分頁主體。 | +| `webrtc_panel.py` | 423 | WebRTC 子分頁主體。 | | `webrtc_dialogs.py` | 529 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | @@ -1430,7 +1430,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `host_panel.py` | 396 | 「分享這台機器」子分頁。 | | `_host_ops.py` | 39 | Start and stop the machine's remote-desktop host on a worker thread. Host 面板與 Quick Connect 共用的 `replace_host`/`stop_host`/`release_host`。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | -| `webrtc_workers.py` | 251 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | +| `webrtc_workers.py` | 253 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | | `tab.py` | 180 | 外層容器分頁。 | | `_helpers.py` | 326 | 面板共用輔助:翻譯、Qt→AC 鍵滑鼠對應、TLS context、狀態徽章、指紋與時間格式化。 | | `remote_screen_window.py` | 140 | 檢視端的彈出視窗。 | @@ -1549,28 +1549,28 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,913 | -| `utils/mcp_server/` | 63 | 22,235 | -| `utils/remote_desktop/` | 77 | 16,910 | +| `gui/` | 166 | 43,919 | +| `utils/mcp_server/` | 63 | 22,241 | +| `utils/remote_desktop/` | 77 | 16,911 | | `utils/executor/` | 11 | 10,755 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | | `utils/accessibility/` | 16 | 3,374 | | `wrapper/` | 25 | 6,046 | | `windows/` | 24 | 2,363 | -| `utils/rest_api/` | 8 | 2,226 | -| `utils/agent/` | 13 | 2,253 | +| `utils/rest_api/` | 8 | 2,228 | +| `utils/agent/` | 13 | 2,254 | | `linux_with_x11/` | 19 | 1,382 | -| `linux_wayland/` | 24 | 4,445 | +| `linux_wayland/` | 24 | 4,448 | | `utils/triggers/` | 4 | 1,408 | -| `utils/ocr/` | 10 | 1,387 | +| `utils/ocr/` | 10 | 1,393 | | `utils/usbip/` | 5 | 1,008 | | `utils/assertion/` | 3 | 888 | | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,566 | -| **總計** | **1,532** | **236,994** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,586 | +| **總計** | **1,532** | **237,039** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 762b450ab..b4b48b7e1 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -697,3 +697,11 @@ - **Tests:** mypy with both flags: 2,060 / 2,052 / 2,052 errors in 198 / 197 / 197 files (win32 / linux / darwin), from 2,396 / 2,384 / 2,384 in 331 / 330 / 330, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; headless tests of the touched modules 372 passed, 3 skipped (the soft-assert and recorder tests 8 passed); doc, file-length and complexity gates 41 passed. - **Files:** 137 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. - **Open items:** `Progress.md` › H (215 modules still outside the tier). + +## U-20261115-08 · 2026-11-15 · 83 more modules join the strict typing tier (four to six fixes each) · #done #typing + +- **What:** the next stage of `Progress.md` › H: the 90 files with four to six strict errors (418 in all). +- **Change:** annotation-only edits in 89 files by the rules of U-20261115-06 and -07. Choices worth knowing: `viewer_panel._own_viewer` returns `Optional[Any]` as `registry.owned` does (the precise viewer type exposes `ClipboardDelivery.dispatch` wanting a `None`-returning callable where `send_clipboard_text` returns `bool`); `webrtc_audio._to_player_pcm` takes `frame: Any` because `recv()` yields frames or packets and the code catches `TypeError` for non-audio ones; `_auto_click_tab._form_panel` accepts `QWidget` or `QLayout` (a `FlowLayout` field, seen with `--extras`); the language tables in `multi_language_wrapper.py` are `Dict[str, str]`; `feature_match.py` uses cv2's real `DMatch` / `KeyPoint` / `ORB` types under `TYPE_CHECKING`. `gamepad/_facade.py` loses a bare `# type: ignore` on `import vgamepad`, which the forced-`Any` override already covers. `gui/vlm_tab.py` stays unchanged (`_show_outcome(value: object)` feeds `_show_located`, which wants `Optional[Tuple[int, int]]`). 83 modules are promoted (strict tier 1,309 → 1,392; baseline 134 → 84, not-yet-strict 81 → 48); six more image modules alias `ImageSource = Any` and stay out (24 in all). +- **Tests:** mypy with both flags: 1,613 / 1,605 / 1,605 errors in 109 / 108 / 108 files (win32 / linux / darwin), from 2,060 / 2,052 / 2,052 in 198 / 197 / 197, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; headless tests of the touched modules 402 passed, 1 skipped, and the input-backend and device audits 34 passed, 3 skipped; doc, file-length and complexity gates 41 passed. +- **Files:** 89 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. +- **Open items:** `Progress.md` › H (132 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index 1a6954a98..4a5366dab 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-08 | 2026-11-15 | 83 more modules join the strict typing tier (four to six fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-07 | 2026-11-15 | 127 more modules join the strict typing tier (two or three fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-06 | 2026-11-15 | 143 more modules join the strict typing tier after one-line fixes | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-05 | 2026-11-15 | 896 older modules join the strict typing tier | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_auto_click_tab.py b/je_auto_control/gui/_auto_click_tab.py index b6e9f5814..063168151 100644 --- a/je_auto_control/gui/_auto_click_tab.py +++ b/je_auto_control/gui/_auto_click_tab.py @@ -1,14 +1,14 @@ """Independent auto-click controls with owned timer and cancellable background input.""" from dataclasses import dataclass from functools import partial -from typing import Callable, Optional +from typing import Callable, Optional, Sequence, Tuple, Union from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( QWidget, QLineEdit, QComboBox, QVBoxLayout, QLabel, QFormLayout, QHBoxLayout, QRadioButton, QButtonGroup, QMessageBox, - QGroupBox, + QGroupBox, QLayout, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin @@ -38,7 +38,7 @@ class _Click: count: int -def _form_panel(rows) -> QWidget: +def _form_panel(rows: Sequence[Tuple[Optional[QWidget], Union[QWidget, QLayout]]]) -> QWidget: """A frameless panel holding ``(label, field)`` form rows; a ``None`` label spans the row.""" panel = QWidget() panel.setProperty("role", "bare") @@ -200,14 +200,14 @@ def retranslate(self) -> None: self._translate("current_position") + self._pos_label_suffix, ) - def _update_click_mode(self): + def _update_click_mode(self) -> None: use_mouse = self.mouse_radio.isChecked() self.cursor_x_input.setEnabled(use_mouse) self.cursor_y_input.setEnabled(use_mouse) self.mouse_button_combo.setEnabled(use_mouse) self.keyboard_button_combo.setEnabled(not use_mouse) - def _start_auto_click(self): + def _start_auto_click(self) -> None: try: interval = int(self.interval_input.text()) except ValueError: @@ -227,7 +227,7 @@ def _start_auto_click(self): self.timer.start() self._refresh_status() - def _stop_auto_click(self): + def _stop_auto_click(self) -> None: """Stop the auto-clicker and ask every running script to stop (Ctrl+4).""" self.dispose() stop_all_script_runs() diff --git a/je_auto_control/gui/_script_tab.py b/je_auto_control/gui/_script_tab.py index 0460e9a99..9df3eb00b 100644 --- a/je_auto_control/gui/_script_tab.py +++ b/je_auto_control/gui/_script_tab.py @@ -133,26 +133,26 @@ def _loaded_script(self, data: object) -> None: def _load_error(self, error: object) -> None: self.script_result_text.setText(f"Error loading: {error}") - def _execute_script(self): + def _execute_script(self) -> None: path = self.script_path_input.text() if path: capture = _requested_manual_run(getattr(self, "script_history_controls", None), source_id="gui.file", script_path=path) self._start_script_run(functools.partial(_run_script_file, path, capture)) - def _browse_script_dir(self): + def _browse_script_dir(self) -> None: path = QFileDialog.getExistingDirectory(self, _t("execute_dir_label")) if path: self.script_dir_input.setText(path) - def _execute_dir(self): + def _execute_dir(self) -> None: path = self.script_dir_input.text() if path: capture = _requested_manual_run(getattr(self, "script_history_controls", None), source_id="gui.directory", script_path=path) self._start_script_run(functools.partial(_run_script_dir, path, capture)) - def _execute_manual_script(self): + def _execute_manual_script(self) -> None: text = self.script_editor.toPlainText().strip() if text: capture = _requested_manual_run(getattr(self, "script_history_controls", None), diff --git a/je_auto_control/gui/a11y_audit_tab.py b/je_auto_control/gui/a11y_audit_tab.py index 9e910c39e..60a6b7b3d 100644 --- a/je_auto_control/gui/a11y_audit_tab.py +++ b/je_auto_control/gui/a11y_audit_tab.py @@ -6,7 +6,7 @@ the contrast check is arithmetic and stays where it is. """ import functools -from typing import Optional +from typing import Any, Callable, Optional from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -31,13 +31,13 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _ints(raw: str): +def _ints(raw: str) -> list[int]: return [int(p.strip()) for p in raw.split(",") if p.strip()] -def _audit(app: Optional[str]) -> dict: +def _audit(app: Optional[str]) -> dict[str, Any]: """Worker thread: run the audit and hand back plain data.""" - report: dict = ac.run_audit(app_name=app).to_dict() + report: dict[str, Any] = ac.run_audit(app_name=app).to_dict() return report @@ -96,7 +96,7 @@ def _build_layout(self) -> None: set_role(self._summary, "hint") root.addWidget(self._summary) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("audit_run", self._on_run), @@ -111,7 +111,7 @@ def _on_run(self) -> None: def _on_audit_error(self, error: object) -> None: self._summary.setText(str(error)) - def _render(self, report: dict) -> None: + def _render(self, report: dict[str, Any]) -> None: issues = report["issues"] self._table.setRowCount(len(issues)) for row, issue in enumerate(issues): diff --git a/je_auto_control/gui/admin_console_tab.py b/je_auto_control/gui/admin_console_tab.py index 6246846bb..740a6ff18 100644 --- a/je_auto_control/gui/admin_console_tab.py +++ b/je_auto_control/gui/admin_console_tab.py @@ -12,7 +12,7 @@ import functools import json import threading -from typing import Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtCore import QSize, QTimer, Qt from PySide6.QtGui import QIcon, QImage, QPixmap @@ -33,7 +33,7 @@ ) from je_auto_control.gui.tab_task_controller import TaskTimeout from je_auto_control.utils.admin.admin_client import ( - default_admin_console, + HostStatus, default_admin_console, ) from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -127,7 +127,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("admin_add", self._on_add), @@ -225,7 +225,7 @@ def _on_broadcast_stop(self) -> None: self._broadcast_stop.set() self._broadcast_status.setText(_t("admin_broadcast_stopping")) - def _show_broadcast(self, results) -> None: + def _show_broadcast(self, results: List[Dict[str, Any]]) -> None: self._broadcast_stop = None self._broadcast_output.setPlainText( json.dumps(results, indent=2, ensure_ascii=False, default=str), @@ -239,7 +239,7 @@ def _show_broadcast_error(self, error: object) -> None: self._broadcast_output.setPlainText(str(error)) self._broadcast_status.setText("") - def _apply_poll_result(self, statuses: list) -> None: + def _apply_poll_result(self, statuses: List[HostStatus]) -> None: self._refresh_table(statuses=statuses) def _apply_poll_failure(self, error: object) -> None: @@ -300,7 +300,7 @@ def _selected_labels(self) -> List[str]: out.append(item.text()) return out - def _refresh_table(self, statuses: Optional[list] = None) -> None: + def _refresh_table(self, statuses: Optional[List[HostStatus]] = None) -> None: hosts = self._client.list_hosts() status_by_label = {s.label: s for s in (statuses or [])} self._table.setRowCount(len(hosts)) diff --git a/je_auto_control/gui/computer_use_tab.py b/je_auto_control/gui/computer_use_tab.py index 11d45d6ac..ce8fe222d 100644 --- a/je_auto_control/gui/computer_use_tab.py +++ b/je_auto_control/gui/computer_use_tab.py @@ -8,7 +8,7 @@ import functools import json import threading -from typing import Optional +from typing import Any, Callable, Optional from PySide6.QtWidgets import ( QFormLayout, QLabel, QLineEdit, QMessageBox, @@ -31,7 +31,7 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _run_agent(params: dict, stop_event: threading.Event) -> dict: +def _run_agent(params: dict[str, Any], stop_event: threading.Event) -> dict[str, Any]: """Worker thread: run the agent until it finishes, hits a limit or ``stop_event`` is set.""" return result_to_dict(run_computer_use(**params, stop_event=stop_event)) @@ -112,7 +112,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("computer_use_run_btn", self._on_run), @@ -142,14 +142,14 @@ def _on_run(self) -> None: self._status.setText(_t("computer_use_running")) self._spawn_worker(params) - def _spawn_worker(self, params: dict) -> None: + def _spawn_worker(self, params: dict[str, Any]) -> None: self._run.start_until_stopped(functools.partial(_run_agent, dict(params))) def _on_stop(self) -> None: if self._run.stop(): self._status.setText(_t("computer_use_stopping")) - def _on_worker_finished(self, data: dict) -> None: + def _on_worker_finished(self, data: dict[str, Any]) -> None: ok = bool(data.get("succeeded")) key = "computer_use_success" if ok else "computer_use_failure" self._status.setText(_t(key)) diff --git a/je_auto_control/gui/flow_editor/scene.py b/je_auto_control/gui/flow_editor/scene.py index 4e1e16283..fbab1e592 100644 --- a/je_auto_control/gui/flow_editor/scene.py +++ b/je_auto_control/gui/flow_editor/scene.py @@ -1,11 +1,11 @@ """Qt scene that paints a :func:`layout_steps` output as a node graph.""" -from typing import Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtCore import QObject, QRectF, Signal from PySide6.QtGui import QBrush, QColor, QFont, QPainter, QPainterPath, QPen from PySide6.QtWidgets import ( QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsScene, - QGraphicsSimpleTextItem, QStyleOptionGraphicsItem, QWidget, + QGraphicsSceneMouseEvent, QGraphicsSimpleTextItem, QStyleOptionGraphicsItem, QWidget, ) from je_auto_control.gui.flow_editor.layout import ( @@ -26,7 +26,7 @@ class FlowNodeItem(QGraphicsRectItem): """One painted command rectangle. Stores the originating step path.""" def __init__(self, position: FlowNodePosition, - on_clicked: Callable[[Tuple], None]) -> None: + on_clicked: Callable[[Tuple[Any, ...]], None]) -> None: super().__init__(QRectF(position.x, position.y, position.width, position.height)) self._path = position.path @@ -38,7 +38,7 @@ def __init__(self, position: FlowNodePosition, self._build_label(position) @property - def step_path(self) -> Tuple: + def step_path(self) -> Tuple[Any, ...]: return self._path def _set_default_brush(self) -> None: @@ -61,7 +61,7 @@ def _build_label(self, position: FlowNodePosition) -> None: detail.setBrush(QBrush(_NODE_LABEL)) detail.setPos(position.x + 8, position.y + 32) - def mousePressEvent(self, event) -> None: + def mousePressEvent(self, event: QGraphicsSceneMouseEvent) -> None: super().mousePressEvent(event) try: self._on_clicked(self._path) @@ -110,7 +110,7 @@ class FlowGraphScene(QGraphicsScene): def __init__(self, parent: Optional[QObject] = None) -> None: super().__init__(parent) self.setBackgroundBrush(QBrush(QColor(30, 35, 45))) - self._nodes: Dict[Tuple, FlowNodeItem] = {} + self._nodes: Dict[Tuple[Any, ...], FlowNodeItem] = {} def load(self, steps: List[Step]) -> FlowLayout: """Replace the scene with a freshly-laid-out ``steps`` tree.""" @@ -137,10 +137,10 @@ def load(self, steps: List[Step]) -> FlowLayout: NODE_WIDTH + 40.0, NODE_HEIGHT + 40.0) return layout - def _emit_selected(self, path: Tuple) -> None: + def _emit_selected(self, path: Tuple[Any, ...]) -> None: self.node_selected.emit(path) - def node_paths(self) -> List[Tuple]: + def node_paths(self) -> List[Tuple[Any, ...]]: return list(self._nodes.keys()) diff --git a/je_auto_control/gui/flow_editor/tab.py b/je_auto_control/gui/flow_editor/tab.py index 4bff346a4..d9e4175ad 100644 --- a/je_auto_control/gui/flow_editor/tab.py +++ b/je_auto_control/gui/flow_editor/tab.py @@ -6,7 +6,7 @@ visual map of what the script will do. """ import json -from typing import List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -42,7 +42,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._view.setDragMode(QGraphicsView.DragMode.RubberBandDrag) self._steps: List[Step] = [] # The other keys of a wrapped file, written back by Save. - self._file_extras: Optional[dict] = None + self._file_extras: Optional[Dict[str, Any]] = None self._inspector = QTextEdit() self._inspector.setReadOnly(True) self._status = QLabel() @@ -71,7 +71,7 @@ def _build_layout(self) -> None: root.addWidget(self._status) self._apply_translations() - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("flow_open_btn", self._on_open), @@ -146,7 +146,7 @@ def _on_fit(self) -> None: return self._view.fitInView(rect, Qt.AspectRatioMode.KeepAspectRatio) - def _on_node_selected(self, path: Tuple) -> None: + def _on_node_selected(self, path: Tuple[object, ...]) -> None: step = _resolve_step(self._steps, path) if step is None: return @@ -159,7 +159,7 @@ def _on_node_selected(self, path: Tuple) -> None: ) -def _resolve_step(roots: List[Step], path: Tuple) -> Optional[Step]: +def _resolve_step(roots: List[Step], path: Tuple[object, ...]) -> Optional[Step]: if not path: return None head, *tail = path diff --git a/je_auto_control/gui/language_wrapper/multi_language_wrapper.py b/je_auto_control/gui/language_wrapper/multi_language_wrapper.py index 6b1295f38..19d94428e 100644 --- a/je_auto_control/gui/language_wrapper/multi_language_wrapper.py +++ b/je_auto_control/gui/language_wrapper/multi_language_wrapper.py @@ -22,7 +22,7 @@ class LanguageWrapper: def __init__(self) -> None: autocontrol_logger.info("Init LanguageWrapper") - self._registry: Dict[str, dict] = { + self._registry: Dict[str, Dict[str, str]] = { "English": english_word_dict, "Traditional_Chinese": traditional_chinese_word_dict, "Simplified_Chinese": simplified_chinese_word_dict, @@ -30,14 +30,14 @@ def __init__(self) -> None: } self.language: str = "English" self._listeners: List[Callable[[str], None]] = [] - self.language_word_dict: dict = self._merged(self.language) + self.language_word_dict: Dict[str, str] = self._merged(self.language) @property def available_languages(self) -> List[str]: """Sorted list of registered language names.""" return sorted(self._registry.keys()) - def register_language(self, name: str, words: dict) -> None: + def register_language(self, name: str, words: Dict[str, str]) -> None: """Add or replace a language dict at runtime (plugin-friendly).""" self._registry[name] = dict(words) if name == self.language: @@ -55,12 +55,12 @@ def reset_language(self, language: str) -> None: except (OSError, RuntimeError) as error: autocontrol_logger.error("language listener failed: %r", error) - def add_listener(self, callback) -> None: + def add_listener(self, callback: Callable[[str], None]) -> None: """Register ``callback(language)`` to fire when the language changes.""" if callback not in self._listeners: self._listeners.append(callback) - def remove_listener(self, callback) -> None: + def remove_listener(self, callback: Callable[[str], None]) -> None: if callback in self._listeners: self._listeners.remove(callback) @@ -74,7 +74,7 @@ def translate(self, key: str, default: str = "") -> str: return fallback return default or key - def _merged(self, language: str) -> dict: + def _merged(self, language: str) -> Dict[str, str]: merged = dict(english_word_dict) merged.update(self._registry.get(language, {})) return merged diff --git a/je_auto_control/gui/llm_planner_tab.py b/je_auto_control/gui/llm_planner_tab.py index a8192cde6..0907ee0ae 100644 --- a/je_auto_control/gui/llm_planner_tab.py +++ b/je_auto_control/gui/llm_planner_tab.py @@ -10,7 +10,7 @@ import copy import functools import json -from typing import List, Optional +from typing import Any, Callable, List, Optional, Tuple from PySide6.QtWidgets import ( QFormLayout, QGroupBox, QLabel, QLineEdit, QMessageBox, @@ -35,7 +35,7 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _run_plan(actions: list) -> object: +def _run_plan(actions: List[List[Any]]) -> object: """Worker thread: execute the reviewed plan.""" return execute_action(actions) @@ -45,7 +45,7 @@ def _run_plan(actions: list) -> object: PLAN_DEADLINE_S = 200.0 -def _plan(description: str, model: Optional[str], known_commands: List[str]) -> list: +def _plan(description: str, model: Optional[str], known_commands: List[str]) -> List[List[Any]]: """Worker thread: ask the model for a plan.""" return plan_actions(description, known_commands=known_commands, model=model) @@ -72,7 +72,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._result_view = QTextEdit() self._result_view.setReadOnly(True) self._status = QLabel() - self._planned_actions: Optional[list] = None + self._planned_actions: Optional[List[List[Any]]] = None self._plans = TabTask(self) self._plans.result.connect(self._on_plan_finished) self._plans.error.connect(self._on_plan_failed) @@ -128,7 +128,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("llm_plan_btn", self._on_plan), @@ -150,7 +150,7 @@ def _on_plan(self) -> None: self._actions_view.clear() self._planned_actions = None - def _on_plan_finished(self, actions: list) -> None: + def _on_plan_finished(self, actions: List[List[Any]]) -> None: self._planned_actions = actions self._actions_view.setText( json.dumps(actions, indent=2, ensure_ascii=False) diff --git a/je_auto_control/gui/ocr_tab.py b/je_auto_control/gui/ocr_tab.py index 093361def..f2a3e60c5 100644 --- a/je_auto_control/gui/ocr_tab.py +++ b/je_auto_control/gui/ocr_tab.py @@ -24,7 +24,7 @@ from je_auto_control.gui.selector import open_region_selector from je_auto_control.gui.tab_task_controller import CancellationToken, TaskHandle, task_controller from je_auto_control.utils.ocr.ocr_engine import ( - find_text_regex, read_text_in_region, + TextMatch, find_text_regex, read_text_in_region, ) @@ -32,7 +32,7 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _matches_to_json(matches) -> str: +def _matches_to_json(matches: list[TextMatch]) -> str: rows = [ { "text": m.text, "x": m.x, "y": m.y, @@ -102,7 +102,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("ocr_pick_region", self._on_pick_region), @@ -117,7 +117,7 @@ def _on_pick_region(self) -> None: x, y, width, height = region self._region.setText(f"{x}, {y}, {width}, {height}") - def _parse_region(self) -> Optional[list]: + def _parse_region(self) -> Optional[list[int]]: text = self._region.text().strip() if not text: return None @@ -151,7 +151,7 @@ def _on_find_regex(self) -> None: return self._run_ocr("ocr_find_regex", find_text_regex, {"pattern": compiled}) - def _run_ocr(self, title_key: str, backend: Callable[..., list], extra: dict) -> None: + def _run_ocr(self, title_key: str, backend: Callable[..., list[TextMatch]], extra: dict[str, Any]) -> None: """Read the fields, then run ``backend`` off the GUI thread; one read at a time.""" if self._task is not None: return @@ -173,7 +173,7 @@ def _run_ocr(self, title_key: str, backend: Callable[..., list], extra: dict) -> def _on_task_finished(self) -> None: self._task = None - def _show_matches(self, matches: list) -> None: + def _show_matches(self, matches: list[TextMatch]) -> None: self._result.setText(_matches_to_json(matches)) self._status.setText( _t("ocr_match_count").replace("{n}", str(len(matches))) @@ -187,6 +187,7 @@ def _show_error(self, error: Exception) -> None: QMessageBox.warning(self, _t(self._title_key), str(error)) -def _call_backend(backend: Callable[..., list], options: dict, _token: CancellationToken) -> Any: +def _call_backend(backend: Callable[..., list[TextMatch]], options: dict[str, Any], + _token: CancellationToken) -> Any: """Worker thread: one OCR read with the options read from the tab.""" return backend(**options) diff --git a/je_auto_control/gui/recording_editor_tab.py b/je_auto_control/gui/recording_editor_tab.py index 8af5ef30c..6f430adfa 100644 --- a/je_auto_control/gui/recording_editor_tab.py +++ b/je_auto_control/gui/recording_editor_tab.py @@ -1,6 +1,6 @@ """Recording Editor tab: trim, filter and rescale recorded action lists.""" import json -from typing import Optional +from typing import Any, Callable, Optional, Union from PySide6.QtGui import QCloseEvent, QKeySequence, QShortcut from PySide6.QtWidgets import ( @@ -33,8 +33,8 @@ class RecordingEditorTab(TranslatableMixin, QWidget): def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() - self._actions: list = [] - self._undo_stack: list = [] + self._actions: list[list[Any]] = [] + self._undo_stack: list[list[list[Any]]] = [] self._path_input = QLineEdit() self._list = QListWidget() self._preview = QTextEdit() @@ -55,7 +55,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: def retranslate(self) -> None: TranslatableMixin.retranslate(self) - def _mutate(self, new_actions: list) -> None: + def _mutate(self, new_actions: list[list[Any]]) -> None: """Apply an edit, snapshotting the prior state for undo (Ctrl+Z).""" self._undo_stack.append(list(self._actions)) self._actions = new_actions @@ -93,7 +93,7 @@ def pair(key: str, field: QWidget) -> QWidget: set_role(self._status, "hint") root.addWidget(self._status) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("re_browse", self._browse), @@ -244,8 +244,8 @@ def _apply_scale(self) -> None: return self._mutate(scale_coordinates(self._actions, fx, fy)) - def _filter_prefix(self, prefix) -> None: - def keep(action: list) -> bool: + def _filter_prefix(self, prefix: Union[str, tuple[str, ...]]) -> None: + def keep(action: list[Any]) -> bool: if not (isinstance(action, list) and action): return False name = action[0] diff --git a/je_auto_control/gui/remote_desktop/_helpers.py b/je_auto_control/gui/remote_desktop/_helpers.py index aa9dd52e5..0e1e2eb5e 100644 --- a/je_auto_control/gui/remote_desktop/_helpers.py +++ b/je_auto_control/gui/remote_desktop/_helpers.py @@ -6,7 +6,7 @@ from PySide6.QtCore import QSize, Qt from PySide6.QtGui import QKeyEvent -from PySide6.QtWidgets import QGroupBox, QHBoxLayout, QLabel, QVBoxLayout, QWidget +from PySide6.QtWidgets import QGroupBox, QHBoxLayout, QLabel, QLayout, QVBoxLayout, QWidget from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, @@ -74,7 +74,7 @@ def _scroll_amount(angle_delta: int) -> int: return 0 -def wire_remote_input(window: Any, send: Callable[[dict], None]) -> None: +def wire_remote_input(window: Any, send: Callable[[dict[str, Any]], None]) -> None: """Forward a remote screen window's mouse and keyboard signals to ``send``. Every viewer that opens a ``RemoteScreenWindow`` wires it here, so one @@ -88,7 +88,7 @@ def wire_remote_input(window: Any, send: Callable[[dict], None]) -> None: """ sink = weakref.WeakMethod(send) if inspect.ismethod(send) else (lambda: send) - def forward(*actions: dict) -> None: + def forward(*actions: dict[str, Any]) -> None: target = sink() if target is None: return @@ -106,7 +106,7 @@ def forward(*actions: dict) -> None: window.type_text.connect(lambda text: forward({"action": "type", "text": text})) -def _read_import_entries(path: str, key: str) -> list: +def _read_import_entries(path: str, key: str) -> list[dict[str, Any]]: """The object entries of an exported JSON file: ``{key: [...]}`` or a bare list. Raises ``OSError`` or ``ValueError`` for a file that cannot be read or has @@ -201,7 +201,7 @@ def __init__(self, title: str = "", def body(self) -> QWidget: return self._body - def set_body_layout(self, layout) -> None: + def set_body_layout(self, layout: QLayout) -> None: self._body.setLayout(layout) def adopt(self, inner: QGroupBox) -> None: diff --git a/je_auto_control/gui/remote_desktop/viewer_panel.py b/je_auto_control/gui/remote_desktop/viewer_panel.py index b0116919f..6b45d55ef 100644 --- a/je_auto_control/gui/remote_desktop/viewer_panel.py +++ b/je_auto_control/gui/remote_desktop/viewer_panel.py @@ -1,7 +1,7 @@ """``_ViewerPanel``: the 'control another machine' Remote Desktop sub-tab.""" import ssl from pathlib import Path -from typing import Optional +from typing import Any, Dict, List, Optional from PySide6.QtCore import Signal from PySide6.QtGui import QGuiApplication, QImage @@ -316,7 +316,7 @@ def _on_connect_failed(self, error: Exception) -> None: # UnicodeError, which once escaped the slot and left the click unanswered. QMessageBox.warning(self, _t("rd_viewer_connect"), str(error)) - def _on_connected(self, viewer) -> None: + def _on_connected(self, viewer: RemoteDesktopViewer) -> None: """GUI thread: the viewer this panel asked for is connected.""" registry.adopt(SLOT_VIEWER, viewer, self._owner, self._view.callback("_on_displaced")) self._clipboard_authority, self._connect_authority = self._connect_authority, None @@ -375,7 +375,7 @@ def _retire_audio_player(self) -> None: if player is not None: self._stops.retire(player.stop) - def _own_viewer(self): + def _own_viewer(self) -> Optional[Any]: """The viewer this panel opened, or None once it is gone or replaced.""" return registry.owned(SLOT_VIEWER, self._owner) @@ -542,7 +542,7 @@ def _on_file_complete_main(self, transfer_id: str, success: bool, # --- input forwarding --------------------------------------------- - def _send(self, action: dict) -> None: + def _send(self, action: Dict[str, Any]) -> None: viewer = self._own_viewer() if viewer is None or not viewer.connected: return @@ -593,7 +593,7 @@ def _on_send_file_clicked(self) -> None: return self._upload_file(source) - def _on_files_dropped(self, paths) -> None: + def _on_files_dropped(self, paths: List[str]) -> None: viewer = self._own_viewer() if viewer is None or not viewer.connected: return diff --git a/je_auto_control/gui/remote_desktop/webrtc_panel.py b/je_auto_control/gui/remote_desktop/webrtc_panel.py index 2d4b6c858..ad57ad6a6 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_panel.py +++ b/je_auto_control/gui/remote_desktop/webrtc_panel.py @@ -18,7 +18,7 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Any, Optional from PySide6.QtCore import QTimer from PySide6.QtWidgets import ( @@ -81,6 +81,7 @@ from je_auto_control.gui.remote_desktop.webrtc_viewer_connection import _ViewerConnectionMixin if TYPE_CHECKING: # imported lazily at runtime to keep startup cheap + from je_auto_control.gui.remote_desktop.frame_display import _FrameDisplay from je_auto_control.utils.remote_desktop.file_sync import ( FolderSyncEngine, ) @@ -104,10 +105,10 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._file_task: Optional[TaskHandle] = None # the file push in progress, off-thread self._stops = StopQueue(self) self._stops.drained.connect(self._on_stops_drained) - self._stopping_sessions: set = set() + self._stopping_sessions: set[str] = set() self._adaptive_controller: Optional[AdaptiveBitrateController] = None self._adaptive_poller: Optional[StatsPoller] = None - self._session_pollers: dict = {} # session_id -> StatsPoller + self._session_pollers: dict[str, StatsPoller] = {} # session_id -> StatsPoller # Lock-protected cache replacing two raw dicts; mutated by the # asyncio bridge thread (StatsPoller cb) and read/cleared by the # Qt thread. See utils/remote_desktop/session_quality_cache.py. @@ -193,7 +194,7 @@ def _on_tray_quit(self) -> None: from PySide6.QtWidgets import QApplication QApplication.quit() - def _on_pending_viewer(self, session_id: str, viewer_id) -> None: + def _on_pending_viewer(self, session_id: str, viewer_id: object) -> None: if self._multi_host is None: return dialog = PendingViewerDialog(viewer_id if isinstance(viewer_id, str) else None, @@ -308,7 +309,7 @@ def _wire_input_signals(self) -> None: # future. self._wire_display_input(self._frame_display) - def _wire_display_input(self, source) -> None: + def _wire_display_input(self, source: _FrameDisplay | RemoteScreenWindow) -> None: """Wire mouse / keyboard / annotation signals from ``source``. ``source`` can be a :class:`_FrameDisplay` or a @@ -403,7 +404,7 @@ def _on_state(self, state: str) -> None: if state in ("failed", "disconnected"): self._maybe_schedule_auto_reconnect() - def _send(self, payload: dict) -> None: + def _send(self, payload: dict[str, Any]) -> None: if self._viewer is None or not self._viewer.authenticated: return try: diff --git a/je_auto_control/gui/remote_desktop/webrtc_workers.py b/je_auto_control/gui/remote_desktop/webrtc_workers.py index ebc87c040..76f25ee6c 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_workers.py +++ b/je_auto_control/gui/remote_desktop/webrtc_workers.py @@ -13,9 +13,10 @@ import secrets from typing import Optional, Set -from PySide6.QtCore import Signal +from PySide6.QtCore import QObject, Signal from je_auto_control.gui._daemon_thread import DaemonThread +from je_auto_control.gui.remote_desktop._webrtc_types import MultiViewerHostT from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop import signaling_client @@ -34,7 +35,7 @@ class HostSignalingWorker(DaemonThread): def __init__(self, *, server_url: str, host_id: str, secret: Optional[str], offer_sdp: str, timeout_s: float = 60.0, - parent=None) -> None: + parent: Optional[QObject] = None) -> None: super().__init__(parent) self._server_url = server_url self._host_id = host_id @@ -69,7 +70,7 @@ class ViewerSignalingWorker(DaemonThread): failed = Signal(str) def __init__(self, *, server_url: str, host_id: str, secret: Optional[str], - timeout_s: float = 60.0, parent=None) -> None: + timeout_s: float = 60.0, parent: Optional[QObject] = None) -> None: super().__init__(parent) self._server_url = server_url self._host_id = host_id @@ -99,7 +100,7 @@ class ViewerAnswerPushWorker(DaemonThread): failed = Signal(str) def __init__(self, *, server_url: str, host_id: str, secret: Optional[str], - answer_sdp: str, parent=None) -> None: + answer_sdp: str, parent: Optional[QObject] = None) -> None: super().__init__(parent) self._server_url = server_url self._host_id = host_id @@ -135,11 +136,11 @@ class HostPublishLoopWorker(DaemonThread): session_connected = Signal(str) # session_id (after accept_answer) failed = Signal(str) - def __init__(self, *, multi_host, server_url: str, host_id: str, + def __init__(self, *, multi_host: MultiViewerHostT, server_url: str, host_id: str, secret: Optional[str], wait_timeout_s: float = 600.0, retry_delay_s: float = 2.0, - parent=None) -> None: + parent: Optional[QObject] = None) -> None: super().__init__(parent) self._multi_host = multi_host self._server_url = server_url @@ -184,7 +185,8 @@ def _publish_one_session(self) -> bool: self._safe_stop_session_if(session_id) return False - def _handle_signaling_error(self, session_id, error) -> bool: + def _handle_signaling_error(self, session_id: Optional[str], + error: signaling_client.SignalingError) -> bool: # Timeout waiting for answer is expected when no one connects. if "no answer" in str(error): self._safe_stop_session_if(session_id) @@ -193,7 +195,7 @@ def _handle_signaling_error(self, session_id, error) -> bool: self._safe_stop_session_if(session_id) return False - def _safe_stop_session_if(self, session_id) -> None: + def _safe_stop_session_if(self, session_id: Optional[str]) -> None: if session_id is not None: self._safe_stop_session(session_id) diff --git a/je_auto_control/gui/script_builder/step_model.py b/je_auto_control/gui/script_builder/step_model.py index d051423f5..3594db797 100644 --- a/je_auto_control/gui/script_builder/step_model.py +++ b/je_auto_control/gui/script_builder/step_model.py @@ -186,7 +186,7 @@ def _subject(result: Any, arguments: Any, path: FieldPath) -> str: return "" -def step_to_action(step: Step) -> list: +def step_to_action(step: Step) -> List[Any]: """Convert a Step to the executor's action list entry.""" if step.args is not None: return [step.command, list(step.args)] @@ -198,7 +198,7 @@ def step_to_action(step: Step) -> list: return [step.command, params] -def action_to_step(action: list) -> Step: +def action_to_step(action: List[Any]) -> Step: """Convert a single action entry back to a Step. Raises ``ValueError`` for anything that is not a ``[command, params?]`` @@ -248,7 +248,7 @@ def actions_to_steps(actions: Any) -> List[Step]: return [action_to_step(entry) for entry in _unwrap_action_list(actions)] -def _unwrap_action_list(actions: Any) -> list: +def _unwrap_action_list(actions: Any) -> List[Any]: """Return the bare action list, unwrapping the ``auto_control`` mapping.""" if isinstance(actions, dict): wrapped = actions.get("auto_control") @@ -262,7 +262,7 @@ def _unwrap_action_list(actions: Any) -> list: return actions -def steps_to_actions(steps: List[Step]) -> list: +def steps_to_actions(steps: List[Step]) -> List[Any]: """Convert a list of Steps back to an AC action list.""" return [step_to_action(step) for step in steps] diff --git a/je_auto_control/gui/usb_browser_tab.py b/je_auto_control/gui/usb_browser_tab.py index 16b1e616e..0c12081d2 100644 --- a/je_auto_control/gui/usb_browser_tab.py +++ b/je_auto_control/gui/usb_browser_tab.py @@ -24,7 +24,7 @@ import urllib.error import urllib.parse from email.message import Message -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtWidgets import ( QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, @@ -118,7 +118,7 @@ def fetch_remote_devices(*, base_url: str, return devices -def _open_local(vendor_id: str, product_id: str, serial: Optional[str]) -> tuple: +def _open_local(vendor_id: str, product_id: str, serial: Optional[str]) -> Tuple[str, str, bytes]: """Open the device locally; return ``(vendor_id, product_id, descriptor)`` for the status line.""" return vendor_id, product_id, open_local_descriptor( vendor_id=vendor_id, product_id=product_id, serial=serial) @@ -164,7 +164,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("usb_browser_fetch", self._on_fetch), @@ -194,7 +194,7 @@ def _on_fetch(self) -> None: if self._start(work, "fetch"): self._status_label.setText(_t("usb_browser_fetching")) - def _start(self, work, tag: str) -> bool: + def _start(self, work: Callable[[], Any], tag: str) -> bool: if self._requests.start(work, tag=tag, timeout_s=REQUEST_DEADLINE_S): return True self._status_label.setText(_t("task_busy")) @@ -210,7 +210,7 @@ def _show_outcome(self, value: Any) -> None: else: self._apply_devices(value) - def _apply_devices(self, devices: list) -> None: + def _apply_devices(self, devices: List[Dict[str, Any]]) -> None: self._status_label.setText( _t("usb_browser_fetched").format(count=len(devices)), ) diff --git a/je_auto_control/gui/usb_devices_tab.py b/je_auto_control/gui/usb_devices_tab.py index e3e9dec2f..9187593b6 100644 --- a/je_auto_control/gui/usb_devices_tab.py +++ b/je_auto_control/gui/usb_devices_tab.py @@ -4,9 +4,10 @@ closing the tab cancels it, which ends the enumeration tool's process (PowerShell, ``lsusb``, ``system_profiler``) instead of leaving it to time out. """ -from typing import Optional +from typing import Any, Callable, Optional from PySide6.QtCore import QTimer +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QCheckBox, QHeaderView, QLabel, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, @@ -20,7 +21,7 @@ from je_auto_control.gui.language_wrapper.multi_language_wrapper import ( language_wrapper, ) -from je_auto_control.utils.usb.usb_devices import list_usb_devices +from je_auto_control.utils.usb.usb_devices import UsbEnumerationResult, list_usb_devices from je_auto_control.utils.usb.usb_watcher import ( default_usb_watcher, hold_default_watcher, release_default_watcher, ) @@ -84,13 +85,13 @@ def dispose(self) -> None: """ release_resources(self, self._hold.release) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("usb_refresh", self._refresh), ] - def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt override """List the devices the first time the tab is shown.""" super().showEvent(event) if not self._listed: @@ -119,7 +120,7 @@ def _refresh(self) -> None: def _show_list_error(self, error: object) -> None: self._error_label.setText(str(error)) - def _apply_devices(self, result) -> None: + def _apply_devices(self, result: UsbEnumerationResult) -> None: self._backend_label.setText(result.backend) self._error_label.setText(result.error or "") self._update_event_summary() @@ -166,7 +167,7 @@ def take(self) -> None: hold_default_watcher() self.held = True - def release(self, *_args) -> None: + def release(self, *_args: Any) -> None: if self.held: self.held = False release_default_watcher(background=True) diff --git a/je_auto_control/gui/usb_passthrough_panel.py b/je_auto_control/gui/usb_passthrough_panel.py index ccc9c94a7..cd1933f53 100644 --- a/je_auto_control/gui/usb_passthrough_panel.py +++ b/je_auto_control/gui/usb_passthrough_panel.py @@ -22,9 +22,10 @@ import functools from pathlib import Path -from typing import Any, Callable, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtCore import QTimer +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QCheckBox, QComboBox, QFileDialog, QFormLayout, QGroupBox, QHeaderView, QLabel, QLineEdit, QMessageBox, QTableWidget, @@ -47,7 +48,7 @@ AclRule, UsbAcl, UsbLoopback, describe_descriptor, enable_usb_passthrough, export_acl_to_file, import_acl_from_file, ) -from je_auto_control.utils.usb.usb_devices import list_usb_devices +from je_auto_control.utils.usb.usb_devices import UsbEnumerationResult, list_usb_devices from je_auto_control.utils.usb.usb_watcher import ( default_usb_watcher, hold_default_watcher, release_default_watcher, ) @@ -145,7 +146,7 @@ def _build_layout(self) -> None: root.setSpacing(12) root.addWidget(ResponsiveBox(self._build_host_section(), self._build_viewer_section()), stretch=1) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("usb_share_enable", self._enable_sharing), @@ -280,7 +281,7 @@ def _refresh_host_badge(self) -> None: # --- local devices + ACL ---------------------------------------------- - def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt override """List the local devices the first time the panel is shown.""" super().showEvent(event) if not self._listed: @@ -293,7 +294,7 @@ def _refresh_local_devices(self) -> None: def _show_list_error(self, error: object) -> None: self._viewer_status.setText(str(error)) - def _show_local_devices(self, result) -> None: + def _show_local_devices(self, result: UsbEnumerationResult) -> None: devices = result.devices self._local_table.setRowCount(len(devices)) for row, device in enumerate(devices): @@ -424,7 +425,7 @@ def _list_shared(self) -> None: if self._start(client.list_devices, "shared"): self._viewer_status.setText(_t("usb_share_listing")) - def _apply_shared(self, devices: List[dict]) -> None: + def _apply_shared(self, devices: List[Dict[str, Any]]) -> None: self._viewer_status.setText( _t("usb_share_listed").format(count=len(devices)), ) @@ -565,7 +566,7 @@ def _default_remote_client() -> Optional[Any]: return registry.webrtc_usb_client() -def _probe_labelled(client: Any, vid: str, pid: str, serial: Optional[str]) -> tuple: +def _probe_labelled(client: Any, vid: str, pid: str, serial: Optional[str]) -> Tuple[str, str, bytes]: """Probe the device; return ``(vid, pid, descriptor)`` for the status line.""" return vid, pid, _probe_device(client, vid, pid, serial) diff --git a/je_auto_control/linux_wayland/keyboard.py b/je_auto_control/linux_wayland/keyboard.py index 4d07eba11..62dec1eea 100644 --- a/je_auto_control/linux_wayland/keyboard.py +++ b/je_auto_control/linux_wayland/keyboard.py @@ -18,7 +18,7 @@ import subprocess # nosec B404 # reason: argv-list, no shell interpolation import time -from typing import Iterable +from typing import TYPE_CHECKING, Iterable from je_auto_control.linux_wayland._detect import ( WAYLAND_WTYPE, WAYLAND_YDOTOOL, binary_path, @@ -30,6 +30,9 @@ from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger +if TYPE_CHECKING: + from je_auto_control.linux_wayland.ei_protocol import InputBackend + _INSTALL_HINT_WTYPE = ( "wtype is required for Wayland keyboard input. " @@ -56,7 +59,7 @@ def _require_ydotool() -> str: return reject_legacy_cli(_require(WAYLAND_YDOTOOL, _INSTALL_HINT_YDOTOOL)) -def _run(argv: list, *, timeout: float = 5.0) -> None: +def _run(argv: list[str], *, timeout: float = 5.0) -> None: # argv comes from a private allow-list (wtype / ydotool absolute # paths via shutil.which), never user input; no shell=True. try: @@ -97,7 +100,7 @@ def release_key(keycode: int) -> None: _run([_require_ydotool(), "key", f"{int(keycode)}:0"]) -def _try_libei(): +def _try_libei() -> InputBackend | None: """Return a connected :class:`LibeiBackend`, or None when CLI should win.""" try: from je_auto_control.linux_wayland._select_input import active_backend @@ -127,7 +130,7 @@ def hotkey(keycodes: Iterable[int]) -> None: _run(args) -def _libei_chord(libei, codes: list) -> bool: +def _libei_chord(libei: InputBackend, codes: list[int]) -> bool: """Send a whole chord through libei; False means the CLI has to redo it. Attempt every owned release on the same backend before propagating a @@ -151,7 +154,7 @@ def _libei_chord(libei, codes: list) -> bool: return taken -def _release_chord(libei, pressed: list, failure: BaseException | None) -> bool: +def _release_chord(libei: InputBackend, pressed: list[int], failure: BaseException | None) -> bool: released = True errors: list[BaseException] = [] for code in reversed(pressed): diff --git a/je_auto_control/utils/accessibility/backends/macos_backend.py b/je_auto_control/utils/accessibility/backends/macos_backend.py index f078341e2..e2ca95787 100644 --- a/je_auto_control/utils/accessibility/backends/macos_backend.py +++ b/je_auto_control/utils/accessibility/backends/macos_backend.py @@ -4,7 +4,7 @@ Settings → Privacy & Security → Accessibility). Enumerates the frontmost application's window tree, or a specific ``app_name``. """ -from typing import List, Optional +from typing import Any, List, Optional, Tuple from je_auto_control.utils.accessibility.backends.base import ( AccessibilityBackend, @@ -98,7 +98,7 @@ def focused_element(self) -> Optional[AccessibilityElement]: return None return _convert_ax(ax_module, element, name, pid) - def _walk(self, ax_module, element, app_name: str, pid: int, + def _walk(self, ax_module: Any, element: Any, app_name: str, pid: int, results: List[AccessibilityElement], max_results: int) -> None: if len(results) >= max_results: return @@ -116,7 +116,7 @@ def _walk(self, ax_module, element, app_name: str, pid: int, self._walk(ax_module, child, app_name, pid, results, max_results) -def _convert_ax(ax_module, element, app_name: str, pid: int, +def _convert_ax(ax_module: Any, element: Any, app_name: str, pid: int, ) -> Optional[AccessibilityElement]: try: _err, role = ax_module.AXUIElementCopyAttributeValue( @@ -143,7 +143,7 @@ def _convert_ax(ax_module, element, app_name: str, pid: int, ) -def _extract_bounds(position, size, ax_module=None) -> tuple: +def _extract_bounds(position: Any, size: Any, ax_module: Any = None) -> Tuple[int, int, int, int]: """``(x, y, width, height)`` from ``AXPosition`` / ``AXSize``; zeros when unreadable. The attributes come back as opaque ``AXValueRef`` objects, not pairs: @@ -157,7 +157,7 @@ def _extract_bounds(position, size, ax_module=None) -> tuple: return (int(point[0]), int(point[1]), int(extent[0]), int(extent[1])) -def _ax_pair(ax_module, value, value_type: str, fields: tuple) -> Optional[tuple]: +def _ax_pair(ax_module: Any, value: Any, value_type: str, fields: Tuple[str, ...]) -> Optional[Tuple[float, ...]]: """Two numbers out of an ``AXValue`` (or a plain pair); ``None`` when unreadable.""" if value is None: return None diff --git a/je_auto_control/utils/accessibility/backends/windows_state.py b/je_auto_control/utils/accessibility/backends/windows_state.py index dc8b87529..0a13dd54e 100644 --- a/je_auto_control/utils/accessibility/backends/windows_state.py +++ b/je_auto_control/utils/accessibility/backends/windows_state.py @@ -34,7 +34,7 @@ TOGGLE_STATES = {0: "off", 1: "on", 2: "mixed"} -def _prop(raw, property_id: int) -> Any: +def _prop(raw: Any, property_id: int) -> Any: """Read one UIA property; ``None`` when it cannot be read. ``UIA_ERRORS`` as every other UIA read uses: it holds ``COMError`` @@ -48,13 +48,13 @@ def _prop(raw, property_id: int) -> Any: return None -def is_password(raw) -> bool: +def is_password(raw: Any) -> bool: """Whether the element is a password field. Unreadable counts as yes.""" value = _prop(raw, _UIA_IS_PASSWORD_PROPERTY) return True if value is None else bool(value) -def _supported_values(raw) -> Dict[str, Any]: +def _supported_values(raw: Any) -> Dict[str, Any]: """Raw values for every pattern the control actually supports.""" state: Dict[str, Any] = {} for key, available_id, value_id in _STATE_READS: @@ -66,7 +66,7 @@ def _supported_values(raw) -> Dict[str, Any]: return state -def _normalise_value(raw, state: Dict[str, Any]) -> None: +def _normalise_value(raw: Any, state: Dict[str, Any]) -> None: """Coerce ``value`` to text, or fall back to the legacy accessible value.""" if "value" in state: state["value"] = str(state["value"] or "") @@ -88,7 +88,7 @@ def _normalise_rest(state: Dict[str, Any]) -> None: state["number"] = float(state["number"]) -def read_state(raw) -> Dict[str, Any]: +def read_state(raw: Any) -> Dict[str, Any]: """``{value?, read_only?, toggle?, selected?, number?}`` for one element. A key is absent when the control does not support it. Password fields diff --git a/je_auto_control/utils/agent/agent_loop.py b/je_auto_control/utils/agent/agent_loop.py index 5f7f440b0..1752b17e9 100644 --- a/je_auto_control/utils/agent/agent_loop.py +++ b/je_auto_control/utils/agent/agent_loop.py @@ -63,7 +63,8 @@ def __init__(self, decisions: Sequence[Dict[str, Any]]) -> None: self._decisions = list(decisions) self._cursor = 0 - def decide_next_action(self, goal, screenshot, history): # noqa: D401 + def decide_next_action(self, goal: str, screenshot: Optional[bytes], # noqa: D401 + history: Sequence[AgentStep]) -> Dict[str, Any]: if self._cursor >= len(self._decisions): return {"stop": True, "message": "fake backend exhausted"} decision = self._decisions[self._cursor] @@ -122,7 +123,7 @@ def run(self, goal: str) -> AgentResult: return result def _run_loop(self, goal: str, started_at: float, - result: AgentResult, metrics) -> None: + result: AgentResult, metrics: Optional[Dict[str, Any]]) -> None: for index in range(self._budget.max_steps): if self._stop_event is not None and self._stop_event.is_set(): result.final_message = "stopped" @@ -135,7 +136,7 @@ def _run_loop(self, goal: str, started_at: float, result.final_message = "max_steps budget exhausted" def _take_one_step(self, goal: str, index: int, - result: AgentResult, metrics) -> bool: + result: AgentResult, metrics: Optional[Dict[str, Any]]) -> bool: """Run one observe→decide→act cycle. Returns True when the loop should stop.""" decision = self._backend.decide_next_action( goal, self._screenshot_fn(), result.steps, @@ -202,7 +203,7 @@ def _default_tool_runner(name: str, args: Dict[str, Any]) -> Any: _AGENT_METRIC_CACHE: Dict[str, Any] = {} -def _agent_metrics(): +def _agent_metrics() -> Optional[Dict[str, Any]]: """Lazy-register agent-loop metrics into the default Prometheus registry.""" if "runs" in _AGENT_METRIC_CACHE: return _AGENT_METRIC_CACHE @@ -230,7 +231,7 @@ def _agent_metrics(): return _AGENT_METRIC_CACHE -def run_agent(goal: str, backend: AgentBackend, **kwargs) -> AgentResult: +def run_agent(goal: str, backend: AgentBackend, **kwargs: Any) -> AgentResult: """Convenience wrapper: ``AgentLoop(backend, **kwargs).run(goal)``.""" return AgentLoop(backend, **kwargs).run(goal) diff --git a/je_auto_control/utils/agent_runtime/android_adapter.py b/je_auto_control/utils/agent_runtime/android_adapter.py index 5f299c457..062e76336 100644 --- a/je_auto_control/utils/agent_runtime/android_adapter.py +++ b/je_auto_control/utils/agent_runtime/android_adapter.py @@ -78,7 +78,7 @@ def ready(self, spec: AgentTaskSpec) -> tuple[bool, str]: self._observed = None return ready, reason - def observe(self) -> dict: + def observe(self) -> dict[str, Any]: """Publish proven app metadata and optionally host-reviewed semantic readback; never raw XML or values.""" spec, check = self._context() if self._spec is None: @@ -128,7 +128,7 @@ def _require_hierarchy(self, signature: str, evidence: AndroidInputEvidence, dea if self._capture_hierarchy(evidence, deadline, check).signature != signature: raise AgentObservationStale("Android semantic hierarchy changed since observation") - def prepare(self, name: str, arguments: dict) -> PreparedRemoteAction: + def prepare(self, name: str, arguments: dict[str, Any]) -> PreparedRemoteAction: """Refuse stale evidence and return one finite call bound to a fresh trusted device lease.""" spec, check = self._context() if self._spec is None or self._observed is None or self._control is None: @@ -156,7 +156,7 @@ def _same_evidence(expected: AndroidInputEvidence, actual: AndroidInputEvidence def _prepared_call(session: AndroidDeviceSession, lease: AndroidCommandLease, name: str, - arguments: dict, deadline: float, check: Callable[[], None], + arguments: dict[str, Any], deadline: float, check: Callable[[], None], verify: Callable[[], None] | None) -> PreparedRemoteAction: results: list[AndroidActionResult] = [] invoked = False @@ -166,7 +166,7 @@ def checkpoint() -> None: lease.checkpoint() _remaining(deadline) - def invoke() -> dict: + def invoke() -> dict[str, Any]: nonlocal invoked if invoked: raise AgentTaskError("Android prepared commands cannot be replayed") @@ -184,7 +184,7 @@ def invoke() -> dict: results.append(result) return {"android_phase": result.phase, "may_have_effect": result.may_have_effect} - def settle() -> dict: + def settle() -> dict[str, Any]: if len(results) != 1: raise AgentTaskError("Android settlement has no complete command result") return _settlement(lease.settle(results[0]), lease) @@ -193,7 +193,7 @@ def settle() -> dict: lease.epoch, invoke, settle) -def _settlement(proof: dict, lease: AndroidCommandLease) -> dict: +def _settlement(proof: dict[str, Any], lease: AndroidCommandLease) -> dict[str, Any]: if (not isinstance(proof, dict) or set(proof) != {"device", "epoch", "inputs_released", "queue_empty", "request_id", "boot_id"} or proof["request_id"] != lease.request_id or proof["boot_id"] != lease.proposal.snapshot.boot_id): diff --git a/je_auto_control/utils/agent_runtime/browser_commands.py b/je_auto_control/utils/agent_runtime/browser_commands.py index ca17170d7..0dbea0367 100644 --- a/je_auto_control/utils/agent_runtime/browser_commands.py +++ b/je_auto_control/utils/agent_runtime/browser_commands.py @@ -34,7 +34,7 @@ def browser_session_scope(session: Any) -> Iterator[None]: _SESSION.reset(token) -def _execute(name: str, arguments: dict, operation: str, *, timeout: float | None = None) -> Any: +def _execute(name: str, arguments: dict[str, Any], operation: str, *, timeout: float | None = None) -> Any: context, session = current_operation(), _SESSION.get() if context is None or session is None: raise AgentTaskError("browser command requires its managed WebRunner session") @@ -54,7 +54,7 @@ def _execute(name: str, arguments: dict, operation: str, *, timeout: float | Non return result -def _sdk_call(session: Any, operation: str, arguments: dict) -> Any: +def _sdk_call(session: Any, operation: str, arguments: dict[str, Any]) -> Any: if operation in {"link", "download", "upload"}: from je_auto_control.utils.agent_runtime.browser_transfers import sdk_transfer return sdk_transfer(session, operation, arguments) @@ -89,7 +89,7 @@ def browser_link(selector: str, frame: str = "") -> str: return str(_execute("AC_browser_link", {"selector": selector, "frame": frame}, "link")) -def browser_download(url: str, directory: str, name: str, sha256: str = "") -> dict: +def browser_download(url: str, directory: str, name: str, sha256: str = "") -> dict[str, Any]: """Download through WebRunner and publish a complete file within explicit task roots.""" _bounded(url, "URL", 4096) _bounded(name, "filename", 255) @@ -97,7 +97,7 @@ def browser_download(url: str, directory: str, name: str, sha256: str = "") -> d "sha256": sha256}, "download")) -def browser_upload(selector: str, path: str, sha256: str = "", frame: str = "") -> dict: +def browser_upload(selector: str, path: str, sha256: str = "", frame: str = "") -> dict[str, Any]: """Send one rooted bounded file as immutable bytes; never submit the form automatically.""" _bounded(selector, "selector", 4096) _bounded(frame, "frame", 4096, empty=True) diff --git a/je_auto_control/utils/agent_runtime/browser_verification.py b/je_auto_control/utils/agent_runtime/browser_verification.py index 07e3e69b9..603a51c19 100644 --- a/je_auto_control/utils/agent_runtime/browser_verification.py +++ b/je_auto_control/utils/agent_runtime/browser_verification.py @@ -14,7 +14,7 @@ from je_auto_control.utils.agent_runtime.target_config import browser_origins -def validate_browser_clause(clause: Mapping) -> None: +def validate_browser_clause(clause: Mapping[str, Any]) -> None: """Accept only exact URL/text/value/visibility checks with finite typed locator data.""" if set(clause) - {"kind", "operation", "selector", "frame", "value"}: raise AgentTaskError("browser completion contains unreviewed fields") @@ -40,7 +40,7 @@ def _expected_value(operation: str, value: Any) -> None: _bounded(value, "completion value", 8000, empty=True) -def validate_browser_scope(spec: AgentTaskSpec, clause: Mapping) -> None: +def validate_browser_scope(spec: AgentTaskSpec, clause: Mapping[str, Any]) -> None: """Completion never adds a read permission, application or network origin to the task.""" validate_browser_clause(clause) if "AC_browser_read" not in spec.allowed_tools or spec.apps: @@ -50,7 +50,7 @@ def validate_browser_scope(spec: AgentTaskSpec, clause: Mapping) -> None: raise AgentTaskError("browser completion URL exceeds task origins") -def evaluate_browser_clause(spec: AgentTaskSpec, session: Any, clause: Mapping) -> bool: +def evaluate_browser_clause(spec: AgentTaskSpec, session: Any, clause: Mapping[str, Any]) -> bool: """Read through the guarded leaf command and compare the full current result exactly.""" from je_auto_control.utils.agent_runtime.policy import TaskPolicy from je_auto_control.utils.tool_use_schema import run_tool_call @@ -77,7 +77,7 @@ def evaluate_browser_clause(spec: AgentTaskSpec, session: Any, clause: Mapping) return result -def _read_condition(clause: Mapping, read: Any) -> bool: +def _read_condition(clause: Mapping[str, Any], read: Any) -> bool: locator = {"selector": clause["selector"], "frame": clause.get("frame", "")} visible = read("AC_browser_read", {**locator, "operation": "visible"}) if not isinstance(visible, bool): diff --git a/je_auto_control/utils/agent_runtime/dag_admission.py b/je_auto_control/utils/agent_runtime/dag_admission.py index 3f465a897..99707b285 100644 --- a/je_auto_control/utils/agent_runtime/dag_admission.py +++ b/je_auto_control/utils/agent_runtime/dag_admission.py @@ -13,11 +13,11 @@ from je_auto_control.utils.rbac.authorization import AuthorizationContext, AuthorizationError, current_authorization from je_auto_control.utils.rbac.deferred import DeferredAuthorization -_ADMISSION: ContextVar[dict | None] = ContextVar("agent_local_dag_admission", default=None) +_ADMISSION: ContextVar[dict[str, Any] | None] = ContextVar("agent_local_dag_admission", default=None) @contextmanager -def admission_scope(value: dict) -> Iterator[None]: +def admission_scope(value: dict[str, Any]) -> Iterator[None]: """Carry service-authored evidence only across the synchronous task acceptance transaction.""" binding = _ADMISSION.set(detached(value)) try: @@ -26,13 +26,13 @@ def admission_scope(value: dict) -> Iterator[None]: _ADMISSION.reset(binding) -def current_admission() -> dict | None: +def current_admission() -> dict[str, Any] | None: """Return a detached trusted envelope; model-visible spec options cannot create admission evidence.""" value = _ADMISSION.get() return detached(value) if value is not None else None -def actor_identity(value: dict) -> tuple[Any, Any]: +def actor_identity(value: dict[str, Any]) -> tuple[Any, Any]: """Use the real user-store namespace without freezing a user's changing role.""" return value.get("user_id"), value.get("store_path") diff --git a/je_auto_control/utils/agent_runtime/dag_batch_recording.py b/je_auto_control/utils/agent_runtime/dag_batch_recording.py index d1c943f42..2cd0ae202 100644 --- a/je_auto_control/utils/agent_runtime/dag_batch_recording.py +++ b/je_auto_control/utils/agent_runtime/dag_batch_recording.py @@ -14,7 +14,7 @@ from je_auto_control.utils.exception.exceptions import AutoControlException -def bound_node(batch: dict, identifier: Any) -> dict: +def bound_node(batch: dict[str, Any], identifier: Any) -> dict[str, Any]: """Resolve a node solely from the immutable batch instead of accepting a caller's destination spec.""" definition = bind_definition(batch["definition"], batch["id"], batch["graph_hash"], batch.get("bindings")) for node in definition["nodes"]: @@ -23,7 +23,7 @@ def bound_node(batch: dict, identifier: Any) -> dict: raise AgentTaskError("batch node does not exist") -def claim_node(connection: Any, batch: dict, request: dict) -> None: +def claim_node(connection: Any, batch: dict[str, Any], request: dict[str, Any]) -> None: """Record possible delivery before networking; a missing reply can never reset this claim.""" node = bound_node(batch, request["node_id"]) if managed_tasks.task_host_binding(node["host"]) != batch["hosts"][node["host"]]: @@ -39,7 +39,7 @@ def claim_node(connection: Any, batch: dict, request: dict) -> None: raise AgentTaskError("batch node was already claimed; explicit recovery is required") -def verify_node(batch: dict, node: dict, task_id: str) -> None: +def verify_node(batch: dict[str, Any], node: dict[str, Any], task_id: str) -> None: """Require the exact tagged spec/key, task identity and independent completion/retirement contract.""" owner = DeferredAuthorization.capture() managed_tasks.authorize_task_host(owner, node["host"]) @@ -64,7 +64,7 @@ def verify_node(batch: dict, node: dict, task_id: str) -> None: managed_tasks.validate_recorded_completion(task, node["task"]["spec"]) -def validate_receipt(receipt: Any) -> dict: +def validate_receipt(receipt: Any) -> dict[str, Any]: """Reject malformed coordination data before any destination lookup or durable transition.""" if not isinstance(receipt, dict) or set(receipt) != {"outcome", "task_id"}: raise AgentTaskError("batch receipt requires outcome and task_id only") @@ -82,7 +82,7 @@ def _receipt_identity(identifier: Any, required: bool) -> None: raise AgentTaskError("invalid batch receipt task identity") -def record_node(connection: Any, batch: dict, request: dict) -> None: +def record_node(connection: Any, batch: dict[str, Any], request: dict[str, Any]) -> None: """Store only bounded coordination identity; completion was independently checked before this transaction.""" receipt = validate_receipt(request["receipt"]) phase = "confirmed" if receipt["outcome"] == "completed" else "unknown" diff --git a/je_auto_control/utils/agent_runtime/dag_local.py b/je_auto_control/utils/agent_runtime/dag_local.py index cc8357379..f1f9a7e17 100644 --- a/je_auto_control/utils/agent_runtime/dag_local.py +++ b/je_auto_control/utils/agent_runtime/dag_local.py @@ -17,12 +17,13 @@ class DagLocalTasks: """Only exact bound local requests can be accepted, inspected or retired through a batch attempt.""" - def __init__(self, runtime: Any, batch: dict, request: dict, actor: DeferredAuthorization) -> None: + def __init__(self, runtime: Any, batch: dict[str, Any], request: dict[str, Any], + actor: DeferredAuthorization) -> None: self.runtime, self.batch, self.request, self.actor = runtime, batch, request, actor self.node = bound_node(batch, request["node_id"]) self.owner = DeferredAuthorization(AuthorizationContext(**batch["owner"]) if batch["owner"] else None) - def control(self) -> dict: + def control(self) -> dict[str, Any]: """Validate closed fields, original authority and trusted request identity before any local operation.""" operation, body = self.request["operation"], self.request["body"] if (not isinstance(operation, str) or self.node["host"] != "local" @@ -47,13 +48,13 @@ def _active(self) -> None: if row is None or row["phase"] != "claimed": raise AgentTaskError("local DAG admission requires an unsettled pre-delivery claim") - def _request_key(self, body: dict) -> None: + def _request_key(self, body: dict[str, Any]) -> None: if body.get("idempotency_key") != self.node["task"]["idempotency_key"]: raise AgentTaskError("local DAG task request key changed") if "spec" in body and submitted_digest(body["spec"]) != submitted_digest(self.node["task"]["spec"]): raise AgentTaskError("local DAG task specification changed") - def _submit(self, body: dict) -> dict: + def _submit(self, body: dict[str, Any]) -> dict[str, Any]: if set(body) != {"spec", "idempotency_key"}: raise AgentTaskError("local DAG submit requires exact spec and request key only") self._request_key(body) @@ -69,7 +70,7 @@ def _submit(self, body: dict) -> dict: jobs.start(task.task_id) return {"task_id": task.task_id, "state": task.state} - def _read(self, operation: str, body: dict) -> dict: + def _read(self, operation: str, body: dict[str, Any]) -> dict[str, Any]: if operation == "lookup": if not {"idempotency_key"} <= set(body) or set(body) - {"idempotency_key", "spec"}: raise AgentTaskError("local DAG lookup accepts only the bound key and optional specification") diff --git a/je_auto_control/utils/agent_runtime/evidence.py b/je_auto_control/utils/agent_runtime/evidence.py index 507ae1394..2ab80aa19 100644 --- a/je_auto_control/utils/agent_runtime/evidence.py +++ b/je_auto_control/utils/agent_runtime/evidence.py @@ -74,7 +74,7 @@ def ensure(self, task_id: str) -> dict[str, Any]: return {"task_id": task_id, "history_id": run_id, "journal_path": str(journal)} @staticmethod - def _current_link(connection: Any, task_id: str, journal: Path) -> dict | None: + def _current_link(connection: Any, task_id: str, journal: Path) -> dict[str, Any] | None: row = connection.execute('SELECT * FROM agent_evidence WHERE task_id=?', (task_id,)).fetchone() if row is None or Path(row['journal_path']) != journal: return None @@ -150,7 +150,7 @@ def publish(self, task_id: str) -> None: "(SELECT 1 FROM agent_tasks WHERE id=? AND updated=?)", (task_id, task_id, row["updated"])) - def image(self, task_id: str, observation_id: str, image: dict) -> None: + def image(self, task_id: str, observation_id: str, image: dict[str, Any]) -> None: """Persist only explicitly opted-in, strict-redacted target images under generated names.""" if image.get("redacted_by") != "strict" or image.get("format") != "jpeg": raise AgentTaskError("persistent task images require strict target redaction") @@ -195,7 +195,7 @@ def _owned_artifact(path: Path) -> bool: re.fullmatch(r"[0-9a-f]{32}\.jpg", path.name) is not None) -def _summary(receipt: dict) -> dict: +def _summary(receipt: dict[str, Any]) -> dict[str, Any]: outcome = json.dumps(receipt["result"], sort_keys=True).encode("utf-8") result = {"id": receipt["id"], "command": receipt["command"], "status": receipt["status"], "created": receipt["created"], "result_sha256": hashlib.sha256(outcome).hexdigest()} @@ -204,7 +204,7 @@ def _summary(receipt: dict) -> dict: return result -def _replay_reasons(receipt: dict) -> tuple[str, ...]: +def _replay_reasons(receipt: dict[str, Any]) -> tuple[str, ...]: if receipt.get("reviewed_by"): return ("owner reviewed outcome",) return ("uncertain effect",) if receipt["status"] == "uncertain" else () diff --git a/je_auto_control/utils/agent_runtime/input_journal.py b/je_auto_control/utils/agent_runtime/input_journal.py index 53d8b88aa..f78532bd3 100644 --- a/je_auto_control/utils/agent_runtime/input_journal.py +++ b/je_auto_control/utils/agent_runtime/input_journal.py @@ -21,7 +21,7 @@ def __init__(self, resource: Path) -> None: self.owner = uuid.uuid4().hex self._data: dict[str, Any] = {} - def read(self) -> dict: + def read(self) -> dict[str, Any]: """Return a bounded witness, treating corrupt or redirected state as requiring review.""" if self.path.is_symlink(): raise AgentTaskError("input recovery witness cannot be a symlink") @@ -40,7 +40,7 @@ def read(self) -> dict: except (OSError, ValueError) as error: raise AgentTaskError("input recovery witness requires operator review") from error - def _validate_witness(self, data: dict) -> None: + def _validate_witness(self, data: dict[str, Any]) -> None: if {"remote_protocol", "remote_effect", "remote_device", "recovery_epoch"} & data.keys(): raise AgentTaskError("remote input witness requires its device-specific recovery protocol") @@ -53,7 +53,7 @@ def acquire(self) -> None: "review": previous.get("review")} self._write() - def update(self, held: dict, operation: str | None = None) -> None: + def update(self, held: dict[str, Any], operation: str | None = None) -> None: """Persist only owned release data and the outstanding operation marker.""" self._data.update(held={} if not any(held.values()) else detached(held), in_flight=operation) self._write() @@ -63,7 +63,7 @@ def release(self) -> None: self._data.update(owner=None, held={}, in_flight=None) self._write() - def recover(self, note: str, probe: Callable[[], None], actor: str) -> dict: + def recover(self, note: str, probe: Callable[[], None], actor: str) -> dict[str, Any]: """Clear stale input only after explicit review and a trusted no-held-input probe.""" if not isinstance(note, str) or not note.strip() or len(note) > 2000: raise AgentTaskError("crash recovery requires an operator review note (1-2000 characters)") diff --git a/je_auto_control/utils/agent_runtime/native_channel.py b/je_auto_control/utils/agent_runtime/native_channel.py index c5d507483..f4d8f2bfc 100644 --- a/je_auto_control/utils/agent_runtime/native_channel.py +++ b/je_auto_control/utils/agent_runtime/native_channel.py @@ -31,7 +31,8 @@ def classify_reply(reply: Any, request_id: str) -> tuple[bool, Any]: return False, detached(reply.get("result")) -def require_event_owner(event: Any, callback: Callable[[dict], None] | None) -> Callable[[dict], None]: +def require_event_owner(event: Any, + callback: Callable[[dict[str, Any]], None] | None) -> Callable[[dict[str, Any]], None]: """Refuse an input announcement that is malformed or that no caller agreed to handle. Returns the callback that agreed to handle it. @@ -148,7 +149,7 @@ def _send(self, value: Any) -> None: def request(self, operation: str, payload: Any, *, timeout: float, check: Callable[[], None] = cancellation_checkpoint, - on_event: Callable[[dict], None] | None = None) -> Any: + on_event: Callable[[dict[str, Any]], None] | None = None) -> Any: """Validate one proposal, wait within its deadline, and reap on every failed operation.""" positive(timeout, "native deadline", 3600) with self._request_lock: @@ -167,7 +168,7 @@ def request(self, operation: str, payload: Any, *, timeout: float, raise def _receive(self, request_id: str, deadline: float, check: Callable[[], None], - on_event: Callable[[dict], None] | None, operation: str = "operation") -> Any: + on_event: Callable[[dict[str, Any]], None] | None, operation: str = "operation") -> Any: while time.monotonic() < deadline: self._fenced() check() @@ -192,7 +193,7 @@ def _fenced(self) -> None: if self._stop.is_set(): raise AgentTaskError("native helper was closed while a request was waiting") - def _event(self, event: Any, callback: Callable[[dict], None] | None, check: Callable[[], None]) -> None: + def _event(self, event: Any, callback: Callable[[dict[str, Any]], None] | None, check: Callable[[], None]) -> None: handler = require_event_owner(event, callback) check() handler(detached(event)) diff --git a/je_auto_control/utils/agent_runtime/presence_broker.py b/je_auto_control/utils/agent_runtime/presence_broker.py index e45751d97..473b8c1bc 100644 --- a/je_auto_control/utils/agent_runtime/presence_broker.py +++ b/je_auto_control/utils/agent_runtime/presence_broker.py @@ -45,7 +45,7 @@ def _ready(value: Any) -> str | None: raise AgentTaskError('physical presence source startup response is invalid') -def _available(reply: dict) -> bool: +def _available(reply: dict[str, Any]) -> bool: if reply['status'] in {'busy', 'lease_lost'}: return False if reply['status'] != 'ok' or reply['result']['state'] not in {'waiting_idle', 'locked', 'monitoring'}: @@ -86,7 +86,7 @@ def _discover(self) -> Any: self._binding.owner = None return self._pipe.connect() - def bootstrap(self) -> dict: + def bootstrap(self) -> dict[str, Any]: """Borrow a verified source or launch one missing source after the parent owns this helper.""" with self._mutex: if self._binding.closed: @@ -110,7 +110,7 @@ def bootstrap(self) -> dict: self.close() raise - def request(self, operation: str, body: dict) -> dict: + def request(self, operation: str, body: dict[str, Any]) -> dict[str, Any]: """Return closed expected gate results; transport/source loss is fatal and never replayed.""" with self._mutex: if self._binding.closed or self._binding.connection is None or self._binding.generation is None: @@ -132,7 +132,7 @@ def request(self, operation: str, body: dict) -> dict: self.close() raise - def dispatch(self, operation: str, body: dict) -> dict: + def dispatch(self, operation: str, body: dict[str, Any]) -> dict[str, Any]: """The host wire may select only bootstrap or the four closed presence operations.""" if operation == 'bootstrap': if not isinstance(body, dict) or body: diff --git a/je_auto_control/utils/agent_runtime/presence_host.py b/je_auto_control/utils/agent_runtime/presence_host.py index 2fc886377..089f1be77 100644 --- a/je_auto_control/utils/agent_runtime/presence_host.py +++ b/je_auto_control/utils/agent_runtime/presence_host.py @@ -45,7 +45,7 @@ def close(self) -> None: self._reference.close() self._reference = None - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Report this runtime's passive binding state without creating any shared reference.""" with self._mutex: if self._reference is None: @@ -56,7 +56,7 @@ def status(self) -> dict: @dataclass(frozen=True) class _Grant: reference: PresenceReference - binding: dict + binding: dict[str, Any] channel: Any spec: Any endpoint: Any = None @@ -73,7 +73,7 @@ def check_platform() -> None: """Refuse unsupported defaults without starting helper, input journal or source.""" require_windows() - def bind(self, operation: Any, channel: Any, timeout: float) -> dict: + def bind(self, operation: Any, channel: Any, timeout: float) -> dict[str, Any]: """Accept only the actual immutable host operation supplied by NativeDesktopTarget.""" if self._grant is not None: if channel is not self._grant.channel or operation.spec != self._grant.spec: @@ -93,7 +93,7 @@ def bind(self, operation: Any, channel: Any, timeout: float) -> dict: endpoint_from_wire(endpoint) if endpoint is not None else None) return dict(binding) - def endpoint(self) -> dict | None: + def endpoint(self) -> dict[str, Any] | None: """Copy only the endpoint pinned with the current helper's host-owned grant.""" if self._grant is None: raise AgentTaskError('presence endpoint requires a bound helper') @@ -107,7 +107,7 @@ def release(self) -> None: self._grant.reference.release(self._grant.binding) self._grant = None - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Expose only coarse binding/source availability; never query or disclose capability identifiers.""" if self._grant is None: return {'state': 'not_bound' if sys.platform == 'win32' else 'not_supported', diff --git a/je_auto_control/utils/agent_runtime/presence_state.py b/je_auto_control/utils/agent_runtime/presence_state.py index 75c3304db..f5ba8971e 100644 --- a/je_auto_control/utils/agent_runtime/presence_state.py +++ b/je_auto_control/utils/agent_runtime/presence_state.py @@ -5,7 +5,7 @@ from dataclasses import dataclass import threading import time -from typing import Callable +from typing import Any, Callable import uuid from je_auto_control.utils.agent_runtime.errors import AgentControlBusy, AgentTaskError @@ -92,7 +92,7 @@ def fail(self) -> None: self._advance() self._flags.failed, self._flags.live = True, False - def _snapshot(self) -> dict: + def _snapshot(self) -> dict[str, Any]: now = self._tick() if (now is not None and self._flags.live and self._timing.sampled is not None and now - self._timing.sampled > 0.25): @@ -115,12 +115,12 @@ def _availability(self, idle: float) -> str: return 'waiting_idle' return 'monitoring' - def inspect(self) -> dict: + def inspect(self) -> dict[str, Any]: """Return detached coarse presence metadata; native acceptance remains unrecorded.""" with self._mutex: return self._snapshot() - def acquire(self) -> dict: + def acquire(self) -> dict[str, str]: """Allocate one finite presence lease after fresh unlocked, released, sixty-second idle.""" with self._mutex: if self._snapshot()['state'] != 'monitoring': @@ -137,7 +137,7 @@ def _validate(self, generation: str, lease_id: str) -> None: if generation != self._generation or not isinstance(lease_id, str) or lease_id not in self._leases: raise AgentTaskError('physical presence lease identity is unavailable') - def check(self, generation: str, lease_id: str) -> dict: + def check(self, generation: str, lease_id: str) -> dict[str, Any]: """Refuse a lost lease permanently; held input alone does not revoke its existing owner.""" with self._mutex: self._validate(generation, lease_id) diff --git a/je_auto_control/utils/agent_runtime/readonly_target.py b/je_auto_control/utils/agent_runtime/readonly_target.py index df0e3a0fc..e01dcf400 100644 --- a/je_auto_control/utils/agent_runtime/readonly_target.py +++ b/je_auto_control/utils/agent_runtime/readonly_target.py @@ -41,11 +41,11 @@ def perform(self, name: str, arguments: dict[str, Any]) -> Any: """Refuse host-side workflow launch/file tools as well as helper-dispatched input.""" raise AgentTaskError("read-only target cannot perform tools") - def recover(self, note: str, *, actor: str) -> dict: + def recover(self, note: str, *, actor: str) -> dict[str, Any]: """Read-only observation cannot clear a previous owner's unknown input witness.""" raise AgentTaskError("read-only target cannot recover input resources") - def _input(self, event: dict, *, cleanup: bool = False) -> None: + def _input(self, event: dict[str, Any], *, cleanup: bool = False) -> None: self._pending = "readonly_input_violation" try: self._ledger.consume(event, cleanup=cleanup) @@ -87,7 +87,7 @@ def _check(self) -> None: self._policy.validate_snapshot() self._parent.checkpoint() - def _call(self, operation: str, body: dict) -> Any: + def _call(self, operation: str, body: dict[str, Any]) -> Any: if current_operation() is not self._parent: raise AgentTaskError("completion reader cannot be borrowed by another operation") actual, captured = current_authorization(), self._authority.context @@ -100,7 +100,7 @@ def _call(self, operation: str, body: dict) -> Any: self._check() return result - def observe(self) -> dict: + def observe(self) -> dict[str, Any]: """Return a fresh scoped observation with no historical-frame or replacement-context fallback.""" return self._call("observe", {}) diff --git a/je_auto_control/utils/agent_runtime/readonly_worker.py b/je_auto_control/utils/agent_runtime/readonly_worker.py index 3b75e3039..51214055e 100644 --- a/je_auto_control/utils/agent_runtime/readonly_worker.py +++ b/je_auto_control/utils/agent_runtime/readonly_worker.py @@ -20,14 +20,14 @@ def __init__(self, source: Any, sink: Any, *, target: Any = None) -> None: super().__init__(source, sink, target=target) self._configuration: str | None = None - def _dispatch(self, operation: str, payload: dict) -> Any: + def _dispatch(self, operation: str, payload: dict[str, Any]) -> Any: if operation == "readonly_capabilities" and payload == {}: return {"contract": 1, "input_supported": False} if operation not in {"bootstrap", "configure", "observe", "verify_browser", "cleanup"}: raise AgentTaskError("read-only helper refuses executable operations") return super()._dispatch(operation, payload) - def _configure_scope(self, payload: dict) -> None: + def _configure_scope(self, payload: dict[str, Any]) -> None: if set(payload) - {"spec", "owner", "profile"}: raise AgentTaskError("read-only helper cannot replace its configured authority") configuration = json.dumps(payload, sort_keys=True, allow_nan=False) @@ -38,7 +38,7 @@ def _configure_scope(self, payload: dict) -> None: super()._configure_scope(payload) self._configuration = configuration - def _operation(self, operation: str, payload: dict) -> Any: + def _operation(self, operation: str, payload: dict[str, Any]) -> Any: if operation == "configure": if self._profile_kind == "browser": return {"ready": False, "reason": "fresh browser startup is not a read-only observation"} @@ -49,10 +49,10 @@ def _operation(self, operation: str, payload: dict) -> Any: def _guard(self, _policy: Any, name: str, _arguments: Any) -> None: raise AgentTaskError(f"read-only observation cannot dispatch {name!r}") - def _input(self, _event: dict) -> None: + def _input(self, _event: dict[str, Any]) -> None: raise AgentTaskError("read-only helper cannot acknowledge native input") - def _release_owned(self, payload: dict) -> dict: + def _release_owned(self, payload: dict[str, Any]) -> dict[str, Any]: if payload != {"keys": [], "buttons": []}: raise AgentTaskError("read-only helper cannot inject cleanup input") with command_guard(lambda name, arguments: self._guard(None, name, arguments)), input_observer(self._input): diff --git a/je_auto_control/utils/agent_runtime/recovery_authorization.py b/je_auto_control/utils/agent_runtime/recovery_authorization.py index 7b356c79d..7d6bb47e6 100644 --- a/je_auto_control/utils/agent_runtime/recovery_authorization.py +++ b/je_auto_control/utils/agent_runtime/recovery_authorization.py @@ -13,7 +13,7 @@ from je_auto_control.utils.rbac.authorization import current_authorization -def prepare_authorization(spec: AgentTaskSpec, snapshot: str) -> dict: +def prepare_authorization(spec: AgentTaskSpec, snapshot: str) -> dict[str, Any]: """Bind review to original task roots and effective live policy intersections, without input.""" if not isinstance(snapshot, str) or re.fullmatch(r"[0-9a-f]{64}", snapshot) is None: raise AgentTaskError("authorization review requires a source snapshot") @@ -31,7 +31,7 @@ def prepare_authorization(spec: AgentTaskSpec, snapshot: str) -> dict: return {"review": request_spec_digest(data), "context": data} -def authorized_template(spec: dict, authorization: dict) -> dict: +def authorized_template(spec: dict[str, Any], authorization: dict[str, Any]) -> dict[str, Any]: """Retain available prior constraints and bind new live origins within the original ceiling.""" result = detached(spec) context = authorization["context"] @@ -47,7 +47,7 @@ def authorized_template(spec: dict, authorization: dict) -> dict: return result -def narrowed_template(template: dict, reviewed: dict) -> dict: +def narrowed_template(template: dict[str, Any], reviewed: dict[str, Any]) -> dict[str, Any]: """Permit only equivalent or smaller roots inside the reviewed effective intersection.""" roots = reviewed["roots"] if any(not any(Path(root).is_relative_to(Path(parent)) for parent in template["roots"]) for root in roots): @@ -57,7 +57,7 @@ def narrowed_template(template: dict, reviewed: dict) -> dict: return result -def authorization_details(authorization: dict, spec: AgentTaskSpec) -> dict: +def authorization_details(authorization: dict[str, Any], spec: AgentTaskSpec) -> dict[str, Any]: """Freeze the exact policy review, approved roots and operator identity for durable provenance.""" identity = current_authorization() return {**authorization, "approved_roots": list(spec.roots), @@ -71,8 +71,8 @@ def _validate_roots(roots: Any) -> None: raise AgentTaskError("origin roots require a fresh authorization review") from None -def _clipped_policies(roots: Any, policies: list[dict]) -> list[dict]: - result: dict[str, dict] = {} +def _clipped_policies(roots: Any, policies: list[dict[str, Any]]) -> list[dict[str, Any]]: + result: dict[str, dict[str, Any]] = {} for policy in policies: _validate_roots(policy["roots"]) result[policy["id"]] = {"id": policy["id"], "roots": _intersect(roots, policy["roots"])} diff --git a/je_auto_control/utils/agent_runtime/remote_effect.py b/je_auto_control/utils/agent_runtime/remote_effect.py index 0a6a66652..9e1d12cb8 100644 --- a/je_auto_control/utils/agent_runtime/remote_effect.py +++ b/je_auto_control/utils/agent_runtime/remote_effect.py @@ -10,7 +10,7 @@ from je_auto_control.utils.agent_runtime.remote_journal import _integer, _token, device_identity -def remote_scope_key(binding: dict) -> str: +def remote_scope_key(binding: dict[str, Any]) -> str: """Compare JSON types exactly, including bool/int/float distinctions in reviewed task inputs.""" return json.dumps(binding, sort_keys=True, ensure_ascii=True, allow_nan=False, separators=(",", ":")) @@ -22,13 +22,13 @@ class PreparedRemoteAction: device: dict[str, str] epoch: str invoke: Callable[[], Any] = field(repr=False) - settle: Callable[[], dict] = field(repr=False) + settle: Callable[[], dict[str, Any]] = field(repr=False) class RemoteEffectController: """One configured SDK writer; missing ACK or settlement poisons this controller permanently.""" - def __init__(self, guard: dict, device: dict[str, str]) -> None: + def __init__(self, guard: dict[str, Any], device: dict[str, str]) -> None: self.device = device_identity(**device) if (not isinstance(guard, dict) or set(guard) != {"controller", "device", "next_sequence"} or guard["device"] != self.device or not _integer(guard["next_sequence"], 1, 2**53 - 1)): @@ -37,12 +37,12 @@ def __init__(self, guard: dict, device: dict[str, str]) -> None: self.sequence = guard["next_sequence"] self._pending = False - def matches(self, guard: dict) -> bool: + def matches(self, guard: dict[str, Any]) -> bool: """Reconfiguration may only refresh the exact live controller, device and next sequence.""" return (isinstance(guard, dict) and _integer(guard.get("next_sequence"), 1, 2**53 - 1) and guard == {"controller": self.owner, "device": self.device, "next_sequence": self.sequence}) - def perform(self, action: PreparedRemoteAction, notify: Callable[[dict], None], + def perform(self, action: PreparedRemoteAction, notify: Callable[[dict[str, Any]], None], check: Callable[[], None]) -> Any: """Invoke once after begin ACK; never infer remote settlement from local return or failure.""" if self._pending: diff --git a/je_auto_control/utils/agent_runtime/remote_target.py b/je_auto_control/utils/agent_runtime/remote_target.py index 9737ee1b8..2babfa498 100644 --- a/je_auto_control/utils/agent_runtime/remote_target.py +++ b/je_auto_control/utils/agent_runtime/remote_target.py @@ -19,7 +19,7 @@ class NativeRemoteTarget: # pylint: disable=too-many-instance-attributes # rea """Trusted adapter prerequisite; no built-in device profile or SDK support is advertised.""" def __init__(self, *, argv: Sequence[str], platform: str, physical_id: str, - recovery_probe: Callable[[], dict] | None = None, resource_path: Path | None = None) -> None: + recovery_probe: Callable[[], dict[str, Any]] | None = None, resource_path: Path | None = None) -> None: if not argv or any(not isinstance(part, str) or not part for part in argv): raise AgentTaskError("remote helper requires fixed trusted host arguments") self._device = device_identity(platform, physical_id) @@ -40,7 +40,7 @@ def can_reobserve(self) -> bool: return (self._channel is not None and not self._channel.retired and self._journal is not None and not self._journal.pending and self._journal.read().get("in_flight") is None) - def check_resume(self, spec: AgentTaskSpec, receipts: list[dict]) -> None: + def check_resume(self, spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> None: """An old finite UI prefix cannot establish a new device/app context.""" connected = self._channel is not None and not self._channel.retired require_context_continuity(spec, receipts, connected, kind="desktop") @@ -88,7 +88,7 @@ def _control(self, _kind: str) -> None: threading.Thread(target=self._takeover, name="RemoteTakeover", daemon=True).start() @staticmethod - def _binding() -> dict: + def _binding() -> dict[str, Any]: context = current_operation() if context is None: raise AgentTaskError("remote target has no managed owner") @@ -96,7 +96,7 @@ def _binding() -> dict: identity = {"user_id": owner.user_id, "role": owner.role, "store_path": owner.store_path} if owner else {} return {"spec": context.spec.to_dict(), "owner": identity} - def _request(self, operation: str, payload: dict) -> Any: + def _request(self, operation: str, payload: dict[str, Any]) -> Any: with self._mutex: context = current_operation() if context is None: @@ -157,7 +157,7 @@ def cleanup(self) -> None: self._resource.close() self._resource = None - def recover(self, note: str, *, actor: str) -> dict: + def recover(self, note: str, *, actor: str) -> dict[str, Any]: """Review without replay; host-provided proof is mandatory even after host restart.""" with self._mutex: if self._probe is None: diff --git a/je_auto_control/utils/agent_runtime/retained_browser_runtime.py b/je_auto_control/utils/agent_runtime/retained_browser_runtime.py index 1ca949198..27e12bd65 100644 --- a/je_auto_control/utils/agent_runtime/retained_browser_runtime.py +++ b/je_auto_control/utils/agent_runtime/retained_browser_runtime.py @@ -9,7 +9,7 @@ from je_auto_control.utils.exception.exceptions import AutoControlException -def retire_target(runtime: Any, row: dict, target: Any, eligible: bool) -> None: +def retire_target(runtime: Any, row: dict[str, Any], target: Any, eligible: bool) -> None: """Keep only eligible actual contexts; every other target uses its established cleanup path.""" if not eligible: target.cleanup() @@ -34,7 +34,7 @@ def retire_target(runtime: Any, row: dict, target: Any, eligible: bool) -> None: raise -def require_source(runtime: Any, effect: dict) -> dict: +def require_source(runtime: Any, effect: dict[str, Any]) -> dict[str, Any]: """Validate live source authority and actual SDK proof before completion preview or admission.""" # pylint: disable-next=protected-access # reason: private effect admission owns this exact runtime collection pool = runtime._retained_browsers @@ -62,10 +62,10 @@ def check() -> None: pool.release(entry) -def completion_adapter(runtime: Any, effect: dict, spec: Any, +def completion_adapter(runtime: Any, effect: dict[str, Any], spec: Any, current_operation: Callable[[], Any]) -> RetainedBrowserTarget: """Construct an inert closed borrower from private effect identity; readiness never launches a helper.""" - def current_source() -> dict: + def current_source() -> dict[str, Any]: # pylint: disable-next=protected-access # reason: private original-effect authority stays live on every read return runtime._retained_source(effect["id"]) # pylint: disable-next=protected-access # reason: share actual runtime-owned process lifetime diff --git a/je_auto_control/utils/agent_runtime/runner.py b/je_auto_control/utils/agent_runtime/runner.py index ce9e511d3..0eb3de2e5 100644 --- a/je_auto_control/utils/agent_runtime/runner.py +++ b/je_auto_control/utils/agent_runtime/runner.py @@ -63,7 +63,7 @@ def _loop(runtime: Any, task_id: str, spec: AgentTaskSpec, backend: Any, guard: return runtime.get(task_id) -def _skill_proposal(spec: AgentTaskSpec, receipts: list[dict]) -> dict | None: +def _skill_proposal(spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> dict[str, Any] | None: """Return the next declared workflow action, or None once every action has a receipt.""" if not verified_prefix(spec, receipts): raise AgentTaskError("previous workflow read-back did not match; review before continuing") @@ -72,7 +72,7 @@ def _skill_proposal(spec: AgentTaskSpec, receipts: list[dict]) -> dict | None: return thaw(spec.actions[len(receipts)]) -def _grounded_action(proposal: dict, values: dict, observation_id: str) -> dict: +def _grounded_action(proposal: dict[str, Any], values: dict[str, Any], observation_id: str) -> dict[str, Any]: action = {"tool": proposal["tool"], "arguments": resolve(proposal.get("arguments", {}), values), "observation_id": observation_id} if proposal.get("reference") is not None: @@ -85,7 +85,8 @@ def _can_reobserve(runtime: Any, task_id: str) -> bool: return getattr(target, "can_reobserve", False) is True -def _check_step(proposal: dict, values: dict, result: Any, action: dict, guard: LoopGuard | None) -> None: +def _check_step(proposal: dict[str, Any], values: dict[str, Any], result: Any, action: dict[str, Any], + guard: LoopGuard | None) -> None: if "expect_not_result" in proposal and thaw(result) == proposal["expect_not_result"]: raise AgentTaskError("workflow confirmation is stale; review before continuing") required, value = expected(proposal, values) @@ -98,7 +99,7 @@ def _check_step(proposal: dict, values: dict, result: Any, action: dict, guard: def _decision(runtime: Any, task_id: str, spec: AgentTaskSpec, backend: Any, observation: Any, - receipts: list[dict]) -> dict: + receipts: list[dict[str, Any]]) -> dict[str, Any]: last_error: AgentTaskError | None = None for _attempt in range(spec.budget.retries + 1): runtime._token(task_id).checkpoint() diff --git a/je_auto_control/utils/agent_runtime/skill_parameters.py b/je_auto_control/utils/agent_runtime/skill_parameters.py index 12a94030d..4baa9a1f8 100644 --- a/je_auto_control/utils/agent_runtime/skill_parameters.py +++ b/je_auto_control/utils/agent_runtime/skill_parameters.py @@ -20,7 +20,7 @@ def digest(value: Any) -> str: return hashlib.sha256(json.dumps(detached(value), sort_keys=True, separators=(",", ":")).encode()).hexdigest() -def _slot(document: dict, pointer: str) -> tuple[Any, Any]: +def _slot(document: dict[str, Any], pointer: str) -> tuple[Any, Any]: if not isinstance(pointer, str) or _DATA.fullmatch(pointer) is None or "~" in pointer: raise AgentTaskError("skill slots must address explicit action/input/criterion data values") pieces = pointer.split("/")[1:] @@ -46,7 +46,7 @@ def _typed(value: Any, kind: str) -> Any: return detached(value) -def parameter_schema(spec: dict, slots: Any) -> dict: +def parameter_schema(spec: dict[str, Any], slots: Any) -> dict[str, Any]: """Freeze explicit primitive defaults from a recorded flow; reject duplicate/overlapping slots.""" if not isinstance(slots, dict) or len(slots) > 50: raise AgentTaskError("skill parameters must be an object with at most fifty entries") @@ -80,7 +80,7 @@ def _overlaps(path: str, occupied: list[str]) -> bool: return any(path == other or path.startswith(other + "/") or other.startswith(path + "/") for other in occupied) -def instantiate(spec: dict, schema: dict, parameters: Any) -> dict: +def instantiate(spec: dict[str, Any], schema: dict[str, Any], parameters: Any) -> dict[str, Any]: """Apply only named literal parameters to detached, explicitly declared data slots.""" if not isinstance(parameters, dict) or set(parameters) - set(schema): raise AgentTaskError("unknown skill parameters") @@ -93,7 +93,7 @@ def instantiate(spec: dict, schema: dict, parameters: Any) -> dict: return result -def repair_data(spec: dict, changes: Any) -> dict: +def repair_data(spec: dict[str, Any], changes: Any) -> dict[str, Any]: """Produce a detached repair proposal limited to existing semantic selector data.""" if not isinstance(changes, list) or not 1 <= len(changes) <= 100: raise AgentTaskError("repair requires between one and one hundred semantic selector changes") diff --git a/je_auto_control/utils/agent_runtime/skill_reauthorization.py b/je_auto_control/utils/agent_runtime/skill_reauthorization.py index 079a543e8..c83fa1c60 100644 --- a/je_auto_control/utils/agent_runtime/skill_reauthorization.py +++ b/je_auto_control/utils/agent_runtime/skill_reauthorization.py @@ -16,7 +16,7 @@ OPERATIONS = ("review_authorization", "create_authorized") -def source_snapshot(connection: Any, parent: dict) -> str: +def source_snapshot(connection: Any, parent: dict[str, Any]) -> str: """Require a real published current version and bind review to its immutable candidate.""" latest = connection.execute("SELECT COALESCE(MAX(version),0) FROM agent_skill_candidates WHERE skill_id=?", (parent["skill_id"],)).fetchone()[0] @@ -25,7 +25,7 @@ def source_snapshot(connection: Any, parent: dict) -> str: return digest({"candidate": parent["id"], "digest": parent["digest"], "version": latest}) -def existing_authorization(connection: Any, provenance: dict, spec_hash: str) -> str | None: +def existing_authorization(connection: Any, provenance: dict[str, Any], spec_hash: str) -> str | None: """Find an identical approved candidate and reject publication races inside the insert transaction.""" if provenance.get("kind") != "origin_reauthorization": return None @@ -49,7 +49,7 @@ class SkillReauthorization: def __init__(self, skills: Any) -> None: self.skills = skills - def control(self, operation: str, request: dict) -> dict: + def control(self, operation: str, request: dict[str, Any]) -> dict[str, Any]: """Review passively or save a new draft; validation and publication remain separate operations.""" fields = {"candidate_id"} if operation == "create_authorized": @@ -73,9 +73,10 @@ def control(self, operation: str, request: dict) -> dict: return self._review(parent, snapshot, authorization, template) return self._create(parent, request, authorization, template) - def _review(self, parent: dict, snapshot: str, authorization: dict, template: dict) -> dict: + def _review(self, parent: dict[str, Any], snapshot: str, authorization: dict[str, Any], + template: dict[str, Any]) -> dict[str, Any]: issues = [] - reviewed: dict | None = None + reviewed: dict[str, Any] | None = None try: # pylint: disable-next=protected-access # reason: reviewed templates use the common host/scope validator reviewed = self.skills.runtime._validated_spec(template).to_dict() @@ -85,7 +86,8 @@ def _review(self, parent: dict, snapshot: str, authorization: dict, template: di "authorization": authorization["context"], "spec": reviewed, "issues": issues, "approval_required": True, "validation_required": True, "publication_inherited": False} - def _create(self, parent: dict, request: dict, authorization: dict, template: dict) -> dict: + def _create(self, parent: dict[str, Any], request: dict[str, Any], authorization: dict[str, Any], + template: dict[str, Any]) -> dict[str, Any]: if (request["snapshot"] != authorization["context"]["source_snapshot"] or request["authorization_review"] != authorization["review"]): raise AgentTaskError("skill authorization context changed; review authorization again") diff --git a/je_auto_control/utils/agent_runtime/targets.py b/je_auto_control/utils/agent_runtime/targets.py index 0d94b9752..ca1ea1daa 100644 --- a/je_auto_control/utils/agent_runtime/targets.py +++ b/je_auto_control/utils/agent_runtime/targets.py @@ -46,7 +46,7 @@ def ready(self, spec: AgentTaskSpec) -> tuple[bool, str]: self._check_foreground() return True, "" - def check_resume(self, spec: AgentTaskSpec, receipts: list[dict]) -> None: + def check_resume(self, spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> None: """A retired desktop scope cannot attest that earlier form/window state is still current.""" require_context_continuity(spec, receipts, self._spec == spec, kind="desktop") @@ -104,7 +104,7 @@ def _observation_window(self) -> tuple[int, str, int] | None: raise @staticmethod - def _image(hwnd: int, elements: list[dict]) -> dict[str, Any]: + def _image(hwnd: int, elements: list[dict[str, Any]]) -> dict[str, Any]: image, origin = _window_frame(hwnd) original = image.size redacted = _redact_frame(image, elements, origin) @@ -137,7 +137,7 @@ def perform(self, name: str, arguments: dict[str, Any]) -> Any: with control_owner_scope(pid, hwnd), driver: return run_tool_call(name, arguments) - def validate_input(self, event: dict) -> None: + def validate_input(self, event: dict[str, Any]) -> None: """Refuse new input after focus changes or a point leaves the authorized window.""" if event["kind"] in {"key_release", "key_released", "mouse_release", "mouse_released"}: return @@ -154,7 +154,7 @@ def validate_input(self, event: dict) -> None: from je_auto_control.utils.agent_runtime.native_scope import check_pointer check_pointer(hwnd, event) - def prepare_input(self, event: dict) -> None: + def prepare_input(self, event: dict[str, Any]) -> None: """Position and confirm the actual pointer before acknowledging an owned button press.""" from je_auto_control.wrapper.auto_control_mouse import set_mouse_position, get_mouse_position point = event["x"], event["y"] @@ -182,7 +182,7 @@ def _window_frame(hwnd: int) -> tuple[Any, tuple[int, int]]: return capture_window(hwnd) -def _redact_frame(image: Any, elements: list[dict], origin: tuple[int, int]) -> Any: +def _redact_frame(image: Any, elements: list[dict[str, Any]], origin: tuple[int, int]) -> Any: from je_auto_control.utils.redaction.engine import RedactionEngine from je_auto_control.utils.redaction.policies import POLICY_STRICT x, y = origin diff --git a/je_auto_control/utils/agent_runtime/task_handoff.py b/je_auto_control/utils/agent_runtime/task_handoff.py index bd6ebe53a..534f400bc 100644 --- a/je_auto_control/utils/agent_runtime/task_handoff.py +++ b/je_auto_control/utils/agent_runtime/task_handoff.py @@ -13,12 +13,13 @@ class TaskHandoffContext: """Derive bounded source ancestry through injected host ownership/snapshot validators.""" - def __init__(self, runtime: Any, snapshot: Callable, identity: Callable, digest: Callable, - owns: Callable) -> None: + def __init__(self, runtime: Any, snapshot: Callable[[Any, dict[str, Any]], dict[str, Any]], + identity: Callable[[Any, Any, dict[str, Any], dict[str, Any], dict[str, Any]], None], + digest: Callable[[Any], str], owns: Callable[[Any, Any], bool]) -> None: self.runtime, self.snapshot, self.identity, self.digest, self.owns = runtime, snapshot, identity, digest, owns def context(self, source_task: str, *, origin_policies: list[str] | None = None, - connection: Any = None, identity_only: bool = False) -> dict: + connection: Any = None, identity_only: bool = False) -> dict[str, Any]: """Bind a real task and any actual accepted request without making a synthetic DAG node.""" transaction = self.runtime.store.connection() if connection is None else nullcontext(connection) with transaction as reading: @@ -33,7 +34,7 @@ def context(self, source_task: str, *, origin_policies: list[str] | None = None, return {'binding': binding, 'source': source, 'state': source['state'], 'policy': policy, 'ancestor_links': len(ancestry) - 1, 'retained_rows': retained} - def _ancestry(self, connection: Any, source: dict) -> list: + def _ancestry(self, connection: Any, source: dict[str, Any]) -> list[dict[str, Any]]: result, seen, row = [], set(), source for _index in range(17): if row['id'] in seen: @@ -56,7 +57,7 @@ def _ancestry(self, connection: Any, source: dict) -> list: raise AgentTaskError('handoff source has no bounded real recovery ancestry') @staticmethod - def _non_dag(connection: Any, row: dict) -> None: + def _non_dag(connection: Any, row: dict[str, Any]) -> None: admitted = connection.execute('SELECT 1 FROM agent_dag_local_tasks WHERE task_id=?', (row['id'],)).fetchone() submitted = connection.execute('SELECT 1 FROM agent_task_submissions WHERE task_id=?', @@ -64,7 +65,7 @@ def _non_dag(connection: Any, row: dict) -> None: if 'dag_batch' in row['spec']['options'] or admitted is not None or submitted is not None: raise AgentTaskError('DAG evidence requires its actual batch and node handoff') - def _requests(self, connection: Any, row: dict) -> list: + def _requests(self, connection: Any, row: dict[str, Any]) -> list[dict[str, Any]]: requests = [dict(item) for item in connection.execute( 'SELECT * FROM agent_request_keys WHERE task_id=? ORDER BY owner_key,key_hash', (row['id'],))] owner = json.dumps([row['owner'].get('user_id'), row['owner'].get('store_path')]) diff --git a/je_auto_control/utils/agent_runtime/transfer_evidence_management.py b/je_auto_control/utils/agent_runtime/transfer_evidence_management.py index 631d42110..862bc4f37 100644 --- a/je_auto_control/utils/agent_runtime/transfer_evidence_management.py +++ b/je_auto_control/utils/agent_runtime/transfer_evidence_management.py @@ -12,12 +12,12 @@ from je_auto_control.utils.agent_runtime.transfer_records import _text -def evidence_digest(summary: Mapping) -> str: +def evidence_digest(summary: Mapping[str, Any]) -> str: """Hash only the exact unresolved public summary approved by the actual source service.""" return sha256(_canonical(portable_evidence(summary, resolved=False))).hexdigest() -def evidence_request(operation: str, request: Mapping) -> dict: +def evidence_request(operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Accept finite source-local identities and explicit consent fields, never caller-supplied principals.""" value = dict(_object(request, EVIDENCE_FIELDS[operation])) if operation == 'review_evidence': @@ -35,7 +35,7 @@ def evidence_request(operation: str, request: Mapping) -> dict: return deepcopy(value) -def evidence_reply(operation: str, reply: Mapping, request: dict) -> dict: +def evidence_reply(operation: str, reply: Mapping[str, Any], request: dict[str, Any]) -> dict[str, Any]: """Check closed management envelopes independently of authenticated evidence resolution and input.""" if operation == 'review_evidence': return _review(reply, request) @@ -50,7 +50,7 @@ def evidence_reply(operation: str, reply: Mapping, request: dict) -> dict: return {'evidence': record} -def _review(reply: Mapping, request: dict) -> dict: +def _review(reply: Mapping[str, Any], request: dict[str, Any]) -> dict[str, Any]: value = _object(reply, {'review', 'digest', 'evidence', 'review_expires', 'approval_required'}) _hex(value['review'], 32) _hex(value['digest'], 64) @@ -64,7 +64,7 @@ def _review(reply: Mapping, request: dict) -> dict: 'review_expires': value['review_expires'], 'approval_required': True} -def _record(reply: Any) -> dict: +def _record(reply: Any) -> dict[str, Any]: value = _object(reply, {'grant_id', 'state', 'summary'}) _hex(value['grant_id'], 32) summary = portable_evidence(value['summary'], resolved=False) @@ -75,7 +75,7 @@ def _record(reply: Any) -> dict: return {'grant_id': value['grant_id'], 'state': state, 'summary': summary} -def _listing(reply: Mapping, source_task: str) -> dict: +def _listing(reply: Mapping[str, Any], source_task: str) -> dict[str, Any]: values = _object(reply, {'evidence'})['evidence'] if not isinstance(values, list) or len(values) > 200: raise AgentTaskError('evidence management list exceeds its finite quota') diff --git a/je_auto_control/utils/agent_runtime/transfer_import_contract.py b/je_auto_control/utils/agent_runtime/transfer_import_contract.py index 3eb1bbb59..ecb80dd59 100644 --- a/je_auto_control/utils/agent_runtime/transfer_import_contract.py +++ b/je_auto_control/utils/agent_runtime/transfer_import_contract.py @@ -17,7 +17,7 @@ STATES = frozenset({'queued', 'receiving', 'verified', 'published', 'requires_review', 'cancelled', 'expired'}) -def import_request(operation: str, request: Mapping) -> dict: +def import_request(operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Validate exact finite fields; only the destination interprets its directory and registered source label.""" if not isinstance(operation, str) or operation not in IMPORT_FIELDS: raise AgentTaskError('destination transfer management operation is unavailable') @@ -40,7 +40,7 @@ def import_request(operation: str, request: Mapping) -> dict: return deepcopy(value) -def import_reply(operation: str, reply: Mapping, request: dict) -> dict: +def import_reply(operation: str, reply: Mapping[str, Any], request: dict[str, Any]) -> dict[str, Any]: """Retain only bounded public receipt fields, never remote issuer, store, origin or cache-account data.""" if not isinstance(operation, str) or operation not in IMPORT_FIELDS: raise AgentTaskError('destination transfer management operation is unavailable') @@ -57,7 +57,7 @@ def import_reply(operation: str, reply: Mapping, request: dict) -> dict: return {'import': receipt} -def _review(reply: Mapping, request: dict) -> dict: +def _review(reply: Mapping[str, Any], request: dict[str, Any]) -> dict[str, Any]: value, manifest = _review_envelope(reply) if manifest.export_id != request['export_id'] or manifest.digest != value['digest']: raise AgentTaskError('destination review does not bind the requested source manifest') @@ -67,7 +67,7 @@ def _review(reply: Mapping, request: dict) -> dict: 'review_expires': value['review_expires'], 'approval_required': True} -def _receipt(reply: Any) -> dict: +def _receipt(reply: Any) -> dict[str, Any]: value = _object(reply, {'import_id', 'state', 'expires', 'manifest_digest', 'files_directory'}) _hex(value['import_id'], 32) _hex(value['manifest_digest'], 64) diff --git a/je_auto_control/utils/agent_runtime/transfer_import_ledger.py b/je_auto_control/utils/agent_runtime/transfer_import_ledger.py index 300189326..8e31c6bd4 100644 --- a/je_auto_control/utils/agent_runtime/transfer_import_ledger.py +++ b/je_auto_control/utils/agent_runtime/transfer_import_ledger.py @@ -86,7 +86,7 @@ def pin_ceilings(self, connection: Any, identifier: str, ceilings: list[str]) -> connection.execute('UPDATE agent_transfer_deliveries SET ceilings=? WHERE id=?', (json.dumps(ceilings), identifier)) - def read(self, connection: Any, identifier: str) -> dict: + def read(self, connection: Any, identifier: str) -> dict[str, Any]: """Read only a real delivery associated with an accepted local import.""" row = connection.execute('SELECT * FROM agent_transfer_deliveries WHERE id=?', (identifier,)).fetchone() if row is None: @@ -121,7 +121,7 @@ def claim(self, item: Any) -> None: connection.execute("UPDATE agent_transfer_deliveries SET claim=?,state='receiving',updated=? WHERE id=?", (item.claim, time.time(), item.reference)) - def check(self, connection: Any, identifier: str, generation: int) -> dict: + def check(self, connection: Any, identifier: str, generation: int) -> dict[str, Any]: """Refuse a retired generation or any delivery whose exact queue performer lost its claim.""" row = self.read(connection, identifier) queue = connection.execute('SELECT status,claim,reference FROM work_items WHERE id=? AND queue=?', @@ -134,7 +134,7 @@ def check(self, connection: Any, identifier: str, generation: int) -> dict: return row def advance(self, connection: Any, identifier: str, generation: int, state: str, *, - publication: dict | None = None, files_directory: str = '') -> None: + publication: dict[str, Any] | None = None, files_directory: str = '') -> None: """Record a verified phase only while the same generation and queue claim remain authoritative.""" if state not in {'receiving', 'verified', 'published', 'requires_review', 'expired'}: raise AgentTaskError('invalid destination import transition') @@ -143,7 +143,7 @@ def advance(self, connection: Any, identifier: str, generation: int, state: str, 'WHERE id=?', (state, json.dumps(row['publication'] if publication is None else publication), files_directory, time.time(), identifier)) - def staging_retired(self, connection: Any, identifier: str, witness: dict) -> None: + def staging_retired(self, connection: Any, identifier: str, witness: dict[str, Any]) -> None: """Acknowledge only a previously journaled allocation's cleanup without granting a delivery generation.""" row = self.read(connection, identifier) publication = row['publication'] diff --git a/je_auto_control/utils/agent_runtime/transfer_management.py b/je_auto_control/utils/agent_runtime/transfer_management.py index 779668936..a41e0cce9 100644 --- a/je_auto_control/utils/agent_runtime/transfer_management.py +++ b/je_auto_control/utils/agent_runtime/transfer_management.py @@ -20,7 +20,7 @@ 'revoke_export': {'export_id'}, 'list_exports': {'source_task'}} -def management_request(operation: str, request: Mapping[str, Any]) -> dict: +def management_request(operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Accept only the finite source operation's exact public fields, never a host or private principal.""" if isinstance(operation, str) and operation in EVIDENCE_FIELDS: return evidence_request(operation, request) @@ -40,7 +40,7 @@ def management_request(operation: str, request: Mapping[str, Any]) -> dict: return deepcopy(value) -def _review_request(value: dict) -> None: +def _review_request(value: dict[str, Any]) -> None: _hex(value['source_task'], 32) _text(value['idempotency_key'], 256, 'idempotency key') if value['recipient_policy'] not in ('caller', 'source_owner'): @@ -51,7 +51,7 @@ def _review_request(value: dict) -> None: TransferSelection.from_dict(item) -def management_reply(operation: str, reply: Mapping[str, Any], request: dict) -> dict: +def management_reply(operation: str, reply: Mapping[str, Any], request: dict[str, Any]) -> dict[str, Any]: """Validate exact bounded public projections without granting source-task visibility or input authority.""" if operation in EVIDENCE_FIELDS: return evidence_reply(operation, reply, request) @@ -70,7 +70,7 @@ def management_reply(operation: str, reply: Mapping[str, Any], request: dict) -> return {'export': value} -def _list_reply(reply: Mapping[str, Any], source_task: str) -> dict: +def _list_reply(reply: Mapping[str, Any], source_task: str) -> dict[str, Any]: value = _object(reply, {'exports'})['exports'] if not isinstance(value, list) or len(value) > 128: raise AgentTaskError('source export list exceeds its finite grant quota') @@ -80,7 +80,7 @@ def _list_reply(reply: Mapping[str, Any], source_task: str) -> dict: return {'exports': exports} -def _review_reply(reply: Mapping[str, Any], request: dict) -> dict: +def _review_reply(reply: Mapping[str, Any], request: dict[str, Any]) -> dict[str, Any]: value, manifest = _review_envelope(reply) if (manifest.source_task != request['source_task'] or manifest.digest != value['digest'] or value['approval_required'] is not True or min(value['review_expires'], manifest.expires) <= time.time()): @@ -89,7 +89,7 @@ def _review_reply(reply: Mapping[str, Any], request: dict) -> dict: 'review_expires': value['review_expires'], 'approval_required': True} -def _export(reply: Any) -> dict: +def _export(reply: Any) -> dict[str, Any]: value = _object(reply, {'export_id', 'state', 'manifest', 'cleanup_pending'}) _hex(value['export_id'], 32) manifest = TransferManifest.from_dict(value['manifest']) diff --git a/je_auto_control/utils/agent_runtime/transfer_protocol.py b/je_auto_control/utils/agent_runtime/transfer_protocol.py index ba4b99dd4..96a2f5e2e 100644 --- a/je_auto_control/utils/agent_runtime/transfer_protocol.py +++ b/je_auto_control/utils/agent_runtime/transfer_protocol.py @@ -58,13 +58,13 @@ def maintenance_pending(store: Any) -> bool: """Find source or destination retirement left by a prior runtime without dispatching new work.""" return source_maintenance_pending(store) or import_maintenance_pending(store) - def control(self, operation: str, request: Mapping[str, Any] | None = None) -> dict: + def control(self, operation: str, request: Mapping[str, Any] | None = None) -> dict[str, Any]: """Apply one finite local management operation without recursively dispatching agents.""" if self._task_active(): raise AgentTaskError('active tasks cannot invoke transfer management') return self._invoke(operation, {} if request is None else request, peer=False) - def peer(self, operation: str, request: Mapping[str, Any]) -> dict: + def peer(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Serve only closed authenticated source reads, never local management delegation.""" return self._invoke(operation, request, peer=True) @@ -95,7 +95,7 @@ def maintain(self) -> None: with self._state: self._life.busy = False - def _invoke(self, operation: str, request: Mapping[str, Any], *, peer: bool) -> dict: + def _invoke(self, operation: str, request: Mapping[str, Any], *, peer: bool) -> dict[str, Any]: with self._mutex: with self._state: if self._life.closed or self._life.busy: @@ -116,7 +116,7 @@ def _invoke(self, operation: str, request: Mapping[str, Any], *, peer: bool) -> with self._state: self._life.busy = False - def _management(self, operation: str, request: Mapping[str, Any]) -> dict: + def _management(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: if not isinstance(request, Mapping): raise AgentTaskError('transfer request must be an object') value = dict(request) @@ -131,7 +131,7 @@ def _management(self, operation: str, request: Mapping[str, Any]) -> dict: return self._life.evidence.control(operation, value) return self.source.control(operation, value) - def _peer(self, operation: str, request: Mapping[str, Any]) -> dict: + def _peer(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: if operation == 'evidence': value = _object(request, {'grant_id', 'binding'}) return self._life.evidence.resolve(value['grant_id'], value['binding']) diff --git a/je_auto_control/utils/agent_runtime/trigger_config.py b/je_auto_control/utils/agent_runtime/trigger_config.py index 930d8bcf0..26d74a283 100644 --- a/je_auto_control/utils/agent_runtime/trigger_config.py +++ b/je_auto_control/utils/agent_runtime/trigger_config.py @@ -13,7 +13,7 @@ KINDS = ("interval", "cron", "file", "event") -def validate_config(kind: str, config: dict, policy: TaskPolicy) -> dict[str, Any]: +def validate_config(kind: str, config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: """Require explicit schedule fields; event input can never select a task scope.""" fields = {"interval": {"seconds"}, "cron": {"expression", "timezone"}, "file": {"path", "stable_seconds"}, "event": set()} @@ -24,7 +24,7 @@ def validate_config(kind: str, config: dict, policy: TaskPolicy) -> dict[str, An return checks[kind](config) -def _interval(config: dict) -> dict: +def _interval(config: dict[str, Any]) -> dict[str, Any]: positive(config.get("seconds"), "trigger seconds", 86400 * 365) seconds = float(config["seconds"]) if seconds < 1: @@ -32,7 +32,7 @@ def _interval(config: dict) -> dict: return {"seconds": seconds} -def _cron(config: dict) -> dict: +def _cron(config: dict[str, Any]) -> dict[str, Any]: from je_auto_control.utils.scheduler.cron import parse_cron expression, timezone = config.get("expression"), config.get("timezone", "UTC") if not isinstance(expression, str) or len(expression) > 128 or not isinstance(timezone, str): @@ -45,7 +45,7 @@ def _cron(config: dict) -> dict: return {"expression": expression, "timezone": timezone} -def _file(config: dict, policy: TaskPolicy) -> dict: +def _file(config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: path = policy.path(config.get("path")) stable = config.get("stable_seconds", 1) positive(stable, "file stability seconds", 300) @@ -54,7 +54,7 @@ def _file(config: dict, policy: TaskPolicy) -> dict: return {"path": path, "stable_seconds": stable} -def next_due(kind: str, config: dict, now: float) -> float: +def next_due(kind: str, config: dict[str, Any], now: float) -> float: """Reuse the existing cron parser; missed schedule windows coalesce rather than replay a backlog.""" if kind == "interval": return now + config["seconds"] diff --git a/je_auto_control/utils/clipboard/clipboard.py b/je_auto_control/utils/clipboard/clipboard.py index b2d9cff8d..dfb29aa9d 100644 --- a/je_auto_control/utils/clipboard/clipboard.py +++ b/je_auto_control/utils/clipboard/clipboard.py @@ -53,7 +53,7 @@ def get_clipboard_image() -> Optional[bytes]: return _linux_get_image() -def _as_png_bytes(image: bytes | bytearray | str | os.PathLike) -> bytes: +def _as_png_bytes(image: bytes | bytearray | str | os.PathLike[str]) -> bytes: """PNG bytes for either raw bytes or a path to any Pillow-readable file.""" if isinstance(image, (bytes, bytearray)): if not image: @@ -75,7 +75,7 @@ def _as_png_bytes(image: bytes | bytearray | str | os.PathLike) -> bytes: def set_clipboard_image( - image: bytes | bytearray | str | os.PathLike) -> None: + image: bytes | bytearray | str | os.PathLike[str]) -> None: """Place an image on the clipboard, from PNG bytes **or** a file path. Both are accepted because both callers are real: the remote-desktop viewer @@ -153,7 +153,7 @@ class ClipboardError(AutoControlException, RuntimeError): """ -def _run_tool(argv: list, data: Optional[bytes] = None) -> "subprocess.CompletedProcess": +def _run_tool(argv: list[str], data: Optional[bytes] = None) -> "subprocess.CompletedProcess[bytes]": """Run a clipboard tool with a 5 s limit; its failure is a :class:`ClipboardError`.""" try: # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit.dangerous-subprocess-use-audit @@ -162,7 +162,7 @@ def _run_tool(argv: list, data: Optional[bytes] = None) -> "subprocess.Completed raise ClipboardError(f"{argv[0]} failed: {error!r}") from error -def _checked(result: "subprocess.CompletedProcess") -> "subprocess.CompletedProcess": +def _checked(result: "subprocess.CompletedProcess[bytes]") -> "subprocess.CompletedProcess[bytes]": if result.returncode != 0: detail = result.stderr.decode("utf-8", errors="replace").strip() raise ClipboardError(f"{result.args[0]} exited {result.returncode}: {detail}") @@ -171,7 +171,7 @@ def _checked(result: "subprocess.CompletedProcess") -> "subprocess.CompletedProc # === Linux backend =========================================================== -def _linux_cmd() -> Optional[list]: +def _linux_cmd() -> Optional[list[str]]: if shutil.which("xclip"): return ["xclip", "-selection", "clipboard"] if shutil.which("xsel"): diff --git a/je_auto_control/utils/color_match/color_match.py b/je_auto_control/utils/color_match/color_match.py index 60180eee3..fd289cdb0 100644 --- a/je_auto_control/utils/color_match/color_match.py +++ b/je_auto_control/utils/color_match/color_match.py @@ -28,7 +28,7 @@ _MIN_SATURATION = 40 -def _hsv(source, region, is_haystack: bool): +def _hsv(source: Optional[ImageSource], region: Optional[Sequence[int]], is_haystack: bool) -> Any: import cv2 if is_haystack: rgb = _to_rgb(source) if source is not None else _grab_rgb(region) @@ -37,7 +37,7 @@ def _hsv(source, region, is_haystack: bool): return cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) -def _chromatic_mask(template_hsv): +def _chromatic_mask(template_hsv: Any) -> Any: """The template pixels that carry colour, or ``None`` when too few do. A thin coloured glyph on white is mostly background: scored over every @@ -50,7 +50,7 @@ def _chromatic_mask(template_hsv): return mask.astype(np.float32) -def _channel_distance(template, haystack, channel: str, mask=None): +def _channel_distance(template: Any, haystack: Any, channel: str, mask: Any = None) -> Any: """Mean squared distance per pixel, scaled to 0..1, for one HSV channel. Plain ``TM_SQDIFF`` divided by the largest possible distance -- not @@ -75,7 +75,7 @@ def _channel_distance(template, haystack, channel: str, mask=None): return np.minimum(direct, shifted) / (pixels * 90.0 ** 2) -def _score_map(template_hsv, haystack_hsv, channels: Sequence[str]): +def _score_map(template_hsv: Any, haystack_hsv: Any, channels: Sequence[str]) -> Any: """Per-channel colour-distance score (higher = better) over the chosen channels. Uses squared distance (not a correlation): correlation methods normalise away the diff --git a/je_auto_control/utils/cv2_utils/screen_record.py b/je_auto_control/utils/cv2_utils/screen_record.py index d4c091f69..d8de86528 100644 --- a/je_auto_control/utils/cv2_utils/screen_record.py +++ b/je_auto_control/utils/cv2_utils/screen_record.py @@ -12,7 +12,7 @@ class ScreenRecorder: - 可同時管理多個錄影執行緒 """ - def __init__(self): + def __init__(self) -> None: self.running_recorder: Dict[str, ScreenRecordThread] = {} def start_new_record( @@ -22,7 +22,7 @@ def start_new_record( codec: str = "XVID", frame_per_sec: int = 30, resolution: Tuple[int, int] = (1920, 1080) - ): + ) -> None: """ Start a new screen recording 開始新的螢幕錄影 @@ -46,7 +46,7 @@ def start_new_record( record_thread.start() self.running_recorder[recorder_name] = record_thread - def stop_record(self, recorder_name: str): + def stop_record(self, recorder_name: str) -> None: """ Stop a specific recorder 停止指定的錄影器 @@ -67,7 +67,8 @@ class ScreenRecordThread(threading.Thread): - 持續擷取螢幕畫面並寫入影片檔案 """ - def __init__(self, path_and_filename, codec, frame_per_sec, resolution: Tuple[int, int]): + def __init__(self, path_and_filename: str, codec: str, frame_per_sec: float, + resolution: Tuple[int, int]) -> None: """Open the writer, refusing a frame rate, size or file it cannot use. An unopened VideoWriter (fps 0 or NaN, an unknown codec, a missing diff --git a/je_auto_control/utils/dag/batch_contract.py b/je_auto_control/utils/dag/batch_contract.py index ab1404fba..b08f3b436 100644 --- a/je_auto_control/utils/dag/batch_contract.py +++ b/je_auto_control/utils/dag/batch_contract.py @@ -11,13 +11,13 @@ from je_auto_control.utils.dag.graph import DagDefinition, parse_definition -def definition_dict(dag: DagDefinition) -> dict: +def definition_dict(dag: DagDefinition) -> dict[str, Any]: """Serialize managed node contracts without borrowing mutable caller arrays.""" return {"nodes": [{"id": node.id, "host": node.host, "depends_on": sorted(node.depends_on), "task": thaw(node.task)} for node in sorted(dag.nodes, key=lambda item: item.id)]} -def batch_definition(value: Any) -> dict: +def batch_definition(value: Any) -> dict[str, Any]: """Reject ambiguous/legacy/action nodes before producing a stable, bounded graph digest.""" data = detached(value) if not isinstance(data, dict) or set(data) != {"nodes"}: @@ -44,7 +44,7 @@ def _node_fields(node: Any) -> None: _node_dependencies(node) -def _node_identity(node: dict) -> None: +def _node_identity(node: dict[str, Any]) -> None: if not isinstance(node["id"], str) or re.fullmatch(r"[A-Za-z0-9_-]{1,128}", node["id"]) is None: raise AgentTaskError("managed batch node id is invalid") host = node.get("host", "local") @@ -52,14 +52,14 @@ def _node_identity(node: dict) -> None: raise AgentTaskError("managed batch host identity is invalid") -def _node_dependencies(node: dict) -> None: +def _node_dependencies(node: dict[str, Any]) -> None: deps = node.get("depends_on", []) if not isinstance(deps, list) or not all(isinstance(item, str) for item in deps) or len(deps) != len(set(deps)): raise AgentTaskError("managed batch dependencies must be distinct node identities") def bind_definition(definition: Mapping[str, Any], batch_id: str, graph_hash: str, - bindings: Mapping[str, Any] | None = None) -> dict: + bindings: Mapping[str, Any] | None = None) -> dict[str, Any]: """Bind every destination spec/key to the same immutable batch, topology and node identity.""" result = detached(definition) for node in result["nodes"]: diff --git a/je_auto_control/utils/dag/batch_execution.py b/je_auto_control/utils/dag/batch_execution.py index a9f67c861..690fa1f62 100644 --- a/je_auto_control/utils/dag/batch_execution.py +++ b/je_auto_control/utils/dag/batch_execution.py @@ -37,7 +37,7 @@ def run_batch(dag: DagDefinition, batch_id: str, max_parallel: int, return execute_started(client, started, stop_event, execute, max_parallel) -def execute_started(client: Any, started: dict, stop_event: threading.Event | None, +def execute_started(client: Any, started: dict[str, Any], stop_event: threading.Event | None, execute: Callable[..., Any], max_parallel: int) -> Any: """Coordinate one pre-authorized attempt with the same claims, verification and finalization path.""" runner = _BatchRun(client, started) @@ -56,15 +56,15 @@ def execute_started(client: Any, started: dict, stop_event: threading.Event | No class _BatchRun: """One authorized attempt; no private coordinator identity enters destination specifications.""" - def __init__(self, client: Any, started: dict) -> None: + def __init__(self, client: Any, started: dict[str, Any]) -> None: self.client, self.started = client, started - def control(self, operation: str, request: dict) -> dict: + def control(self, operation: str, request: dict[str, Any]) -> dict[str, Any]: """Send only the frozen batch/attempt identity with bounded lifecycle fields.""" return self.client.call("dag", {"operation": operation, "request": { "batch_id": self.started["batch_id"], "attempt": self.started["attempt"], **request}}) - def run_node(self, node: Any, _definition: Any) -> dict: + def run_node(self, node: Any, _definition: Any) -> dict[str, Any]: """Claim before destination contact; report independently checked completion before releasing dependants.""" if node.id in self.started.get("adopted", {}): return self.control("validate_node", {"node_id": node.id}) @@ -83,13 +83,14 @@ def run_node(self, node: Any, _definition: Any) -> dict: pass # the durable pre-delivery claim remains an unsettled, non-replayable witness raise - def _dispatch(self, node: Any) -> dict: + def _dispatch(self, node: Any) -> dict[str, Any]: if node.host == "local": with managed_local_scope(partial(self._local_transport, node.id)): return run_managed_task(node.host, node.task, host_binding=self.started["hosts"][node.host]) return run_managed_task(node.host, node.task, host_binding=self.started["hosts"][node.host]) - def _local_transport(self, node_id: str, operation: str, body: dict, timeout: float) -> dict: + def _local_transport(self, node_id: str, operation: str, body: dict[str, Any], + timeout: float) -> dict[str, Any]: return self.client.call("dag", {"operation": "local_task", "request": { "batch_id": self.started["batch_id"], "attempt": self.started["attempt"], "node_id": node_id, "operation": operation, "body": body}}, timeout=timeout) diff --git a/je_auto_control/utils/dag/inspection.py b/je_auto_control/utils/dag/inspection.py index 8890df10b..40e741ab2 100644 --- a/je_auto_control/utils/dag/inspection.py +++ b/je_auto_control/utils/dag/inspection.py @@ -82,7 +82,7 @@ def _matching_supported(reply: Any) -> bool: def _match_request(host: str, task: Mapping[str, Any], owner: DeferredAuthorization, deadline: float, - connection: managed_tasks.Call, initial: dict) -> dict[str, Any]: + connection: managed_tasks.Call, initial: dict[str, Any]) -> dict[str, Any]: if not _matching_supported(initial): return {} spec = task["spec"] @@ -100,7 +100,7 @@ def _match_request(host: str, task: Mapping[str, Any], owner: DeferredAuthorizat return _match_snapshot(initial, reply, spec) -def _match_snapshot(initial: dict, reply: Any, spec: Mapping[str, Any]) -> dict[str, Any]: +def _match_snapshot(initial: dict[str, Any], reply: Any, spec: Mapping[str, Any]) -> dict[str, Any]: if not _matching_supported(reply): return {"request_match": "unverifiable"} try: @@ -118,7 +118,7 @@ def _match_snapshot(initial: dict, reply: Any, spec: Mapping[str, Any]) -> dict[ return snapshot -def _matched_completion(task: dict, spec: Mapping[str, Any]) -> bool: +def _matched_completion(task: dict[str, Any], spec: Mapping[str, Any]) -> bool: try: managed_tasks.validate_recorded_completion(task, spec) except AgentTaskError: @@ -155,7 +155,7 @@ def _task_identity(task: Any) -> tuple[str, str]: return identifier, state -def _recorded_completion(task: dict, metadata: dict) -> bool: +def _recorded_completion(task: dict[str, Any], metadata: dict[str, Any]) -> bool: version, reports = metadata.get("completion_contract"), task.get("verification") # pylint: disable-next=unidiomatic-typecheck # reason: the protocol excludes bool and int subclasses if type(version) is not int or version != 1 or metadata.get("input_released") is not True: diff --git a/je_auto_control/utils/dag/runner.py b/je_auto_control/utils/dag/runner.py index 96be7f156..a0f7eece5 100644 --- a/je_auto_control/utils/dag/runner.py +++ b/je_auto_control/utils/dag/runner.py @@ -165,7 +165,7 @@ def _execute_with_pool(dag: DagDefinition, stop_event: Optional[threading.Event] = None) -> None: """Schedule nodes whose deps are all done; cascade skip on failure.""" pending: Set[str] = set(results) - inflight: Dict[Future, str] = {} + inflight: Dict[Future[None], str] = {} ancestors: Dict[str, Set[str]] = _ancestor_index(dag) nodes_by_id = dag.by_id() with ThreadPoolExecutor(max_workers=max_parallel) as pool: @@ -182,7 +182,7 @@ def _execute_with_pool(dag: DagDefinition, _harvest_one(inflight, results) -def _spawn_ready_nodes(pending: Set[str], inflight: Dict[Future, str], +def _spawn_ready_nodes(pending: Set[str], inflight: Dict[Future[None], str], results: Dict[str, NodeResult], ancestors: Dict[str, Set[str]], nodes_by_id: Dict[str, DagNode], @@ -229,7 +229,7 @@ def _blocked_by_ancestor(ancestor_ids: Set[str], ) -def _harvest_one(inflight: Dict[Future, str], +def _harvest_one(inflight: Dict[Future[None], str], results: Dict[str, NodeResult]) -> None: # Whichever node finishes first: waiting on the oldest submitted one # held back every node whose inputs a faster sibling had just produced. @@ -238,7 +238,7 @@ def _harvest_one(inflight: Dict[Future, str], _record_future(inflight.pop(finished), finished, results) -def _record_future(nid: str, finished: Future, +def _record_future(nid: str, finished: Future[None], results: Dict[str, NodeResult]) -> None: try: finished.result() diff --git a/je_auto_control/utils/executor/action_schema.py b/je_auto_control/utils/executor/action_schema.py index 0a6ff074d..7fbdfb119 100644 --- a/je_auto_control/utils/executor/action_schema.py +++ b/je_auto_control/utils/executor/action_schema.py @@ -94,7 +94,7 @@ def __init__(self, loadable: Optional[Callable[[str], bool]]) -> None: self._loadable = loadable self._prefixes: List[str] = [] - def note(self, name: Any, action: list) -> None: + def note(self, name: Any, action: List[Any]) -> None: """Remember the package ``action`` loads, if it is a load the gate allows.""" if self._loadable is None or name not in PACKAGE_LOAD_COMMANDS: return @@ -108,7 +108,7 @@ def covers(self, name: str) -> bool: for prefix in self._prefixes) -def _literal_package(action: list) -> Optional[str]: +def _literal_package(action: List[Any]) -> Optional[str]: """The package a load command names: ``[name, [pkg]]`` or ``[name, {"package": pkg}]``.""" if len(action) != 2: return None @@ -164,7 +164,7 @@ def unknown_command_names(actions: Any, return unknown -def _iter_actions(actions: Any, trail: str) -> Iterator[Tuple[str, Any, list]]: +def _iter_actions(actions: Any, trail: str) -> Iterator[Tuple[str, Any, List[Any]]]: """Yield ``(trail, command_name, action)`` for every action in the tree, in order. Structural problems raise as they are met, but whether the name is in the @@ -194,8 +194,8 @@ def _iter_actions(actions: Any, trail: str) -> Iterator[Tuple[str, Any, list]]: yield from _iter_nested_actions(action[0], action, node) -def _iter_nested_actions(name: Any, action: list, - trail: str) -> Iterator[Tuple[str, Any, list]]: +def _iter_nested_actions(name: Any, action: List[Any], + trail: str) -> Iterator[Tuple[str, Any, List[Any]]]: """Yield the actions held in a flow-control command's nested body keys.""" # ``name`` arrives unvalidated — the collector does not stop on a bad one — # and an unhashable name would blow up the two lookups below. diff --git a/je_auto_control/utils/feature_match/feature_match.py b/je_auto_control/utils/feature_match/feature_match.py index e6c2b4682..bd4c256a6 100644 --- a/je_auto_control/utils/feature_match/feature_match.py +++ b/je_auto_control/utils/feature_match/feature_match.py @@ -16,12 +16,15 @@ """ from dataclasses import asdict, dataclass import dataclasses -from typing import Any, Dict, List, Optional, Sequence +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.visual_match.visual_match import ( _contain_cv2_error, _haystack_gray_with_origin, _to_gray, ) +if TYPE_CHECKING: + import cv2 + ImageSource = Any @@ -40,7 +43,7 @@ def to_dict(self) -> Dict[str, Any]: return asdict(self) -def _ratio_filter(knn_matches, ratio: float) -> list: +def _ratio_filter(knn_matches: Sequence[Sequence["cv2.DMatch"]], ratio: float) -> List["cv2.DMatch"]: """Lowe's ratio test: keep matches clearly better than their runner-up.""" good = [] for pair in knn_matches: @@ -49,7 +52,7 @@ def _ratio_filter(knn_matches, ratio: float) -> list: return good -def _make_orb(template_gray, max_features: int): +def _make_orb(template_gray: Any, max_features: int) -> "cv2.ORB": """Build an ORB detector with border/patch sizes that suit small templates. OpenCV's default ``edgeThreshold``/``patchSize`` (31) reject every keypoint @@ -64,7 +67,8 @@ def _make_orb(template_gray, max_features: int): patchSize=patch) -def _keypoint_matches(template_gray, scene_gray, max_features: int, ratio: float): +def _keypoint_matches(template_gray: Any, scene_gray: Any, max_features: int, ratio: float + ) -> Optional[Tuple[Sequence["cv2.KeyPoint"], Sequence["cv2.KeyPoint"], List["cv2.DMatch"]]]: """Return (kp_template, kp_scene, good_matches) or None if too few features.""" import cv2 orb = _make_orb(template_gray, max_features) @@ -77,8 +81,8 @@ def _keypoint_matches(template_gray, scene_gray, max_features: int, ratio: float return kp1, kp2, good -def _locate(template_shape, kp1, kp2, good, min_inliers: int - ) -> Optional[FeatureMatch]: +def _locate(template_shape: Tuple[int, ...], kp1: Sequence["cv2.KeyPoint"], kp2: Sequence["cv2.KeyPoint"], + good: List["cv2.DMatch"], min_inliers: int) -> Optional[FeatureMatch]: """Fit a RANSAC homography from ``good`` matches and project the template box.""" import cv2 import numpy as np diff --git a/je_auto_control/utils/gamepad/_facade.py b/je_auto_control/utils/gamepad/_facade.py index b343f1bd1..e64d190bd 100644 --- a/je_auto_control/utils/gamepad/_facade.py +++ b/je_auto_control/utils/gamepad/_facade.py @@ -14,7 +14,8 @@ from __future__ import annotations import threading -from typing import Dict, Optional, Tuple +from types import ModuleType, TracebackType +from typing import Any, Dict, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException @@ -70,10 +71,10 @@ class GamepadUnavailable(AutoControlException, RuntimeError): _DPAD_ALL = (_DPAD_UP, _DPAD_DOWN, _DPAD_LEFT, _DPAD_RIGHT) -def _import_vgamepad(): +def _import_vgamepad() -> ModuleType: """Resolve ``vgamepad`` lazily so the optional dep is opt-in.""" try: - import vgamepad # type: ignore + import vgamepad except ImportError as exc: # pragma: no cover - optional dep raise GamepadUnavailable( "vgamepad is not installed. Run " @@ -109,7 +110,7 @@ def is_available() -> bool: return True -def _clamp_signed_short(value) -> int: +def _clamp_signed_short(value: float) -> int: """Clamp ``value`` to the int16 range vgamepad's left/right sticks expect.""" n = int(value) if n > 32767: @@ -119,7 +120,7 @@ def _clamp_signed_short(value) -> int: return n -def _clamp_byte(value) -> int: +def _clamp_byte(value: float) -> int: """Clamp ``value`` to the 0..255 trigger range.""" n = int(value) if n > 255: @@ -158,7 +159,7 @@ def __init__(self) -> None: # --- buttons ------------------------------------------------------------- - def _resolve_button(self, name: str): + def _resolve_button(self, name: str) -> Any: try: attr = _BUTTON_ATTR_MAP[name.lower()] except KeyError as exc: @@ -265,7 +266,8 @@ def close(self) -> None: def __enter__(self) -> "VirtualGamepad": return self - def __exit__(self, exc_type, exc, tb) -> None: + def __exit__(self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], + tb: Optional[TracebackType]) -> None: self.close() diff --git a/je_auto_control/utils/hotkey/backends/macos_backend.py b/je_auto_control/utils/hotkey/backends/macos_backend.py index a4187c5fe..93ab2233a 100644 --- a/je_auto_control/utils/hotkey/backends/macos_backend.py +++ b/je_auto_control/utils/hotkey/backends/macos_backend.py @@ -4,11 +4,11 @@ Accessibility) for the Python interpreter or the host application. Without it ``CGEventTapCreate`` silently returns ``None`` and we log + exit. """ -from typing import Dict, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple from je_auto_control.utils.hotkey.backends.base import FailedCombos, HotkeyBackend from je_auto_control.utils.hotkey.hotkey_daemon import ( - BackendContext, split_combo, + BackendContext, HotkeyBinding, split_combo, ) from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -80,7 +80,7 @@ def __init__(self) -> None: # binding_id -> (combo, flags_mask, keycode) self._registered: Dict[str, Tuple[str, int, int]] = {} self._failed = FailedCombos() - self._pending_fires: list = [] + self._pending_fires: List[str] = [] def run_forever(self, context: BackendContext) -> None: try: @@ -96,7 +96,7 @@ def _loop(self, context: BackendContext) -> None: CFRunLoopRunInMode, kCFRunLoopDefaultMode, ) - def tap_callback(_proxy, _event_type, event, _refcon): + def tap_callback(_proxy: Any, _event_type: Any, event: Any, _refcon: Any) -> Any: keycode = Quartz.CGEventGetIntegerValueField( event, Quartz.kCGKeyboardEventKeycode, ) @@ -137,7 +137,7 @@ def tap_callback(_proxy, _event_type, event, _refcon): run_loop, source, kCFRunLoopDefaultMode, ) - def _sync(self, bindings) -> None: + def _sync(self, bindings: List[HotkeyBinding]) -> None: current_ids = {b.binding_id for b in bindings} for stale in [bid for bid in self._registered if bid not in current_ids]: self._registered.pop(stale, None) @@ -170,6 +170,6 @@ def _match(self, keycode: int, flags: int) -> Optional[str]: return bid return None - def _drain_fires(self, fire) -> None: + def _drain_fires(self, fire: Callable[[str], None]) -> None: while self._pending_fires: fire(self._pending_fires.pop(0)) diff --git a/je_auto_control/utils/hsv_segment/hsv_segment.py b/je_auto_control/utils/hsv_segment/hsv_segment.py index 38546820d..df92651bd 100644 --- a/je_auto_control/utils/hsv_segment/hsv_segment.py +++ b/je_auto_control/utils/hsv_segment/hsv_segment.py @@ -19,13 +19,13 @@ ImageSource = Any -def _hsv(haystack: Optional[ImageSource], region: Optional[Sequence[int]]): +def _hsv(haystack: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: import cv2 rgb = _to_rgb(haystack) if haystack is not None else _grab_rgb(region) return cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) -def _uint8_bound(values: Sequence[int]): +def _uint8_bound(values: Sequence[int]) -> Any: """An inRange bound, clamped to 0..255: numpy 2 raises on 256 or -1.""" import numpy as np return np.array([min(255, max(0, int(value))) for value in values], @@ -34,7 +34,7 @@ def _uint8_bound(values: Sequence[int]): def color_mask(haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, - lower_hsv: Sequence[int], upper_hsv: Sequence[int]): + lower_hsv: Sequence[int], upper_hsv: Sequence[int]) -> Any: """Return a uint8 mask of pixels inside the ``lower_hsv``..``upper_hsv`` band. HSV ranges are OpenCV's: H in 0..179, S and V in 0..255. A bound outside @@ -56,7 +56,7 @@ def segment_hsv(haystack: Optional[ImageSource] = None, *, return connected_boxes(mask, int(min_area), origin=_origin(haystack, region)) -def _hue_mask(hsv, hue: int, hue_tol: int, sat_min: int, val_min: int): +def _hue_mask(hsv: Any, hue: int, hue_tol: int, sat_min: int, val_min: int) -> Any: """Build an inRange mask for ``hue`` ± ``hue_tol``, OR-ing the two parts when it wraps 0/180. The hue is taken round OpenCV's 180-step circle and a tolerance of 90 or @@ -68,7 +68,7 @@ def _hue_mask(hsv, hue: int, hue_tol: int, sat_min: int, val_min: int): raise ValueError(f"hue_tol must be >= 0, got {hue_tol}") floor = [int(sat_min), int(val_min)] - def band(start: int, end: int): + def band(start: int, end: int) -> Any: return cv2.inRange(hsv, _uint8_bound([start, *floor]), _uint8_bound([end, 255, 255])) diff --git a/je_auto_control/utils/http_client/http_client.py b/je_auto_control/utils/http_client/http_client.py index a5a2fabca..2b6c38ad6 100644 --- a/je_auto_control/utils/http_client/http_client.py +++ b/je_auto_control/utils/http_client/http_client.py @@ -16,7 +16,7 @@ from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.http_headers import CREDENTIAL_HEADERS -from typing import Any, Dict, Mapping, Optional +from typing import IO, Any, Dict, Mapping, Optional # NOSONAR python:S5332 — http is allow-listed deliberately (other schemes # are rejected); plain http is required for internal/localhost endpoints. @@ -114,7 +114,7 @@ def _read_response(response: Any, want_bytes: bool = False, *, return result -def _collect_headers(raw_headers: Any) -> "tuple[Dict[str, str], list]": +def _collect_headers(raw_headers: Any) -> "tuple[Dict[str, str], list[str]]": """Response headers with repeats joined, plus every ``Set-Cookie`` value. ``dict(headers.items())`` kept only the last of a repeated header, so a @@ -124,7 +124,7 @@ def _collect_headers(raw_headers: Any) -> "tuple[Dict[str, str], list]": them in the list. """ headers: Dict[str, str] = {} - set_cookie: list = [] + set_cookie: list[str] = [] for name, value in (raw_headers.items() if raw_headers else []): if name.lower() == "set-cookie": set_cookie.append(value) @@ -157,7 +157,9 @@ class _CheckedRedirectHandler(urllib.request.HTTPRedirectHandler): could redirect to any other host -- or to ``ftp://``. """ - def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102 + def redirect_request(self, req: urllib.request.Request, fp: IO[bytes], code: int, # noqa: D102 + msg: str, headers: http.client.HTTPMessage, + newurl: str) -> Optional[urllib.request.Request]: from je_auto_control.utils.egress.egress_policy import get_egress_policy _validate_url(newurl) get_egress_policy().check(newurl) @@ -175,7 +177,9 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102 class _RefusingRedirectHandler(urllib.request.HTTPRedirectHandler): """Return a 3xx as the response instead of following it.""" - def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102 + def redirect_request(self, req: urllib.request.Request, fp: IO[bytes], code: int, # noqa: D102 + msg: str, headers: http.client.HTTPMessage, + newurl: str) -> Optional[urllib.request.Request]: return None diff --git a/je_auto_control/utils/json_contract/json_contract.py b/je_auto_control/utils/json_contract/json_contract.py index 311627d84..fa095c499 100644 --- a/je_auto_control/utils/json_contract/json_contract.py +++ b/je_auto_control/utils/json_contract/json_contract.py @@ -41,7 +41,7 @@ def _json_equal(left: Any, right: Any) -> bool: return left == right -def _diff_dict(actual: Dict, expected: Dict, path: str, +def _diff_dict(actual: Dict[Any, Any], expected: Dict[Any, Any], path: str, diffs: List[Dict[str, Any]]) -> None: for key, value in expected.items(): child = f"{path}.{key}" @@ -55,7 +55,7 @@ def _diff_dict(actual: Dict, expected: Dict, path: str, "actual": value}) -def _diff_list(actual: List, expected: List, path: str, +def _diff_list(actual: List[Any], expected: List[Any], path: str, diffs: List[Dict[str, Any]]) -> None: common = min(len(actual), len(expected)) for index in range(common): @@ -92,7 +92,7 @@ def _type_match(left: Any, right: Any) -> bool: return type(left) is type(right) -def _is_ignored(path: str, ignored: set) -> bool: +def _is_ignored(path: str, ignored: set[str]) -> bool: """Whether ``path`` is an ignored path or lies under one. Only exact paths were ignored, so ``ignore=["$.ts"]`` did not cover a @@ -121,7 +121,7 @@ def match_json(actual: Any, expected: Any, *, ignore: Iterable[str] = (), return MatchReport(ok=not kept, mismatches=kept) -def _normalize(value: Any, drop: set) -> Any: +def _normalize(value: Any, drop: set[str]) -> Any: if isinstance(value, dict): return {key: _normalize(val, drop) for key, val in sorted(value.items()) if key not in drop} diff --git a/je_auto_control/utils/json_patch/json_patch.py b/je_auto_control/utils/json_patch/json_patch.py index dbb9cece7..272a051fa 100644 --- a/je_auto_control/utils/json_patch/json_patch.py +++ b/je_auto_control/utils/json_patch/json_patch.py @@ -155,12 +155,12 @@ def _delete(parent: Any, ref: str) -> None: # --- equality (bool stays distinct from int) ------------------------------- -def _dict_equal(left: Dict, right: Dict) -> bool: +def _dict_equal(left: Dict[str, Any], right: Dict[str, Any]) -> bool: return left.keys() == right.keys() and all( _json_equal(left[key], right[key]) for key in left) -def _list_equal(left: List, right: List) -> bool: +def _list_equal(left: List[Any], right: List[Any]) -> bool: return len(left) == len(right) and all( _json_equal(a, b) for a, b in zip(left, right)) @@ -274,7 +274,7 @@ def apply_patch(doc: Any, patch: List[Dict[str, Any]]) -> Any: return result -def _diff_dict(old: Dict, new: Dict, path: str) -> List[Dict[str, Any]]: +def _diff_dict(old: Dict[str, Any], new: Dict[str, Any], path: str) -> List[Dict[str, Any]]: ops: List[Dict[str, Any]] = [] for key in old: if key not in new: @@ -288,7 +288,7 @@ def _diff_dict(old: Dict, new: Dict, path: str) -> List[Dict[str, Any]]: return ops -def _diff_list(old: List, new: List, path: str) -> List[Dict[str, Any]]: +def _diff_list(old: List[Any], new: List[Any], path: str) -> List[Dict[str, Any]]: ops: List[Dict[str, Any]] = [] for index in range(min(len(old), len(new))): ops.extend(make_patch(old[index], new[index], f"{path}/{index}")) diff --git a/je_auto_control/utils/mcp_server/server.py b/je_auto_control/utils/mcp_server/server.py index 57946690b..75f2d04d2 100644 --- a/je_auto_control/utils/mcp_server/server.py +++ b/je_auto_control/utils/mcp_server/server.py @@ -13,7 +13,7 @@ import sys import threading import time -from typing import Any, Callable, Dict, List, Optional, TextIO +from typing import Any, Callable, Dict, Iterator, List, Optional, TextIO from je_auto_control.utils.cli_output import utf8_stream from je_auto_control.utils.exception.exceptions import AutoControlException @@ -148,7 +148,7 @@ def _notifier(self) -> Optional[Callable[[str, Dict[str, Any]], None]]: return getattr(self._local, "notifier", None) or self._default_notifier @_notifier.setter - def _notifier(self, value) -> None: + def _notifier(self, value: Optional[Callable[[str, Dict[str, Any]], None]]) -> None: self._default_notifier = value @property @@ -156,7 +156,7 @@ def _writer(self) -> Optional[Callable[[str], None]]: return getattr(self._local, "writer", None) or self._default_writer @_writer.setter - def _writer(self, value) -> None: + def _writer(self, value: Optional[Callable[[str], None]]) -> None: self._default_writer = value @property @@ -167,7 +167,7 @@ def _concurrent_tools(self) -> bool: return scoped @_concurrent_tools.setter - def _concurrent_tools(self, value) -> None: + def _concurrent_tools(self, value: bool) -> None: self._default_concurrent_tools = bool(value) @property @@ -196,8 +196,11 @@ def _client_capabilities(self, value: Dict[str, Any]) -> None: self._client_caps_by_conn[conn] = value @contextlib.contextmanager - def connection_scope(self, *, notifier=None, writer=None, - concurrent_tools=None, connection_id=None): + def connection_scope(self, *, + notifier: Optional[Callable[[str, Dict[str, Any]], None]] = None, + writer: Optional[Callable[[str], None]] = None, + concurrent_tools: Optional[bool] = None, + connection_id: Any = None) -> Iterator["MCPServer"]: """Bind notifier/writer/concurrency/identity to the calling thread only. Transports that serve more than one peer must wrap each request in diff --git a/je_auto_control/utils/mcp_server/tools/_discovery.py b/je_auto_control/utils/mcp_server/tools/_discovery.py index 2038348dc..615a53957 100644 --- a/je_auto_control/utils/mcp_server/tools/_discovery.py +++ b/je_auto_control/utils/mcp_server/tools/_discovery.py @@ -1,13 +1,16 @@ """Small discovery tools query the active server registry instead of constructing another catalogue.""" from __future__ import annotations -from typing import Any +from typing import TYPE_CHECKING, Any from je_auto_control.utils.mcp_server.context import ToolCallContext from je_auto_control.utils.mcp_server.tools._base import MCPTool, READ_ONLY, schema +if TYPE_CHECKING: + from je_auto_control.utils.mcp_server.discovery import ToolSummary -def _search(query: str, limit: int = 10, ctx: ToolCallContext | None = None) -> list: + +def _search(query: str, limit: int = 10, ctx: ToolCallContext | None = None) -> list[ToolSummary]: if ctx is not None and ctx.tool_catalog is not None: ctx.check_cancelled() return ctx.tool_catalog().search(query, limit=limit) @@ -34,15 +37,15 @@ def _view(ctx: ToolCallContext | None) -> Any: return ctx.tool_catalog() -def _state(ctx: ToolCallContext | None = None) -> dict: +def _state(ctx: ToolCallContext | None = None) -> dict[str, Any]: return _view(ctx).state() -def _enable(names: list[str], ctx: ToolCallContext | None = None) -> dict: +def _enable(names: list[str], ctx: ToolCallContext | None = None) -> dict[str, Any]: return _view(ctx).enable(names) -def _disable(names: list[str], ctx: ToolCallContext | None = None) -> dict: +def _disable(names: list[str], ctx: ToolCallContext | None = None) -> dict[str, Any]: return _view(ctx).disable(names) diff --git a/je_auto_control/utils/observability/tracing.py b/je_auto_control/utils/observability/tracing.py index ac5330ea0..6c60f1fa6 100644 --- a/je_auto_control/utils/observability/tracing.py +++ b/je_auto_control/utils/observability/tracing.py @@ -15,7 +15,7 @@ class NoOpSpan: def __init__(self, name: str) -> None: self.name = name - self.attributes: dict = {} + self.attributes: dict[str, Any] = {} self.start_ns = time.monotonic_ns() self.end_ns: Optional[int] = None @@ -50,7 +50,7 @@ class NoOpTracer: @contextmanager def start_as_current_span(self, name: str, - attributes: Optional[dict] = None, + attributes: Optional[dict[str, Any]] = None, ) -> Iterator[Span]: span = NoOpSpan(name) if attributes: @@ -76,7 +76,7 @@ def __init__(self, otel_tracer: Any) -> None: @contextmanager def start_as_current_span(self, name: str, - attributes: Optional[dict] = None, + attributes: Optional[dict[str, Any]] = None, ) -> Iterator[Any]: with self._tracer.start_as_current_span( name, attributes=attributes or None, @@ -109,7 +109,7 @@ def backend_name(self) -> str: @contextmanager def start_as_current_span(self, name: str, - attributes: Optional[dict] = None, + attributes: Optional[dict[str, Any]] = None, ) -> Iterator[Any]: inner = self._resolve_inner() with inner.start_as_current_span(name, attributes) as span: @@ -158,7 +158,7 @@ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]: name = str(span_name or getattr(fn, "__qualname__", fn.__name__)) @wraps(fn) - def wrapper(*args, **kwargs): + def wrapper(*args: Any, **kwargs: Any) -> Any: real_tracer = tracer or default_tracer() attrs = None if record_args: diff --git a/je_auto_control/utils/ocr/backends/easyocr_backend.py b/je_auto_control/utils/ocr/backends/easyocr_backend.py index 9455ad535..31515492c 100644 --- a/je_auto_control/utils/ocr/backends/easyocr_backend.py +++ b/je_auto_control/utils/ocr/backends/easyocr_backend.py @@ -8,17 +8,20 @@ from __future__ import annotations from threading import Lock -from typing import Any, Dict, List +from typing import TYPE_CHECKING, Any, Dict, List from je_auto_control.utils.ocr.backends.base import OCRBackendNotAvailableError +if TYPE_CHECKING: # pragma: no cover + from je_auto_control.utils.ocr.ocr_engine import TextMatch + _easyocr = None _readers: Dict[str, Any] = {} _reader_lock = Lock() -def _load(): +def _load() -> Any: global _easyocr if _easyocr is not None: return _easyocr @@ -59,7 +62,7 @@ def _resolve_langs(lang: str) -> List[str]: return [lang] -def _get_reader(lang: str): +def _get_reader(lang: str) -> Any: """Lazily build (and cache) the EasyOCR Reader for ``lang``.""" codes = _resolve_langs(lang) key = ",".join(codes) @@ -89,8 +92,8 @@ def __init__(self) -> None: def available(self) -> bool: return self._available - def image_to_matches(self, image, lang: str, - min_confidence: float) -> List: + def image_to_matches(self, image: Any, lang: str, + min_confidence: float) -> List[TextMatch]: # Import inside to avoid circular import at module load. from je_auto_control.utils.ocr.ocr_engine import TextMatch import numpy as np diff --git a/je_auto_control/utils/ocr/backends/paddleocr_backend.py b/je_auto_control/utils/ocr/backends/paddleocr_backend.py index 1fb7309f3..7907316ff 100644 --- a/je_auto_control/utils/ocr/backends/paddleocr_backend.py +++ b/je_auto_control/utils/ocr/backends/paddleocr_backend.py @@ -13,19 +13,22 @@ from __future__ import annotations from threading import Lock -from typing import Dict, List +from typing import TYPE_CHECKING, Any, Dict, List, Optional from je_auto_control.utils.ocr.backends.base import ( OCRBackendNotAvailableError, ) +if TYPE_CHECKING: # pragma: no cover + from je_auto_control.utils.ocr.ocr_engine import TextMatch + _paddle = None _readers: Dict[str, object] = {} _reader_lock = Lock() -def _load(): +def _load() -> Any: """Lazily import paddleocr. Raises a clear error if missing.""" global _paddle if _paddle is not None: @@ -59,7 +62,7 @@ def _resolve_lang(lang: str) -> str: return PADDLEOCR_LANG.get(lang, lang or "en") -def _get_reader(lang: str): +def _get_reader(lang: str) -> Any: """Build + cache one PaddleOCR Reader per language.""" code = _resolve_lang(lang) with _reader_lock: @@ -76,7 +79,7 @@ def _get_reader(lang: str): return reader -def _entry_to_match(entry, threshold: float): +def _entry_to_match(entry: Any, threshold: float) -> Optional[TextMatch]: """Convert one PaddleOCR row into a ``TextMatch`` or ``None`` to skip.""" from je_auto_control.utils.ocr.ocr_engine import TextMatch if not entry or len(entry) < 2: @@ -116,8 +119,8 @@ def __init__(self) -> None: def available(self) -> bool: return self._available - def image_to_matches(self, image, lang: str, - min_confidence: float) -> List: + def image_to_matches(self, image: Any, lang: str, + min_confidence: float) -> List[TextMatch]: import numpy as np reader = _get_reader(lang) diff --git a/je_auto_control/utils/postcondition/postcondition.py b/je_auto_control/utils/postcondition/postcondition.py index 91febb0e5..46d00c020 100644 --- a/je_auto_control/utils/postcondition/postcondition.py +++ b/je_auto_control/utils/postcondition/postcondition.py @@ -80,11 +80,11 @@ def _enabled_state(after: Sequence[Element], param: Dict[str, Any], return False, "element not found" -def _enabled(after, before, param): +def _enabled(after: Sequence[Element], before: Optional[Sequence[Element]], param: Dict[str, Any]) -> Report: return _enabled_state(after, param, True) -def _disabled(after, before, param): +def _disabled(after: Sequence[Element], before: Optional[Sequence[Element]], param: Dict[str, Any]) -> Report: return _enabled_state(after, param, False) @@ -93,15 +93,15 @@ def _text(after: Sequence[Element], text: Any, want_present: bool) -> Report: return found == want_present, "present" if found else "absent" -def _text_present(after, before, param): +def _text_present(after: Sequence[Element], before: Optional[Sequence[Element]], param: Any) -> Report: return _text(after, param, True) -def _text_absent(after, before, param): +def _text_absent(after: Sequence[Element], before: Optional[Sequence[Element]], param: Any) -> Report: return _text(after, param, False) -def _count(after, before, param: Dict[str, Any]) -> Report: +def _count(after: Sequence[Element], before: Optional[Sequence[Element]], param: Dict[str, Any]) -> Report: number = sum(1 for e in after if _matches(e, param.get("match", {}))) if "equals" in param: return number == int(param["equals"]), f"count={number}" diff --git a/je_auto_control/utils/rate_limit/rate_limit.py b/je_auto_control/utils/rate_limit/rate_limit.py index c09266e73..32db3d295 100644 --- a/je_auto_control/utils/rate_limit/rate_limit.py +++ b/je_auto_control/utils/rate_limit/rate_limit.py @@ -18,7 +18,7 @@ import math import threading import time -from typing import Callable, Dict, Optional +from typing import Any, Callable, Dict, Optional from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.executor.run_control import pause @@ -179,7 +179,7 @@ def time_until_available(self, n: int = 1) -> float: def throttle(interval_s: float, *, - clock: Callable[[], float] = time.monotonic) -> Callable: + clock: Callable[[], float] = time.monotonic) -> Callable[[Callable[..., Any]], Callable[..., Any]]: """Decorator: call the wrapped function at most once per ``interval_s``. Leading-edge — the first call fires immediately; calls within the interval @@ -189,12 +189,12 @@ def throttle(interval_s: float, *, if not float(interval_s) >= 0: # NOSONAR python:S1940 # reason: "< 0" is false for NaN raise AutoControlException(f"interval_s must be a number >= 0, got {interval_s!r}") - def decorator(func: Callable) -> Callable: + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: state: Dict[str, Optional[float]] = {"last": None} lock = threading.Lock() @functools.wraps(func) - def wrapper(*args, **kwargs): + def wrapper(*args: Any, **kwargs: Any) -> Any: with lock: now = clock() last = state["last"] @@ -208,7 +208,7 @@ def wrapper(*args, **kwargs): return decorator -_NAMED_BUCKETS: Dict[str, "tuple"] = {} +_NAMED_BUCKETS: Dict[str, tuple[float, float, TokenBucket]] = {} _NAMED_LOCK = threading.Lock() diff --git a/je_auto_control/utils/remote_desktop/audio.py b/je_auto_control/utils/remote_desktop/audio.py index 2456bfcb0..b1aad4b59 100644 --- a/je_auto_control/utils/remote_desktop/audio.py +++ b/je_auto_control/utils/remote_desktop/audio.py @@ -35,7 +35,7 @@ class AudioBackendError(AutoControlException, RuntimeError): """Raised when ``sounddevice`` cannot be loaded or an audio device fails.""" -def _load_sounddevice(): +def _load_sounddevice() -> Any: """Import ``sounddevice`` lazily; raise a helpful error if missing. ``OSError`` too: sounddevice raises it when the PortAudio library @@ -51,7 +51,7 @@ def _load_sounddevice(): return sounddevice -def _device_errors(sd: Any) -> tuple: +def _device_errors(sd: Any) -> tuple[type[BaseException], ...]: """What a PortAudio call may raise: ``PortAudioError`` derives from ``Exception`` directly.""" return (OSError, RuntimeError, sd.PortAudioError) @@ -178,7 +178,7 @@ def start(self) -> None: callback=lambda *args: self._raw_callback_for(lease, *args), )) - def _raw_callback_for(self, lease, *args) -> None: + def _raw_callback_for(self, lease: AudioLease, *args: Any) -> None: if not lease.enter(): return try: @@ -186,7 +186,7 @@ def _raw_callback_for(self, lease, *args) -> None: finally: lease.leave() - def _raw_callback(self, indata, frames, time_info, status) -> None: + def _raw_callback(self, indata: Any, frames: int, time_info: Any, status: Any) -> None: del frames, time_info # unused — block size is fixed if status: # An overflow flag still comes with valid samples; dropping the @@ -211,7 +211,7 @@ def __init__(self, device: Optional[int] = None, self._sample_rate = int(sample_rate) self._channels = int(channels) self._lease: Optional[AudioLease] = None - self._write_errors: tuple = (OSError, RuntimeError) + self._write_errors: tuple[type[BaseException], ...] = (OSError, RuntimeError) self._lock = threading.Lock() @property diff --git a/je_auto_control/utils/remote_desktop/signaling_client.py b/je_auto_control/utils/remote_desktop/signaling_client.py index c3769f4a9..63ca050bf 100644 --- a/je_auto_control/utils/remote_desktop/signaling_client.py +++ b/je_auto_control/utils/remote_desktop/signaling_client.py @@ -14,7 +14,7 @@ import time import urllib.parse from concurrent.futures import CancelledError -from typing import Callable, Optional +from typing import Any, Callable, Optional from je_auto_control.utils.exception.cancellation import current_cancellation_token from je_auto_control.utils.exception.exceptions import AutoControlException @@ -30,9 +30,9 @@ class SignalingError(AutoControlException, RuntimeError): def _request(method: str, url: str, *, - body: Optional[dict] = None, + body: Optional[dict[str, Any]] = None, secret: Optional[str] = None, - timeout: float = _DEFAULT_TIMEOUT_S) -> Optional[dict]: + timeout: float = _DEFAULT_TIMEOUT_S) -> Optional[dict[str, Any]]: from je_auto_control.utils.http_client.http_client import build_call, perform_call headers = {"X-Signaling-Secret": secret} if secret else None try: @@ -49,7 +49,7 @@ def _request(method: str, url: str, *, return _json_reply(method, url, response) -def _json_reply(method: str, url: str, response: dict) -> Optional[dict]: +def _json_reply(method: str, url: str, response: dict[str, Any]) -> Optional[dict[str, Any]]: """The reply's JSON object: ``None`` for a 404, ``{}`` for an empty body.""" status = int(response["status"]) if status == 404: @@ -68,7 +68,7 @@ def _json_reply(method: str, url: str, response: dict) -> Optional[dict]: return payload -def _sdp(response: Optional[dict]) -> Optional[str]: +def _sdp(response: Optional[dict[str, Any]]) -> Optional[str]: """The ``sdp`` field of a fetch reply, which must be a string when present.""" if response is None: return None diff --git a/je_auto_control/utils/remote_desktop/webrtc_audio.py b/je_auto_control/utils/remote_desktop/webrtc_audio.py index 3ebbd9633..7b9717189 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_audio.py +++ b/je_auto_control/utils/remote_desktop/webrtc_audio.py @@ -65,7 +65,7 @@ def __init__(self, sample_rate: int = _DEFAULT_SAMPLE_RATE, self._sample_rate = sample_rate self._channels = channels self._device = device - self._queue: asyncio.Queue = asyncio.Queue(maxsize=50) + self._queue: asyncio.Queue[Optional[bytes]] = asyncio.Queue(maxsize=50) self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() self._timestamp = 0 self._capture: Optional[AudioCapture] = None @@ -179,12 +179,12 @@ def __init__(self, sample_rate: int = _DEFAULT_SAMPLE_RATE, device=device, sample_rate=sample_rate, channels=channels, ) self._player.start() - self._task: Optional[asyncio.Task] = None + self._task: Optional[asyncio.Task[None]] = None self._stopped = False self._player_retired = False self._resampler: Optional[Any] = None - def consume(self, track) -> None: + def consume(self, track: MediaStreamTrack) -> None: """Spawn a background task that drains ``track.recv()`` into the player.""" if self._stopped: raise AudioBackendError("audio receiver is stopped") @@ -192,7 +192,7 @@ def consume(self, track) -> None: return self._task = asyncio.ensure_future(self._loop(track)) - async def _loop(self, track) -> None: + async def _loop(self, track: MediaStreamTrack) -> None: from aiortc.mediastreams import MediaStreamError try: while not self._stopped: @@ -207,7 +207,7 @@ async def _loop(self, track) -> None: raise_caused_run_interruption(error) autocontrol_logger.info("opus mic receiver ended: %r", error) - def _to_player_pcm(self, frame) -> list: + def _to_player_pcm(self, frame: Any) -> list[bytes]: """int16 PCM in the player's layout and rate. aiortc's Opus decoder always yields 48 kHz stereo; written as is to a diff --git a/je_auto_control/utils/remote_desktop/webrtc_host_media.py b/je_auto_control/utils/remote_desktop/webrtc_host_media.py index 18b914886..7cad5032d 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host_media.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host_media.py @@ -49,10 +49,10 @@ class MediaNegotiationMixin: _closed: threading.Event _host_voice_track: Optional["OpusMicAudioTrack"] _config: "WebRTCConfig" - _viewer_video_task: Optional[asyncio.Task] + _viewer_video_task: Optional[asyncio.Task[Any]] _opus_audio_receiver: Optional["OpusMicReceiver"] _send_ctrl: Callable[[Mapping[str, Any]], None] - _spawn_bg: Callable[[Any], asyncio.Task] + _spawn_bg: Callable[[Any], asyncio.Task[Any]] _consume_viewer_video: Callable[[Any], Coroutine[Any, Any, None]] _start_opus_audio_receive: Callable[[Any], None] @@ -111,7 +111,7 @@ def _maybe_resubscribe_viewer_audio(self) -> None: return @staticmethod - def _receiver_track(transceiver): + def _receiver_track(transceiver: Any) -> Any: receiver = transceiver.receiver return receiver.track if receiver is not None else None @@ -230,7 +230,7 @@ def _deactivate_recvonly_audio(self) -> None: return self._media_owners.schedule("opus receiver", lambda: self._retire_live_audio(peer, receiver)) - async def _retire_live_audio(self, peer, receiver) -> None: + async def _retire_live_audio(self, peer: Optional["RTCPeerConnection"], receiver: "OpusMicReceiver") -> None: if self._pc is not peer or self._opus_audio_receiver is not receiver: return await self._media_owners.stop_field_async("opus receiver", receiver) @@ -239,7 +239,8 @@ async def _retire_live_audio(self, peer, receiver) -> None: if self._pc is peer and not self._closed.is_set(): self._spawn_bg(self._async_renegotiate()) - async def _retire_live_video(self, peer, task) -> None: + async def _retire_live_video(self, peer: Optional["RTCPeerConnection"], + task: Optional[asyncio.Task[Any]]) -> None: if self._pc is not peer or self._viewer_video_task is not task: return if task is not None: diff --git a/je_auto_control/utils/rest_api/rest_server.py b/je_auto_control/utils/rest_api/rest_server.py index a65095ea9..a6b0cd3cd 100644 --- a/je_auto_control/utils/rest_api/rest_server.py +++ b/je_auto_control/utils/rest_api/rest_server.py @@ -14,6 +14,7 @@ import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path +from types import FrameType from typing import Any, Callable, Dict, List, Optional, Tuple, Type from urllib.parse import urlparse @@ -129,7 +130,7 @@ class _RestRequestHandler(BaseHTTPRequestHandler): # the auth gate, so that client has to hold a valid token. timeout = 30.0 - def log_message(self, format, *args) -> None: # noqa: A002 # pylint: disable=redefined-builtin # reason: stdlib BaseHTTPRequestHandler override + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 # pylint: disable=redefined-builtin # reason: stdlib BaseHTTPRequestHandler override autocontrol_logger.info("rest-api %s - %s", self.address_string(), log_safe(format % args)) @@ -429,7 +430,8 @@ def _read_json_body(self) -> Any: return _BODY_ERROR_SENT def _send_json(self, payload: Dict[str, Any], status: int = 200, - default=None, headers: Optional[Dict[str, str]] = None) -> int: + default: Optional[Callable[[Any], Any]] = None, + headers: Optional[Dict[str, str]] = None) -> int: """Write ``payload`` as the response; return the status actually sent. A payload that cannot be serialised (a circular reference, nesting @@ -663,7 +665,7 @@ def start_rest_api_server(host: str = "127.0.0.1", port: int = 9939, __all__ = ["RestApiServer", "start_rest_api_server"] -def _main(argv: Optional[list] = None) -> int: +def _main(argv: Optional[List[str]] = None) -> int: """Foreground entrypoint used by ``python -m je_auto_control.utils.rest_api.rest_server``. Starts a :class:`RestApiServer` and blocks the main thread until @@ -693,7 +695,7 @@ def _main(argv: Optional[list] = None) -> int: stop_event = threading.Event() - def _handle_signal(_signum, _frame): + def _handle_signal(_signum: int, _frame: Optional[FrameType]) -> None: stop_event.set() signal.signal(signal.SIGINT, _handle_signal) diff --git a/je_auto_control/utils/rotated_match/rotated_match.py b/je_auto_control/utils/rotated_match/rotated_match.py index 1f8a6127e..64f5506fa 100644 --- a/je_auto_control/utils/rotated_match/rotated_match.py +++ b/je_auto_control/utils/rotated_match/rotated_match.py @@ -16,7 +16,7 @@ Imports no ``PySide6``. """ from dataclasses import asdict, dataclass -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.visual_match.visual_match import ( _NMS_CANDIDATE_FACTOR, _NMS_CANDIDATE_MIN, _contain_cv2_error, @@ -51,7 +51,7 @@ def to_dict(self) -> Dict[str, Any]: return data -def _rotate(template, angle: float): +def _rotate(template: Any, angle: float) -> Any: """Rotate ``template`` by ``angle`` degrees, expanding the canvas to fit it.""" import cv2 if abs(angle) < 1e-9: @@ -68,7 +68,7 @@ def _rotate(template, angle: float): return cv2.warpAffine(template, matrix, (new_w, new_h)) -def _rotate_with_mask(template, angle: float): +def _rotate_with_mask(template: Any, angle: float) -> Tuple[Any, Any]: """The rotated template and a mask of its real pixels. The enlarged canvas is padded with black, and without a mask the black @@ -87,7 +87,8 @@ def scale_space(min_scale: float = 0.8, max_scale: float = 1.25, for s in np.linspace(float(min_scale), float(max_scale), int(steps))] -def _scores_at(hay, tmpl, scale: float, angle: float, metric: int): +def _scores_at(hay: Any, tmpl: Any, scale: float, angle: float, + metric: int) -> Optional[Tuple[Any, int, int]]: """The score map (higher is better) for one (scale, angle) and the warped size, or ``None``.""" import cv2 import numpy as np @@ -101,7 +102,8 @@ def _scores_at(hay, tmpl, scale: float, angle: float, metric: int): return np.nan_to_num(scores, nan=-1.0, posinf=-1.0, neginf=-1.0), warped.shape[1], warped.shape[0] -def _best_at(hay, tmpl, scale: float, angle: float, metric: int): +def _best_at(hay: Any, tmpl: Any, scale: float, angle: float, + metric: int) -> Optional[RotatedMatch]: """Return the best ``RotatedMatch`` for one (scale, angle), or ``None``.""" import cv2 found = _scores_at(hay, tmpl, scale, angle, metric) @@ -113,7 +115,7 @@ def _best_at(hay, tmpl, scale: float, angle: float, metric: int): round(float(max_val), 4), float(scale), float(angle)) -def _hits_at(hay, tmpl, scale: float, angle: float, metric: int, +def _hits_at(hay: Any, tmpl: Any, scale: float, angle: float, metric: int, min_score: float, cap: int) -> List[RotatedMatch]: """Every position of one (scale, angle) scoring >= ``min_score``, the best ``cap`` of them. diff --git a/je_auto_control/utils/run_diff/run_diff.py b/je_auto_control/utils/run_diff/run_diff.py index 6194bdfc7..7ef348fb0 100644 --- a/je_auto_control/utils/run_diff/run_diff.py +++ b/je_auto_control/utils/run_diff/run_diff.py @@ -15,7 +15,7 @@ ``duration`` / ``error``. Pure standard library; no device, no ``PySide6``. """ import math -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Set, Tuple Step = Dict[str, Any] @@ -24,7 +24,7 @@ _ZERO_BASELINE_S = 0.1 -def _lcs_pairs(left: Sequence[str], right: Sequence[str]) -> List[tuple]: +def _lcs_pairs(left: Sequence[str], right: Sequence[str]) -> List[Tuple[int, int]]: """Return aligned ``(i, j)`` index pairs of the longest common subsequence.""" n, m = len(left), len(right) table = [[0] * (m + 1) for _ in range(n + 1)] @@ -85,8 +85,8 @@ def _regression(before: Step, after: Step, name: str, def _aligned_changes(before: Sequence[Step], after: Sequence[Step], - names: Sequence[str], pairs: List[tuple], - factor: float) -> tuple: + names: Sequence[str], pairs: List[Tuple[int, int]], + factor: float) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: """Classify the LCS-aligned pairs into (status flips, timing regressions).""" flips, regressions = [], [] for i, j in pairs: @@ -102,7 +102,7 @@ def _keys(steps: Sequence[Step], key: str) -> List[str]: return [str(step.get(key, "")) for step in steps] -def _unmatched(steps: Sequence[Step], matched: set) -> List[Step]: +def _unmatched(steps: Sequence[Step], matched: Set[int]) -> List[Step]: return [steps[k] for k in range(len(steps)) if k not in matched] diff --git a/je_auto_control/utils/saliency/saliency.py b/je_auto_control/utils/saliency/saliency.py index cc12ef1b5..f5f05cfac 100644 --- a/je_auto_control/utils/saliency/saliency.py +++ b/je_auto_control/utils/saliency/saliency.py @@ -18,17 +18,17 @@ ImageSource = Any -def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]): +def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: from je_auto_control.utils.visual_match.visual_match import _haystack_gray return _haystack_gray(source, region) -def _gray_with_origin(source: Optional[ImageSource], region: Optional[Sequence[int]]): +def _gray_with_origin(source: Optional[ImageSource], region: Optional[Sequence[int]]) -> Tuple[Any, int, int]: from je_auto_control.utils.visual_match.visual_match import _haystack_gray_with_origin return _haystack_gray_with_origin(source, region) -def _saliency_from_gray(gray, size: int): +def _saliency_from_gray(gray: Any, size: int) -> Any: import cv2 import numpy as np small = cv2.resize(gray, (size, size), @@ -45,7 +45,7 @@ def _saliency_from_gray(gray, size: int): def saliency_map(source: Optional[ImageSource] = None, *, - region: Optional[Sequence[int]] = None, size: int = 64): + region: Optional[Sequence[int]] = None, size: int = 64) -> Any: """Return the normalised (0–1) spectral-residual saliency map as an ndarray. The map is computed at ``size`` x ``size`` (the algorithm's native low @@ -54,7 +54,7 @@ def saliency_map(source: Optional[ImageSource] = None, *, return _saliency_from_gray(_gray(source, region), int(size)) -def _regions_from_saliency(saliency, orig_shape: Tuple[int, int], +def _regions_from_saliency(saliency: Any, orig_shape: Tuple[int, int], threshold: Optional[float], min_area: int, size: int) -> List[Dict[str, Any]]: from je_auto_control.utils.cv2_utils.blobs import connected_boxes diff --git a/je_auto_control/utils/schema_compat/schema_compat.py b/je_auto_control/utils/schema_compat/schema_compat.py index 6943d698e..85c009527 100644 --- a/je_auto_control/utils/schema_compat/schema_compat.py +++ b/je_auto_control/utils/schema_compat/schema_compat.py @@ -13,7 +13,7 @@ """ from dataclasses import dataclass import json -from typing import Any, Dict, FrozenSet, List, Mapping +from typing import Any, Dict, FrozenSet, List, Mapping, Set _BACKWARD = frozenset({"backward"}) _FORWARD = frozenset({"forward"}) @@ -38,7 +38,7 @@ def _properties(schema: Mapping[str, Any]) -> Dict[str, Any]: return schema.get("properties", {}) or {} -def _required(schema: Mapping[str, Any]) -> set: +def _required(schema: Mapping[str, Any]) -> Set[str]: return set(schema.get("required", []) or []) @@ -60,8 +60,8 @@ def _is_subset(narrow: FrozenSet[str], wide: FrozenSet[str]) -> bool: for kind in narrow) -def _diff_requiredness(name: str, old_req: set, - new_req: set) -> List[SchemaChange]: +def _diff_requiredness(name: str, old_req: Set[str], + new_req: Set[str]) -> List[SchemaChange]: if name in new_req and name not in old_req: return [SchemaChange(name, "field_made_required", _BACKWARD)] if name in old_req and name not in new_req: @@ -99,14 +99,14 @@ def _diff_enum(name: str, old_prop: Mapping[str, Any], return changes -def _enum_keys(values: Any) -> set: +def _enum_keys(values: Any) -> Set[str]: """Enum members as canonical JSON: objects and arrays are hashable, and true is not 1.""" return {json.dumps(value, sort_keys=True) for value in values} def _diff_property(name: str, old_prop: Mapping[str, Any], - new_prop: Mapping[str, Any], old_req: set, - new_req: set) -> List[SchemaChange]: + new_prop: Mapping[str, Any], old_req: Set[str], + new_req: Set[str]) -> List[SchemaChange]: changes = _diff_requiredness(name, old_req, new_req) changes.extend(_diff_type(name, old_prop, new_prop)) changes.extend(_diff_enum(name, old_prop, new_prop)) diff --git a/je_auto_control/utils/screen_state/screen_state.py b/je_auto_control/utils/screen_state/screen_state.py index 1649f61e6..0ad189c2c 100644 --- a/je_auto_control/utils/screen_state/screen_state.py +++ b/je_auto_control/utils/screen_state/screen_state.py @@ -13,7 +13,7 @@ elements) are unit-testable without a live desktop. """ import math -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional, Tuple _INTERACTIVE_HINTS = ("button", "edit", "text", "combo", "check", "radio", "menu", "link", "tab", "list", "slider") @@ -46,23 +46,23 @@ def snapshot(elements: List[Any]) -> List[Dict[str, Any]]: for el in elements] -def _key(item: Dict[str, Any]) -> tuple: +def _key(item: Dict[str, Any]) -> Tuple[Any, Any]: return (item.get("role", ""), item.get("name", "")) -def _group(items: List[Dict[str, Any]]) -> Dict[tuple, List[Dict[str, Any]]]: - groups: Dict[tuple, List[Dict[str, Any]]] = {} +def _group(items: List[Dict[str, Any]]) -> Dict[Tuple[Any, Any], List[Dict[str, Any]]]: + groups: Dict[Tuple[Any, Any], List[Dict[str, Any]]] = {} for item in items: groups.setdefault(_key(item), []).append(item) return groups -def _centre(item: Dict[str, Any]) -> tuple: +def _centre(item: Dict[str, Any]) -> Tuple[float, float]: bbox = list(item.get("bbox") or [0, 0, 0, 0])[:4] + [0, 0, 0, 0] return (bbox[0] + bbox[2] / 2.0, bbox[1] + bbox[3] / 2.0) -def _distance_from(target: tuple) -> Callable[[Dict[str, Any]], float]: +def _distance_from(target: Tuple[float, float]) -> Callable[[Dict[str, Any]], float]: """Key function: how far an item's centre is from ``target``.""" return lambda item: math.dist(_centre(item), target) diff --git a/je_auto_control/utils/ssim/ssim.py b/je_auto_control/utils/ssim/ssim.py index 47e24b8c6..049f31693 100644 --- a/je_auto_control/utils/ssim/ssim.py +++ b/je_auto_control/utils/ssim/ssim.py @@ -12,7 +12,7 @@ arrays without a real screen. OpenCV + NumPy come in via ``je_open_cv`` and are imported lazily. Imports no ``PySide6``. """ -from typing import Any, Dict, List, Optional, Sequence +from typing import Any, Dict, List, Optional, Sequence, Tuple ImageSource = Any IgnoreBoxes = Optional[Sequence[Sequence[int]]] @@ -29,7 +29,7 @@ def _gray_code(channels: int, is_bgr: bool) -> int: return cv2.COLOR_BGR2GRAY if is_bgr else cv2.COLOR_RGB2GRAY -def _data_range(array) -> float: +def _data_range(array: Any) -> float: """The dynamic range L of an image (Wang et al. 2004): 255 for 8-bit, 1 for 0..1 floats.""" import numpy as np if np.issubdtype(array.dtype, np.integer): @@ -39,7 +39,7 @@ def _data_range(array) -> float: return 1.0 if array.size and float(np.nanmax(array)) <= 1.0 else 255.0 -def _to_gray_f(source: ImageSource): +def _to_gray_f(source: ImageSource) -> Tuple[Any, float]: """Load a path / ndarray / PIL image as ``(2-D float64 grayscale, dynamic range)``. Channel order is tracked so luminance weights stay correct: ``cv2.imread`` @@ -71,13 +71,13 @@ def _to_gray_f(source: ImageSource): return array.astype(np.float64), data_range -def _grab_gray_f(region: Optional[Sequence[int]]): +def _grab_gray_f(region: Optional[Sequence[int]]) -> Tuple[Any, float]: from je_auto_control.utils.cv2_utils.region_capture import grab_screen_region return _to_gray_f(grab_screen_region(region)) def _resolve_pair(reference: ImageSource, current: Optional[ImageSource], - region: Optional[Sequence[int]]): + region: Optional[Sequence[int]]) -> Tuple[Any, Any, float]: reference_gray, reference_range = _to_gray_f(reference) current_gray, current_range = (_to_gray_f(current) if current is not None else _grab_gray_f(region)) @@ -87,7 +87,7 @@ def _resolve_pair(reference: ImageSource, current: Optional[ImageSource], return reference_gray, current_gray, max(reference_range, current_range) -def _ssim_map(reference, current, data_range: float): +def _ssim_map(reference: Any, current: Any, data_range: float) -> Any: """Per-pixel SSIM map via an 11x11 Gaussian window (sigma 1.5). C1 and C2 scale with the images' dynamic range: fixed at 255, two 0..1 @@ -106,7 +106,7 @@ def _ssim_map(reference, current, data_range: float): return numerator / denominator -def _keep_mask(shape, ignore: IgnoreBoxes): +def _keep_mask(shape: Tuple[int, ...], ignore: IgnoreBoxes) -> Any: """Boolean keep-mask (True = counted); ``ignore`` boxes [x,y,w,h] set False.""" import numpy as np keep = np.ones(shape, dtype=bool) diff --git a/je_auto_control/utils/triggers/webhook_server.py b/je_auto_control/utils/triggers/webhook_server.py index d3ffbad18..16c73a8ce 100644 --- a/je_auto_control/utils/triggers/webhook_server.py +++ b/je_auto_control/utils/triggers/webhook_server.py @@ -144,7 +144,7 @@ class _WebhookHandler(BaseHTTPRequestHandler): # rename or annotation drift; the shadow of the stdlib 'format' is # the parent class's choice, not ours. # pylint: disable=redefined-builtin - def log_message(self, format, *args): # noqa: A002 + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 autocontrol_logger.debug("webhook %s", log_safe(format % args)) # pylint: enable=redefined-builtin @@ -276,7 +276,7 @@ class WebhookTriggerServer: """Push-based trigger: external HTTP requests fire the registered script.""" def __init__(self, - executor: Optional[Callable[[list, Dict[str, Any]], Any]] = None, + executor: Optional[Callable[[List[Any], Dict[str, Any]], Any]] = None, ) -> None: self._lock = threading.RLock() # Serialise firings so concurrent webhook hits do not race on the @@ -286,7 +286,7 @@ def __init__(self, self._server: Optional[ThreadingHTTPServer] = None self._thread: Optional[threading.Thread] = None self._bound: Optional[Tuple[str, int]] = None - self._executor: Callable[[list, Dict[str, Any]], Any] = ( + self._executor: Callable[[List[Any], Dict[str, Any]], Any] = ( self._default_executor if executor is None else executor ) @@ -449,7 +449,7 @@ def stop(self, timeout: float = 2.0) -> None: thread.join(timeout=timeout) @staticmethod - def _default_executor(actions: list, variables: Dict[str, Any]) -> Any: + def _default_executor(actions: List[Any], variables: Dict[str, Any]) -> Any: """Default: thread-safe global executor with ``variables`` seeded.""" from je_auto_control.utils.executor.action_executor import ( execute_action_with_vars, diff --git a/je_auto_control/utils/usbip/libusb_backend.py b/je_auto_control/utils/usbip/libusb_backend.py index b8e5e0174..541e9762d 100644 --- a/je_auto_control/utils/usbip/libusb_backend.py +++ b/je_auto_control/utils/usbip/libusb_backend.py @@ -32,7 +32,7 @@ _USB_TIMEOUT_MS = 5_000 # 5 s ceiling per URB; matches kernel default. -def _try_pyusb(): +def _try_pyusb() -> bool: try: import usb.core # noqa: F401 import usb.util # noqa: F401 @@ -64,7 +64,7 @@ class LibUsbBackend(UrbBackend): def __init__(self) -> None: self._available = _try_pyusb() - self._device_cache: dict = {} + self._device_cache: dict[int, Any] = {} @property def available(self) -> bool: @@ -141,7 +141,7 @@ def submit_urb(self, request: UrbRequest) -> UrbResponse: # --- per-endpoint-type helpers -------------------------------------- @staticmethod - def _submit_control(device, request: UrbRequest) -> UrbResponse: + def _submit_control(device: Any, request: UrbRequest) -> UrbResponse: """Control transfer (ep 0). Setup packet lives in ``request.setup``.""" if len(request.setup) != 8: return UrbResponse(status=-22, actual_length=0) # -EINVAL @@ -168,7 +168,7 @@ def _submit_control(device, request: UrbRequest) -> UrbResponse: return UrbResponse(status=0, actual_length=int(sent or 0)) @staticmethod - def _submit_bulk_or_interrupt(device, request: UrbRequest) -> UrbResponse: + def _submit_bulk_or_interrupt(device: Any, request: UrbRequest) -> UrbResponse: """Bulk / interrupt transfer through ``Device.read`` or ``Device.write``.""" endpoint = _endpoint_address(request.direction, request.ep) if _direction_in(request.direction): diff --git a/je_auto_control/utils/visual_regression/compare.py b/je_auto_control/utils/visual_regression/compare.py index ac6e2edbe..da48d82c1 100644 --- a/je_auto_control/utils/visual_regression/compare.py +++ b/je_auto_control/utils/visual_regression/compare.py @@ -44,7 +44,7 @@ def summary(self) -> str: f"{self.differing_pixels}/{self.total_pixels} pixels" ) - def write_diff(self, path) -> Path: + def write_diff(self, path: str | os.PathLike[str]) -> Path: """Persist the diff overlay; idempotent — returns the target path.""" target = Path(os.path.expanduser(str(path))) if self.diff_image is None: @@ -54,7 +54,7 @@ def write_diff(self, path) -> Path: return target -def _expand_path(path) -> Path: +def _expand_path(path: str | os.PathLike[str]) -> Path: return Path(os.path.expanduser(str(path))) @@ -73,7 +73,7 @@ def _apply_masks(image: Image.Image, return result -def take_golden(path, +def take_golden(path: str | os.PathLike[str], *, source: Optional[Image.Image] = None, region: Optional[Sequence[int]] = None) -> Path: """Capture and save a golden image. @@ -160,7 +160,7 @@ def _masked_pixels(size: Tuple[int, int], masks: Sequence[MaskRegion]) -> int: return int(sum(stencil.histogram()[1:])) -def compare_to_golden(golden_path, +def compare_to_golden(golden_path: str | os.PathLike[str], *, actual: Optional[Image.Image] = None, region: Optional[Sequence[int]] = None, tolerance: float = 0.0, diff --git a/je_auto_control/windows/message/window_message.py b/je_auto_control/windows/message/window_message.py index 535922134..19158eb97 100644 --- a/je_auto_control/windows/message/window_message.py +++ b/je_auto_control/windows/message/window_message.py @@ -46,7 +46,7 @@ def send_message_to_window(window_name: str, action_message: int, - key_code_1: int, key_code_2: int): + key_code_1: int, key_code_2: int) -> tuple[int, int]: """ 使用 SendMessageW 對指定視窗名稱傳送訊息 Send message to a window by name using SendMessageW @@ -64,8 +64,8 @@ def send_message_to_window(window_name: str, action_message: int, return hwnd, post_status -def send_message_to_window_hwnd(hwnd, action_message: int, - key_code_1: int, key_code_2: int): +def send_message_to_window_hwnd(hwnd: int, action_message: int, + key_code_1: int, key_code_2: int) -> tuple[int, int]: """ 使用 SendMessageW 對指定 HWND 傳送訊息 Send message to a window by HWND using SendMessageW @@ -75,7 +75,7 @@ def send_message_to_window_hwnd(hwnd, action_message: int, def post_message_to_window(window_name: str, action_message: int, - key_code_1: int, key_code_2: int): + key_code_1: int, key_code_2: int) -> tuple[int, int]: """ 使用 PostMessageW 對指定視窗名稱投遞訊息 Post message to a window by name using PostMessageW @@ -87,8 +87,8 @@ def post_message_to_window(window_name: str, action_message: int, return hwnd, post_status -def post_message_to_window_hwnd(hwnd, action_message: int, - key_code_1: int, key_code_2: int): +def post_message_to_window_hwnd(hwnd: int, action_message: int, + key_code_1: int, key_code_2: int) -> tuple[int, int]: """ 使用 PostMessageW 對指定 HWND 投遞訊息 Post message to a window by HWND using PostMessageW diff --git a/pyproject.toml b/pyproject.toml index febcf2d3d..5d797f535 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -371,6 +371,7 @@ module = [ "je_auto_control.cli", "je_auto_control.gui", "je_auto_control.gui._arrow_icons", + "je_auto_control.gui._auto_click_tab", "je_auto_control.gui._daemon_thread", "je_auto_control.gui._dispose", "je_auto_control.gui._i18n_helpers", @@ -379,6 +380,7 @@ module = [ "je_auto_control.gui._report_tab", "je_auto_control.gui._screen_geometry", "je_auto_control.gui._screenshot_tab", + "je_auto_control.gui._script_tab", "je_auto_control.gui._slow_op", "je_auto_control.gui._stop_custody", "je_auto_control.gui._tab_close_icon", @@ -387,15 +389,18 @@ module = [ "je_auto_control.gui._validators", "je_auto_control.gui._weak_call", "je_auto_control.gui._worker_thread", + "je_auto_control.gui.a11y_audit_tab", "je_auto_control.gui.accessibility_tab", "je_auto_control.gui.adaptive", "je_auto_control.gui.adaptive.*", "je_auto_control.gui.adaptive_window", + "je_auto_control.gui.admin_console_tab", "je_auto_control.gui.agent_observation_view", "je_auto_control.gui.agent_transfer_view", "je_auto_control.gui.assertions_tab", "je_auto_control.gui.audit_log_tab", "je_auto_control.gui.chatops_tab", + "je_auto_control.gui.computer_use_tab", "je_auto_control.gui.config_sync_tab", "je_auto_control.gui.config_sync_worker", "je_auto_control.gui.data_source_tab", @@ -406,6 +411,8 @@ module = [ "je_auto_control.gui.failed_stops_view", "je_auto_control.gui.flakiness_tab", "je_auto_control.gui.flow_editor", + "je_auto_control.gui.flow_editor.scene", + "je_auto_control.gui.flow_editor.tab", "je_auto_control.gui.healing_evaluation_panel", "je_auto_control.gui.healing_evaluation_worker", "je_auto_control.gui.hotkeys_tab", @@ -416,11 +423,9 @@ module = [ "je_auto_control.gui.journal_candidate_panel", "je_auto_control.gui.journal_candidate_worker", "je_auto_control.gui.language_wrapper", - "je_auto_control.gui.language_wrapper.english", - "je_auto_control.gui.language_wrapper.japanese", - "je_auto_control.gui.language_wrapper.simplified_chinese", - "je_auto_control.gui.language_wrapper.traditional_chinese", + "je_auto_control.gui.language_wrapper.*", "je_auto_control.gui.live_hud_tab", + "je_auto_control.gui.llm_planner_tab", "je_auto_control.gui.main_widget", "je_auto_control.gui.main_window", "je_auto_control.gui.manual_run_controls", @@ -428,12 +433,15 @@ module = [ "je_auto_control.gui.media_checks_tab", "je_auto_control.gui.mobile_tab", "je_auto_control.gui.navigation", + "je_auto_control.gui.ocr_tab", "je_auto_control.gui.plugins_tab", "je_auto_control.gui.presence_tab", "je_auto_control.gui.profiler_tab", "je_auto_control.gui.rbac_users_panel", + "je_auto_control.gui.recording_editor_tab", "je_auto_control.gui.remote_desktop", "je_auto_control.gui.remote_desktop._connect_task", + "je_auto_control.gui.remote_desktop._helpers", "je_auto_control.gui.remote_desktop._host_ops", "je_auto_control.gui.remote_desktop._webrtc_types", "je_auto_control.gui.remote_desktop.advanced_group", @@ -452,12 +460,14 @@ module = [ "je_auto_control.gui.remote_desktop.view_frames", "je_auto_control.gui.remote_desktop.view_lifetime", "je_auto_control.gui.remote_desktop.view_upload", + "je_auto_control.gui.remote_desktop.viewer_panel", "je_auto_control.gui.remote_desktop.viewer_screen_window", "je_auto_control.gui.remote_desktop.webrtc_host_connection", "je_auto_control.gui.remote_desktop.webrtc_host_media", "je_auto_control.gui.remote_desktop.webrtc_host_sessions", "je_auto_control.gui.remote_desktop.webrtc_host_trust", "je_auto_control.gui.remote_desktop.webrtc_host_ui", + "je_auto_control.gui.remote_desktop.webrtc_panel", "je_auto_control.gui.remote_desktop.webrtc_panel_common", "je_auto_control.gui.remote_desktop.webrtc_panel_state", "je_auto_control.gui.remote_desktop.webrtc_viewer_address_book", @@ -465,17 +475,14 @@ module = [ "je_auto_control.gui.remote_desktop.webrtc_viewer_files", "je_auto_control.gui.remote_desktop.webrtc_viewer_media", "je_auto_control.gui.remote_desktop.webrtc_viewer_ui", + "je_auto_control.gui.remote_desktop.webrtc_workers", "je_auto_control.gui.remote_desktop_tab", "je_auto_control.gui.rest_api_tab", "je_auto_control.gui.run_history_tab", "je_auto_control.gui.run_history_timeline", "je_auto_control.gui.scheduler_tab", "je_auto_control.gui.script_builder", - "je_auto_control.gui.script_builder.builder_tab", - "je_auto_control.gui.script_builder.command_schema", - "je_auto_control.gui.script_builder.one_time_dialog", - "je_auto_control.gui.script_builder.step_form_view", - "je_auto_control.gui.script_builder.step_list_view", + "je_auto_control.gui.script_builder.*", "je_auto_control.gui.secrets_tab", "je_auto_control.gui.selector", "je_auto_control.gui.selector.*", @@ -488,6 +495,9 @@ module = [ "je_auto_control.gui.test_suite_tab", "je_auto_control.gui.theme", "je_auto_control.gui.trace_replay_tab", + "je_auto_control.gui.usb_browser_tab", + "je_auto_control.gui.usb_devices_tab", + "je_auto_control.gui.usb_passthrough_panel", "je_auto_control.gui.usb_passthrough_prompt", "je_auto_control.gui.variables_tab", "je_auto_control.gui.webhooks_tab", @@ -517,6 +527,7 @@ module = [ "je_auto_control.linux_wayland.ei_worker", "je_auto_control.linux_wayland.global_shortcuts", "je_auto_control.linux_wayland.input_events", + "je_auto_control.linux_wayland.keyboard", "je_auto_control.linux_wayland.keymap", "je_auto_control.linux_wayland.listener", "je_auto_control.linux_wayland.mouse", @@ -551,9 +562,11 @@ module = [ "je_auto_control.utils.accessibility.backends", "je_auto_control.utils.accessibility.backends.base", "je_auto_control.utils.accessibility.backends.linux_backend", + "je_auto_control.utils.accessibility.backends.macos_backend", "je_auto_control.utils.accessibility.backends.null_backend", "je_auto_control.utils.accessibility.backends.windows_automation", "je_auto_control.utils.accessibility.backends.windows_events", + "je_auto_control.utils.accessibility.backends.windows_state", "je_auto_control.utils.accessibility.element", "je_auto_control.utils.accessibility.recorder", "je_auto_control.utils.accessibility.tree", @@ -579,9 +592,7 @@ module = [ "je_auto_control.utils.admin", "je_auto_control.utils.admin.*", "je_auto_control.utils.agent", - "je_auto_control.utils.agent.backends", - "je_auto_control.utils.agent.backends.*", - "je_auto_control.utils.agent.computer_use", + "je_auto_control.utils.agent.*", "je_auto_control.utils.agent_memory", "je_auto_control.utils.agent_memory.*", "je_auto_control.utils.agent_replay", @@ -591,6 +602,7 @@ module = [ "je_auto_control.utils.agent_runtime.activity", "je_auto_control.utils.agent_runtime.activity_windows", "je_auto_control.utils.agent_runtime.android_action_result", + "je_auto_control.utils.agent_runtime.android_adapter", "je_auto_control.utils.agent_runtime.android_commands", "je_auto_control.utils.agent_runtime.android_control", "je_auto_control.utils.agent_runtime.android_geometry", @@ -600,11 +612,13 @@ module = [ "je_auto_control.utils.agent_runtime.android_session", "je_auto_control.utils.agent_runtime.android_transport", "je_auto_control.utils.agent_runtime.api", + "je_auto_control.utils.agent_runtime.browser_commands", "je_auto_control.utils.agent_runtime.browser_environment", "je_auto_control.utils.agent_runtime.browser_readonly_scope", "je_auto_control.utils.agent_runtime.browser_retirement", "je_auto_control.utils.agent_runtime.browser_transfers", "je_auto_control.utils.agent_runtime.browser_validation", + "je_auto_control.utils.agent_runtime.browser_verification", "je_auto_control.utils.agent_runtime.budget_clock", "je_auto_control.utils.agent_runtime.cli", "je_auto_control.utils.agent_runtime.client", @@ -612,24 +626,30 @@ module = [ "je_auto_control.utils.agent_runtime.completion_contract", "je_auto_control.utils.agent_runtime.context", "je_auto_control.utils.agent_runtime.control_admission", + "je_auto_control.utils.agent_runtime.dag_admission", + "je_auto_control.utils.agent_runtime.dag_batch_recording", "je_auto_control.utils.agent_runtime.dag_jobs", + "je_auto_control.utils.agent_runtime.dag_local", "je_auto_control.utils.agent_runtime.dag_retention", "je_auto_control.utils.agent_runtime.dag_service_client", "je_auto_control.utils.agent_runtime.delegation", "je_auto_control.utils.agent_runtime.dialog_scope", "je_auto_control.utils.agent_runtime.document_launch", "je_auto_control.utils.agent_runtime.errors", + "je_auto_control.utils.agent_runtime.evidence", "je_auto_control.utils.agent_runtime.evidence_cache", "je_auto_control.utils.agent_runtime.file_dialog_scope", "je_auto_control.utils.agent_runtime.file_target", "je_auto_control.utils.agent_runtime.helper_environment", "je_auto_control.utils.agent_runtime.helper_owner_linux", "je_auto_control.utils.agent_runtime.images", + "je_auto_control.utils.agent_runtime.input_journal", "je_auto_control.utils.agent_runtime.jobs", "je_auto_control.utils.agent_runtime.local_evidence", "je_auto_control.utils.agent_runtime.manifest_evidence", "je_auto_control.utils.agent_runtime.model_tools", "je_auto_control.utils.agent_runtime.models", + "je_auto_control.utils.agent_runtime.native_channel", "je_auto_control.utils.agent_runtime.native_control", "je_auto_control.utils.agent_runtime.native_job", "je_auto_control.utils.agent_runtime.native_recovery", @@ -643,9 +663,11 @@ module = [ "je_auto_control.utils.agent_runtime.parent_watch", "je_auto_control.utils.agent_runtime.path_identity", "je_auto_control.utils.agent_runtime.policy", + "je_auto_control.utils.agent_runtime.presence_broker", "je_auto_control.utils.agent_runtime.presence_channel_linux", "je_auto_control.utils.agent_runtime.presence_endpoint_linux", "je_auto_control.utils.agent_runtime.presence_handshake", + "je_auto_control.utils.agent_runtime.presence_host", "je_auto_control.utils.agent_runtime.presence_messages_linux", "je_auto_control.utils.agent_runtime.presence_native_types", "je_auto_control.utils.agent_runtime.presence_owner", @@ -659,30 +681,48 @@ module = [ "je_auto_control.utils.agent_runtime.presence_security_windows", "je_auto_control.utils.agent_runtime.presence_server", "je_auto_control.utils.agent_runtime.presence_session_windows", + "je_auto_control.utils.agent_runtime.presence_state", "je_auto_control.utils.agent_runtime.presence_win32", "je_auto_control.utils.agent_runtime.presence_worker", "je_auto_control.utils.agent_runtime.presence_x11", "je_auto_control.utils.agent_runtime.readiness", + "je_auto_control.utils.agent_runtime.readonly_target", + "je_auto_control.utils.agent_runtime.readonly_worker", "je_auto_control.utils.agent_runtime.receipts", + "je_auto_control.utils.agent_runtime.recovery_authorization", + "je_auto_control.utils.agent_runtime.remote_effect", + "je_auto_control.utils.agent_runtime.remote_target", "je_auto_control.utils.agent_runtime.resume_gate", + "je_auto_control.utils.agent_runtime.retained_browser_runtime", "je_auto_control.utils.agent_runtime.retention", + "je_auto_control.utils.agent_runtime.runner", "je_auto_control.utils.agent_runtime.runtime", "je_auto_control.utils.agent_runtime.runtime_lock", "je_auto_control.utils.agent_runtime.service", + "je_auto_control.utils.agent_runtime.skill_parameters", + "je_auto_control.utils.agent_runtime.skill_reauthorization", "je_auto_control.utils.agent_runtime.submission", "je_auto_control.utils.agent_runtime.target_config", "je_auto_control.utils.agent_runtime.target_continuity", "je_auto_control.utils.agent_runtime.target_factory", + "je_auto_control.utils.agent_runtime.targets", + "je_auto_control.utils.agent_runtime.task_handoff", "je_auto_control.utils.agent_runtime.transfer_adoption", "je_auto_control.utils.agent_runtime.transfer_cache", "je_auto_control.utils.agent_runtime.transfer_destination_scope", + "je_auto_control.utils.agent_runtime.transfer_evidence_management", "je_auto_control.utils.agent_runtime.transfer_files", + "je_auto_control.utils.agent_runtime.transfer_import_contract", "je_auto_control.utils.agent_runtime.transfer_import_jobs", + "je_auto_control.utils.agent_runtime.transfer_import_ledger", + "je_auto_control.utils.agent_runtime.transfer_management", "je_auto_control.utils.agent_runtime.transfer_models", "je_auto_control.utils.agent_runtime.transfer_operations", "je_auto_control.utils.agent_runtime.transfer_privacy", + "je_auto_control.utils.agent_runtime.transfer_protocol", "je_auto_control.utils.agent_runtime.transfer_records", "je_auto_control.utils.agent_runtime.transport", + "je_auto_control.utils.agent_runtime.trigger_config", "je_auto_control.utils.agent_runtime.trigger_history", "je_auto_control.utils.agent_runtime.trigger_registration", "je_auto_control.utils.agent_runtime.window_pixels", @@ -743,7 +783,7 @@ module = [ "je_auto_control.utils.ci_annotations.*", "je_auto_control.utils.cli_output", "je_auto_control.utils.clipboard", - "je_auto_control.utils.clipboard.win32_clipboard_api", + "je_auto_control.utils.clipboard.*", "je_auto_control.utils.clipboard_files", "je_auto_control.utils.clipboard_files.*", "je_auto_control.utils.clipboard_formats", @@ -798,22 +838,11 @@ module = [ "je_auto_control.utils.cua_action", "je_auto_control.utils.cua_action.*", "je_auto_control.utils.cv2_utils", - "je_auto_control.utils.cv2_utils.blobs", - "je_auto_control.utils.cv2_utils.frame_clock", - "je_auto_control.utils.cv2_utils.image_file", - "je_auto_control.utils.cv2_utils.locator_frame", - "je_auto_control.utils.cv2_utils.optional", - "je_auto_control.utils.cv2_utils.region_capture", - "je_auto_control.utils.cv2_utils.screen_grabber", - "je_auto_control.utils.cv2_utils.screenshot", - "je_auto_control.utils.cv2_utils.template_detection", - "je_auto_control.utils.cv2_utils.video_recording", + "je_auto_control.utils.cv2_utils.*", "je_auto_control.utils.cvd_simulate", "je_auto_control.utils.cvd_simulate.*", "je_auto_control.utils.dag", - "je_auto_control.utils.dag.graph", - "je_auto_control.utils.dag.managed_tasks", - "je_auto_control.utils.dag.task_contract", + "je_auto_control.utils.dag.*", "je_auto_control.utils.data_drift", "je_auto_control.utils.data_drift.*", "je_auto_control.utils.data_profile", @@ -863,6 +892,7 @@ module = [ "je_auto_control.utils.exception.*", "je_auto_control.utils.executor", "je_auto_control.utils.executor.action_redaction", + "je_auto_control.utils.executor.action_schema", "je_auto_control.utils.executor.dispatch", "je_auto_control.utils.executor.flags", "je_auto_control.utils.executor.flow_data_commands", @@ -903,6 +933,7 @@ module = [ "je_auto_control.utils.fuzzy", "je_auto_control.utils.fuzzy.*", "je_auto_control.utils.gamepad", + "je_auto_control.utils.gamepad.*", "je_auto_control.utils.generate_report", "je_auto_control.utils.generate_report.*", "je_auto_control.utils.gettext_catalog", @@ -920,12 +951,14 @@ module = [ "je_auto_control.utils.hotkey", "je_auto_control.utils.hotkey.backends", "je_auto_control.utils.hotkey.backends.base", + "je_auto_control.utils.hotkey.backends.macos_backend", "je_auto_control.utils.hotkey.backends.windows_backend", "je_auto_control.utils.hotkey.hotkey_daemon", "je_auto_control.utils.hsv_segment", "je_auto_control.utils.http_cassette", "je_auto_control.utils.http_cassette.*", "je_auto_control.utils.http_client", + "je_auto_control.utils.http_client.*", "je_auto_control.utils.http_conditional", "je_auto_control.utils.http_conditional.*", "je_auto_control.utils.http_content", @@ -955,7 +988,9 @@ module = [ "je_auto_control.utils.json", "je_auto_control.utils.json.*", "je_auto_control.utils.json_contract", + "je_auto_control.utils.json_contract.*", "je_auto_control.utils.json_patch", + "je_auto_control.utils.json_patch.*", "je_auto_control.utils.json_schema", "je_auto_control.utils.json_schema.ecma_regex", "je_auto_control.utils.json_store", @@ -1032,12 +1067,14 @@ module = [ "je_auto_control.utils.mcp_server.prompts", "je_auto_control.utils.mcp_server.rate_limit", "je_auto_control.utils.mcp_server.resources", + "je_auto_control.utils.mcp_server.server", "je_auto_control.utils.mcp_server.stdio", "je_auto_control.utils.mcp_server.tools", "je_auto_control.utils.mcp_server.tools._agent_tasks", "je_auto_control.utils.mcp_server.tools._base", "je_auto_control.utils.mcp_server.tools._capabilities", "je_auto_control.utils.mcp_server.tools._diagnostics", + "je_auto_control.utils.mcp_server.tools._discovery", "je_auto_control.utils.mcp_server.tools._factories", "je_auto_control.utils.mcp_server.tools._handlers_accessibility_executor", "je_auto_control.utils.mcp_server.tools._handlers_automation_executor", @@ -1080,8 +1117,7 @@ module = [ "je_auto_control.utils.notify_channels", "je_auto_control.utils.notify_channels.*", "je_auto_control.utils.observability", - "je_auto_control.utils.observability.exporter", - "je_auto_control.utils.observability.metrics", + "je_auto_control.utils.observability.*", "je_auto_control.utils.observation", "je_auto_control.utils.observation.*", "je_auto_control.utils.observation_delta", @@ -1089,13 +1125,7 @@ module = [ "je_auto_control.utils.observer", "je_auto_control.utils.observer.*", "je_auto_control.utils.ocr", - "je_auto_control.utils.ocr.backends", - "je_auto_control.utils.ocr.backends.base", - "je_auto_control.utils.ocr.backends.tesseract_backend", - "je_auto_control.utils.ocr.ocr_engine", - "je_auto_control.utils.ocr.structure", - "je_auto_control.utils.ocr.tesseract_setup", - "je_auto_control.utils.ocr.text_span", + "je_auto_control.utils.ocr.*", "je_auto_control.utils.office", "je_auto_control.utils.office.*", "je_auto_control.utils.optimistic", @@ -1124,6 +1154,7 @@ module = [ "je_auto_control.utils.plugin_sdk", "je_auto_control.utils.plugin_sdk.*", "je_auto_control.utils.postcondition", + "je_auto_control.utils.postcondition.*", "je_auto_control.utils.preprocess", "je_auto_control.utils.process_doc", "je_auto_control.utils.process_doc.*", @@ -1144,6 +1175,7 @@ module = [ "je_auto_control.utils.quarantine", "je_auto_control.utils.quarantine.*", "je_auto_control.utils.rate_limit", + "je_auto_control.utils.rate_limit.*", "je_auto_control.utils.rbac", "je_auto_control.utils.rbac.*", "je_auto_control.utils.readability", @@ -1162,6 +1194,7 @@ module = [ "je_auto_control.utils.remote_desktop._optional", "je_auto_control.utils.remote_desktop._optional.*", "je_auto_control.utils.remote_desktop.adaptive_bitrate", + "je_auto_control.utils.remote_desktop.audio", "je_auto_control.utils.remote_desktop.audio_retirement", "je_auto_control.utils.remote_desktop.audit_log", "je_auto_control.utils.remote_desktop.auth", @@ -1191,6 +1224,7 @@ module = [ "je_auto_control.utils.remote_desktop.session_actions", "je_auto_control.utils.remote_desktop.session_quality_cache", "je_auto_control.utils.remote_desktop.session_recorder", + "je_auto_control.utils.remote_desktop.signaling_client", "je_auto_control.utils.remote_desktop.totp", "je_auto_control.utils.remote_desktop.transport", "je_auto_control.utils.remote_desktop.trust_list", @@ -1199,12 +1233,14 @@ module = [ "je_auto_control.utils.remote_desktop.viewer", "je_auto_control.utils.remote_desktop.viewer_id", "je_auto_control.utils.remote_desktop.wake_on_lan", + "je_auto_control.utils.remote_desktop.webrtc_audio", "je_auto_control.utils.remote_desktop.webrtc_file_callbacks", "je_auto_control.utils.remote_desktop.webrtc_file_commit", "je_auto_control.utils.remote_desktop.webrtc_file_receive", "je_auto_control.utils.remote_desktop.webrtc_file_tasks", "je_auto_control.utils.remote_desktop.webrtc_file_write", "je_auto_control.utils.remote_desktop.webrtc_host_auth", + "je_auto_control.utils.remote_desktop.webrtc_host_media", "je_auto_control.utils.remote_desktop.webrtc_inspector", "je_auto_control.utils.remote_desktop.webrtc_media_owners", "je_auto_control.utils.remote_desktop.webrtc_mic", @@ -1216,18 +1252,14 @@ module = [ "je_auto_control.utils.resilience", "je_auto_control.utils.resilience.*", "je_auto_control.utils.rest_api", - "je_auto_control.utils.rest_api.__main__", - "je_auto_control.utils.rest_api.rest_auth", - "je_auto_control.utils.rest_api.rest_handlers", - "je_auto_control.utils.rest_api.rest_metrics", - "je_auto_control.utils.rest_api.rest_openapi", - "je_auto_control.utils.rest_api.rest_registry", + "je_auto_control.utils.rest_api.*", "je_auto_control.utils.retry_budget", "je_auto_control.utils.retry_budget.*", "je_auto_control.utils.rich_clipboard", "je_auto_control.utils.rich_clipboard.*", "je_auto_control.utils.rotated_match", "je_auto_control.utils.run_diff", + "je_auto_control.utils.run_diff.*", "je_auto_control.utils.run_history", "je_auto_control.utils.run_history.*", "je_auto_control.utils.saga", @@ -1241,9 +1273,11 @@ module = [ "je_auto_control.utils.scheduler", "je_auto_control.utils.scheduler.*", "je_auto_control.utils.schema_compat", + "je_auto_control.utils.schema_compat.*", "je_auto_control.utils.screen_grid", "je_auto_control.utils.screen_grid.*", "je_auto_control.utils.screen_state", + "je_auto_control.utils.screen_state.*", "je_auto_control.utils.script_vars", "je_auto_control.utils.script_vars.*", "je_auto_control.utils.scroll_find", @@ -1351,6 +1385,7 @@ module = [ "je_auto_control.utils.trash.*", "je_auto_control.utils.triggers", "je_auto_control.utils.triggers.trigger_engine", + "je_auto_control.utils.triggers.webhook_server", "je_auto_control.utils.tween_drag", "je_auto_control.utils.tween_drag.*", "je_auto_control.utils.url_canon", @@ -1375,9 +1410,7 @@ module = [ "je_auto_control.utils.usb.usb_devices", "je_auto_control.utils.usb.usb_watcher", "je_auto_control.utils.usbip", - "je_auto_control.utils.usbip.backend", - "je_auto_control.utils.usbip.protocol", - "je_auto_control.utils.usbip.server", + "je_auto_control.utils.usbip.*", "je_auto_control.utils.verify_field", "je_auto_control.utils.verify_field.*", "je_auto_control.utils.vex", @@ -1395,6 +1428,7 @@ module = [ "je_auto_control.utils.vision.vlm_api", "je_auto_control.utils.visual_match", "je_auto_control.utils.visual_regression", + "je_auto_control.utils.visual_regression.*", "je_auto_control.utils.voice", "je_auto_control.utils.voice.*", "je_auto_control.utils.vuln_scan", @@ -1425,6 +1459,7 @@ module = [ "je_auto_control.windows.keyboard", "je_auto_control.windows.keyboard.*", "je_auto_control.windows.message", + "je_auto_control.windows.message.*", "je_auto_control.windows.mouse", "je_auto_control.windows.mouse.*", "je_auto_control.windows.record", diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index 3c24e1dd6..a8d1aee0a 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -6,83 +6,50 @@ # shrink. Move a module into the strict block once mypy passes it there, and # delete its line. je_auto_control.gui.agent_tasks_tab -je_auto_control.utils.agent_runtime.android_adapter je_auto_control.utils.agent_runtime.android_hierarchy -je_auto_control.utils.agent_runtime.browser_commands je_auto_control.utils.agent_runtime.browser_target -je_auto_control.utils.agent_runtime.browser_verification je_auto_control.utils.agent_runtime.browser_workflows je_auto_control.utils.agent_runtime.completion_recovery -je_auto_control.utils.agent_runtime.dag_admission -je_auto_control.utils.agent_runtime.dag_batch_recording je_auto_control.utils.agent_runtime.dag_batches je_auto_control.utils.agent_runtime.dag_continuation je_auto_control.utils.agent_runtime.dag_continuation_evidence je_auto_control.utils.agent_runtime.dag_continuation_plan -je_auto_control.utils.agent_runtime.dag_local je_auto_control.utils.agent_runtime.dag_transfer_checks je_auto_control.utils.agent_runtime.dag_transfer_stop -je_auto_control.utils.agent_runtime.evidence je_auto_control.utils.agent_runtime.evidence_handoff je_auto_control.utils.agent_runtime.handoff_records -je_auto_control.utils.agent_runtime.input_journal je_auto_control.utils.agent_runtime.input_ledger -je_auto_control.utils.agent_runtime.native_channel je_auto_control.utils.agent_runtime.native_target je_auto_control.utils.agent_runtime.native_worker je_auto_control.utils.agent_runtime.observation_refs -je_auto_control.utils.agent_runtime.presence_broker je_auto_control.utils.agent_runtime.presence_frames -je_auto_control.utils.agent_runtime.presence_host je_auto_control.utils.agent_runtime.presence_pool -je_auto_control.utils.agent_runtime.presence_state je_auto_control.utils.agent_runtime.presence_windows -je_auto_control.utils.agent_runtime.readonly_target -je_auto_control.utils.agent_runtime.readonly_worker -je_auto_control.utils.agent_runtime.recovery_authorization -je_auto_control.utils.agent_runtime.remote_effect je_auto_control.utils.agent_runtime.remote_journal -je_auto_control.utils.agent_runtime.remote_target je_auto_control.utils.agent_runtime.remote_worker je_auto_control.utils.agent_runtime.retained_browser -je_auto_control.utils.agent_runtime.retained_browser_runtime je_auto_control.utils.agent_runtime.retained_browser_target je_auto_control.utils.agent_runtime.routes -je_auto_control.utils.agent_runtime.runner je_auto_control.utils.agent_runtime.skill_completion je_auto_control.utils.agent_runtime.skill_execution -je_auto_control.utils.agent_runtime.skill_parameters -je_auto_control.utils.agent_runtime.skill_reauthorization je_auto_control.utils.agent_runtime.skill_recording je_auto_control.utils.agent_runtime.store je_auto_control.utils.agent_runtime.target_profiles -je_auto_control.utils.agent_runtime.targets je_auto_control.utils.agent_runtime.task_authority -je_auto_control.utils.agent_runtime.task_handoff je_auto_control.utils.agent_runtime.task_recovery je_auto_control.utils.agent_runtime.task_skills je_auto_control.utils.agent_runtime.task_triggers je_auto_control.utils.agent_runtime.transfer_evidence je_auto_control.utils.agent_runtime.transfer_evidence_contract -je_auto_control.utils.agent_runtime.transfer_evidence_management je_auto_control.utils.agent_runtime.transfer_host je_auto_control.utils.agent_runtime.transfer_import -je_auto_control.utils.agent_runtime.transfer_import_contract je_auto_control.utils.agent_runtime.transfer_import_files -je_auto_control.utils.agent_runtime.transfer_import_ledger je_auto_control.utils.agent_runtime.transfer_lineage -je_auto_control.utils.agent_runtime.transfer_management -je_auto_control.utils.agent_runtime.transfer_protocol je_auto_control.utils.agent_runtime.transfer_routing je_auto_control.utils.agent_runtime.transfer_selection je_auto_control.utils.agent_runtime.transfer_source je_auto_control.utils.agent_runtime.transfer_staging je_auto_control.utils.agent_runtime.transfer_transport -je_auto_control.utils.agent_runtime.trigger_config je_auto_control.utils.agent_runtime.trigger_reauthorization je_auto_control.utils.agent_runtime.verification je_auto_control.utils.agent_runtime.workflow_specs -je_auto_control.utils.dag.batch_contract -je_auto_control.utils.dag.batch_execution -je_auto_control.utils.dag.inspection -je_auto_control.utils.mcp_server.tools._discovery diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index e29aa4fc0..c54f654a7 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -14,117 +14,71 @@ # written later under the same name is new and therefore strict. # je_auto_control.android.client -je_auto_control.gui._auto_click_tab je_auto_control.gui._record_tab -je_auto_control.gui._script_tab -je_auto_control.gui.a11y_audit_tab -je_auto_control.gui.admin_console_tab -je_auto_control.gui.computer_use_tab je_auto_control.gui.dag_tab je_auto_control.gui.flow_editor.layout -je_auto_control.gui.flow_editor.scene -je_auto_control.gui.flow_editor.tab -je_auto_control.gui.language_wrapper.multi_language_wrapper -je_auto_control.gui.llm_planner_tab -je_auto_control.gui.ocr_tab -je_auto_control.gui.recording_editor_tab -je_auto_control.gui.remote_desktop._helpers je_auto_control.gui.remote_desktop.annotation_overlay je_auto_control.gui.remote_desktop.connection_screen -je_auto_control.gui.remote_desktop.viewer_panel je_auto_control.gui.remote_desktop.webrtc_dialogs je_auto_control.gui.remote_desktop.webrtc_known_hosts -je_auto_control.gui.remote_desktop.webrtc_panel -je_auto_control.gui.remote_desktop.webrtc_workers -je_auto_control.gui.script_builder.step_model je_auto_control.gui.triggers_tab -je_auto_control.gui.usb_browser_tab -je_auto_control.gui.usb_devices_tab -je_auto_control.gui.usb_passthrough_panel je_auto_control.gui.vlm_tab je_auto_control.ios.client -je_auto_control.linux_wayland.keyboard je_auto_control.linux_wayland.libei je_auto_control.linux_with_x11.listener.x11_linux_listener je_auto_control.utils.accessibility.accessibility_api -je_auto_control.utils.accessibility.backends.macos_backend je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.accessibility.backends.windows_query je_auto_control.utils.accessibility.backends.windows_reads -je_auto_control.utils.accessibility.backends.windows_state je_auto_control.utils.actionability.actionability -je_auto_control.utils.agent.agent_loop je_auto_control.utils.barcode.barcode je_auto_control.utils.callback.callback_function_executor -je_auto_control.utils.clipboard.clipboard je_auto_control.utils.codegen.codegen je_auto_control.utils.color_match.color_match je_auto_control.utils.color_region.color_region -je_auto_control.utils.cv2_utils.screen_record -je_auto_control.utils.dag.runner je_auto_control.utils.edge_lines.edge_lines je_auto_control.utils.edge_match.edge_match je_auto_control.utils.executor.action_executor -je_auto_control.utils.executor.action_schema je_auto_control.utils.executor.flow_control je_auto_control.utils.feature_match.feature_match -je_auto_control.utils.gamepad._facade je_auto_control.utils.grid_locator.grid_locator je_auto_control.utils.grounding_consensus.grounding_consensus je_auto_control.utils.hotkey.backends.linux_backend -je_auto_control.utils.hotkey.backends.macos_backend je_auto_control.utils.hsv_segment.hsv_segment -je_auto_control.utils.http_client.http_client je_auto_control.utils.image_quality.image_quality je_auto_control.utils.img_histogram.img_histogram je_auto_control.utils.input_macro.input_macro je_auto_control.utils.input_macro.recorder_base -je_auto_control.utils.json_contract.json_contract -je_auto_control.utils.json_patch.json_patch je_auto_control.utils.json_schema.json_schema je_auto_control.utils.logging.logging_instance je_auto_control.utils.match_autothresh.match_autothresh je_auto_control.utils.match_ensemble.match_ensemble je_auto_control.utils.match_stability.match_stability je_auto_control.utils.match_trust.match_trust -je_auto_control.utils.mcp_server.server je_auto_control.utils.mcp_server.tools._handlers je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations je_auto_control.utils.mcp_server.tools._handlers_system je_auto_control.utils.message_format.message_format je_auto_control.utils.motion_regions.motion_regions -je_auto_control.utils.observability.tracing -je_auto_control.utils.ocr.backends.easyocr_backend -je_auto_control.utils.ocr.backends.paddleocr_backend je_auto_control.utils.perceptual_diff.perceptual_diff -je_auto_control.utils.postcondition.postcondition je_auto_control.utils.preprocess.preprocess -je_auto_control.utils.rate_limit.rate_limit je_auto_control.utils.recording_edit.editor je_auto_control.utils.remote_desktop.address_book -je_auto_control.utils.remote_desktop.audio je_auto_control.utils.remote_desktop.host je_auto_control.utils.remote_desktop.host_service je_auto_control.utils.remote_desktop.hw_codec je_auto_control.utils.remote_desktop.lan_discovery je_auto_control.utils.remote_desktop.multi_viewer -je_auto_control.utils.remote_desktop.signaling_client je_auto_control.utils.remote_desktop.signaling_server -je_auto_control.utils.remote_desktop.webrtc_audio je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host -je_auto_control.utils.remote_desktop.webrtc_host_media je_auto_control.utils.remote_desktop.webrtc_stats je_auto_control.utils.remote_desktop.webrtc_transport je_auto_control.utils.remote_desktop.webrtc_viewer -je_auto_control.utils.rest_api.rest_server je_auto_control.utils.rotated_match.rotated_match -je_auto_control.utils.run_diff.run_diff je_auto_control.utils.saliency.saliency je_auto_control.utils.scale_detect.scale_detect -je_auto_control.utils.schema_compat.schema_compat -je_auto_control.utils.screen_state.screen_state je_auto_control.utils.secrets.secret_store je_auto_control.utils.shape_locator.shape_locator je_auto_control.utils.shell_process.shell_exec @@ -134,14 +88,10 @@ je_auto_control.utils.table_grid_fill.table_grid_fill je_auto_control.utils.text_regions.text_regions je_auto_control.utils.tool_use_schema.schema je_auto_control.utils.triggers.email_trigger -je_auto_control.utils.triggers.webhook_server je_auto_control.utils.usb.passthrough.acl -je_auto_control.utils.usbip.libusb_backend je_auto_control.utils.vision.backends.anthropic_backend je_auto_control.utils.vision.backends.openai_backend je_auto_control.utils.visual_match.visual_match -je_auto_control.utils.visual_regression.compare -je_auto_control.windows.message.window_message je_auto_control.windows.record.win32_input_hook je_auto_control.wrapper.auto_control_keyboard je_auto_control.wrapper.backend_contract From 739f18ca0b82cac10cfb77e3749f4cd1d8ff4bab Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 13:31:46 +0800 Subject: [PATCH 126/161] Annotate 57 modules and hold 52 more to the strict typing tier These had seven to ten missing annotations or bare generics each. The unscoped ignores on optional backend imports go: the forced-Any override already covers those modules. --- Progress.md | 2 +- architecture_explore.md | 106 ++++++++--------- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + je_auto_control/gui/_record_tab.py | 23 ++-- je_auto_control/gui/flow_editor/layout.py | 4 +- .../gui/remote_desktop/annotation_overlay.py | 20 ++-- .../gui/remote_desktop/connection_screen.py | 18 +-- .../gui/remote_desktop/webrtc_known_hosts.py | 24 ++-- je_auto_control/gui/triggers_tab.py | 25 ++-- .../listener/x11_linux_listener.py | 22 ++-- .../accessibility/backends/windows_query.py | 16 +-- .../accessibility/backends/windows_reads.py | 21 ++-- .../utils/agent_runtime/android_hierarchy.py | 16 +-- .../utils/agent_runtime/browser_target.py | 18 +-- .../agent_runtime/dag_continuation_plan.py | 18 +-- .../agent_runtime/dag_transfer_checks.py | 15 +-- .../utils/agent_runtime/dag_transfer_stop.py | 17 +-- .../utils/agent_runtime/handoff_records.py | 21 ++-- .../utils/agent_runtime/native_target.py | 14 +-- .../utils/agent_runtime/observation_refs.py | 22 ++-- .../utils/agent_runtime/presence_frames.py | 18 +-- .../utils/agent_runtime/presence_windows.py | 15 +-- .../utils/agent_runtime/remote_journal.py | 16 +-- .../utils/agent_runtime/remote_worker.py | 20 ++-- .../utils/agent_runtime/retained_browser.py | 16 +-- .../agent_runtime/retained_browser_target.py | 16 +-- .../utils/agent_runtime/skill_recording.py | 18 +-- je_auto_control/utils/agent_runtime/store.py | 19 ++-- .../utils/agent_runtime/target_profiles.py | 20 ++-- .../transfer_evidence_contract.py | 18 +-- .../agent_runtime/transfer_import_files.py | 20 ++-- .../utils/agent_runtime/transfer_routing.py | 19 ++-- .../utils/agent_runtime/transfer_selection.py | 16 +-- .../utils/agent_runtime/transfer_staging.py | 16 +-- .../utils/agent_runtime/transfer_transport.py | 22 ++-- .../agent_runtime/trigger_reauthorization.py | 19 ++-- .../utils/agent_runtime/verification.py | 16 +-- .../callback/callback_function_executor.py | 15 +-- .../utils/executor/flow_control.py | 17 +-- .../utils/hotkey/backends/linux_backend.py | 17 +-- .../utils/input_macro/input_macro.py | 15 +-- .../utils/input_macro/recorder_base.py | 21 ++-- .../utils/perceptual_diff/perceptual_diff.py | 19 ++-- .../utils/remote_desktop/address_book.py | 18 +-- je_auto_control/utils/remote_desktop/host.py | 22 ++-- .../utils/remote_desktop/host_service.py | 30 ++--- .../utils/remote_desktop/lan_discovery.py | 20 ++-- .../utils/remote_desktop/webrtc_stats.py | 19 ++-- .../utils/remote_desktop/webrtc_transport.py | 25 ++-- je_auto_control/utils/secrets/secret_store.py | 23 ++-- .../utils/shell_process/shell_exec.py | 19 ++-- .../utils/triggers/email_trigger.py | 23 ++-- je_auto_control/utils/usb/passthrough/acl.py | 18 +-- .../windows/record/win32_input_hook.py | 16 +-- .../wrapper/auto_control_keyboard.py | 16 +-- .../wrapper/window_backends/x11_backend.py | 22 ++-- pyproject.toml | 107 +++++++++--------- test/verify/typing_not_yet_strict.txt | 25 ---- test/verify/typing_strict_baseline.txt | 27 ----- 60 files changed, 639 insertions(+), 630 deletions(-) diff --git a/Progress.md b/Progress.md index 6993a2980..5d854d055 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~08,共 1,392 個)。仍缺:`test/verify/typing_strict_baseline.txt` 84 個與 `typing_not_yet_strict.txt` 48 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`(三平台約 1,600 個錯誤,集中在 109 個檔案,大多是每檔 7 個以上,最多的是 MCP handler 模組與 `action_executor.py`;其中 24 個影像/定位模組只差模組層級的 `ImageSource = Any` 之類的別名,要先定一個共用型別;另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`)),以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~09,共 1,444 個)。仍缺:`test/verify/typing_strict_baseline.txt` 57 個與 `typing_not_yet_strict.txt` 23 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:43 個每檔 11 個以上錯誤的大檔(三平台約 1,150 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),25 個影像/定位模組只差模組層級的 `ImageSource = Any` 之類的別名(要先定一個共用型別),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 4421ea024..03f7b536e 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,544 | -| 程式碼總行數 | 237,784 | +| 程式碼總行數 | 237,841 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -198,7 +198,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `wrapper/auto_control_image.py` | 89 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | | `wrapper/auto_control_record.py` | 124 | 錄製 API:`record`/`stop_record`/`record_to_json`(支援 stop event 與逾時)。 | | `wrapper/auto_control_window.py` | 338 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | -| `wrapper/window_backends/` | 1,149 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | +| `wrapper/window_backends/` | 1,153 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | ### 5.3 平台後端 @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,557 行。 +> 25 個套件、約 19,562 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -304,9 +304,9 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,755 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,756 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | -| `utils/input_macro/` | 477 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | +| `utils/input_macro/` | 481 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | | `utils/json_store/` | 281 | JSON 字典檔持久化的共用小工具(內部管線) | | `utils/loop_guard/` | 158 | 機械式卡死迴圈偵測(agent loop 用) | @@ -324,11 +324,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,864 行。 +> 15 個套件、約 4,866 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `utils/callback/` | 214 | Observer 模式:`callback_executor` 以字串名觸發功能;trigger 與 callback 共用秘密遮罩至錯誤處理結束 | +| `utils/callback/` | 215 | Observer 模式:`callback_executor` 以字串名觸發功能;trigger 與 callback 共用秘密遮罩至錯誤處理結束 | | `utils/config_bundle/` | 424 | 使用者設定的單檔匯出/匯入 | | `utils/critical_exit/` | 132 | 監看緊急停止鍵的守護執行緒,用於中止失控腳本 | | `utils/diagnostics/` | 358 | 跨子系統的「一切正常嗎」健檢,附 `python -m` 進入點 | @@ -341,23 +341,23 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | | `utils/process_memory/` | 1,063 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測與失敗 handle 回收;檔案證據不等於載入程式碼身分,可信啟動及 runtime 整合待完成 | -| `utils/shell_process/` | 279 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | +| `utils/shell_process/` | 280 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | ### 5.4.3 排程、觸發與背景監看 -> 11 個套件、約 4,398 行。 +> 11 個套件、約 4,400 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `utils/hotkey/` | 866 | 全域熱鍵守護行程,把 OS 層熱鍵綁到 action 檔(Win/macOS/X11 三後端) | +| `utils/hotkey/` | 867 | 全域熱鍵守護行程,把 OS 層熱鍵綁到 action 檔(Win/macOS/X11 三後端) | | `utils/idle_keepawake/` | 245 | 偵測使用者閒置時間並在無人值守執行期間阻止系統睡眠 | | `utils/lock_session/` | 167 | 鎖定工作站、等待解鎖並分類鎖定狀態轉換 | | `utils/observer/` | 256 | 反應式畫面觀察者;每條規則涵蓋 predicate/handler 的秘密遮罩與隔離 | | `utils/recurrence/` | 470 | RFC 5545 重複規則解析與發生時間展開 | | `utils/scheduler/` | 503 | 間隔式與 cron 式的 action JSON 排程器 | | `utils/session_guard/` | 62 | 驅動輸入前先偵測工作階段是否已鎖定/非互動 | -| `utils/triggers/` | 1,408 | 事件驅動觸發引擎:影像/視窗/像素/檔案/webhook/IMAP 郵件 | +| `utils/triggers/` | 1,409 | 事件驅動觸發引擎:影像/視窗/像素/檔案/webhook/IMAP 郵件 | | `utils/voice/` | 99 | 語音指令路由:把辨識到的語句對應到 `AC_*` action list | | `utils/watchdog/` | 232 | 背景彈窗/中斷看門狗;每條規則涵蓋 matcher/action 與錯誤日誌的秘密遮罩 | | `utils/watcher/` | 90 | 無頭輪詢原語:滑鼠位置、像素顏色、log tail | @@ -393,7 +393,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,571 行。 +> 37 個套件、約 6,572 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -419,7 +419,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/match_trust/` | 155 | 樣板比對可信度評分(次峰比 + peak-to-sidelobe) | | `utils/monitor_layout/` | 558 | 多螢幕/虛擬桌面幾何(在哪個螢幕、位置、重映射)+ `logical_frame` 以滑鼠座標空間擷取畫面 | | `utils/motion_regions/` | 78 | 兩影格間的局部變化/活動偵測(absdiff) | -| `utils/perceptual_diff/` | 202 | 感知式(YIQ)影像差異,抑制反鋸齒邊緣誤報 | +| `utils/perceptual_diff/` | 203 | 感知式(YIQ)影像差異,抑制反鋸齒邊緣誤報 | | `utils/preprocess/` | 276 | OCR/比對前的影像前處理(灰階、二值化、去傾斜…) | | `utils/qr/` | 59 | 從影像或螢幕區域解碼 QR code(OpenCV) | | `utils/rotated_match/` | 203 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | @@ -463,12 +463,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,925 行。 +> 16 個套件、約 4,926 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a11y_audit/` | 362 | 以無障礙樹 + OCR 進行無障礙與 i18n 稽核 | -| `utils/accessibility/` | 3,374 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | +| `utils/accessibility/` | 3,375 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | | `utils/ax_text/` | 105 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | @@ -516,13 +516,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 52,980 行。 +> 14 個套件、約 53,003 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,254 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 25,979 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 26,002 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,239 行。 +> 6 個套件、約 32,245 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,911 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,917 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,752 行。 +> 13 個套件、約 4,757 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -678,7 +678,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | -| `utils/secrets/` | 371 | 加密機密儲存庫,供 `${secrets.NAME}` 解析 | +| `utils/secrets/` | 376 | 加密機密儲存庫,供 `${secrets.NAME}` 解析 | | `utils/secrets_scan/` | 138 | 掃描 action JSON/資料中應入庫卻硬編碼的機密 | | `utils/vex/` | 178 | OpenVEX 陳述撰寫與漏洞分類處置 | | `utils/vuln_scan/` | 276 | 以 OSV 比對 SBOM 元件的漏洞(純標準庫) | @@ -744,12 +744,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | | `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,755 行)— 執行核心 +#### `utils/executor/`(10,756 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `action_executor.py` | 8,679 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | -| `flow_control.py` | 726 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | +| `flow_control.py` | 727 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | | `flow_data_commands.py` | 275 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | | `action_schema.py` | 225 | action list 的結構驗證:形狀、參數型別、未知指令拒絕。單一走訪同時支援兩種消費方式:`validate_actions()` 遇到第一個問題就拋、`unknown_command_names()` 收齊全部不認得的名字(REST `/execute` 用它回 400)。 | | `action_redaction.py` | 196 | 記錄與紀錄鍵用的遮蔽:`AC_secret_*` 的參數(金庫通行碼、機密值)在寫進 log、當成結果紀錄的鍵之前換成 `***`,巢狀在區塊指令裡的也一樣。 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,911 行/77 檔) +#### `utils/remote_desktop/`(16,917 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -831,12 +831,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_retirement.py` | 186 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | | `webrtc_media_owners.py` | 249 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | | `webrtc_peer_cleanup.py` | 166 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | -| `host.py` | 700 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | +| `host.py` | 702 | TCP 主機:接受迴圈、TLS 包裝、連線/認證握手、音訊與剪貼簿廣播、檔案推送、單次 token。 | | `viewer.py` | 748 | TCP 檢視端。 | | `host_service.py` | 561 | 無頭 WebRTC 主機執行器 + 多平台服務安裝器。 | | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | -| `webrtc_transport.py` | 421 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | +| `webrtc_transport.py` | 422 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | | `multi_viewer.py` | 519 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | @@ -863,7 +863,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 258 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | | `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | -| `webrtc_stats.py` | 223 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | +| `webrtc_stats.py` | 226 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | | `adaptive_bitrate.py` | 151 | 依統計調整主機擷取 FPS。 | | `signaling_client.py` | 194 | 純標準庫的訊令用戶端。 | @@ -1045,7 +1045,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(25,979 行/182 檔) +#### `utils/agent_runtime/`(26,002 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1087,7 +1087,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `dag_batches.py` | 366 | Owner-scoped graph lifecycle and runtime-owned task/artifact host adapters. | | `dag_continuation.py` | 339 | Whole-graph review and one-shot continuation approval never replay a possible delivery. | | `dag_continuation_evidence.py` | 169 | Bounded read-only destination evidence for explicit whole-batch continuation decisions. | -| `dag_continuation_plan.py` | 89 | Explicit per-node decisions preserve graph scope and never reset a possible delivery claim. | +| `dag_continuation_plan.py` | 91 | Explicit per-node decisions preserve graph scope and never reset a possible delivery claim. | | `dag_jobs.py` | 140 | Service-owned durable DAG deliveries never replay an interrupted coordinator attempt. | | `dag_local.py` | 98 | Closed local-node transport admits claimed DAG work under the original owner's authority. | | `dag_retention.py` | 127 | Expire settled DAG records while retaining unresolved input and referenced recovery evidence. | @@ -1101,7 +1101,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `evidence_handoff.py` | 368 | Explicit revocable evidence-only grants preserve ordinary task ownership and input isolation. | | `file_dialog_scope.py` | 62 | Bind the existing file-dialog executor to one task-owned window and rooted absolute path. | | `file_target.py` | 35 | A noninteractive target for rooted archive workflows, separate from desktop input. | -| `handoff_records.py` | 115 | Fixed-family handoff records and host-only access to explicitly granted evidence. | +| `handoff_records.py` | 116 | Fixed-family handoff records and host-only access to explicitly granted evidence. | | `helper_environment.py` | 56 | Host-reviewed browser Python environments and bounded owned dependency-probe helpers. | | `helper_owner_linux.py` | 452 | Linux owner-service channel: one lease per helper, relayed JSON lines, fenced close. | | `images.py` | 42 | Bounded redacted JPEG validation is shared by point grounding, previews and persistence. | @@ -1119,7 +1119,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `native_scope.py` | 111 | Scope native window and control targets before their existing backend performs an action. | | `native_target.py` | 310 | Native desktop proxy with private IPC, host input ledger and cross-database ownership. | | `native_worker.py` | 349 | Private native helper entry point; stdout is a bounded owner-only JSON protocol. | -| `observation_refs.py` | 151 | Resolve observation-local elements and thumbnail points into host-checked native coordinates. | +| `observation_refs.py` | 155 | Resolve observation-local elements and thumbnail points into host-checked native coordinates. | | `ollama.py` | 82 | Local-only Ollama decisions over bounded HTTP, without an SDK or remote fallback. | | `origin_policy.py` | 193 | Live origin path ceilings remain restrictive across accepted tasks, workers and service processes. | | `owned_channel_factory.py` | 203 | Choose each helper's owned channel: local pipes, or the Linux owner service the host bound. | @@ -1153,7 +1153,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence_platform.py` | 67 | Pick the physical presence API for this helper's platform; a platform without a trusted source refuses. | | `presence_quartz.py` | 165 | macOS physical presence: a listen-only session event tap that counts hardware events, plus console lock state. | | `presence_win32.py` | 255 | Header-only Raw Input observation in the dedicated helper, with fresh supported-console checks. | -| `presence_windows.py` | 254 | Fresh bounded source actor with retained native resources, independent of input-helper lifetimes. | +| `presence_windows.py` | 255 | Fresh bounded source actor with retained native resources, independent of input-helper lifetimes. | | `presence_x11.py` | 185 | X11 physical presence: XInput2 raw events from real devices, never from XTEST, plus logind lock state. | | `presence_worker.py` | 88 | Fixed contained source child; bootstrap and endpoint ownership precede observation. | | `readonly_target.py` | 157 | Fresh isolated completion observations with live scope checks and permanent no-input helper contracts. | @@ -1177,8 +1177,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `skill_execution.py` | 110 | Exact original skill effects across real reviewed recovery, without granting input or replacing trials. | | `skill_parameters.py` | 110 | Explicit typed parameter slots modify data values without widening a skill's authority. | | `skill_reauthorization.py` | 107 | Review origin renewal into a new immutable candidate without inheriting skill publication. | -| `skill_recording.py` | 105 | Semantic skill drafts retain verified actions, original scope and independent completion evidence. | -| `store.py` | 431 | Transactional task metadata, durable action receipts and input ownership. | +| `skill_recording.py` | 107 | Semantic skill drafts retain verified actions, original scope and independent completion evidence. | +| `store.py` | 432 | Transactional task metadata, durable action receipts and input ownership. | | `submission.py` | 40 | Admission witnesses bind tagged DAG requests before live scope normalization, without granting authority. | | `target_config.py` | 198 | Immutable host-reviewed target configuration, distinct from untrusted task options. | | `target_continuity.py` | 16 | Require a live UI target context before trusting a finite skill's verified prefix. | @@ -1204,17 +1204,17 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `transfer_models.py` | 191 | Portable criterion selections and immutable descriptors for reviewed outcome transfers. | | `transfer_privacy.py` | 53 | Exclude actual host private stores and evidence roots without reserving ordinary output basenames. | | `transfer_protocol.py` | 171 | Runtime-owned transfer serialization coordinates source consent and service-owned destination imports. | -| `transfer_transport.py` | 147 | Bounded source reads and management replies use an injected adapter without foreign task authority. | +| `transfer_transport.py` | 151 | Bounded source reads and management replies use an injected adapter without foreign task authority. | | `transfer_management.py` | 103 | Closed management envelopes validate foreign source and destination replies before retaining consent. | | `transfer_evidence_management.py` | 85 | Closed management projections validate portable evidence consent without importing foreign authority. | -| `transfer_routing.py` | 133 | Coordinator-owned routed consent persists exact approval before forwarding source or destination creation. | +| `transfer_routing.py` | 136 | Coordinator-owned routed consent persists exact approval before forwarding source or destination creation. | | `transfer_records.py` | 292 | Private transfer reservations bind consent and retain capacity until owned cleanup is confirmed. | -| `transfer_selection.py` | 134 | Resolve only source-owned passed file criteria and their explicitly selected manifest names. | +| `transfer_selection.py` | 136 | Resolve only source-owned passed file criteria and their explicitly selected manifest names. | | `transfer_source.py` | 273 | Explicitly reviewed source artifacts publish immutable blobs under live host-derived authority. | | `transport.py` | 128 | Bounded HTTP requests; cancellation discards late inference replies before any input. | | `trigger_config.py` | 69 | Validate durable trigger schedules and rooted file-version notifications without side effects. | | `trigger_history.py` | 89 | Renewed trigger lineages share accepted event tombstones and outstanding-task limits. | -| `trigger_reauthorization.py` | 149 | Explicitly replace a trigger's unavailable origins while retaining its event history and template. | +| `trigger_reauthorization.py` | 150 | Explicitly replace a trigger's unavailable origins while retaining its event history and template. | | `trigger_registration.py` | 21 | Insert normal and explicitly renewed trigger templates through one bounded transaction contract. | | `verification.py` | 153 | Deterministic completion evidence with explicit passed, failed and unknown states. | | `window_pixels.py` | 118 | Capture only an identified Windows window, with no desktop-pixel fallback. | @@ -1325,7 +1325,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `_screenshot_tab.py` | 180 | 獨立延遲建立的截圖/像素分頁;背景讀取、輸入快照與關閉後結果丟棄。 | | `_image_detect_tab.py` | 158 | 獨立影像偵測分頁,擁有輸入、背景工作與關閉生命週期。 | | `_script_tab.py` | 183 | 獨立腳本執行分頁;背景載入與執行,關閉取消並釋放控制項。 | -| `_record_tab.py` | 166 | 獨立錄製/回放檢視;背景工作與共享錄製器狀態,關閉檢視不停止錄製器。 | +| `_record_tab.py` | 167 | 獨立錄製/回放檢視;背景工作與共享錄製器狀態,關閉檢視不停止錄製器。 | | `_report_tab.py` | 106 | 報表分頁 mixin。 | | `_i18n_helpers.py` | 79 | 需要即時語言切換的分頁共用的翻譯註冊 mixin。 | | `_validators.py` | 29 | `int_validator()`/`double_validator()`:以 C locale 驗證的數字輸入框 validator,接受的正是 `int()`/`float()` 讀得懂的寫法(預設 locale 在法文、德文下只收小數逗號)。所有數字 `QLineEdit` 都用它。 | @@ -1355,7 +1355,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | auto_click | `_auto_click_tab.py` | 321 | 自動點擊:座標、間隔、熱鍵、`write`、捲動。 | | screenshot | `_screenshot_tab.py` | 180 | 截圖、選區、螢幕尺寸、取像素色。 | | image_detect | `_image_detect_tab.py` | 158 | 樣板裁切、定位、定位全部、定位並點擊。 | -| record | `_record_tab.py` | 166 | 錄製/停止/回放/存檔/載入。 | +| record | `_record_tab.py` | 167 | 錄製/停止/回放/存檔/載入。 | | script_builder | `script_builder/` | 6,957 | **視覺化腳本編輯器**:`command_schema.py`(5,551 行 `AC_*` 參數綱要)、`step_model.py`(步驟模型與 AC JSON 序列化)、`step_list_view.py`(含巢狀 body 的樹狀檢視)、`step_form_view.py`(綱要驅動表單)、`builder_tab.py`(含日誌候選預覽與明確匯入,保留來源)。 | | flow_editor | `flow_editor/` | 498 | 節點式流程圖檢視:`layout.py`(純 Python 佈局演算法,可單測)、`scene.py`(Qt 場景繪製)、`tab.py`。 | | script | `_script_tab.py` | 183 | 載入/執行單檔或整個目錄、內建編輯器執行。 | @@ -1372,7 +1372,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | agent_tasks | `agent_tasks_tab.py` | 618 | 受管任務輸入、狀態與 Actions menu;服務獨立於視圖生命週期。 | | scheduler | `scheduler_tab.py` | 175 | 註冊間隔式 action JSON 執行。 | | hotkeys | `hotkeys_tab.py` | 167 | 將全域熱鍵綁到 action 檔。 | -| triggers | `triggers_tab.py` | 401 | 影像/視窗/像素/檔案事件監看。 | +| triggers | `triggers_tab.py` | 402 | 影像/視窗/像素/檔案事件監看。 | | webhooks | `webhooks_tab.py` | 222 | 將 HTTP 請求綁到 action 腳本。 | | email_triggers | `email_triggers_tab.py` | 254 | 將 IMAP 信箱綁到 action 腳本。 | | test_suite | `test_suite_tab.py` | 201 | 執行 QA 套件規格並管理易碎隔離區。 | @@ -1391,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,567 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,573 | 見下。 | | presence | `presence_tab.py` | 171 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,567 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,573 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1426,7 +1426,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | | `connection_screen.py` | 723 | Quick Connect —— AnyDesk 風格單畫面入口。 | | `viewer_panel.py` | 617 | 「控制另一台機器」子分頁。 | -| `webrtc_known_hosts.py` | 339 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | +| `webrtc_known_hosts.py` | 345 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | | `host_panel.py` | 396 | 「分享這台機器」子分頁。 | | `_host_ops.py` | 39 | Start and stop the machine's remote-desktop host on a worker thread. Host 面板與 Quick Connect 共用的 `replace_host`/`stop_host`/`release_host`。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | @@ -1549,28 +1549,28 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,919 | +| `gui/` | 166 | 43,927 | | `utils/mcp_server/` | 63 | 22,241 | -| `utils/remote_desktop/` | 77 | 16,911 | -| `utils/executor/` | 11 | 10,755 | +| `utils/remote_desktop/` | 77 | 16,917 | +| `utils/executor/` | 11 | 10,756 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | -| `utils/accessibility/` | 16 | 3,374 | -| `wrapper/` | 25 | 6,046 | +| `utils/accessibility/` | 16 | 3,375 | +| `wrapper/` | 25 | 6,050 | | `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,228 | | `utils/agent/` | 13 | 2,254 | | `linux_with_x11/` | 19 | 1,382 | | `linux_wayland/` | 24 | 4,448 | -| `utils/triggers/` | 4 | 1,408 | +| `utils/triggers/` | 4 | 1,409 | | `utils/ocr/` | 10 | 1,393 | | `utils/usbip/` | 5 | 1,008 | | `utils/assertion/` | 3 | 888 | | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | -| `utils/hotkey/` | 7 | 866 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,586 | -| **總計** | **1,532** | **237,039** | +| `utils/hotkey/` | 7 | 867 | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,621 | +| **總計** | **1,532** | **237,096** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index b4b48b7e1..068e89446 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -705,3 +705,11 @@ - **Tests:** mypy with both flags: 1,613 / 1,605 / 1,605 errors in 109 / 108 / 108 files (win32 / linux / darwin), from 2,060 / 2,052 / 2,052 in 198 / 197 / 197, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; headless tests of the touched modules 402 passed, 1 skipped, and the input-backend and device audits 34 passed, 3 skipped; doc, file-length and complexity gates 41 passed. - **Files:** 89 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. - **Open items:** `Progress.md` › H (132 modules still outside the tier). + +## U-20261115-09 · 2026-11-15 · 52 more modules join the strict typing tier (seven to ten fixes each) · #done #typing + +- **What:** the next stage of `Progress.md` › H: the 53 files with seven to ten strict errors (430 in all). +- **Change:** annotation-only edits in all 53, by the rules of U-20261115-06 to -08. Choices worth knowing: `secret_store._fernet` is declared `Optional["Fernet"]` (Fernet under `TYPE_CHECKING`, as `action_signing/cipher.py` does), which removes its `# type: ignore[assignment]`; `connection_screen._viewer_callbacks` returns `dict[str, Any]` because it is unpacked as keyword arguments into a constructor with differently typed parameters; `auto_control_keyboard`'s `key_code_list` is `Sequence[int | str]` (a `list[str]` caller fails `--extras` against `list[int | str]`); new private aliases `NodePath`, `_LegacyAction`, `_Validator` and `_T` TypeVars, none bound to `Any`; `shell_exec` uses `Popen[bytes]` / `CompletedProcess[bytes]`. The contract's AST check then asked for more: `-> None` on `ShellManager.__init__` and the two X11 listener constructors, and the bare `# type: ignore`s on the pywin32, `mss`, Quartz and Xlib imports in `host_service.py` and `webrtc_transport.py` go (the forced-`Any` override already covers them); `host_service`'s `_WindowsService = None` keeps one ignore scoped to `[misc, assignment]` where the class exists (win32), and the other branch needs none (checked with `--warn-unused-ignores` on all three platforms). 52 modules are promoted (strict tier 1,392 → 1,444; baseline 84 → 57, not-yet-strict 48 → 23); `perceptual_diff` aliases `ImageSource = Any` and stays out (25 in all). +- **Tests:** mypy with both flags: 1,154 errors in 56 files on each of win32 / linux / darwin, from 1,613 / 1,605 / 1,605 in 109 / 108 / 108, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; headless tests of the touched modules (accessibility, flow editor, triggers, remote desktop, agent runtime, callback, flow control, hotkey, shell, X11): every run passed, and the host-service, installer, WebRTC-transport and shell tests 79 passed after the follow-up edits; doc, file-length and complexity gates 41 passed. +- **Files:** 57 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. +- **Open items:** `Progress.md` › H (80 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index 4a5366dab..89915f8b3 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-09 | 2026-11-15 | 52 more modules join the strict typing tier (seven to ten fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-08 | 2026-11-15 | 83 more modules join the strict typing tier (four to six fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-07 | 2026-11-15 | 127 more modules join the strict typing tier (two or three fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-06 | 2026-11-15 | 143 more modules join the strict typing tier after one-line fixes | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_record_tab.py b/je_auto_control/gui/_record_tab.py index 46ff328ea..bdb4b2b41 100644 --- a/je_auto_control/gui/_record_tab.py +++ b/je_auto_control/gui/_record_tab.py @@ -6,8 +6,9 @@ import functools import json -from typing import Callable +from typing import Any, Callable, Optional +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QFileDialog, QLabel, QMessageBox, QTextEdit, QVBoxLayout, QWidget, ) @@ -30,7 +31,7 @@ def _t(key: str) -> str: return language_wrapper.translate(key, key) -def _play_actions(actions: list) -> object: +def _play_actions(actions: list[Any]) -> object: """Worker thread: replay a recording.""" return execute_action(actions) @@ -43,10 +44,10 @@ def _start_recording() -> None: class RecordTab(TranslatableMixin, QWidget): """Owns playback and view state; the shared recorder outlives this page.""" - def __init__(self, parent=None): + def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._tr_init() - self._record_data: list = [] + self._record_data: list[Any] = [] layout = QVBoxLayout(self) layout.setSpacing(12) @@ -95,7 +96,7 @@ def sync_with_engine(self) -> None: ) self._apply_record_status_label() - def showEvent(self, event) -> None: + def showEvent(self, event: QShowEvent) -> None: self.sync_with_engine() super().showEvent(event) @@ -103,10 +104,10 @@ def _start_work(self, work: Callable[[], object], *, tag: str = "") -> None: self._work.start(work, tag=tag) self.sync_with_engine() - def _start_record(self): + def _start_record(self) -> None: self._start_work(_start_recording, tag="start") - def _stop_record(self): + def _stop_record(self) -> None: self._start_work(stop_record, tag="data") def _on_result(self, result: object) -> None: @@ -114,7 +115,7 @@ def _on_result(self, result: object) -> None: self._record_data = result self.record_list_text.setText(json.dumps(result, indent=2, ensure_ascii=False)) - def _playback_record(self): + def _playback_record(self) -> None: if not self._record_data: QMessageBox.warning(self, "Warning", "No recorded data") return @@ -137,7 +138,7 @@ def _on_playback_error(self, error: object) -> None: def _on_playback_finished(self) -> None: self.sync_with_engine() - def _save_record(self): + def _save_record(self) -> None: try: if not self._record_data: QMessageBox.warning(self, "Warning", "No recorded data") @@ -148,7 +149,7 @@ def _save_record(self): except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: QMessageBox.warning(self, "Error", str(error)) - def _load_record(self): + def _load_record(self) -> None: try: path, _ = QFileDialog.getOpenFileName(self, _t("load_record"), "", _JSON_FILE_FILTER) if path: @@ -156,7 +157,7 @@ def _load_record(self): except (AutoControlException, OSError, ValueError, TypeError, RuntimeError) as error: QMessageBox.warning(self, "Error", str(error)) - def menu_actions(self) -> list[tuple[str, Callable]]: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: return [("start_record", self._start_record), ("stop_record", self._stop_record), ("playback", self._playback_record), ("stop_playback", self._stop_playback), ("save_record", self._save_record), ("load_record", self._load_record)] diff --git a/je_auto_control/gui/flow_editor/layout.py b/je_auto_control/gui/flow_editor/layout.py index fb354b7bf..e62dddbb6 100644 --- a/je_auto_control/gui/flow_editor/layout.py +++ b/je_auto_control/gui/flow_editor/layout.py @@ -9,7 +9,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import Dict, List, Tuple +from typing import Dict, List, Tuple, Union from je_auto_control.gui.script_builder.step_model import Step @@ -20,7 +20,7 @@ V_GAP = 30.0 # Path = tuple of (step_index | (body_key, child_index), ...) -NodePath = Tuple +NodePath = Tuple[Union[int, Tuple[str, int]], ...] @dataclass(frozen=True) diff --git a/je_auto_control/gui/remote_desktop/annotation_overlay.py b/je_auto_control/gui/remote_desktop/annotation_overlay.py index 51899ac51..b7f0f7888 100644 --- a/je_auto_control/gui/remote_desktop/annotation_overlay.py +++ b/je_auto_control/gui/remote_desktop/annotation_overlay.py @@ -12,10 +12,10 @@ from __future__ import annotations import math -from typing import List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple from PySide6.QtCore import QPointF, Qt -from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPen, QPolygonF +from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPaintEvent, QPen, QPolygonF from PySide6.QtWidgets import QWidget from je_auto_control.gui._screen_geometry import logical_point, screen_at_native @@ -28,7 +28,7 @@ _DEFAULT_WIDTH = 3 -def _point(event: dict) -> Optional[Tuple[float, float]]: +def _point(event: Dict[str, Any]) -> Optional[Tuple[float, float]]: """The event's finite (x, y), or ``None``.""" try: x, y = float(event.get("x", 0)), float(event.get("y", 0)) @@ -37,7 +37,7 @@ def _point(event: dict) -> Optional[Tuple[float, float]]: return (x, y) if math.isfinite(x) and math.isfinite(y) else None -def _origin(value) -> Tuple[int, int]: +def _origin(value: Any) -> Tuple[int, int]: """The host-stamped frame origin; (0, 0) when missing or malformed.""" try: x, y = value @@ -46,7 +46,7 @@ def _origin(value) -> Tuple[int, int]: return 0, 0 -def _width(value) -> int: +def _width(value: Any) -> int: """A pen width between 1 and ``_MAX_WIDTH``.""" try: return min(_MAX_WIDTH, max(1, int(value or _DEFAULT_WIDTH))) @@ -67,8 +67,8 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents) self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating) - self._strokes: List[dict] = [] - self._current: Optional[dict] = None + self._strokes: List[Dict[str, Any]] = [] + self._current: Optional[Dict[str, Any]] = None # The primary screen until a point lands on another one. self._target = QGuiApplication.primaryScreen() if self._target is not None: @@ -78,7 +78,7 @@ def show_overlay(self) -> None: if not self.isVisible(): self.showFullScreen() - def apply(self, event: dict) -> None: + def apply(self, event: Dict[str, Any]) -> None: """Apply one ``begin`` / ``point`` / ``end`` / ``clear`` event from a viewer. The event comes from the remote viewer: a coordinate or width that is @@ -148,7 +148,7 @@ def clear(self) -> None: self._current = None self.update() - def paintEvent(self, _event) -> None: # noqa: N802 Qt override + def paintEvent(self, _event: QPaintEvent) -> None: # noqa: N802 Qt override painter = QPainter(self) try: painter.setRenderHint(QPainter.RenderHint.Antialiasing) @@ -158,7 +158,7 @@ def paintEvent(self, _event) -> None: # noqa: N802 Qt override painter.end() @staticmethod - def _paint_stroke(painter: QPainter, stroke: dict) -> None: + def _paint_stroke(painter: QPainter, stroke: Dict[str, Any]) -> None: points: List[Tuple[float, float]] = stroke.get("points") or [] if len(points) < 2: return diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 5e341cd88..582daa157 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -18,7 +18,7 @@ import functools import secrets from pathlib import Path -from typing import Any, List, Optional +from typing import Any, Callable, List, Optional from PySide6.QtCore import Qt, QTimer, Signal from PySide6.QtGui import QGuiApplication, QImage @@ -338,7 +338,7 @@ def _on_host_stop_failed(self, error: Exception) -> None: self._refresh_status() QMessageBox.warning(self, _t("rd_quick_stop_host"), str(error)) - def _host_approval_callback(self, pending: PendingViewer): + def _host_approval_callback(self, pending: PendingViewer) -> str | bool: """Bridge incoming viewers to a GUI Allow/View-only/Deny dialog. Runs on the host's accept thread — we ship the request over to @@ -455,7 +455,7 @@ def _dispatch_target(self, target: ConnectTarget, token: str) -> None: self, _t("rd_quick_connect_btn"), _t("rd_quick_bad_target"), ) - def _take_slot(self, slot: str) -> Optional[functools.partial]: + def _take_slot(self, slot: str) -> Optional[functools.partial[None]]: """Clear ``slot`` for a new session and let go of this screen's other one. Both slots are free when this returns; the shutdown of what they held @@ -466,7 +466,7 @@ def _take_slot(self, slot: str) -> Optional[functools.partial]: registry.detach(slot, self._owner)) if close is not None] return functools.partial(stop_each, *closes) if closes else None - def _own_viewer(self): + def _own_viewer(self) -> Optional[Any]: """The viewer this screen opened, or None once it is gone or replaced.""" return (registry.owned(SLOT_VIEWER, self._owner) or registry.owned(SLOT_WS_VIEWER, self._owner)) @@ -478,7 +478,7 @@ def _on_displaced(self, slot: str, _by: str) -> None: self._close_screen_window() self._refresh_status() - def _viewer_callbacks(self) -> dict: + def _viewer_callbacks(self) -> dict[str, Any]: """Callbacks for a new viewer session; they carry its number, and only the current session's land.""" self._session += 1 return {"on_frame": self._view.tagged("_on_session_frame", self._session), @@ -497,7 +497,7 @@ def _on_session_error(self, session: int, message: str) -> None: if session == self._session: # an error from a session already replaced or closed is not news self._on_error(message) - def _begin_connect(self, slot: str, build, on_live) -> None: + def _begin_connect(self, slot: str, build: Callable[[], Any], on_live: Callable[[], None]) -> None: """Take ``slot``, build the viewer, and connect it off the GUI thread (see ``_connect_task``). ``on_live`` is a method of this screen or a partial of one; it is held weakly. @@ -518,7 +518,7 @@ def _begin_connect(self, slot: str, build, on_live) -> None: self._connect_task.finished.connect(self._on_connect_finished) self._refresh_status() - def _on_viewer_live(self, slot: str, on_live: WeakCall, live_viewer) -> None: + def _on_viewer_live(self, slot: str, on_live: WeakCall, live_viewer: Any) -> None: """GUI thread: the connect succeeded; register the viewer and show it.""" registry.adopt(slot, live_viewer, self._owner, self._view.callback("_on_displaced")) on_live() @@ -627,7 +627,7 @@ def _open_screen_window(self, title: str) -> None: self._screen_window.raise_() self._screen_window.activateWindow() - def _send_input(self, action: dict) -> None: + def _send_input(self, action: dict[str, Any]) -> None: """Forward one input action from the popup to the live viewer.""" viewer = self._own_viewer() if viewer is None or not viewer.connected: @@ -637,7 +637,7 @@ def _send_input(self, action: dict) -> None: except OSError as error: self._error_arrived.emit(str(error)) - def _on_files_dropped(self, paths) -> None: + def _on_files_dropped(self, paths: List[str]) -> None: """Upload each dropped file to the host's home directory.""" viewer = self._own_viewer() if viewer is None or not viewer.connected: diff --git a/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py b/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py index bc361b1eb..4a6d6b91b 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py +++ b/je_auto_control/gui/remote_desktop/webrtc_known_hosts.py @@ -7,7 +7,7 @@ """ from __future__ import annotations -from typing import Optional +from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple from PySide6.QtCore import Qt from PySide6.QtGui import QColor @@ -22,11 +22,16 @@ _format_last_seen, _short_fp, _t, ) +if TYPE_CHECKING: + from datetime import datetime, timedelta + + from je_auto_control.utils.remote_desktop.fingerprint import KnownHosts + class KnownHostsDialog(QDialog): """Browse + forget the persistent KnownHosts (TOFU app + DTLS fingerprints).""" - def __init__(self, known_hosts, parent: Optional[QWidget] = None) -> None: + def __init__(self, known_hosts: KnownHosts, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._known = known_hosts self.setWindowTitle(_t("rd_webrtc_known_hosts_title")) @@ -90,8 +95,8 @@ def _refresh(self) -> None: now=now, stale_after=stale_after, stale_color=stale_color) - def _populate_row(self, row: int, host_id: str, fps: dict, *, - now, stale_after, stale_color) -> None: + def _populate_row(self, row: int, host_id: str, fps: Dict[str, Optional[str]], *, + now: datetime, stale_after: timedelta, stale_color: QColor) -> None: items = [ QTableWidgetItem(host_id), QTableWidgetItem(_short_fp(fps.get("app_fp"))), @@ -108,7 +113,7 @@ def _populate_row(self, row: int, host_id: str, fps: dict, *, self._table.setItem(row, col, item) @staticmethod - def _is_stale(last_seen, *, now, stale_after) -> bool: + def _is_stale(last_seen: Optional[str], *, now: datetime, stale_after: timedelta) -> bool: if not last_seen: return False from datetime import datetime, timezone @@ -205,7 +210,7 @@ def _on_import(self) -> None: ) self._refresh() - def _prompt_import_data(self): + def _prompt_import_data(self) -> Optional[Dict[str, Any]]: import json path, _filter = QFileDialog.getOpenFileName( self, _t("rd_webrtc_kh_import"), "", "JSON (*.json);;All (*)", @@ -225,7 +230,8 @@ def _prompt_import_data(self): return None return data - def _import_one(self, host_id, value, existing) -> str: + def _import_one(self, host_id: object, value: object, + existing: Dict[str, Dict[str, Optional[str]]]) -> str: """Return ``"added"``, ``"skipped"``, or ``"ignored"`` per entry.""" if not isinstance(host_id, str): return "ignored" @@ -241,7 +247,7 @@ def _import_one(self, host_id, value, existing) -> str: return "added" @staticmethod - def _extract_fingerprints(value): + def _extract_fingerprints(value: object) -> Tuple[object, object]: if isinstance(value, str): return value, None if isinstance(value, dict): @@ -331,7 +337,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: button_row.addWidget(ok) layout.addLayout(button_row) - def values(self) -> tuple: + def values(self) -> Tuple[str, str, str]: return ( self._host_edit.text().strip(), self._app_edit.text().strip(), diff --git a/je_auto_control/gui/triggers_tab.py b/je_auto_control/gui/triggers_tab.py index f7cffc907..6ed993152 100644 --- a/je_auto_control/gui/triggers_tab.py +++ b/je_auto_control/gui/triggers_tab.py @@ -1,7 +1,8 @@ """Triggers tab: image / window / pixel / file event watchers.""" -from typing import Any, Dict, Iterable, List, Optional, Sequence, TypedDict +from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, TypedDict from PySide6.QtCore import QTimer +from PySide6.QtGui import QShowEvent from PySide6.QtWidgets import ( QCheckBox, QComboBox, QFileDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QStackedWidget, QTableWidget, QTableWidgetItem, @@ -19,7 +20,7 @@ from je_auto_control.utils.triggers.trigger_engine import ( AllOfTrigger, AnyOfTrigger, CronTrigger, FilePathTrigger, ImageAppearsTrigger, PixelColorTrigger, SequenceTrigger, - WindowAppearsTrigger, default_trigger_engine, + WindowAppearsTrigger, _TriggerBase, default_trigger_engine, ) @@ -117,7 +118,7 @@ def sync_with_engine(self) -> None: self._timer.stop() self._apply_status() - def showEvent(self, event) -> None: # noqa: N802 # reason: Qt override + def showEvent(self, event: QShowEvent) -> None: # noqa: N802 # reason: Qt override """Catch up with an engine started or stopped elsewhere while hidden.""" super().showEvent(event) self.sync_with_engine() @@ -177,7 +178,7 @@ def _add_page(self, *rows: QWidget) -> None: layout.addWidget(row) self._stack.addWidget(page) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("browse", self._browse_script), @@ -190,7 +191,7 @@ def menu_actions(self) -> list: ("tr_stop_engine", self._on_stop), ] - def _build_image_form(self) -> dict: + def _build_image_form(self) -> Dict[str, QLineEdit]: path_input = QLineEdit() threshold_input = QLineEdit("0.8") browse = self._tr(QPushButton(), "browse") @@ -202,12 +203,12 @@ def _build_image_form(self) -> dict: self._add_page(self._field_row("tr_image_label", path_input, browse), threshold) return {"path": path_input, "threshold": threshold_input} - def _build_window_form(self) -> dict: + def _build_window_form(self) -> Dict[str, QLineEdit]: title_input = QLineEdit() self._add_page(self._field_row("tr_title_contains_label", title_input)) return {"title": title_input} - def _build_pixel_form(self) -> dict: + def _build_pixel_form(self) -> Dict[str, QLineEdit]: x_input = QLineEdit("0") y_input = QLineEdit("0") r_input = QLineEdit("0") @@ -223,7 +224,7 @@ def _build_pixel_form(self) -> dict: return {"x": x_input, "y": y_input, "r": r_input, "g": g_input, "b": b_input, "tol": tol_input} - def _build_file_form(self) -> dict: + def _build_file_form(self) -> Dict[str, QLineEdit]: path_input = QLineEdit() browse = self._tr(QPushButton(), "browse") browse.setProperty("line_edit", path_input) @@ -278,7 +279,7 @@ def _on_add(self) -> None: default_trigger_engine.add(trigger) self._refresh() - def _build_trigger(self, script: str): + def _build_trigger(self, script: str) -> _TriggerBase: idx = self._type_combo.currentIndex() common: _TriggerOptions = {"trigger_id": "", "script_path": script, "repeat": self._repeat_check.isChecked()} @@ -305,12 +306,12 @@ def _build_trigger(self, script: str): **common, ) - def _build_cron_form(self) -> dict: + def _build_cron_form(self) -> Dict[str, QLineEdit]: cron_input = QLineEdit("* * * * *") self._add_page(self._field_row("tr_cron_label", cron_input)) return {"cron": cron_input} - def _build_pixel_trigger(self, common: _TriggerOptions): + def _build_pixel_trigger(self, common: _TriggerOptions) -> PixelColorTrigger: w = self._pixel_widgets return PixelColorTrigger( x=int(w["x"].text() or "0"), y=int(w["y"].text() or "0"), @@ -389,7 +390,7 @@ def _refresh(self) -> None: self._table.setItem(row, col, QTableWidgetItem(value)) -def _describe(trigger) -> str: +def _describe(trigger: _TriggerBase) -> str: if isinstance(trigger, ImageAppearsTrigger): return f"img={trigger.image_path} th={trigger.threshold}" if isinstance(trigger, WindowAppearsTrigger): diff --git a/je_auto_control/linux_with_x11/listener/x11_linux_listener.py b/je_auto_control/linux_with_x11/listener/x11_linux_listener.py index 20275e2c9..2d2dcaf10 100644 --- a/je_auto_control/linux_with_x11/listener/x11_linux_listener.py +++ b/je_auto_control/linux_with_x11/listener/x11_linux_listener.py @@ -34,7 +34,7 @@ class KeypressHandler: ``record_enable_context`` callback, never started as their own thread. """ - def __init__(self, default_daemon: bool = True, display: Any = None): + def __init__(self, default_daemon: bool = True, display: Any = None) -> None: """ :param default_daemon: kept for backwards compatibility; the handler is no longer a Thread, so this flag is informational only. @@ -43,7 +43,7 @@ def __init__(self, default_daemon: bool = True, display: Any = None): self.daemon = default_daemon self.still_listener = True self.record_flag = False - self.record_queue: Optional[Queue] = None + self.record_queue: Optional[Queue[tuple[int, int, int, int]]] = None self.event_keycode = 0 self.event_position = (0, 0) @@ -57,7 +57,7 @@ def check_is_press(self, keycode: int) -> bool: return True return False - def handle_reply(self, reply) -> None: + def handle_reply(self, reply: Any) -> None: """ 處理 X11 回傳的事件資料 Handle X11 reply data and parse events @@ -80,7 +80,7 @@ def handle_reply(self, reply) -> None: except (OSError, RuntimeError, AttributeError, TypeError, ValueError) as error: raise AutoControlException(f"{listener_error_message}: {error}") from error - def record(self, record_queue: Queue) -> None: + def record(self, record_queue: Queue[tuple[int, int, int, int]]) -> None: """ 開始記錄事件 Start recording events into the given queue @@ -88,7 +88,7 @@ def record(self, record_queue: Queue) -> None: self.record_flag = True self.record_queue = record_queue - def stop_record(self) -> Queue: + def stop_record(self) -> Queue[tuple[int, int, int, int]]: """ 停止記錄事件並回傳 Queue Stop recording and return the recorded queue @@ -114,7 +114,7 @@ class XWindowsKeypressListener(Thread): - 啟動 KeypressHandler """ - def __init__(self, default_daemon: bool = True): + def __init__(self, default_daemon: bool = True) -> None: super().__init__(daemon=default_daemon) self.still_listener = True self._record_lock = Lock() @@ -182,7 +182,7 @@ def run(self) -> None: finally: self.handler.still_listener = False - def record(self, record_queue: Queue) -> None: + def record(self, record_queue: Queue[tuple[int, int, int, int]]) -> None: """ 開始記錄事件 Start recording events @@ -192,7 +192,7 @@ def record(self, record_queue: Queue) -> None: raise AutoControlException("X11 listener is retiring; recording was not started") self.handler.record(record_queue) - def stop_record(self) -> Queue: + def stop_record(self) -> Queue[tuple[int, int, int, int]]: """ 停止記錄事件 Stop recording events @@ -204,7 +204,7 @@ def stop_record(self) -> Queue: _listener_lock = Lock() -def _get_listener(record_queue: Queue | None = None) -> XWindowsKeypressListener: +def _get_listener(record_queue: Queue[tuple[int, int, int, int]] | None = None) -> XWindowsKeypressListener: global _LISTENER # pylint: disable=global-statement # reason: one module owns this lazy cache with _listener_lock: if _LISTENER is not None and not _LISTENER.closed.is_set() and _LISTENER.failure is not None: @@ -232,12 +232,12 @@ def check_key_is_press(keycode: int) -> bool: return _get_listener().check_is_press(keycode) -def x11_linux_record(record_queue: Queue) -> None: +def x11_linux_record(record_queue: Queue[tuple[int, int, int, int]]) -> None: """Arm the queue before starting a newly acquired RECORD listener.""" _get_listener(record_queue) -def x11_linux_stop_record() -> Queue: +def x11_linux_stop_record() -> Queue[tuple[int, int, int, int]]: """Stop queue insertion; stopping before first use acquires no resources.""" with _listener_lock: return Queue() if _LISTENER is None else _LISTENER.stop_record() diff --git a/je_auto_control/utils/accessibility/backends/windows_query.py b/je_auto_control/utils/accessibility/backends/windows_query.py index 7e87442e9..dc06d7ad8 100644 --- a/je_auto_control/utils/accessibility/backends/windows_query.py +++ b/je_auto_control/utils/accessibility/backends/windows_query.py @@ -61,7 +61,7 @@ def _uia_errors() -> Tuple[Type[BaseException], ...]: ) -def search_root(automation, window_title: Optional[str]): +def search_root(automation: Any, window_title: Optional[str]) -> Any: """The element to search from: one window by title substring, else the desktop.""" if not window_title: return automation.GetRootElement() @@ -85,7 +85,7 @@ def search_root(automation, window_title: Optional[str]): f"no visible window title contains {window_title!r}") -def search_roots(automation, window_title: Optional[str]) -> Iterator[Any]: +def search_roots(automation: Any, window_title: Optional[str]) -> Iterator[Any]: """The roots to search, one at a time, front-most window first. Unscoped, this yields each visible top-level window rather than the desktop @@ -110,7 +110,7 @@ def search_roots(automation, window_title: Optional[str]) -> Iterator[Any]: yield element -def cache_request(automation): +def cache_request(automation: Any) -> Any: """A cache request for every property the element conversion reads.""" request = automation.CreateCacheRequest() for prop in CACHED_PROPERTIES: @@ -118,7 +118,7 @@ def cache_request(automation): return request -def _is_null(element) -> bool: +def _is_null(element: object) -> bool: """Whether a walker returned "no such element". ``comtypes`` hands back a **wrapper around a NULL pointer**, not ``None``, @@ -129,7 +129,7 @@ def _is_null(element) -> bool: return element is None or not bool(element) -def focused_raw(automation): +def focused_raw(automation: Any) -> Any: """The raw element holding keyboard focus, or ``None`` when none does. ``GetFocusedElement`` answers with an error rather than an empty result @@ -145,14 +145,14 @@ def focused_raw(automation): return None if _is_null(element) else element -def _children(walker, node, request, limit: int) -> list: +def _children(walker: Any, node: Any, request: Any, limit: int) -> List[Any]: """Up to ``limit`` control-view children of ``node``, properties cached. Capped because the caller can never need more siblings from one node than its whole remaining budget — and a node with tens of thousands of children would otherwise cost that many calls before the walk could descend. """ - out: list = [] + out: List[Any] = [] if limit <= 0: return out try: @@ -168,7 +168,7 @@ def _children(walker, node, request, limit: int) -> list: return out -def walk_elements(automation, root, limit: int) -> Iterator[Any]: +def walk_elements(automation: Any, root: Any, limit: int) -> Iterator[Any]: """Yield up to ``limit`` control elements under ``root``, in reading order. The point is that it can be **stopped**. ``FindAll`` is one call that diff --git a/je_auto_control/utils/accessibility/backends/windows_reads.py b/je_auto_control/utils/accessibility/backends/windows_reads.py index feb374c70..9a8c1a8e1 100644 --- a/je_auto_control/utils/accessibility/backends/windows_reads.py +++ b/je_auto_control/utils/accessibility/backends/windows_reads.py @@ -8,7 +8,7 @@ Imports no ``PySide6``. """ -from typing import Any, Dict, List, Tuple, Type +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar from je_auto_control.utils.accessibility.backends.windows_query import UIA_ERRORS @@ -17,9 +17,10 @@ #: several of these reads coerce whatever the provider returned. UIA_READ_ERRORS: Tuple[Type[BaseException], ...] = UIA_ERRORS + (TypeError,) _UIA_ERRORS = UIA_READ_ERRORS +_T = TypeVar("_T") -def _view_name(pattern, view_id) -> str: +def _view_name(pattern: Any, view_id: Any) -> str: """Return a MultipleViewPattern view's name, or '' on failure.""" try: return str(pattern.GetViewName(int(view_id)) or "") @@ -27,7 +28,7 @@ def _view_name(pattern, view_id) -> str: return "" -def _header_names(array) -> List[str]: +def _header_names(array: Any) -> List[str]: """Read an IUIAutomationElementArray of header elements into name strings.""" names: List[str] = [] try: @@ -42,7 +43,7 @@ def _header_names(array) -> List[str]: return names -def _read_cell(item_pattern, cell, row: int, column: int) -> Dict[str, Any]: +def _read_cell(item_pattern: Any, cell: Any, row: int, column: int) -> Dict[str, Any]: """Build a cell record, enriching with GridItemPattern row/col/span if present.""" info: Dict[str, Any] = { "value": _safe_name(cell), "row": row, "column": column, @@ -59,14 +60,14 @@ def _read_cell(item_pattern, cell, row: int, column: int) -> Dict[str, Any]: return info -def _safe_name(raw) -> str: +def _safe_name(raw: Any) -> str: try: return str(raw.CurrentName or "") except _UIA_ERRORS: return "" -def _as_text(value) -> str: +def _as_text(value: object) -> str: return str(value or "") @@ -78,7 +79,7 @@ def _as_text(value) -> str: _TEXT_ATTR_IS_ITALIC = 40014 -def _attr(text_range, attribute_id, cast): +def _attr(text_range: Any, attribute_id: int, cast: Callable[[Any], _T]) -> Optional[_T]: """One text attribute, or ``None`` when unreadable, mixed or unsupported. For a range with mixed formatting UIA returns a sentinel object, not a @@ -93,7 +94,7 @@ def _attr(text_range, attribute_id, cast): return cast(value) -def _read_text_attributes(text_range) -> Dict[str, Any]: +def _read_text_attributes(text_range: Any) -> Dict[str, Any]: """Read font / colour formatting of a TextRange into a plain dict.""" weight = _attr(text_range, _TEXT_ATTR_FONT_WEIGHT, int) return { @@ -116,7 +117,7 @@ def _read_text_attributes(text_range) -> Dict[str, Any]: ) -def _read_legacy(pattern) -> Dict[str, Any]: +def _read_legacy(pattern: Any) -> Dict[str, Any]: """Read a LegacyIAccessiblePattern's MSAA fields into a plain dict.""" info: Dict[str, Any] = {} for key, attribute, cast in _LEGACY_READS: @@ -139,7 +140,7 @@ def _read_legacy(pattern) -> Dict[str, Any]: ) -def _read_properties(raw) -> Dict[str, Any]: +def _read_properties(raw: Any) -> Dict[str, Any]: """Read the rich UIA properties of a raw element into a plain dict.""" properties: Dict[str, Any] = {} for key, attribute, cast in _PROPERTY_READS: diff --git a/je_auto_control/utils/agent_runtime/android_hierarchy.py b/je_auto_control/utils/agent_runtime/android_hierarchy.py index 4a7bdd693..7e4764b2a 100644 --- a/je_auto_control/utils/agent_runtime/android_hierarchy.py +++ b/je_auto_control/utils/agent_runtime/android_hierarchy.py @@ -71,7 +71,7 @@ def same_source(self, other: AndroidHierarchyView) -> bool: """Compare private source witnesses without publishing a reusable fingerprint of hidden values.""" return hmac.compare_digest(self.signature, other.signature) - def to_dict(self) -> dict: + def to_dict(self) -> dict[str, Any]: """Return detached semantic readback without the raw source or any text-authority token.""" return detached({'elements': self.elements, 'text': self.text, 'text_redacted': self.text_redacted, 'semantic_observation': True}) @@ -160,7 +160,7 @@ def __init__(self, evidence: AndroidInputEvidence, grants: frozenset[str]) -> No self.evidence, self.grants = evidence, grants self.stack: list[_Frame] = [] self.seen: set[str] = set() - self.elements: list[dict] = [] + self.elements: list[dict[str, Any]] = [] self.count = 0 self.root_seen = False @@ -198,7 +198,7 @@ def _root(self, node: Any) -> None: self.root_seen = True self.stack.append(_Frame('')) - def _element(self, attrs: dict, flags: dict, frame: _Frame, parent_visible: bool) -> None: + def _element(self, attrs: dict[str, str], flags: dict[str, bool], frame: _Frame, parent_visible: bool) -> None: bounds = _bounds(attrs['bounds'], self.evidence.size) frame.visible = _visible(parent_visible, flags, bounds) if frame.skipped: @@ -213,14 +213,14 @@ def _element(self, attrs: dict, flags: dict, frame: _Frame, parent_visible: bool actionable=data['actionable'] and _point_allowed(self.evidence, bounds)) self.elements.append(data) - def finish(self) -> list[dict]: + def finish(self) -> list[dict[str, Any]]: """Never accept missing grants, empty/multiple roots or unfinished XML state.""" if self.stack or not self.root_seen or not self.elements or not self.grants.issubset(self.seen): raise AgentTaskError('Android hierarchy is incomplete or has stale text grants') return self.elements -def _node_frame(parent: _Frame, attrs: dict, flags: dict, package: str) -> _Frame: +def _node_frame(parent: _Frame, attrs: dict[str, str], flags: dict[str, bool], package: str) -> _Frame: index = attrs['index'] if index in parent.indices or (not parent.path and index != '0'): raise AgentTaskError('Android hierarchy sibling index is ambiguous') @@ -231,11 +231,11 @@ def _node_frame(parent: _Frame, attrs: dict, flags: dict, package: str) -> _Fram or attrs['class'] == 'android.widget.EditText', parent.enabled and flags['enabled']) -def _visible(parent: bool, flags: dict, bounds: list[int]) -> bool: +def _visible(parent: bool, flags: dict[str, bool], bounds: list[int]) -> bool: return parent and flags.get('visible-to-user', True) and bounds[2] > 0 and bounds[3] > 0 -def _node_data(attrs: dict, flags: dict, frame: _Frame, grants: frozenset[str]) -> dict: +def _node_data(attrs: dict[str, str], flags: dict[str, bool], frame: _Frame, grants: frozenset[str]) -> dict[str, Any]: name, text = '', '' reviewed = frame.path in grants and not frame.protected and frame.visible if reviewed: @@ -248,7 +248,7 @@ def _node_data(attrs: dict, flags: dict, frame: _Frame, grants: frozenset[str]) 'text_redacted': not reviewed} -def _attributes(attrs: dict) -> tuple[dict, dict[str, bool]]: +def _attributes(attrs: dict[str, str]) -> tuple[dict[str, str], dict[str, bool]]: if _FIELDS - set(attrs) or set(attrs) - (_FIELDS | _OPTIONAL): raise AgentTaskError('Android hierarchy node attributes are unsupported') if any(len(value) > 512 for value in attrs.values()) or _INDEX.fullmatch(attrs['index']) is None: diff --git a/je_auto_control/utils/agent_runtime/browser_target.py b/je_auto_control/utils/agent_runtime/browser_target.py index 42f42c499..7c344dc24 100644 --- a/je_auto_control/utils/agent_runtime/browser_target.py +++ b/je_auto_control/utils/agent_runtime/browser_target.py @@ -96,7 +96,7 @@ def input_retired(self) -> bool: """Report the monotonic input gate, independently of whether SDK cleanup was confirmed.""" return self._readonly is not None - def freeze_readonly(self) -> dict: + def freeze_readonly(self) -> dict[str, Any]: """Permanently retire the actual SDK owner before issuing any same-context proof.""" if self._readonly is not None: return self.readonly_capabilities() @@ -114,7 +114,7 @@ def freeze_readonly(self) -> dict: self._readonly = result["context_id"] return result - def readonly_capabilities(self) -> dict: + def readonly_capabilities(self) -> dict[str, Any]: """Check the current actual SDK view rather than trusting a saved description.""" if not self._readonly or self._session is None: raise AgentTaskError(_RETIREMENT_UNCONFIRMED) @@ -131,7 +131,7 @@ def readonly_spec(self) -> AgentTaskSpec: raise AgentTaskError("read-only browser has no original scope") return self._reader_spec if self._reader_spec is not None else self._spec - def bind_readonly(self, value: Any, *, validate: Callable[[AgentTaskSpec], Any]) -> dict: + def bind_readonly(self, value: Any, *, validate: Callable[[AgentTaskSpec], Any]) -> dict[str, Any]: """Bind only a host-admitted no-action verification scope; never configure or launch input.""" proof = self.readonly_capabilities() if self._spec is None: @@ -142,11 +142,11 @@ def bind_readonly(self, value: Any, *, validate: Callable[[AgentTaskSpec], Any]) self._reader_spec = proposed return proof - def check_resume(self, spec: AgentTaskSpec, receipts: list[dict]) -> None: + def check_resume(self, spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> None: """Refuse a finite prefix after context retirement; an unchanged live context remains usable.""" require_context_continuity(spec, receipts, self._session is not None and self._spec == spec, kind="browser") - def observe(self) -> dict: + def observe(self) -> dict[str, Any]: """Flatten semantic main/frame elements into observation-local indexes; no values or image files.""" if self._session is None: raise AgentTaskError("browser session is unavailable") @@ -156,7 +156,7 @@ def observe(self) -> dict: if getattr(error, "reason", "") == "human_review_required": raise AgentHumanReview("browser dialog requires human review") from None raise AgentTaskError("managed WebRunner observation failed") from None - elements: list[dict] = [] + elements: list[dict[str, Any]] = [] self._elements(elements, raw.get("elements", []), "") for frame in raw.get("frames", []): self._elements(elements, frame.get("elements", []), frame["selector"]) @@ -165,13 +165,13 @@ def observe(self) -> dict: "semantic_observation": True, "text_redacted": True} @staticmethod - def _elements(result: list[dict], values: list[dict], frame: str) -> None: + def _elements(result: list[dict[str, Any]], values: list[dict[str, Any]], frame: str) -> None: for value in values: result.append({"index": len(result), "selector": value["selector"], "frame": frame, "name": value.get("text", ""), "role": value.get("role") or value.get("tag", ""), "enabled": value.get("is_enabled", False), "visible": value.get("is_visible", False)}) - def perform(self, name: str, arguments: dict) -> Any: + def perform(self, name: str, arguments: dict[str, Any]) -> Any: """Use the shared command authority gates, with the session bound only for this dispatch.""" if self._readonly is not None: raise AgentTaskError("read-only browser cannot perform tools") @@ -203,6 +203,6 @@ def verify_browser(self, clause: Mapping[str, Any]) -> bool: except Exception: # noqa: BLE001 - SDK URL/read failures must not expose raw browser data raise AgentTaskError("managed browser verification is unavailable") from None - def validate_input(self, _event: dict) -> None: + def validate_input(self, _event: dict[str, Any]) -> None: """Browser sessions grant no native mouse, keyboard, clipboard or file-dialog access.""" raise AgentTaskError("browser tasks cannot drive native desktop input") diff --git a/je_auto_control/utils/agent_runtime/dag_continuation_plan.py b/je_auto_control/utils/agent_runtime/dag_continuation_plan.py index df5fdf2d9..c2aa3f546 100644 --- a/je_auto_control/utils/agent_runtime/dag_continuation_plan.py +++ b/je_auto_control/utils/agent_runtime/dag_continuation_plan.py @@ -14,7 +14,8 @@ ) -def dispatch_template(runtime: Any, node: dict, snapshot: str) -> tuple[dict, dict | None]: +def dispatch_template(runtime: Any, node: dict[str, Any], + snapshot: str) -> tuple[dict[str, Any], dict[str, Any] | None]: """Renew only local unavailable origin restrictions; remote authority stays at its destination.""" source = node["task"]["spec"] if node["host"] != "local": @@ -26,8 +27,8 @@ def dispatch_template(runtime: Any, node: dict, snapshot: str) -> tuple[dict, di return runtime._validated_spec(template).to_dict(), authority -def validate_decision(runtime: Any, decision: dict, node: dict, phase: str, - original: dict | None, evidence: ContinuationEvidence, snapshot: str) -> dict: +def validate_decision(runtime: Any, decision: dict[str, Any], node: dict[str, Any], phase: str, + original: dict[str, Any] | None, evidence: ContinuationEvidence, snapshot: str) -> dict[str, Any]: """Return frozen adoption/dispatch proof for one explicitly selected logical node.""" action = decision.get("action") if not isinstance(action, str): @@ -41,8 +42,8 @@ def validate_decision(runtime: Any, decision: dict, node: dict, phase: str, raise AgentTaskError("invalid DAG continuation decision") -def _dispatch(runtime: Any, decision: dict, node: dict, phase: str, - original: dict | None, snapshot: str) -> dict: +def _dispatch(runtime: Any, decision: dict[str, Any], node: dict[str, Any], phase: str, + original: dict[str, Any] | None, snapshot: str) -> dict[str, Any]: if set(decision) != {"node_id", "action", "spec"} or phase != "pending" or original is not None: raise AgentTaskError("DAG dispatch requires a never-claimed node with no accepted destination request") template, authority = dispatch_template(runtime, node, snapshot) @@ -57,7 +58,7 @@ def _dispatch(runtime: Any, decision: dict, node: dict, phase: str, return {"decision": {**decision, "spec": spec}, "ready": True, "original": None, "authority": authority} -def _adoption_fields(decision: dict) -> None: +def _adoption_fields(decision: dict[str, Any]) -> None: fields = {'node_id', 'action', 'task_id'} if decision.get('action') == 'successor' and 'handoff_id' in decision: fields.add('handoff_id') @@ -67,7 +68,8 @@ def _adoption_fields(decision: dict) -> None: raise AgentTaskError("DAG adoption requires a verified accepted original request") -def _adopt(decision: dict, node: dict, phase: str, original: dict | None, evidence: ContinuationEvidence) -> dict: +def _adopt(decision: dict[str, Any], node: dict[str, Any], phase: str, original: dict[str, Any] | None, + evidence: ContinuationEvidence) -> dict[str, Any]: _adoption_fields(decision) if original is None: raise AgentTaskError('DAG adoption requires a verified accepted original request') @@ -76,7 +78,7 @@ def _adopt(decision: dict, node: dict, phase: str, original: dict | None, eviden identifier = decision["task_id"] if not isinstance(identifier, str) or not identifier or len(identifier) > 256: raise AgentTaskError("DAG adoption requires a bounded task identity") - chain: list[dict] = [] + chain: list[dict[str, Any]] = [] if decision["action"] == "adopt": if identifier != original.get("task_id"): raise AgentTaskError("DAG adoption task differs from the bound original request") diff --git a/je_auto_control/utils/agent_runtime/dag_transfer_checks.py b/je_auto_control/utils/agent_runtime/dag_transfer_checks.py index dc2a1ce01..69fea9e30 100644 --- a/je_auto_control/utils/agent_runtime/dag_transfer_checks.py +++ b/je_auto_control/utils/agent_runtime/dag_transfer_checks.py @@ -12,7 +12,7 @@ _ERRORS = (AutoControlException, OSError, RuntimeError, ValueError, TypeError, LookupError) -def remote_reports(batch: dict, reports: list[dict]) -> list[dict]: +def remote_reports(batch: dict[str, Any], reports: list[dict[str, Any]]) -> list[dict[str, Any]]: """Select actual remote handoff decisions from the immutable coordinator graph.""" hosts = {node['id']: node['host'] for node in batch['definition']['nodes']} return [report for report in reports if 'handoff_id' in report['decision'] @@ -22,9 +22,10 @@ def remote_reports(batch: dict, reports: list[dict]) -> list[dict]: class DagTransferChecks: """A persisted pending phase supplies no authority to dispatch or accept downstream completion.""" - def __init__(self, store: Any, batch: dict, verify: Callable[[], None], *, baseline: dict | None = None) -> None: + def __init__(self, store: Any, batch: dict[str, Any], verify: Callable[[], None], *, + baseline: dict[str, Any] | None = None) -> None: self.store, self.batch, self.verify = store, batch, verify - self.pinned: tuple | None = None + self.pinned: tuple[Any, ...] | None = None self.owner = DeferredAuthorization.capture() with store.connection() as connection: self.local = self._snapshot(connection) @@ -35,7 +36,7 @@ def __init__(self, store: Any, batch: dict, verify: Callable[[], None], *, basel if baseline is not None: self._baseline(baseline) - def _baseline(self, baseline: dict) -> None: + def _baseline(self, baseline: dict[str, Any]) -> None: nodes = tuple(tuple(row[name] for name in ('node_id', 'phase', 'receipt', 'updated')) for row in sorted(baseline['nodes'], key=lambda item: item['node_id'])) bindings = tuple(sorted(baseline['batch']['bindings'].items())) @@ -43,7 +44,7 @@ def _baseline(self, baseline: dict) -> None: if self.local[1:] != (nodes, bindings, inputs): raise AgentTaskError('coordinator node claims or bindings changed during remote review') - def _snapshot(self, connection: Any) -> tuple: + def _snapshot(self, connection: Any) -> tuple[Any, ...]: row = connection.execute('SELECT id,state,attempt,graph_hash,owner,definition,hosts,max_parallel ' 'FROM agent_dag_batches WHERE id=?', (self.batch['id'],)).fetchone() nodes = connection.execute('SELECT node_id,phase,receipt,updated FROM agent_dag_nodes ' @@ -58,7 +59,7 @@ def _snapshot(self, connection: Any) -> tuple: tuple((item['node_id'], json.loads(item['task'])) for item in bindings), None if inputs is None else json.loads(inputs[0])) - def _approval(self, connection: Any, identifier: str) -> tuple: + def _approval(self, connection: Any, identifier: str) -> tuple[Any, ...]: row = connection.execute('SELECT id,batch_id,source_snapshot,plan_hash,details,created ' 'FROM agent_dag_approvals WHERE id=? AND batch_id=?', (identifier, self.batch['id'])).fetchone() if row is None: @@ -77,7 +78,7 @@ def guard(self, connection: Any, identifier: str, phase: str) -> None: self._approval(connection, identifier) != self.pinned): raise AgentTaskError('provisional remote consent or coordinator state changed') - def finish(self, identifier: str, phase: str, commit: Callable) -> None: + def finish(self, identifier: str, phase: str, commit: Callable[[Any], None]) -> None: """Resolve outside the writer, then atomically accept only the same still-pending local intent.""" try: with self.owner.scope(): diff --git a/je_auto_control/utils/agent_runtime/dag_transfer_stop.py b/je_auto_control/utils/agent_runtime/dag_transfer_stop.py index 92dc69991..ffd73a638 100644 --- a/je_auto_control/utils/agent_runtime/dag_transfer_stop.py +++ b/je_auto_control/utils/agent_runtime/dag_transfer_stop.py @@ -14,7 +14,7 @@ _ERRORS = (AutoControlException, OSError, RuntimeError, ValueError, TypeError, LookupError) -def _dependents(nodes: list, source: str) -> set[str]: +def _dependents(nodes: list[dict[str, Any]], source: str) -> set[str]: selected = {source} for _index in range(len(nodes)): enlarged = selected | {node['id'] for node in nodes if selected.intersection(node['depends_on'])} @@ -24,7 +24,7 @@ def _dependents(nodes: list, source: str) -> set[str]: return selected - {source} -def _accepted(reply: dict) -> str: +def _accepted(reply: dict[str, Any]) -> str: version = reply.get('spec_match_contract') if (not isinstance(version, int) or isinstance(version, bool) or version != 1 or reply.get('found') is not True or reply.get('spec_match') != 'matches'): @@ -41,12 +41,12 @@ class _OwnedPause: """Carry the actual coordinator account and one finite cleanup deadline across dependent lookups.""" runtime: Any - batch: dict - connect: Callable + batch: dict[str, Any] + connect: Callable[[str], Any] owner: DeferredAuthorization = field(default_factory=DeferredAuthorization.capture) deadline: float = field(default_factory=lambda: time.monotonic() + 5) - def _call(self, node: dict, operation: str, body: dict) -> dict: + def _call(self, node: dict[str, Any], operation: str, body: dict[str, Any]) -> dict[str, Any]: remaining = self.deadline - time.monotonic() if remaining <= 0: raise AgentTaskError('dependent pause cleanup deadline expired') @@ -57,7 +57,7 @@ def _call(self, node: dict, operation: str, body: dict) -> dict: call = self.connect(node['host']) return call(operation, body, remaining) - def request(self, node: dict, receipt: dict) -> dict: + def request(self, node: dict[str, Any], receipt: dict[str, Any]) -> dict[str, Any]: """Pause only an independently matched accepted request while retaining unknown retirement.""" result = {'outcome': 'requires_review', 'task_id': receipt.get('task_id')} try: @@ -73,7 +73,7 @@ def request(self, node: dict, receipt: dict) -> dict: pass return result - def _local_admission(self, node: dict, identifier: str) -> None: + def _local_admission(self, node: dict[str, Any], identifier: str) -> None: with self.runtime.store.connection() as connection: row = connection.execute('SELECT batch_id,node_id FROM agent_dag_local_tasks WHERE task_id=?', (identifier,)).fetchone() @@ -81,7 +81,8 @@ def _local_admission(self, node: dict, identifier: str) -> None: raise AgentTaskError('local dependent pause requires its original private admission') -def pause_dependents(runtime: Any, batch: dict, source: str, nodes: list, connections: Callable) -> None: +def pause_dependents(runtime: Any, batch: dict[str, Any], source: str, nodes: list[dict[str, Any]], + connections: Callable[[str], Any]) -> None: """Preserve possible effects and never pause unrelated work, replay a claim or invent a retirement ACK.""" selected = _dependents(nodes, source) pending = {} diff --git a/je_auto_control/utils/agent_runtime/handoff_records.py b/je_auto_control/utils/agent_runtime/handoff_records.py index 260bd07c8..1559812de 100644 --- a/je_auto_control/utils/agent_runtime/handoff_records.py +++ b/je_auto_control/utils/agent_runtime/handoff_records.py @@ -19,12 +19,12 @@ class HandoffPolicy: class HandoffAccess: """A private validated projection; caller JSON cannot create task-read authority.""" - projection: dict - rows: dict[str, dict] - links: list[tuple[dict, dict, dict]] + projection: dict[str, Any] + rows: dict[str, dict[str, Any]] + links: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] authority: HandoffPolicy - witness: Callable - grant: dict + witness: Callable[..., dict[str, Any]] + grant: dict[str, Any] @property def policy(self) -> Any: @@ -36,19 +36,20 @@ def renewed(self) -> bool: """Whether the actual leaf has privately reviewed renewal evidence.""" return self.authority.renewed - def read(self, identifier: str) -> dict: + def read(self, identifier: str) -> dict[str, Any]: """Read only a real task already included in this explicitly validated grant.""" if identifier not in self.rows: raise AgentTaskError('task is outside the explicit evidence handoff') return self.rows[identifier] - def reply(self, identifier: str) -> dict: + def reply(self, identifier: str) -> dict[str, Any]: """Supply only the exact independently verified final completion projection.""" if identifier != self.projection['task_id']: raise AgentTaskError('handoff does not select this completion task') return self.projection - def __call__(self, connection: Any, source: dict, child: dict, link: dict) -> dict: + def __call__(self, connection: Any, source: dict[str, Any], child: dict[str, Any], + link: dict[str, Any]) -> dict[str, Any]: """Recheck only an actual granted source/child pair through the injected host witness.""" actual = next((item for item in self.links if (item[0]['id'], item[1]['id']) == (source['id'], child['id'])), None) @@ -78,7 +79,7 @@ def previous(self, connection: Any, review: str) -> Any: return connection.execute(self._sql("SELECT * FROM @records WHERE review=? AND state='active'"), (review,)).fetchone() - def insert(self, connection: Any, row: dict) -> None: + def insert(self, connection: Any, row: dict[str, Any]) -> None: """Persist one family-shaped grant without inventing an unrelated DAG binding.""" fields = ('id', *(() if self.standalone else ('batch_id', 'node_id')), 'source_task', 'task_id', 'review', 'details', 'note', 'state', 'created', 'expires') @@ -86,7 +87,7 @@ def insert(self, connection: Any, row: dict) -> None: statement = self._sql('INSERT INTO @records VALUES (@values)').replace('@values', placeholders) connection.execute(statement, tuple(row[field] for field in fields)) - def list(self, connection: Any, binding: dict) -> list: + def list(self, connection: Any, binding: dict[str, Any]) -> list[Any]: """List bounded history for this exact real source or DAG node.""" filters = ' AND '.join(field + '=?' for field in self.binding_fields) statement = self._sql('SELECT * FROM @records WHERE @filter ORDER BY created DESC LIMIT 200') diff --git a/je_auto_control/utils/agent_runtime/native_target.py b/je_auto_control/utils/agent_runtime/native_target.py index 7b054b19f..8fdaeb4ee 100644 --- a/je_auto_control/utils/agent_runtime/native_target.py +++ b/je_auto_control/utils/agent_runtime/native_target.py @@ -47,7 +47,7 @@ class NativeDesktopTarget: _worker_module = "je_auto_control.utils.agent_runtime.native_worker" def __init__(self, *, argv: Sequence[str] | None = None, resource_path: Path | None = None, - recovery_probe: Callable[[], None] = no_held_input, profile: dict | None = None) -> None: + recovery_probe: Callable[[], None] = no_held_input, profile: dict[str, Any] | None = None) -> None: self._profile = AgentTargetProfile.from_dict(profile) if profile is not None else None self._argv = tuple(argv) if argv is not None else ( sys.executable, "-u", "-m", self._worker_module) @@ -84,7 +84,7 @@ def _ensure(self) -> HelperChannel: self._channel_control = control return self._channel - def check_resume(self, spec: AgentTaskSpec, receipts: list[dict]) -> None: + def check_resume(self, spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> None: """Fence UI prefixes before launching a replacement helper; file recovery uses persistent evidence.""" if self._profile is not None: kind = self._profile.kind @@ -110,7 +110,7 @@ def has_browser_context(self) -> bool: return self.is_managed_browser and self._channel is not None and not self._channel.retired @property - def presence_status(self) -> dict: + def presence_status(self) -> dict[str, Any]: """Return passive source/binding metadata without any monitor, helper or native probe.""" result = self._presence.status() if self._channel_control is not None: @@ -149,7 +149,7 @@ def can_reobserve(self) -> bool: return (self._channel is not None and not self._channel.retired and self._ledger.empty and self._pending is None) - def _request(self, operation: str, payload: dict, *, deadline: float | None = None) -> Any: + def _request(self, operation: str, payload: dict[str, Any], *, deadline: float | None = None) -> Any: context = current_operation() if context is None: raise AgentTaskError("native targets require an explicitly managed operation scope") @@ -172,11 +172,11 @@ def _persist(self) -> None: if self._journal is not None: self._journal.update(self._ledger.snapshot(), self._pending) - def _input(self, event: dict, *, cleanup: bool = False) -> None: + def _input(self, event: dict[str, Any], *, cleanup: bool = False) -> None: self._ledger.consume(event, cleanup=cleanup) self._persist() - def recover(self, note: str, *, actor: str) -> dict: + def recover(self, note: str, *, actor: str) -> dict[str, Any]: """Review a stale witness while exclusively owning the resource; never replay old input.""" path = self._resource_path or _desktop_lock_path() lock = RuntimeLock(path) @@ -251,7 +251,7 @@ def _readonly_source_channel(self) -> HelperChannel | None: raise AgentTaskError("browser retirement requires its original input ownership") return channel - def detach_readonly(self) -> tuple[HelperChannel, dict] | None: + def detach_readonly(self) -> tuple[HelperChannel, dict[str, Any]] | None: """Transfer only the actual frozen browser channel after confirmed empty input ownership.""" channel = self._readonly_source_channel() if channel is None: diff --git a/je_auto_control/utils/agent_runtime/observation_refs.py b/je_auto_control/utils/agent_runtime/observation_refs.py index 0ec9aa98f..7a241e5e3 100644 --- a/je_auto_control/utils/agent_runtime/observation_refs.py +++ b/je_auto_control/utils/agent_runtime/observation_refs.py @@ -46,7 +46,8 @@ def _size(value: Any) -> list[float]: return result -def _element(data: Mapping, index: int, *, require_actionable: bool = False) -> tuple[list[int], dict]: +def _element(data: Mapping[str, Any], index: int, *, + require_actionable: bool = False) -> tuple[list[int], dict[str, Any]]: elements = data.get("elements", ()) if not isinstance(elements, (list, tuple)) or index >= len(elements): raise AgentTaskError("element index is outside this observation") @@ -62,11 +63,11 @@ def _element(data: Mapping, index: int, *, require_actionable: bool = False) -> return [math.floor(x + width / 2), math.floor(y + height / 2)], detached(evidence) -def _element_enabled(item: Mapping, require_actionable: bool) -> bool: +def _element_enabled(item: Mapping[str, Any], require_actionable: bool) -> bool: return item.get("enabled", True) is True and (not require_actionable or item.get("actionable") is True) -def _image_point(data: Mapping, value: Any) -> list[int]: +def _image_point(data: Mapping[str, Any], value: Any) -> list[int]: image = data.get("image") if not isinstance(image, Mapping) or image.get("redacted_by") != "strict": raise AgentTaskError("image reference requires trusted redacted observation geometry") @@ -83,9 +84,10 @@ def _image_point(data: Mapping, value: Any) -> list[int]: for start, position, full, scaled in zip(origin, point, original, rendered)] -def resolve_action(tool: str, arguments: Mapping, reference: Any, data: Mapping) -> tuple[dict, dict]: +def resolve_action(tool: str, arguments: Mapping[str, Any], reference: Any, + data: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: """Resolve only reviewed point tools, preserving original arguments and non-image provenance.""" - kwargs: dict = detached(arguments) + kwargs: dict[str, Any] = detached(arguments) evidence = {"requested_arguments": kwargs, "identity": detached(data.get("identity"))} image = data.get("image") if isinstance(image, Mapping): @@ -98,7 +100,8 @@ def resolve_action(tool: str, arguments: Mapping, reference: Any, data: Mapping) return _point_reference(tool, kwargs, reference, data, evidence) -def _point_reference(tool: str, kwargs: dict, reference: Mapping, data: Mapping, evidence: dict) -> tuple[dict, dict]: +def _point_reference(tool: str, kwargs: dict[str, Any], reference: Mapping[str, Any], data: Mapping[str, Any], + evidence: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: if tool not in POINT_TOOLS: raise AgentTaskError("observation references require a reviewed point action") if {"x", "y"} & set(kwargs): @@ -116,7 +119,7 @@ def _point_reference(tool: str, kwargs: dict, reference: Mapping, data: Mapping, return {**kwargs, "x": point[0], "y": point[1]}, evidence -def _android_reference(reference: Mapping, data: Mapping) -> None: +def _android_reference(reference: Mapping[str, Any], data: Mapping[str, Any]) -> None: identity = data.get("identity") if not isinstance(identity, Mapping) or "element_index" not in reference: raise AgentTaskError("Android references require a semantic element observation") @@ -127,7 +130,8 @@ def _android_reference(reference: Mapping, data: Mapping) -> None: raise AgentTaskError("Android element observation has no verified hierarchy signature") -def _browser_element(tool: str, kwargs: dict, reference: Mapping, data: Mapping, evidence: dict) -> tuple[dict, dict]: +def _browser_element(tool: str, kwargs: dict[str, Any], reference: Mapping[str, Any], data: Mapping[str, Any], + evidence: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: if "element_index" not in reference or {"selector", "frame"} & set(kwargs): raise AgentTaskError("browser reference requires one DOM index without explicit selector or frame") index = reference["element_index"] @@ -139,7 +143,7 @@ def _browser_element(tool: str, kwargs: dict, reference: Mapping, data: Mapping, return {**kwargs, "selector": selector, "frame": frame}, evidence -def _observed_dom_element(index: int, data: Mapping, *, require_enabled: bool) -> Mapping: +def _observed_dom_element(index: int, data: Mapping[str, Any], *, require_enabled: bool) -> Mapping[str, Any]: elements = data.get("elements", ()) if not isinstance(elements, (list, tuple)) or index >= len(elements): raise AgentTaskError("DOM index is outside this observation") diff --git a/je_auto_control/utils/agent_runtime/presence_frames.py b/je_auto_control/utils/agent_runtime/presence_frames.py index 7348eb1df..358607b7a 100644 --- a/je_auto_control/utils/agent_runtime/presence_frames.py +++ b/je_auto_control/utils/agent_runtime/presence_frames.py @@ -13,7 +13,7 @@ _STATES = {'not_started', 'waiting_idle', 'monitoring', 'locked', 'unavailable'} -def encode_frame(value: dict) -> bytes: +def encode_frame(value: dict[str, Any]) -> bytes: """Encode one bounded finite object without arbitrary object serialization.""" if not isinstance(value, dict): raise AgentTaskError('physical presence frame must be an object') @@ -26,7 +26,7 @@ def encode_frame(value: dict) -> bytes: return result -def _unique(pairs: list[tuple[str, Any]]) -> dict: +def _unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result = {} for key, value in pairs: if key in result: @@ -35,7 +35,7 @@ def _unique(pairs: list[tuple[str, Any]]) -> dict: return result -def decode_frame(raw: bytes) -> dict: +def decode_frame(raw: bytes) -> dict[str, Any]: """Reject oversized/invalid/duplicate JSON before any presence operation is dispatched.""" if not isinstance(raw, bytes) or len(raw) > 4096: raise AgentTaskError('physical presence frame must be at most4096bytes') @@ -61,13 +61,13 @@ def unsigned(value: Any, maximum: int, minimum: int = 0) -> int: return value -def _fields(value: Any, expected: set[str]) -> dict: +def _fields(value: Any, expected: set[str]) -> dict[str, Any]: if not isinstance(value, dict) or set(value) != expected: raise AgentTaskError('physical presence fields are invalid') return value -def presence_body(operation: str, value: dict) -> dict: +def presence_body(operation: str, value: dict[str, Any]) -> dict[str, Any]: """Share the source's exact finite operation/lease body contract.""" if not isinstance(operation, str) or operation not in _FIELDS: raise AgentTaskError('unknown physical presence operation') @@ -77,7 +77,7 @@ def presence_body(operation: str, value: dict) -> dict: return dict(body) -def validate_request(value: dict) -> tuple[int, str, dict]: +def validate_request(value: dict[str, Any]) -> tuple[int, str, dict[str, Any]]: """Read a closed request with a bounded integer connection sequence.""" value = _fields(value, {'request_id', 'operation', 'body'}) sequence = unsigned(value['request_id'], (1 << 63) - 1, 1) @@ -85,7 +85,7 @@ def validate_request(value: dict) -> tuple[int, str, dict]: return sequence, value['operation'], body -def _snapshot(value: dict, generation: str) -> None: +def _snapshot(value: dict[str, Any], generation: str) -> None: value = _fields(value, {'state', 'idle_seconds', 'interactive', 'held', 'generation', 'revision', 'native_evidence'}) if not isinstance(value['state'], str) or value['state'] not in _STATES: @@ -103,7 +103,7 @@ def _idle(idle: Any) -> None: raise AgentTaskError('physical presence idle is invalid') -def _result(operation: str, value: dict, generation: str) -> None: +def _result(operation: str, value: dict[str, Any], generation: str) -> None: if operation in ('inspect', 'check'): _snapshot(value, generation) elif operation == 'acquire': @@ -117,7 +117,7 @@ def _result(operation: str, value: dict, generation: str) -> None: raise AgentTaskError('unknown physical presence response operation') -def validate_response(value: dict, operation: str, sequence: int, generation: str) -> dict: +def validate_response(value: dict[str, Any], operation: str, sequence: int, generation: str) -> dict[str, Any]: """Validate exact result/status/sequence and the actual live connection's generation.""" try: value = _fields(value, {'request_id', 'status', 'result'}) diff --git a/je_auto_control/utils/agent_runtime/presence_windows.py b/je_auto_control/utils/agent_runtime/presence_windows.py index 7de8f4063..c78f82acd 100644 --- a/je_auto_control/utils/agent_runtime/presence_windows.py +++ b/je_auto_control/utils/agent_runtime/presence_windows.py @@ -24,12 +24,13 @@ @dataclass class _Ticket: operation: str - body: dict + body: dict[str, Any] deadline: float - reply: queue.Queue = field(default_factory=lambda: queue.Queue(maxsize=1), init=False) + reply: queue.Queue[dict[str, Any] | AgentTaskError] = field( + default_factory=lambda: queue.Queue(maxsize=1), init=False) abandoned: threading.Event = field(default_factory=threading.Event, init=False) accepted: threading.Event = field(default_factory=threading.Event, init=False) - lease: dict | None = field(default=None, init=False) + lease: dict[str, Any] | None = field(default=None, init=False) @dataclass @@ -127,7 +128,7 @@ def _reject_queued(self, error: AgentTaskError) -> None: return ticket.reply.put_nowait(error) - def _dispatch(self, ticket: _Ticket) -> dict: + def _dispatch(self, ticket: _Ticket) -> dict[str, Any]: if ticket.operation == 'inspect': return self._state.inspect() if ticket.operation == 'acquire': @@ -197,7 +198,7 @@ def _locked(self, deadline: float) -> Iterator[None]: finally: self._mutex.release() - def _enqueue(self, operation: str, body: dict, deadline: float) -> _Ticket: + def _enqueue(self, operation: str, body: dict[str, Any], deadline: float) -> _Ticket: with self._locked(deadline): if self._lifecycle.closed or self._thread is None or not self._thread.is_alive(): raise AgentTaskError('physical presence source is unavailable') @@ -208,7 +209,7 @@ def _enqueue(self, operation: str, body: dict, deadline: float) -> _Ticket: raise AgentControlBusy('physical presence request capacity is busy') from error return ticket - def request(self, operation: str, body: dict, timeout: float = 0.25) -> dict: + def request(self, operation: str, body: dict[str, Any], timeout: float = 0.25) -> dict[str, Any]: """Apply one closed request after a fresh native poll, never a cached heartbeat alone.""" positive(timeout, 'physical presence request deadline', 0.25) deadline = time.monotonic() + timeout @@ -231,7 +232,7 @@ def request(self, operation: str, body: dict, timeout: float = 0.25) -> dict: ticket.accepted.set() return result - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Read passive availability only; this cannot authorize input or start native monitoring.""" return self._state.inspect() diff --git a/je_auto_control/utils/agent_runtime/remote_journal.py b/je_auto_control/utils/agent_runtime/remote_journal.py index fe0bc42ae..b623971c3 100644 --- a/je_auto_control/utils/agent_runtime/remote_journal.py +++ b/je_auto_control/utils/agent_runtime/remote_journal.py @@ -5,7 +5,7 @@ import json import time from pathlib import Path -from typing import Callable +from typing import Any, Callable from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.input_journal import InputJournal @@ -45,7 +45,7 @@ def __init__(self, resource: Path, device: dict[str, str]) -> None: super().__init__(resource) self.device = device_identity(**device) - def _validate_witness(self, data: dict) -> None: + def _validate_witness(self, data: dict[str, Any]) -> None: self._validate_header(data) if not _integer(data["next_sequence"], 1, 2**53): raise AgentTaskError("remote input witness has an invalid sequence") @@ -62,14 +62,14 @@ def _validate_witness(self, data: dict) -> None: raise AgentTaskError("remote effect witness has no matching perform operation") self._validate_event(data["remote_effect"], "remote_begin", data) - def _validate_header(self, data: dict) -> None: + def _validate_header(self, data: dict[str, Any]) -> None: required = {"version", "remote_protocol", "remote_device", "owner", "held", "in_flight", "review", "remote_effect", "next_sequence", "recovery_epoch"} if (set(data) != required or not _integer(data["version"], 1, 1) or not _integer(data["remote_protocol"], 1, 1) or data["remote_device"] != self.device): raise AgentTaskError("remote input witness is incompatible with this device") - def _fresh(self, review: dict | None = None) -> dict: + def _fresh(self, review: dict[str, Any] | None = None) -> dict[str, Any]: return {"version": 1, "remote_protocol": 1, "remote_device": detached(self.device), "owner": None, "held": {}, "in_flight": None, "review": review, "remote_effect": None, "next_sequence": 1, "recovery_epoch": None} @@ -93,7 +93,7 @@ def acquire(self) -> None: self._data["owner"] = self.owner self._write() - def update(self, held: dict, operation: str | None = None) -> None: + def update(self, held: dict[str, Any], operation: str | None = None) -> None: """Keep the remote marker intact; desktop release data is never valid here.""" if held or operation not in (None, "configure", "observe", "perform"): raise AgentTaskError("remote guard cannot record desktop input or an unknown operation") @@ -102,7 +102,7 @@ def update(self, held: dict, operation: str | None = None) -> None: self._data["in_flight"] = operation self._write() - def _validate_event(self, event: dict, kind: str, state: dict) -> None: + def _validate_event(self, event: dict[str, Any], kind: str, state: dict[str, Any]) -> None: if (not isinstance(event, dict) or set(event) != {"kind", "controller", "device", "sequence", "epoch"} or event["kind"] != kind): @@ -113,7 +113,7 @@ def _validate_event(self, event: dict, kind: str, state: dict) -> None: raise AgentTaskError("remote effect event does not match its controller, device or sequence") _token(event["epoch"], "effect epoch") - def consume(self, event: dict) -> None: + def consume(self, event: dict[str, Any]) -> None: """Persist a matched begin/end before returning permission to acknowledge it.""" kind = event.get("kind") if kind not in ("remote_begin", "remote_end") or self._data.get("in_flight") != "perform": @@ -137,7 +137,7 @@ def release(self) -> None: self._data.update(owner=None, in_flight=None) self._write() - def recover(self, note: str, probe: Callable[[], object], actor: str) -> dict: + def recover(self, note: str, probe: Callable[[], object], actor: str) -> dict[str, Any]: """Require a trusted post-retirement epoch change invalidating all old commands. The host probe must certify this physical device, all old writers retired, diff --git a/je_auto_control/utils/agent_runtime/remote_worker.py b/je_auto_control/utils/agent_runtime/remote_worker.py index d24a1e778..1307ad6d6 100644 --- a/je_auto_control/utils/agent_runtime/remote_worker.py +++ b/je_auto_control/utils/agent_runtime/remote_worker.py @@ -35,10 +35,10 @@ class RemoteDeviceAdapter(Protocol): def ready(self, spec: AgentTaskSpec) -> tuple[bool, str]: """Validate fixed host app/tool scope and trusted presence/held-input providers without input.""" - def observe(self) -> dict: + def observe(self) -> dict[str, Any]: """Read only reviewed device/app evidence; never dispatch input.""" - def prepare(self, name: str, arguments: dict) -> PreparedRemoteAction: + def prepare(self, name: str, arguments: dict[str, Any]) -> PreparedRemoteAction: """Read fresh identity, routing and security evidence and return one finite host-only call.""" def checkpoint(self) -> None: @@ -64,7 +64,7 @@ def __init__(self, source: Any, sink: Any, adapter: RemoteDeviceAdapter) -> None self._expires = 0.0 adapter.set_takeover_handler(self.notify_physical_input) - def _send(self, payload: dict) -> None: + def _send(self, payload: dict[str, Any]) -> None: packet = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8") + b"\n" if len(packet) > _LIMIT: raise AgentTaskError("remote worker packet exceeds its bound") @@ -77,7 +77,7 @@ def notify_physical_input(self) -> None: self._takeover.set() self._send({"control": "physical_input"}) - def _read(self) -> dict: + def _read(self) -> dict[str, Any]: line = self._source.readline(_LIMIT + 1) if not line or len(line) > _LIMIT or not line.endswith(b"\n"): raise AgentTaskError("remote worker request is missing or exceeds its bound") @@ -86,7 +86,7 @@ def _read(self) -> dict: raise AgentTaskError("remote worker requires a closed object") return value - def _notify(self, event: dict) -> None: + def _notify(self, event: dict[str, Any]) -> None: self._send({"id": self._request_id, "event": event}) ack = self._read() if set(ack) != {"ack"} or ack["ack"] is not True: @@ -110,14 +110,14 @@ def run(self) -> None: return @staticmethod - def _validate_request(request: dict) -> None: + def _validate_request(request: dict[str, Any]) -> None: if (set(request) != {"id", "operation", "payload"} or not isinstance(request["id"], str) or re.fullmatch("[0-9a-f]{32}", request["id"]) is None): raise AgentTaskError("remote worker request has an invalid identity") if not isinstance(request["operation"], str) or not isinstance(request["payload"], dict): raise AgentTaskError("remote worker request has invalid operation fields") - def _dispatch(self, operation: str, payload: dict) -> Any: + def _dispatch(self, operation: str, payload: dict[str, Any]) -> Any: if operation in {"bootstrap", "remote_capabilities"}: if payload: raise AgentTaskError("remote worker negotiation accepts no configuration") @@ -134,7 +134,7 @@ def _dispatch(self, operation: str, payload: dict) -> Any: stack.enter_context(operation_scope(TaskOperation(self._spec, self._checkpoint, self._authority.context))) return self._operation(operation, payload) - def _configure(self, payload: dict) -> None: + def _configure(self, payload: dict[str, Any]) -> None: if set(payload) != {"spec", "owner", "remote_guard"}: raise AgentTaskError("remote worker configuration has unreviewed fields") if not isinstance(payload["owner"], dict): @@ -181,7 +181,7 @@ def invoke() -> Any: return self._controller.perform(replace(action, invoke=invoke), self._notify, self._checkpoint) - def _ready_adapter(self) -> dict: + def _ready_adapter(self) -> dict[str, Any]: if self._spec is None: raise AgentTaskError("remote worker has no task specification") ready, reason = self._adapter.ready(self._spec) @@ -192,7 +192,7 @@ def _ready_adapter(self) -> dict: self._checkpoint() return {"ready": ready, "reason": reason} - def _operation(self, operation: str, payload: dict) -> Any: + def _operation(self, operation: str, payload: dict[str, Any]) -> Any: if operation == "configure": return self._ready_adapter() if not self._ready: diff --git a/je_auto_control/utils/agent_runtime/retained_browser.py b/je_auto_control/utils/agent_runtime/retained_browser.py index c1507e92c..06211d72e 100644 --- a/je_auto_control/utils/agent_runtime/retained_browser.py +++ b/je_auto_control/utils/agent_runtime/retained_browser.py @@ -17,7 +17,7 @@ _UNAVAILABLE = "retained browser context is unavailable" -def _binding(row: Mapping) -> dict: +def _binding(row: Mapping[str, Any]) -> dict[str, Any]: return {"id": row["id"], "spec": deepcopy(row["spec"]), "owner": deepcopy(row["owner"])} @@ -25,9 +25,9 @@ def _binding(row: Mapping) -> dict: class RetainedBrowser: """One host-only reservation; neither a saved proof nor a matching ID creates ownership.""" - source: dict + source: dict[str, Any] channel: Any = None - proof: dict | None = None + proof: dict[str, Any] | None = None expires: float = 0 busy: bool = False invalid: bool = False @@ -49,7 +49,7 @@ def full(self) -> bool: return len(self._records) >= _CAPACITY @contextmanager - def reserve(self, row: Mapping) -> Iterator[RetainedBrowser | None]: + def reserve(self, row: Mapping[str, Any]) -> Iterator[RetainedBrowser | None]: """Atomically reserve a bounded slot; never hold the lock during SDK/IPC or cleanup.""" source = _binding(row) with self._lock: @@ -66,7 +66,7 @@ def reserve(self, row: Mapping) -> Iterator[RetainedBrowser | None]: if entry is not None and entry.proof is None: self.discard(source["id"]) - def commit(self, entry: RetainedBrowser, channel: Any, proof: dict) -> None: + def commit(self, entry: RetainedBrowser, channel: Any, proof: dict[str, Any]) -> None: """Accept only the actual reserved slot; failed proof validation still owns detached cleanup.""" with self._lock: if self._records.get(entry.source["id"]) is not entry or entry.channel is not None: @@ -78,7 +78,7 @@ def commit(self, entry: RetainedBrowser, channel: Any, proof: dict) -> None: raise AgentTaskError(_UNAVAILABLE) entry.proof = description - def require(self, row: Mapping) -> RetainedBrowser: + def require(self, row: Mapping[str, Any]) -> RetainedBrowser: """Validate original task/spec/owner and current lifetime; never manufacture a replacement.""" source = _binding(row) with self._lock: @@ -95,7 +95,7 @@ def require(self, row: Mapping) -> RetainedBrowser: self.discard(source["id"]) raise AgentTaskError(_UNAVAILABLE) - def borrow(self, row: Mapping) -> RetainedBrowser: + def borrow(self, row: Mapping[str, Any]) -> RetainedBrowser: """Grant one transient read borrower while process lifetime stays with this collection.""" entry = self.require(row) with self._lock: @@ -127,7 +127,7 @@ def discard(self, task_id: str) -> None: if self._records.get(task_id) is entry: del self._records[task_id] - def sources(self) -> list[dict]: + def sources(self) -> list[dict[str, Any]]: """Return private copies for maintenance, including failed transfers but not live reservations.""" with self._lock: return [deepcopy(entry.source) for entry in self._records.values() diff --git a/je_auto_control/utils/agent_runtime/retained_browser_target.py b/je_auto_control/utils/agent_runtime/retained_browser_target.py index 973852d37..3c0eb92df 100644 --- a/je_auto_control/utils/agent_runtime/retained_browser_target.py +++ b/je_auto_control/utils/agent_runtime/retained_browser_target.py @@ -12,8 +12,8 @@ class RetainedBrowserTarget: """Read only the private effect binding's real original context, never a new helper or page.""" - def __init__(self, pool: RetainedBrowsers, source: Mapping, spec: Any, - current_source: Callable[[], dict], current_operation: Callable[[], Any]) -> None: + def __init__(self, pool: RetainedBrowsers, source: Mapping[str, Any], spec: Any, + current_source: Callable[[], dict[str, Any]], current_operation: Callable[[], Any]) -> None: self._pool, self._source, self._spec = pool, deepcopy(dict(source)), spec self._current_source = current_source self._current_operation = current_operation @@ -47,7 +47,7 @@ def _check(self) -> None: if self._pool.require(self._current_source()) is not entry: raise AgentTaskError("retained browser context is unavailable") - def _request(self, operation: str, payload: dict) -> Any: + def _request(self, operation: str, payload: dict[str, Any]) -> Any: self._check() if self._entry is None: raise AgentTaskError("retained browser reader is unavailable") @@ -56,12 +56,12 @@ def _request(self, operation: str, payload: dict) -> Any: self._check() return result - def _capabilities(self) -> dict: + def _capabilities(self) -> dict[str, Any]: if self._entry is None or self._entry.proof is None: raise AgentTaskError("retained browser context is unavailable") return retirement_proof(self._request("readonly_capabilities", {}), self._entry.proof["context_id"]) - def _call(self, operation: str, payload: dict) -> Any: + def _call(self, operation: str, payload: dict[str, Any]) -> Any: try: self._capabilities() result = self._request(operation, payload) @@ -77,17 +77,17 @@ def _fail(self) -> None: finally: self.cleanup() - def observe(self) -> dict: + def observe(self) -> dict[str, Any]: """Return fresh scoped DOM observation from the retained original SDK page.""" return self._call("observe", {}) - def verify_browser(self, clause: Mapping) -> Any: + def verify_browser(self, clause: Mapping[str, Any]) -> Any: """Read only this task's unchanged pinned independent browser criterion.""" if clause not in self._spec.success_criteria: raise AgentTaskError("browser criterion is not pinned to this read-only task") return self._call("verify_browser", {"clause": dict(clause)}) - def perform(self, _name: str, _arguments: dict) -> Any: + def perform(self, _name: str, _arguments: dict[str, Any]) -> Any: """Read borrowers cannot execute tools or reuse the ordinary target.""" raise AgentTaskError("read-only browser cannot perform tools") diff --git a/je_auto_control/utils/agent_runtime/skill_recording.py b/je_auto_control/utils/agent_runtime/skill_recording.py index deff752c4..53fb8755f 100644 --- a/je_auto_control/utils/agent_runtime/skill_recording.py +++ b/je_auto_control/utils/agent_runtime/skill_recording.py @@ -12,14 +12,15 @@ "AC_press_mouse", "AC_release_mouse"}) -def recorded_spec(runtime: Any, task_id: str, criteria: Any = None) -> dict: +def recorded_spec(runtime: Any, task_id: str, criteria: Any = None) -> dict[str, Any]: """Record a succeeded flow without inventing success from an agent's stop signal.""" row = runtime._row(task_id) assert_verified(row) return recording_template(runtime, row, criteria) -def verified_skill_actions(spec: dict, receipts: list[dict], *, complete: bool = False) -> list[dict]: +def verified_skill_actions(spec: dict[str, Any], receipts: list[dict[str, Any]], *, + complete: bool = False) -> list[dict[str, Any]]: """Verify actual finite semantic effects without restoring captures or constructing executable plans.""" # pylint: disable-next=import-outside-toplevel # reason: receipt semantics are needed only for explicit evidence review from je_auto_control.utils.agent_runtime.workflow_values import complete as whole, verified_prefix @@ -35,7 +36,7 @@ def verified_skill_actions(spec: dict, receipts: list[dict], *, complete: bool = return active -def _strict_effects(spec: AgentTaskSpec, receipts: list[dict]) -> bool: +def _strict_effects(spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> bool: # pylint: disable-next=import-outside-toplevel # reason: strict review shares existing capture/expectation semantics from je_auto_control.utils.agent_runtime.workflow_values import captures, expected, resolve values = captures(spec, receipts) @@ -54,7 +55,8 @@ def _strict_effects(spec: AgentTaskSpec, receipts: list[dict]) -> bool: return True -def recording_template(runtime: Any, row: dict, criteria: Any = None, *, scope: dict | None = None) -> dict: +def recording_template(runtime: Any, row: dict[str, Any], criteria: Any = None, *, + scope: dict[str, Any] | None = None) -> dict[str, Any]: """Derive semantic actions after the trusted caller has separately verified source completion.""" spec = detached(scope if scope is not None else row['spec']) spec["actions"] = _actions(runtime, row) @@ -71,7 +73,7 @@ def recording_template(runtime: Any, row: dict, criteria: Any = None, *, scope: return runtime._validated_spec(spec).to_dict() -def _actions(runtime: Any, row: dict) -> list[dict]: +def _actions(runtime: Any, row: dict[str, Any]) -> list[dict[str, Any]]: receipts = effective_actions(runtime.store.actions(row["id"])) if not receipts or any(receipt["status"] != "confirmed" for receipt in receipts): raise AgentTaskError("skill recording requires confirmed action receipts") @@ -85,14 +87,14 @@ def _actions(runtime: Any, row: dict) -> list[dict]: return [{"tool": receipt["command"], "arguments": receipt["arguments"]} for receipt in receipts] -def assert_verified(row: dict) -> None: +def assert_verified(row: dict[str, Any]) -> None: """Require durable succeeded state and all real completion checks passing.""" reports = row["verification"] if row["state"] != "succeeded" or not reports or any(item["status"] != "passed" for item in reports): raise AgentTaskError("skill evidence task must have independently verified success") -def independent_evidence(spec: dict) -> bool: +def independent_evidence(spec: dict[str, Any]) -> bool: """Accept explicit evidence or reviewed semantic read-back, never dispatch-only completion.""" if any(clause["kind"] != "actions_complete" for clause in spec["success_criteria"]): return True @@ -100,6 +102,6 @@ def independent_evidence(spec: dict) -> bool: and ("expect_result" in action or "expect_capture" in action) for action in spec["actions"]) -def _read_back(action: dict) -> bool: +def _read_back(action: dict[str, Any]) -> bool: return (action["tool"] in {"AC_workflow_wait", "AC_browser_wait", "AC_browser_read"} or action["tool"] == "AC_workflow_control" and action["arguments"].get("operation") in {"get", "state"}) diff --git a/je_auto_control/utils/agent_runtime/store.py b/je_auto_control/utils/agent_runtime/store.py index fa53923b1..aaacb2ea2 100644 --- a/je_auto_control/utils/agent_runtime/store.py +++ b/je_auto_control/utils/agent_runtime/store.py @@ -161,7 +161,7 @@ def _open_connection(driver: Any, path: str) -> Any: raise AgentTaskError("agent runtime database could not be opened") from error -def _request_identity(owner: dict, key: str) -> tuple[str, str]: +def _request_identity(owner: dict[str, Any], key: str) -> tuple[str, str]: if not isinstance(key, str) or not key or len(key) > 256: raise AgentTaskError("idempotency_key requires between one and 256 characters") owner_key = json.dumps([owner.get("user_id"), owner.get("store_path")]) @@ -172,7 +172,7 @@ def _request_identity(owner: dict, key: str) -> tuple[str, str]: return owner_key, digest -def _request_key(connection: Any, owner: dict, key: str, spec: dict, identifier: str) -> str | None: +def _request_key(connection: Any, owner: dict[str, Any], key: str, spec: dict[str, Any], identifier: str) -> str | None: owner_key, digest = _request_identity(owner, key) spec_hash = request_spec_digest(spec) row = connection.execute("SELECT task_id,spec_hash FROM agent_request_keys WHERE owner_key=? AND key_hash=?", @@ -186,7 +186,7 @@ def _request_key(connection: Any, owner: dict, key: str, spec: dict, identifier: return None -def request_spec_digest(spec: dict) -> str: +def request_spec_digest(spec: dict[str, Any]) -> str: """Hash the exact normalized specification used by accepted request keys.""" return hashlib.sha256(json.dumps(spec, sort_keys=True).encode("utf-8")).hexdigest() @@ -236,10 +236,10 @@ def connection(self, *, write: bool = False) -> Iterator[Any]: finally: connection.close() - def create(self, spec: dict | TaskAdmission, owner: dict, *, idempotency_key: str | None = None, + def create(self, spec: dict[str, Any] | TaskAdmission, owner: dict[str, Any], *, idempotency_key: str | None = None, trigger_event: tuple[str, str, str] | None = None, recovery: tuple[str, str, str] | None = None, - authorization: dict | RecoveryBinding | CompletionBinding | None = None) -> str: + authorization: dict[str, Any] | RecoveryBinding | CompletionBinding | None = None) -> str: """Persist an immutable authorized task snapshot before it can execute.""" identifier = uuid.uuid4().hex now = time.time() @@ -270,12 +270,12 @@ def create(self, spec: dict | TaskAdmission, owner: dict, *, idempotency_key: st bind_recovery(connection, identifier, authorization, owner) return identifier - def lookup_request(self, owner: dict, key: str) -> str | None: + def lookup_request(self, owner: dict[str, Any], key: str) -> str | None: """Read the exact owner's request key without creating or resubmitting a task.""" record = self.request_record(owner, key) return record["task_id"] if record else None - def request_record(self, owner: dict, key: str, *, connection: Any = None) -> dict[str, Any] | None: + def request_record(self, owner: dict[str, Any], key: str, *, connection: Any = None) -> dict[str, Any] | None: """Read accepted identity and immutable spec digest from the same request snapshot.""" identity = _request_identity(owner, key) transaction = self.connection() if connection is None else nullcontext(connection) @@ -366,7 +366,8 @@ def start(self, task_id: str) -> None: if cursor.rowcount != 1: raise AgentTaskError("task stopped before control activation") - def prepare(self, task_id: str, command: str, arguments: dict, *, grounding: dict | None = None) -> str: + def prepare(self, task_id: str, command: str, arguments: dict[str, Any], *, + grounding: dict[str, Any] | None = None) -> str: """Durably record the next operation before any external side effect.""" identifier = uuid.uuid4().hex with self.connection(write=True) as connection: @@ -421,7 +422,7 @@ def recover(self) -> None: connection.execute("UPDATE agent_control SET owner=''") -def _receipt(row: Any) -> dict: +def _receipt(row: Any) -> dict[str, Any]: result = dict(row) result["arguments"] = json.loads(result["arguments"]) result["result"] = json.loads(result["result"]) if result["result"] is not None else None diff --git a/je_auto_control/utils/agent_runtime/target_profiles.py b/je_auto_control/utils/agent_runtime/target_profiles.py index 7f5f835ef..795c12905 100644 --- a/je_auto_control/utils/agent_runtime/target_profiles.py +++ b/je_auto_control/utils/agent_runtime/target_profiles.py @@ -22,7 +22,7 @@ "not_supported"}) -def _transfer_profile(profile: AgentTargetProfile, row: Any) -> dict: +def _transfer_profile(profile: AgentTargetProfile, row: Any) -> dict[str, Any]: if row is None or row['digest'] != profile.digest or row['config'] != json.dumps(profile.to_dict()): raise AgentTaskError('destination target profile integrity changed') if profile.kind != 'files' or not profile.roots: @@ -38,7 +38,7 @@ def __init__(self, runtime: Any) -> None: self._runtime = runtime self._profiles: dict[str, AgentTargetProfile] = {} self._enabled: dict[str, bool] = {} - self._last_probes: dict[str, dict] = {} + self._last_probes: dict[str, dict[str, Any]] = {} with runtime.store.connection() as connection: rows = connection.execute("SELECT * FROM agent_target_profiles ORDER BY created,name LIMIT 101").fetchall() controls = connection.execute("SELECT * FROM agent_target_controls").fetchall() @@ -55,7 +55,7 @@ def __init__(self, runtime: Any) -> None: raise AgentTaskError("stored target enable control is invalid") self._enabled[row["name"]] = bool(row["enabled"]) - def control(self, operation: str, request: Mapping | None = None) -> dict: + def control(self, operation: str, request: Mapping[str, Any] | None = None) -> dict[str, Any]: """Register an immutable profile or explicitly change target availability with host authority.""" identity = current_authorization() if identity is not None and not identity.allows("manage_hosts"): @@ -73,7 +73,7 @@ def control(self, operation: str, request: Mapping | None = None) -> dict: self._toggle(name, operation == "enable") return self._details(name) - def _probe(self, value: dict) -> dict: + def _probe(self, value: dict[str, Any]) -> dict[str, Any]: with self._runtime._mutex: name = self._request_name(value) adapter = self._runtime._targets[name] @@ -91,14 +91,14 @@ def _probe(self, value: dict) -> dict: details["probe"] = detached(self._last_probes[name]) return details - def _request_name(self, value: dict) -> str: + def _request_name(self, value: dict[str, Any]) -> str: if set(value) != {"name"} or not isinstance(value["name"], str): raise AgentTaskError("target operation requires one configured name") if value["name"] not in self._runtime._targets: raise AgentTaskError("target operation requires one configured name") return value["name"] - def _register(self, value: dict) -> dict: + def _register(self, value: dict[str, Any]) -> dict[str, Any]: profile = AgentTargetProfile.from_dict(value) name = profile.name if name in self._runtime._targets or name in self._enabled: @@ -150,12 +150,12 @@ def check(self, spec: AgentTaskSpec, *, require_pin: bool = True) -> None: raise AgentTaskError("task target profile identity changed or its pin is invalid") profile.check(spec) - def describe(self) -> dict: + def describe(self) -> dict[str, Any]: """List resource names and declared adapter support without native probes or sensitive configuration.""" with self._runtime._mutex: return {"targets": [self._summary(name) for name in sorted(self._runtime._targets)]} - def transfer_profile(self, name: str, *, connection: Any = None) -> dict: + def transfer_profile(self, name: str, *, connection: Any = None) -> dict[str, Any]: """Require an actual enabled immutable files profile using the caller's existing SQL snapshot.""" if not isinstance(name, str) or name not in self._profiles: raise AgentTaskError('destination requires a configured files target profile') @@ -167,7 +167,7 @@ def transfer_profile(self, name: str, *, connection: Any = None) -> dict: raise AgentTaskError('destination target profile is disabled') return _transfer_profile(self._profiles[name], row) - def _summary(self, name: str) -> dict: + def _summary(self, name: str) -> dict[str, Any]: profile = self._profiles.get(name) if profile is not None: kind, tools = profile.kind, list(profile.allowed_tools) @@ -190,7 +190,7 @@ def _summary(self, name: str) -> dict: result["last_probe"] = detached(self._last_probes[name]) return result - def _details(self, name: str) -> dict: + def _details(self, name: str) -> dict[str, Any]: profile = self._profiles.get(name) result = self._summary(name) if profile is not None: diff --git a/je_auto_control/utils/agent_runtime/transfer_evidence_contract.py b/je_auto_control/utils/agent_runtime/transfer_evidence_contract.py index 613d33042..26ef79945 100644 --- a/je_auto_control/utils/agent_runtime/transfer_evidence_contract.py +++ b/je_auto_control/utils/agent_runtime/transfer_evidence_contract.py @@ -3,7 +3,7 @@ from copy import deepcopy from hashlib import sha256 -from typing import Mapping +from typing import Any, Mapping from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.transfer_models import MAX_MANIFEST_BYTES, _canonical, _deadline, _hex, _object @@ -18,7 +18,7 @@ _NODE = {'batch_id', 'graph_hash', 'node_id'} -def evidence_binding(value: Mapping) -> dict: +def evidence_binding(value: Mapping[str, Any]) -> dict[str, Any]: """Require the exact original accepted key/spec and optional actual DAG identity.""" if not isinstance(value, Mapping): raise AgentTaskError('portable evidence binding must be an object') @@ -31,7 +31,7 @@ def evidence_binding(value: Mapping) -> dict: return result -def _node(value: Mapping, *, projection: bool) -> None: +def _node(value: Mapping[str, Any], *, projection: bool) -> None: _hex(value['batch_id'], 32) _hex(value['graph_hash'], 64) _text(value['node_id'], 256, 'node identity') @@ -39,13 +39,13 @@ def _node(value: Mapping, *, projection: bool) -> None: _hex(value['request_digest'], 64) -def request_digest(binding: Mapping) -> str: +def request_digest(binding: Mapping[str, Any]) -> str: """Hash only the key and accepted specification actually received by the source.""" return sha256(_canonical({'key_hash': binding['request_key_hash'], 'submitted_spec_digest': binding['submitted_spec_digest']})).hexdigest() -def portable_evidence(value: Mapping, *, resolved: bool = True) -> dict: +def portable_evidence(value: Mapping[str, Any], *, resolved: bool = True) -> dict[str, Any]: """Validate a bounded redacted proof; a validated DTO alone supplies no current source authority.""" if not isinstance(value, Mapping): raise AgentTaskError('portable evidence must be an object') @@ -66,14 +66,14 @@ def portable_evidence(value: Mapping, *, resolved: bool = True) -> dict: return deepcopy(result) -def _flags(value: dict) -> None: +def _flags(value: dict[str, Any]) -> None: contract = value['contract'] if (not isinstance(contract, int) or isinstance(contract, bool) or contract != 1 or value['evidence_only'] is not True or value['input_authorized'] is not False): raise AgentTaskError('portable evidence requires the exact evidence-only contract') -def _reports(reports: list) -> None: +def _reports(reports: list[Any]) -> None: if not isinstance(reports, list) or not reports: raise AgentTaskError('portable evidence requires independent finite verification') for report in reports: @@ -83,7 +83,7 @@ def _reports(reports: list) -> None: raise AgentTaskError('portable evidence contains an unconfirmed criterion') -def _chain(value: dict) -> None: +def _chain(value: dict[str, Any]) -> None: chain = value['chain'] if not isinstance(chain, list) or not 1 <= len(chain) <= 16: raise AgentTaskError('portable evidence requires one to sixteen real recovery links') @@ -100,7 +100,7 @@ def _chain(value: dict) -> None: raise AgentTaskError('portable evidence chain changed its final completion witness') -def _link(value: Mapping) -> None: +def _link(value: Mapping[str, Any]) -> None: _object(value, {'source_task', 'task_id', 'source_snapshot', 'snapshot', 'completion_snapshot'}) for name in ('source_task', 'task_id'): _hex(value[name], 32) diff --git a/je_auto_control/utils/agent_runtime/transfer_import_files.py b/je_auto_control/utils/agent_runtime/transfer_import_files.py index 3f54d0cfd..f454fd3ac 100644 --- a/je_auto_control/utils/agent_runtime/transfer_import_files.py +++ b/je_auto_control/utils/agent_runtime/transfer_import_files.py @@ -18,7 +18,7 @@ def _assets(manifest: TransferManifest) -> AssetManifest: return AssetManifest(tuple(AssetFile(item.name, item.blob.sha256, item.blob.size) for item in manifest.files)) -def publication_root(record: dict, publication: dict) -> Path: +def publication_root(record: dict[str, Any], publication: dict[str, Any]) -> Path: """Require the exact host-derived directory and persisted filesystem identity before inspecting bytes.""" root = Path(record['scope']['destination']['directory']) / ('import-' + record['id']) if publication.get('root') != str(root) or publication.get('phase') not in {'owned', 'verified'}: @@ -29,7 +29,7 @@ def publication_root(record: dict, publication: dict) -> Path: return root -def retire_import_staging(record: dict, publication: dict) -> dict | None: +def retire_import_staging(record: dict[str, Any], publication: dict[str, Any]) -> dict[str, Any] | None: """Retire a journaled allocation without touching published generations or unrelated output.""" if not publication or publication.get('phase') == 'preparing': return None @@ -43,7 +43,7 @@ def retire_import_staging(record: dict, publication: dict) -> dict | None: return witness -def inspect_import(record: dict, manifest: TransferManifest, publication: dict, +def inspect_import(record: dict[str, Any], manifest: TransferManifest, publication: dict[str, Any], check: Callable[[], None]) -> AssetSyncResult: """Hash an owned existing generation through the shared validator without creating, deleting or publishing files.""" root, assets = publication_root(record, publication), _assets(manifest) @@ -72,8 +72,8 @@ def open(self, asset: AssetFile) -> BinaryIO: return self.cache.store.open(self.account, selected.blob) -def receive_chunks(record: dict, manifest: TransferManifest, cache: Any, read: Callable, - check: Callable[[], None]) -> None: +def receive_chunks(record: dict[str, Any], manifest: TransferManifest, cache: Any, + read: Callable[[str], dict[str, Any]], check: Callable[[], None]) -> None: """Commit bounded content-addressed blobs only after current authority is rechecked around every cache effect.""" for item in manifest.files: check() @@ -90,9 +90,9 @@ def receive_chunks(record: dict, manifest: TransferManifest, cache: Any, read: C check() -def publish_import(record: dict, manifest: TransferManifest, cache: Any, check: Callable[[], None], - record_publication: Callable[[dict], None], - stage_retired: Callable[[dict], None] | None = None) -> AssetSyncResult: +def publish_import(record: dict[str, Any], manifest: TransferManifest, cache: Any, check: Callable[[], None], + record_publication: Callable[[dict[str, Any]], None], + stage_retired: Callable[[dict[str, Any]], None] | None = None) -> AssetSyncResult: """Use an exclusive per-import directory and the established generation layout without replacing user output.""" directory = Path(record['scope']['destination']['directory']) root = directory / ('import-' + record['id']) @@ -112,10 +112,10 @@ def cancelled() -> bool: if resolved(root) != root or [root.stat().st_dev, root.stat().st_ino] != publication['identity']: raise AgentTaskError('owned import publication directory changed') return False - def staged(witness: dict) -> None: + def staged(witness: dict[str, Any]) -> None: publication['staging'] = witness record_publication(publication) - def retired(witness: dict) -> None: + def retired(witness: dict[str, Any]) -> None: publication['staging'] = {**witness, 'cleaned': True} if stage_retired is not None: stage_retired(witness) diff --git a/je_auto_control/utils/agent_runtime/transfer_routing.py b/je_auto_control/utils/agent_runtime/transfer_routing.py index 27e2da48e..3364b7220 100644 --- a/je_auto_control/utils/agent_runtime/transfer_routing.py +++ b/je_auto_control/utils/agent_runtime/transfer_routing.py @@ -14,7 +14,7 @@ from je_auto_control.utils.agent_runtime.transfer_records import TransferRecords, _text -def _created_digest(operation: str, reply: dict) -> str: +def _created_digest(operation: str, reply: dict[str, Any]) -> str: if operation == 'create_evidence': return evidence_digest(reply['evidence']['summary']) if operation == 'create_import': @@ -25,14 +25,14 @@ def _created_digest(operation: str, reply: dict) -> str: class RoutedTransfers: """A local opaque review binds its actual caller, host fingerprint, foreign review, digest and key.""" - def __init__(self, runtime: Any, records: TransferRecords, peer: Any, binding: Callable, + def __init__(self, runtime: Any, records: TransferRecords, peer: Any, binding: Callable[[str], str], checkpoint: Callable[[], float]) -> None: self.runtime, self.records, self.peer = runtime, records, peer self.binding, self.checkpoint = binding, checkpoint - self._reviews: dict[str, dict] = {} + self._reviews: dict[str, dict[str, Any]] = {} self._initialized = False - def control(self, host: str, operation: str, request: Mapping) -> dict: + def control(self, host: str, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Route only closed source operations; no coordinator path or principal crosses the wire.""" value = management_request(operation, request) if self.peer is None: @@ -63,7 +63,8 @@ def _prepare(self, host: str, binding: str) -> None: self._check(host, binding) self._initialized = True - def _review(self, host: str, binding: str, request: dict, actor: dict, operation: str) -> dict: + def _review(self, host: str, binding: str, request: dict[str, Any], actor: dict[str, Any], + operation: str) -> dict[str, Any]: self._prepare(host, binding) now = time.time() self._reviews = {key: record for key, record in self._reviews.items() if record['review_expires'] > now} @@ -85,7 +86,8 @@ def _review(self, host: str, binding: str, request: dict, actor: dict, operation 'request': deepcopy(request)}} return {**reply, 'review': review, 'review_expires': review_expiry} - def _create(self, host: str, binding: str, request: dict, actor: dict, operation: str) -> dict: + def _create(self, host: str, binding: str, request: dict[str, Any], actor: dict[str, Any], + operation: str) -> dict[str, Any]: self._prepare(host, binding) record = self._approved(host, binding, request, actor, operation) self._check(host, binding) @@ -97,7 +99,8 @@ def _create(self, host: str, binding: str, request: dict, actor: dict, operation raise AgentTaskError('routed creation reply differs from its approved immutable manifest') return reply - def _approved(self, host: str, binding: str, request: dict, actor: dict, operation: str) -> dict: + def _approved(self, host: str, binding: str, request: dict[str, Any], actor: dict[str, Any], + operation: str) -> dict[str, Any]: key_hash = _text(request['idempotency_key'], 256, 'idempotency key') note_hash = _text(request['note'], 4000, 'approval note') with self.runtime.store.connection() as connection: @@ -125,7 +128,7 @@ def _approved(self, host: str, binding: str, request: dict, actor: dict, operati return created @staticmethod - def _bound(record: dict, host: str, binding: str, actor: dict, operation: str) -> None: + def _bound(record: dict[str, Any], host: str, binding: str, actor: dict[str, Any], operation: str) -> None: scope = record['scope'] if (record['kind'] != 'route' or record['actor'] != actor_key(actor) or scope.get('host') != host or scope.get('binding') != binding diff --git a/je_auto_control/utils/agent_runtime/transfer_selection.py b/je_auto_control/utils/agent_runtime/transfer_selection.py index 46d7ae4b6..010ba596d 100644 --- a/je_auto_control/utils/agent_runtime/transfer_selection.py +++ b/je_auto_control/utils/agent_runtime/transfer_selection.py @@ -39,7 +39,8 @@ def _decode(self, body: bytes, *, final: bool) -> None: self._tail = window[-(len(self._expected) - 1):] if len(self._expected) > 1 else '' -def selected_files(context: dict, values: Any, checkpoint: Callable[[], None]) -> list[tuple[str, dict]]: +def selected_files(context: dict[str, Any], values: Any, + checkpoint: Callable[[], None]) -> list[tuple[str, dict[str, Any]]]: """Compile exact source criteria; no request path or replacement filename is accepted.""" criteria = _criteria(context, values) _check_paths(context, criteria, checkpoint) @@ -53,12 +54,13 @@ def selected_files(context: dict, values: Any, checkpoint: Callable[[], None]) - return result -def check_source_paths(context: dict, values: Any, checkpoint: Callable[[], None]) -> None: +def check_source_paths(context: dict[str, Any], values: Any, checkpoint: Callable[[], None]) -> None: """Recheck selected source path authority without rereading historical output or manifest bytes.""" _check_paths(context, _criteria(context, values), checkpoint) -def _check_paths(context: dict, criteria: list[tuple[TransferSelection, dict]], checkpoint: Callable[[], None]) -> None: +def _check_paths(context: dict[str, Any], criteria: list[tuple[TransferSelection, dict[str, Any]]], + checkpoint: Callable[[], None]) -> None: for selection, clause in criteria: paths = ([Path(clause['directory']) / name for name in selection.names] if clause['kind'] == 'file_manifest' else [Path(clause['path'])]) @@ -68,7 +70,7 @@ def _check_paths(context: dict, criteria: list[tuple[TransferSelection, dict]], checkpoint() -def _criteria(context: dict, values: Any) -> list[tuple[TransferSelection, dict]]: +def _criteria(context: dict[str, Any], values: Any) -> list[tuple[TransferSelection, dict[str, Any]]]: result = [] count = 0 for selection in _selections(values): @@ -80,7 +82,7 @@ def _criteria(context: dict, values: Any) -> list[tuple[TransferSelection, dict] return result -def _source_criterion(criteria: list, selection: TransferSelection) -> dict: +def _source_criterion(criteria: list[dict[str, Any]], selection: TransferSelection) -> dict[str, Any]: if selection.criterion >= len(criteria): raise AgentTaskError('selected criterion is outside the completed source') clause = criteria[selection.criterion] @@ -101,8 +103,8 @@ def _selections(values: Any) -> list[TransferSelection]: return selections -def _manifest_selection(policy: Any, clause: dict, selection: TransferSelection, - checkpoint: Callable[[], None]) -> list[tuple[str, dict]]: +def _manifest_selection(policy: Any, clause: dict[str, Any], selection: TransferSelection, + checkpoint: Callable[[], None]) -> list[tuple[str, dict[str, Any]]]: pieces: list[bytes] = [] source = snapshot_file(policy, clause['path'], checkpoint, max_bytes=1_000_000, inspect=pieces.append) try: diff --git a/je_auto_control/utils/agent_runtime/transfer_staging.py b/je_auto_control/utils/agent_runtime/transfer_staging.py index db6c99377..44c06a5e5 100644 --- a/je_auto_control/utils/agent_runtime/transfer_staging.py +++ b/je_auto_control/utils/agent_runtime/transfer_staging.py @@ -26,7 +26,7 @@ def _object(path: Path, identity: list[int], *, directory: bool) -> None: raise AgentTaskError('owned staging filesystem identity changed') -def _stage(root: Path, root_identity: list[int], witness: dict) -> Path: +def _stage(root: Path, root_identity: list[int], witness: dict[str, Any]) -> Path: stage = Path(witness['path']) if stage.parent != root or not stage.name.startswith('.incoming-') or not stage.is_absolute(): raise AgentTaskError('staging journal is outside its exact import root') @@ -43,7 +43,7 @@ def _known_path(stage: Path, name: str) -> Path: return path -def _parents(stage: Path, path: Path, directories: dict) -> None: +def _parents(stage: Path, path: Path, directories: dict[str, list[int]]) -> None: for parent in (path.parent, *path.parent.parents): if parent == stage.parent: break @@ -57,12 +57,12 @@ def _present(path: Path) -> bool: return path.exists() or path.is_symlink() -def _known_objects(stage: Path, witness: dict) -> set[Path]: +def _known_objects(stage: Path, witness: dict[str, Any]) -> set[Path]: return {stage, *[_known_path(stage, name) for name in witness['directories'] if name], *[_known_path(stage, name) for name in witness['files']]} -def _validate_contents(stage: Path, witness: dict) -> None: +def _validate_contents(stage: Path, witness: dict[str, Any]) -> None: directories, files = witness['directories'], witness['files'] known = _known_objects(stage, witness) for name, identity in directories.items(): @@ -79,7 +79,7 @@ def _validate_contents(stage: Path, witness: dict) -> None: _object(path, identity, directory=False) -def cleanup_staging(root: Path, root_identity: list[int], witness: dict) -> None: +def cleanup_staging(root: Path, root_identity: list[int], witness: dict[str, Any]) -> None: """Remove only journaled files and empty directories after validating the complete candidate tree.""" stage = _stage(root, root_identity, witness) if not _present(stage): @@ -104,15 +104,15 @@ def cleanup_staging(root: Path, root_identity: list[int], witness: dict) -> None @dataclass class _StagingState: - witness: dict = field(default_factory=dict) + witness: dict[str, Any] = field(default_factory=dict[str, Any]) used: set[str] = field(default_factory=set) class ImportStaging: """Preallocate and journal all exclusive output identities before the shared publisher writes bytes.""" - def __init__(self, root: Path, identity: list[int], record: Callable[[dict], None], - retired: Callable[[dict], None]) -> None: + def __init__(self, root: Path, identity: list[int], record: Callable[[dict[str, Any]], None], + retired: Callable[[dict[str, Any]], None]) -> None: self.root, self.identity, self.record, self.retired = root, identity, record, retired self._state = _StagingState() diff --git a/je_auto_control/utils/agent_runtime/transfer_transport.py b/je_auto_control/utils/agent_runtime/transfer_transport.py index 210a19acb..d3f39665c 100644 --- a/je_auto_control/utils/agent_runtime/transfer_transport.py +++ b/je_auto_control/utils/agent_runtime/transfer_transport.py @@ -19,14 +19,16 @@ from je_auto_control.utils.exception.cancellation import cancellation_checkpoint _PEER_SECONDS = 30 # the longest timeout one peer request may carry +_Validator = Callable[[dict[str, Any]], dict[str, Any]] # checks one peer reply, returns its result @dataclass(frozen=True) class TransferPeer: """Validate descriptors, chunks and management projections under the host's current registered identity.""" - invoke: Callable[[str, str, str, dict, float], dict] + invoke: Callable[[str, str, str, dict[str, Any], float], dict[str, Any]] - def call(self, host: str, binding: str, operation: str, request: Mapping, timeout: float) -> dict: + def call(self, host: str, binding: str, operation: str, request: Mapping[str, Any], + timeout: float) -> dict[str, Any]: """Read an exact source export or content hash with bounded bytes and a fixed local deadline.""" value = self._request(host, binding, operation, request, timeout) deadline = time.monotonic() + timeout @@ -34,7 +36,7 @@ def call(self, host: str, binding: str, operation: str, request: Mapping, timeou return self._exchange(host, binding, '/agent/transfer/peer', {'operation': operation, 'request': value}, deadline, validate) - def _validator(self, operation: str, value: dict) -> Callable: + def _validator(self, operation: str, value: dict[str, Any]) -> _Validator: if operation == 'evidence': return lambda reply: self._evidence(reply, value) if operation == 'export': @@ -42,7 +44,7 @@ def _validator(self, operation: str, value: dict) -> Callable: return lambda reply: self._chunk(reply, value['sha256']) @staticmethod - def _evidence(reply: dict, request: dict) -> dict: + def _evidence(reply: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: result = portable_evidence(reply) if result['expires'] <= time.time(): raise AgentTaskError('portable evidence source retention has expired') @@ -58,14 +60,16 @@ def _evidence(reply: dict, request: dict) -> dict: raise AgentTaskError('portable evidence reply changed its actual accepted request') return result - def manage(self, host: str, binding: str, operation: str, request: Mapping, timeout: float) -> dict: + def manage(self, host: str, binding: str, operation: str, request: Mapping[str, Any], + timeout: float) -> dict[str, Any]: """Use only closed source management fields and validate the foreign public projection.""" self._identity(host, binding, timeout) value = management_request(operation, request) return self._exchange(host, binding, '/agent/transfer', {'operation': operation, 'request': value}, time.monotonic() + timeout, lambda reply: management_reply(operation, reply, value)) - def _exchange(self, host: str, binding: str, path: str, body: dict, deadline: float, validate: Callable) -> dict: + def _exchange(self, host: str, binding: str, path: str, body: dict[str, Any], deadline: float, + validate: _Validator) -> dict[str, Any]: self._checkpoint(deadline) try: # Capped: on an unchanged clock reading, (t + 30) - t can round just above 30, which the route refuses. @@ -83,7 +87,7 @@ def _exchange(self, host: str, binding: str, path: str, body: dict, deadline: fl raise AgentTaskError('peer transfer is unavailable or its reply is malformed') from error @staticmethod - def _request(host: str, binding: str, operation: str, request: Mapping, timeout: float) -> dict: + def _request(host: str, binding: str, operation: str, request: Mapping[str, Any], timeout: float) -> dict[str, Any]: TransferPeer._identity(host, binding, timeout) fields = {'export': {'export_id'}, 'chunk': {'export_id', 'sha256'}, 'evidence': {'grant_id', 'binding'}} if not isinstance(operation, str) or operation not in fields: @@ -119,14 +123,14 @@ def _checkpoint(deadline: float) -> None: raise AgentTaskError('peer transfer deadline exhausted') @staticmethod - def _manifest(reply: dict, identifier: str) -> dict: + def _manifest(reply: dict[str, Any], identifier: str) -> dict[str, Any]: manifest = TransferManifest.from_dict(reply) if manifest.export_id != identifier or manifest.expires <= time.time(): raise AgentTaskError('peer export identity changed or its grant is expired') return manifest.to_dict() @staticmethod - def _chunk(reply: dict, digest: str) -> dict: + def _chunk(reply: dict[str, Any], digest: str) -> dict[str, Any]: value = _object(reply, {'contract', 'sha256', 'data'}) version = value['contract'] if isinstance(version, bool) or not isinstance(version, int) or version != 1: diff --git a/je_auto_control/utils/agent_runtime/trigger_reauthorization.py b/je_auto_control/utils/agent_runtime/trigger_reauthorization.py index 26c8769b5..5035402c2 100644 --- a/je_auto_control/utils/agent_runtime/trigger_reauthorization.py +++ b/je_auto_control/utils/agent_runtime/trigger_reauthorization.py @@ -22,7 +22,7 @@ OPERATIONS = ("review_authorization", "create_authorized") -def authorization_metadata(connection: Any, identifier: str) -> dict: +def authorization_metadata(connection: Any, identifier: str) -> dict[str, Any]: """Expose only an authorized binding's lineage proof and durable replacement identity.""" result = {} row = connection.execute("SELECT details,source_trigger FROM agent_trigger_authorizations WHERE trigger_id=?", @@ -36,7 +36,7 @@ def authorization_metadata(connection: Any, identifier: str) -> dict: return result -def _snapshot(connection: Any, source: dict) -> tuple[str, int]: +def _snapshot(connection: Any, source: dict[str, Any]) -> tuple[str, int]: live = connection.execute("SELECT * FROM agent_triggers WHERE id=?", (source["id"],)).fetchone() if live is None: raise AgentTaskError("trigger snapshot changed; review authorization again") @@ -51,7 +51,7 @@ class TriggerReauthorization: def __init__(self, triggers: Any) -> None: self.triggers = triggers - def control(self, operation: str, request: dict) -> dict: + def control(self, operation: str, request: dict[str, Any]) -> dict[str, Any]: """Require current owner/operator review; old tasks and native input ownership are never resumed.""" fields = {"trigger_id"} if operation == "create_authorized": @@ -67,7 +67,7 @@ def control(self, operation: str, request: dict) -> dict: return self._review(source) return self._create(source, request) - def _review(self, source: dict) -> dict: + def _review(self, source: dict[str, Any]) -> dict[str, Any]: runtime = self.triggers.runtime with runtime.store.connection() as connection: metadata = authorization_metadata(connection, source["id"]) @@ -77,7 +77,7 @@ def _review(self, source: dict) -> dict: "spec": None, "issues": ["already_reauthorized"], "approval_required": False} authorization = prepare_authorization(AgentTaskSpec.from_dict(source["spec"]), snapshot) template = self._template(source, authorization) - reviewed: dict | None = None + reviewed: dict[str, Any] | None = None issues = [] try: # pylint: disable-next=protected-access # reason: renewal cannot advertise a template outside current scope @@ -93,12 +93,12 @@ def _review(self, source: dict) -> dict: "approval_required": True, "activation": "future_events"} @staticmethod - def _template(source: dict, authorization: dict) -> dict: + def _template(source: dict[str, Any], authorization: dict[str, Any]) -> dict[str, Any]: template = authorized_template(source["spec"], authorization) template["actions"] = source["spec"]["actions"] return template - def _create(self, source: dict, request: dict) -> dict: + def _create(self, source: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: runtime = self.triggers.runtime note = request["note"] if not isinstance(note, str) or not note.strip() or len(note) > 4000: @@ -117,7 +117,8 @@ def _create(self, source: dict, request: dict) -> dict: with DeferredAuthorization(owner).scope(): return self._insert(source, request, spec, config, details) - def _insert(self, source: dict, request: dict, spec: AgentTaskSpec, config: dict, details: dict) -> dict: + def _insert(self, source: dict[str, Any], request: dict[str, Any], spec: AgentTaskSpec, config: dict[str, Any], + details: dict[str, Any]) -> dict[str, Any]: with self.triggers.runtime.store.connection(write=True) as connection: previous = connection.execute("SELECT * FROM agent_trigger_authorizations WHERE source_trigger=?", (source["id"],)).fetchone() @@ -137,7 +138,7 @@ def _insert(self, source: dict, request: dict, spec: AgentTaskSpec, config: dict "kind": source["kind"], "reauthorization": details} @staticmethod - def _existing(connection: Any, previous: Any, request: dict, spec_hash: str) -> dict: + def _existing(connection: Any, previous: Any, request: dict[str, Any], spec_hash: str) -> dict[str, Any]: details = json.loads(previous["details"]) if (previous["snapshot"] != request["snapshot"] or previous["spec_hash"] != spec_hash or details["review"] != request["authorization_review"]): diff --git a/je_auto_control/utils/agent_runtime/verification.py b/je_auto_control/utils/agent_runtime/verification.py index de22b791d..d5e69747d 100644 --- a/je_auto_control/utils/agent_runtime/verification.py +++ b/je_auto_control/utils/agent_runtime/verification.py @@ -41,14 +41,14 @@ def _validate_clause(kind: str, clause: Mapping[str, Any]) -> None: def verify(policy: TaskPolicy, receipts: Sequence[Mapping[str, Any]], observation: Mapping[str, Any], *, - browser_read: Callable[[Mapping], Any] | None = None) -> list[dict[str, Any]]: + browser_read: Callable[[Mapping[str, Any]], Any] | None = None) -> list[dict[str, Any]]: """Evaluate all clauses against confirmed results and fresh target observations.""" return verify_clauses(policy.spec.success_criteria, policy, receipts, observation, browser_read=browser_read) def verify_clauses(clauses: Sequence[Mapping[str, Any]], policy: TaskPolicy, receipts: Sequence[Mapping[str, Any]], observation: Mapping[str, Any], *, - browser_read: Callable[[Mapping], Any] | None = None) -> list[dict[str, Any]]: + browser_read: Callable[[Mapping[str, Any]], Any] | None = None) -> list[dict[str, Any]]: """Evaluate the given clauses; a failure to decide one is ``unknown``, never ``passed``.""" reports = [] for clause in clauses: @@ -67,7 +67,7 @@ def verify_clauses(clauses: Sequence[Mapping[str, Any]], policy: TaskPolicy, rec def _evaluate(clause: Mapping[str, Any], policy: TaskPolicy, receipts: Sequence[Mapping[str, Any]], - observation: Mapping[str, Any], browser_read: Callable[[Mapping], Any] | None) -> bool | None: + observation: Mapping[str, Any], browser_read: Callable[[Mapping[str, Any]], Any] | None) -> bool | None: kind = clause["kind"] if kind == "browser": value = browser_read(clause) if browser_read is not None else None @@ -85,7 +85,7 @@ def _evaluate(clause: Mapping[str, Any], policy: TaskPolicy, receipts: Sequence[ return _file_evidence(clause, policy) -def _screen_evidence(observation: Mapping, spec: dict) -> bool | None: +def _screen_evidence(observation: Mapping[str, Any], spec: dict[str, Any]) -> bool | None: elements = observation.get("elements") if not isinstance(elements, (list, tuple)) or observation.get("semantic_observation", True) is not True: return None @@ -98,7 +98,7 @@ def _screen_evidence(observation: Mapping, spec: dict) -> bool | None: return _partial_screen_evidence(elements, spec) -def _partial_screen_evidence(elements: Sequence[Mapping], spec: dict) -> bool | None: +def _partial_screen_evidence(elements: Sequence[Mapping[str, Any]], spec: dict[str, Any]) -> bool | None: reviewed = [{"name": _reviewed_label(item)} for item in elements] results = [_partial_text_evidence(reviewed, key, value) for key, value in spec.items()] if False in results: @@ -106,7 +106,7 @@ def _partial_screen_evidence(elements: Sequence[Mapping], spec: dict) -> bool | return True if results and all(value is True for value in results) else None -def _reviewed_label(element: Mapping) -> str: +def _reviewed_label(element: Mapping[str, Any]) -> str: if element.get("visible", True) is not True: return "" if any(element.get(key, False) is not False for key in ("is_password", "sensitive", "text_redacted")): @@ -118,7 +118,7 @@ def _reviewed_label(element: Mapping) -> str: return "" -def _partial_text_evidence(elements: list[dict], key: str, value: Any) -> bool | None: +def _partial_text_evidence(elements: list[dict[str, Any]], key: str, value: Any) -> bool | None: if key not in {"text_present", "text_absent"} or not isinstance(value, str) or not value: return None passed = check_postcondition(elements, {key: value}).ok @@ -127,7 +127,7 @@ def _partial_text_evidence(elements: list[dict], key: str, value: Any) -> bool | return None if passed else False -def _last_result(clause: Mapping, receipts: Sequence[Mapping[str, Any]]) -> bool | None: +def _last_result(clause: Mapping[str, Any], receipts: Sequence[Mapping[str, Any]]) -> bool | None: confirmed = [row for row in receipts if row["status"] == "confirmed"] if not confirmed: return None diff --git a/je_auto_control/utils/callback/callback_function_executor.py b/je_auto_control/utils/callback/callback_function_executor.py index 458a3549a..f0a8bc47c 100644 --- a/je_auto_control/utils/callback/callback_function_executor.py +++ b/je_auto_control/utils/callback/callback_function_executor.py @@ -64,9 +64,9 @@ class CallbackFunctionExecutor: - 執行後可呼叫 callback_function """ - def __init__(self): + def __init__(self) -> None: # 事件字典,對應字串名稱到實際函式 - self.event_dict: dict = { + self.event_dict: dict[str, Callable[..., Any]] = { # mouse 滑鼠相關 **MOUSE_BUTTON_COMMANDS, "AC_click_mouse": click_mouse, @@ -144,10 +144,10 @@ def __init__(self): def callback_function( self, trigger_function_name: str, - callback_function: Callable, - callback_function_param: dict | None = None, + callback_function: Callable[..., Any], + callback_function_param: dict[str, Any] | None = None, callback_param_method: str = "kwargs", - **kwargs + **kwargs: Any ) -> Any: """ Execute trigger and callback with one run-local diagnostic mask @@ -197,8 +197,9 @@ def callback_function( return execute_return_value @staticmethod - def _invoke_callback(callback_function: Callable, - callback_function_param: dict | None, + def _invoke_callback(callback_function: Callable[..., Any], + callback_function_param: dict[str, Any] | None, + callback_param_method: str) -> None: """Invoke ``callback_function`` with the configured parameter passing.""" if callback_function_param is None: diff --git a/je_auto_control/utils/executor/flow_control.py b/je_auto_control/utils/executor/flow_control.py index 7aa2067a1..12c6b5e3b 100644 --- a/je_auto_control/utils/executor/flow_control.py +++ b/je_auto_control/utils/executor/flow_control.py @@ -73,14 +73,14 @@ def _pixel_matches(x: int, y: int, rgb: Sequence[int], tolerance: int) -> bool: return all(abs(int(color[i]) - int(rgb[i])) <= tolerance for i in range(3)) -def _run_branch(executor: Any, body: Optional[list]) -> Any: +def _run_branch(executor: Any, body: Optional[list[Any]]) -> Any: """Execute a nested branch only when it is a non-empty list.""" if not body: return None return executor.execute_action(body, _validated=True) -def _run_strict(executor: Any, body: list) -> Any: +def _run_strict(executor: Any, body: list[Any]) -> Any: """Execute a nested body, re-raising the first error. An empty body is a valid no-op (matching :func:`_run_branch`); it must @@ -91,7 +91,7 @@ def _run_strict(executor: Any, body: list) -> Any: return executor.execute_action(body, raise_on_error=True, _validated=True) -def _run_loop_body(executor: Any, body: Optional[list]) -> None: +def _run_loop_body(executor: Any, body: Optional[list[Any]]) -> None: """Execute a loop body once, treating an empty body as a no-op. A loop with an empty ``body`` is valid (it does nothing each pass) and @@ -441,14 +441,14 @@ def exec_for_each_row(executor: Any, args: Mapping[str, Any]) -> int: return iterations -def _as_list(value: Any) -> list: +def _as_list(value: Any) -> list[Any]: """Accept a native list or a JSON-string list (for the visual builder).""" if isinstance(value, str): return json.loads(value) if value.strip() else [] return list(value) if value else [] -def _parallel_branches(executor: Any, raw_branches: Any) -> list: +def _parallel_branches(executor: Any, raw_branches: Any) -> list[Any]: """The branch lists of an ``AC_parallel``, validated when they came as a string. A JSON-string list is parsed only here, after dispatch-time validation, @@ -474,7 +474,7 @@ class _ParallelRun: here, on the parent thread, and handed to every branch. """ - def __init__(self, executor: Any, branches: list) -> None: + def __init__(self, executor: Any, branches: list[Any]) -> None: from je_auto_control.utils.executor import action_executor as executor_module self._module = executor_module # Snapshot before spawning threads so branch workers never read the @@ -503,8 +503,9 @@ def __init__(self, executor: Any, branches: list) -> None: self._stop_token = current_stop_token() self._result_hook = capture_branch_hook() self._stopped: Optional[ExecutionStopped] = None - self.results: list = [None] * len(branches) - self._failures: list = [0] * len(branches) + self.results: list[Any] = [None] * len(branches) + self._failures: list[int] = [0] * len(branches) + self._errors: Dict[int, str] = {} self._assertions: Dict[int, AutoControlAssertionException] = {} self._interruptions: list[Optional[BaseException]] = [None] * len(branches) diff --git a/je_auto_control/utils/hotkey/backends/linux_backend.py b/je_auto_control/utils/hotkey/backends/linux_backend.py index 9233ca645..b9095f712 100644 --- a/je_auto_control/utils/hotkey/backends/linux_backend.py +++ b/je_auto_control/utils/hotkey/backends/linux_backend.py @@ -4,7 +4,7 @@ key, matching Windows ``RegisterHotKey`` semantics. NumLock / CapsLock are masked so the hotkey still fires with those toggles active. """ -from typing import Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Set, Tuple from je_auto_control.utils.hotkey.backends.base import FailedCombos, HotkeyBackend from je_auto_control.utils.hotkey.hotkey_daemon import ( @@ -89,7 +89,7 @@ def run_forever(self, context: BackendContext) -> None: self._ungrab_all(disp, root) disp.close() - def _sync(self, disp, root, bindings: List[HotkeyBinding]) -> None: + def _sync(self, disp: Any, root: Any, bindings: List[HotkeyBinding]) -> None: current_ids = {b.binding_id for b in bindings} self._ungrab_stale(root, current_ids) self._failed.forget_missing(current_ids) @@ -97,13 +97,13 @@ def _sync(self, disp, root, bindings: List[HotkeyBinding]) -> None: self._sync_one(root, binding) disp.sync() - def _ungrab_stale(self, root, current_ids: set) -> None: + def _ungrab_stale(self, root: Any, current_ids: Set[str]) -> None: stale_ids = [bid for bid in self._registered if bid not in current_ids] for stale in stale_ids: _combo, mask, keycode = self._registered.pop(stale) self._ungrab_masked(root, keycode, mask) - def _sync_one(self, root, binding: HotkeyBinding) -> None: + def _sync_one(self, root: Any, binding: HotkeyBinding) -> None: prior = self._registered.get(binding.binding_id) if prior is not None and prior[0] == binding.combo: return @@ -137,7 +137,7 @@ def _sync_one(self, root, binding: HotkeyBinding) -> None: self._failed.record(binding) @staticmethod - def _ungrab_masked(root, keycode: int, mask: int) -> None: + def _ungrab_masked(root: Any, keycode: int, mask: int) -> None: for extra_mask in _lock_mask_variants(): try: root.ungrab_key(keycode, mask | extra_mask) @@ -145,7 +145,7 @@ def _ungrab_masked(root, keycode: int, mask: int) -> None: pass @staticmethod - def _grab_masked(root, binding: HotkeyBinding, + def _grab_masked(root: Any, binding: HotkeyBinding, mask: int, keycode: int) -> bool: from Xlib import X @@ -172,7 +172,7 @@ def _grab_masked(root, binding: HotkeyBinding, grabbed.append(extra_mask) return True - def _drain(self, disp, fire: Callable[[str], None]) -> None: + def _drain(self, disp: Any, fire: Callable[[str], None]) -> None: from Xlib import X while disp.pending_events(): @@ -191,7 +191,8 @@ def _find_binding(self, keycode: int, state: int) -> Optional[str]: return bid return None - def _ungrab_all(self, disp, root) -> None: + def _ungrab_all(self, disp: Any, root: Any) -> None: + for _combo, mask, keycode in self._registered.values(): for extra_mask in _lock_mask_variants(): try: diff --git a/je_auto_control/utils/input_macro/input_macro.py b/je_auto_control/utils/input_macro/input_macro.py index cbd8c829a..15e4466ef 100644 --- a/je_auto_control/utils/input_macro/input_macro.py +++ b/je_auto_control/utils/input_macro/input_macro.py @@ -160,7 +160,7 @@ class _HeldInputs: a mouse button) held down after the call returned. """ - def __init__(self, dispatch: Callable) -> None: + def __init__(self, dispatch: Callable[[Dict[str, Any]], None]) -> None: self._dispatch = dispatch self._held: List[Tuple[str, str, Any]] = [] @@ -204,8 +204,8 @@ def _finite_seconds(milliseconds: Any, name: str) -> float: def replay_timeline(events: List[Dict[str, Any]], *, speed: float = 1.0, - sink: Optional[Callable] = None, - sleep: Optional[Callable] = None, + sink: Optional[Callable[[Dict[str, Any]], None]] = None, + sleep: Optional[Callable[[float], None]] = None, min_gap: float = 0.0, max_gap: Optional[float] = None) -> int: """Replay ``events`` honoring per-event ``delta_ms`` gaps; return count. @@ -242,8 +242,8 @@ def _stoppable_sleep(seconds: float) -> None: pause(seconds, time.sleep) -def _run_steps(steps: List[Dict[str, Any]], dispatch: Callable, - sleeper: Callable, log: List[Dict[str, Any]]) -> None: +def _run_steps(steps: List[Dict[str, Any]], dispatch: Callable[[Dict[str, Any]], None], + sleeper: Callable[[float], None], log: List[Dict[str, Any]]) -> None: for step in steps: op = step.get("op") if op == "repeat": @@ -259,8 +259,9 @@ def _run_steps(steps: List[Dict[str, Any]], dispatch: Callable, def run_sequence(steps: List[Dict[str, Any]], *, - sink: Optional[Callable] = None, - sleep: Optional[Callable] = None) -> List[Dict[str, Any]]: + sink: Optional[Callable[[Dict[str, Any]], None]] = None, + sleep: Optional[Callable[[float], None]] = None) -> List[Dict[str, Any]]: + """Run a declarative input sequence; return the flattened executed log. Steps are ``{op: press|release|key|click|move|scroll}`` plus control ops diff --git a/je_auto_control/utils/input_macro/recorder_base.py b/je_auto_control/utils/input_macro/recorder_base.py index fc105a5dd..e25bb683e 100644 --- a/je_auto_control/utils/input_macro/recorder_base.py +++ b/je_auto_control/utils/input_macro/recorder_base.py @@ -24,7 +24,7 @@ must treat the result as sensitive. """ from queue import Queue -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union #: A hook left installed grows its event list forever. Recording is bounded so #: a forgotten session cannot consume the process. @@ -43,6 +43,9 @@ #: Both capture kinds, which is what a plain ``record()`` asks for. ALL_KINDS: Tuple[str, ...] = ("keyboard", "mouse") +#: One legacy queue entry: ``("AC_type_keyboard", vk)`` or ``(mouse_command, x, y)``. +_LegacyAction = Union[Tuple[str, int], Tuple[str, int, int]] + def event_kind(event: Dict[str, Any]) -> str: """Return ``"keyboard"`` or ``"mouse"`` for one raw event.""" @@ -70,9 +73,9 @@ def timeline(events: List[Dict[str, Any]]) -> List[Dict[str, Any]]: return out -def legacy_action_queue(events: List[Dict[str, Any]]) -> Queue: +def legacy_action_queue(events: List[Dict[str, Any]]) -> Queue[_LegacyAction]: """The historical shape: one executor command per press, no releases.""" - queue: Queue = Queue() + queue: Queue[_LegacyAction] = Queue() for event in events: operation = event.get("op") if operation == "key_down": @@ -95,8 +98,8 @@ class InputRecorder: def __init__(self) -> None: self.hook: Any = None - self.record_queue: Optional[Queue] = None - self.result_queue: Optional[Queue] = None + self.record_queue: Optional[Queue[_LegacyAction]] = None + self.result_queue: Optional[Queue[_LegacyAction]] = None self._kinds: Tuple[str, ...] = ALL_KINDS @property @@ -130,7 +133,7 @@ def _stop(self) -> List[Dict[str, Any]]: self.hook = None return events - def _as_queue(self, events: List[Dict[str, Any]]) -> Queue: + def _as_queue(self, events: List[Dict[str, Any]]) -> Queue[_LegacyAction]: queue = legacy_action_queue(events) self.record_queue = None self.result_queue = queue @@ -144,7 +147,7 @@ def record(self) -> None: """ self._start(ALL_KINDS) - def stop_record(self) -> Queue: + def stop_record(self) -> Queue[_LegacyAction]: """ 停止錄製並回傳事件 Stop recording and return recorded events @@ -167,7 +170,7 @@ def record_mouse(self) -> None: """ self._start(("mouse",)) - def stop_record_mouse(self) -> Queue: + def stop_record_mouse(self) -> Queue[_LegacyAction]: """ 停止錄製滑鼠事件並回傳結果 Stop recording mouse events and return results @@ -181,7 +184,7 @@ def record_keyboard(self) -> None: """ self._start(("keyboard",)) - def stop_record_keyboard(self) -> Queue: + def stop_record_keyboard(self) -> Queue[_LegacyAction]: """ 停止錄製鍵盤事件並回傳結果 Stop recording keyboard events and return results diff --git a/je_auto_control/utils/perceptual_diff/perceptual_diff.py b/je_auto_control/utils/perceptual_diff/perceptual_diff.py index 3a392f4f1..02e825ce0 100644 --- a/je_auto_control/utils/perceptual_diff/perceptual_diff.py +++ b/je_auto_control/utils/perceptual_diff/perceptual_diff.py @@ -15,7 +15,7 @@ connected-component helper and the RGB loader. Imports no ``PySide6``. """ from dataclasses import dataclass -from typing import Any, Dict, List +from typing import Any, Dict, List, Tuple # Reuse the RGB loader (single source of truth, no copy). from je_auto_control.utils.color_region.color_region import _to_rgb @@ -39,13 +39,13 @@ class PerceptualDiffResult: regions: List[Dict[str, Any]] -def _yiq_delta(first, second): +def _yiq_delta(first: Any, second: Any) -> Any: """Return the per-pixel squared YIQ colour distance between two RGB float images.""" weights_y = (0.29889531, 0.58662247, 0.11448223) weights_i = (0.59597799, -0.27417610, -0.32180189) weights_q = (0.21147017, -0.52261711, 0.31114694) - def channel(image, weights): + def channel(image: Any, weights: Tuple[float, float, float]) -> Any: return (image[..., 0] * weights[0] + image[..., 1] * weights[1] + image[..., 2] * weights[2]) @@ -59,14 +59,14 @@ def channel(image, weights): _CHUNK = 1 << 18 -def _padded(image): +def _padded(image: Any) -> Any: """``image`` with a one-pixel NaN border, so neighbours off the edge compare unequal.""" import numpy as np pad = ((1, 1), (1, 1)) + ((0, 0),) * (image.ndim - 2) return np.pad(image, pad, constant_values=np.nan) -def _sibling_map(image): +def _sibling_map(image: Any) -> Any: """pixelmatch ``hasManySiblings`` for every pixel: 3+ identical neighbours. A pixel on the border starts its count at one, as in pixelmatch. @@ -88,14 +88,14 @@ class _Image: mapped for the whole frame once many pixels differ (cheaper per point). """ - def __init__(self, rgb, whole_frame: bool) -> None: + def __init__(self, rgb: Any, whole_frame: bool) -> None: import numpy as np self.shape = rgb.shape[:2] self.luma = _padded(rgb @ np.array(_LUMA)) self._rgb: Any = None if whole_frame else _padded(rgb) self._map: Any = _sibling_map(rgb) if whole_frame else None - def many_siblings(self, ys, xs): + def many_siblings(self, ys: Any, xs: Any) -> Any: """pixelmatch ``hasManySiblings`` at the pixels ``(ys, xs)``.""" import numpy as np if self._map is not None: @@ -108,7 +108,7 @@ def many_siblings(self, ys, xs): return count > 2 -def _antialiased(image: _Image, other: _Image, ys, xs): +def _antialiased(image: _Image, other: _Image, ys: Any, xs: Any) -> Any: """pixelmatch ``antialiased()`` for the pixels ``(ys, xs)`` of ``image``. True where the pixel has at most two equal-brightness neighbours, both a @@ -135,7 +135,8 @@ def _antialiased(image: _Image, other: _Image, ys, xs): return candidate & flat -def _drop_antialiased(mask, first, second) -> None: +def _drop_antialiased(mask: Any, first: Any, second: Any) -> None: + """Clear the pixels of ``mask`` that either image renders as anti-aliasing.""" import numpy as np ys, xs = np.nonzero(mask) diff --git a/je_auto_control/utils/remote_desktop/address_book.py b/je_auto_control/utils/remote_desktop/address_book.py index d5708bfc3..990d47bed 100644 --- a/je_auto_control/utils/remote_desktop/address_book.py +++ b/je_auto_control/utils/remote_desktop/address_book.py @@ -20,7 +20,7 @@ import threading from datetime import datetime, timezone from pathlib import Path -from typing import List, Optional +from typing import Any, Dict, List, Optional from je_auto_control.utils.json_store.json_store import ( atomic_write_text, load_json_or_quarantine, quarantine_file, @@ -36,7 +36,7 @@ def default_address_book_path() -> Path: return home / _DEFAULT_PATH_RELATIVE -def _normalised(entry: dict) -> dict: +def _normalised(entry: Dict[str, Any]) -> Dict[str, Any]: """Keep the tag and timestamp shapes the address book writes itself. From a hand-edited file, ``"tags": "work"`` matched the tag filter by @@ -59,7 +59,7 @@ def __init__(self, path: Optional[Path] = None) -> None: self._path = (Path(path) if path is not None else default_address_book_path()) self._lock = threading.Lock() - self._entries: List[dict] = [] + self._entries: List[Dict[str, Any]] = [] self._load() def _load(self) -> None: @@ -87,7 +87,7 @@ def _save(self) -> None: # --- public API --------------------------------------------------------- - def list_entries(self) -> List[dict]: + def list_entries(self) -> List[Dict[str, Any]]: with self._lock: return [dict(entry) for entry in self._entries] @@ -116,7 +116,7 @@ def upsert(self, *, host_id: str, server_url: str, self._save() def _find_entry_locked(self, host_id: str, - server_url: str) -> Optional[dict]: + server_url: str) -> Optional[Dict[str, Any]]: for entry in self._entries: if (entry.get("host_id") == host_id and entry.get("server_url") == server_url): @@ -124,7 +124,7 @@ def _find_entry_locked(self, host_id: str, return None @staticmethod - def _refresh_entry_locked(entry: dict, *, now: str, label: str, + def _refresh_entry_locked(entry: Dict[str, Any], *, now: str, label: str, mac_address: Optional[str], broadcast_address: Optional[str]) -> None: entry["last_used"] = now @@ -140,7 +140,7 @@ def _refresh_entry_locked(entry: dict, *, now: str, label: str, def _build_entry(*, host_id: str, server_url: str, label: str, now: str, mac_address: Optional[str], - broadcast_address: Optional[str]) -> dict: + broadcast_address: Optional[str]) -> Dict[str, Any]: new_entry = { "label": label, "server_url": server_url, @@ -155,7 +155,7 @@ def _build_entry(*, host_id: str, server_url: str, return new_entry def set_tags(self, *, host_id: str, server_url: str, - tags: list) -> None: + tags: List[Any]) -> None: """Replace ``tags`` on the matching entry. A JSON ``null`` reaches here as None, and ``str(None)`` is the @@ -172,7 +172,7 @@ def set_tags(self, *, host_id: str, server_url: str, self._save() return - def all_tags(self) -> list: + def all_tags(self) -> List[str]: """Return distinct tags across all entries (sorted).""" seen = set() with self._lock: diff --git a/je_auto_control/utils/remote_desktop/host.py b/je_auto_control/utils/remote_desktop/host.py index 42f2f1d19..74b6f9f30 100644 --- a/je_auto_control/utils/remote_desktop/host.py +++ b/je_auto_control/utils/remote_desktop/host.py @@ -5,7 +5,8 @@ import threading import time from functools import partial -from typing import Any, Callable, List, Mapping, Optional, Sequence +from types import TracebackType +from typing import Any, Callable, List, Mapping, Optional, Sequence, Tuple from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.remote_desktop.media_retirement import MediaRetirementError @@ -21,7 +22,7 @@ encode_image, encode_text, ) from je_auto_control.utils.remote_desktop.file_transfer import ( - FileReceiver, FileTransferError, send_file, + FileReceiver, FileTransferError, ProgressCallback, send_file, ) from je_auto_control.utils.remote_desktop.host_id import ( load_or_create_host_id, validate_host_id, @@ -427,7 +428,7 @@ def _ensure_file_receiver(self) -> FileReceiver: return self._file_receiver def send_file_to_viewers(self, source_path: str, dest_path: str, - on_progress=None) -> int: + on_progress: Optional[ProgressCallback] = None) -> int: """Stream ``source_path`` to every authenticated viewer. ``dest_path`` is relative to each viewer's download directory: a @@ -547,7 +548,7 @@ def broadcast_chat(self, text: str, sender: str = "host") -> int: ) return sent - def _ip_allowed(self, address) -> bool: + def _ip_allowed(self, address: Tuple[Any, ...]) -> bool: """Apply the Phase 4.3 allowlist; log + reject silently otherwise.""" peer_ip = address[0] if address else "" if _ip_in_allowlist(self._ip_allowlist, peer_ip): @@ -558,7 +559,7 @@ def _ip_allowed(self, address) -> bool: return False def _open_channel(self, client_sock: socket.socket, - address) -> Optional[MessageChannel]: + address: Tuple[Any, ...]) -> Optional[MessageChannel]: """TLS-wrap + WS/TCP handshake. Closes the socket on failure.""" wrapped = self._maybe_wrap_tls(client_sock, address) if wrapped is None: @@ -610,7 +611,7 @@ def _accept_loop(self, stop: threading.Event) -> None: name="rd-handshake", daemon=True, ).start() - def _handshake(self, client_sock: socket.socket, address, + def _handshake(self, client_sock: socket.socket, address: Tuple[Any, ...], stop: threading.Event) -> None: """Open the channel, register the client, then authenticate it.""" try: @@ -623,7 +624,7 @@ def _handshake(self, client_sock: socket.socket, address, finally: self._handshake_slots.release() - def _register_client(self, handler: "_ClientHandler", address, + def _register_client(self, handler: "_ClientHandler", address: Tuple[Any, ...], stop: threading.Event) -> bool: """Add ``handler`` to the client table unless stopped or full.""" # Prune handlers whose viewer already disconnected *before* the @@ -653,7 +654,7 @@ def _register_client(self, handler: "_ClientHandler", address, return True def _build_channel(self, sock: socket.socket, - address) -> MessageChannel: + address: Tuple[Any, ...]) -> MessageChannel: """Hook for transports: TCP wraps directly, WS overrides this.""" del address return TcpMessageChannel(sock) @@ -663,7 +664,7 @@ def _transport_name(self) -> str: return "tcp" def _maybe_wrap_tls(self, client_sock: socket.socket, - address) -> Optional[socket.socket]: + address: Tuple[Any, ...]) -> Optional[socket.socket]: """Return a TLS-wrapped socket when an ssl_context is configured.""" if self._ssl_context is None: return client_sock @@ -696,5 +697,6 @@ def __enter__(self) -> "RemoteDesktopHost": self.start() return self - def __exit__(self, exc_type, exc, tb) -> None: + def __exit__(self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], + tb: Optional[TracebackType]) -> None: self.stop() diff --git a/je_auto_control/utils/remote_desktop/host_service.py b/je_auto_control/utils/remote_desktop/host_service.py index 482d192e5..49b0fc932 100644 --- a/je_auto_control/utils/remote_desktop/host_service.py +++ b/je_auto_control/utils/remote_desktop/host_service.py @@ -27,7 +27,7 @@ import time from dataclasses import dataclass from pathlib import Path -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional, Sequence from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -363,7 +363,7 @@ def _install_windows_service(config_path: Path) -> int: # Windows service auto-discovers its config at runtime. del config_path # suppress S1172 try: - import win32serviceutil # type: ignore # noqa: F401 + import win32serviceutil # noqa: F401 except ImportError: print("pywin32 is required: pip install pywin32", file=sys.stderr) return 2 @@ -389,9 +389,9 @@ def _install_windows_service(config_path: Path) -> int: if sys.platform == "win32": # pragma: no cover - Windows-only try: - import win32event # type: ignore - import win32service # type: ignore - import win32serviceutil # type: ignore + import win32event + import win32service + import win32serviceutil class _WindowsService(win32serviceutil.ServiceFramework): _svc_name_ = "JeAutoControlRemoteHost" @@ -401,7 +401,7 @@ class _WindowsService(win32serviceutil.ServiceFramework): "to a signaling server for remote-desktop connections." ) - def __init__(self, args) -> None: + def __init__(self, args: Sequence[str]) -> None: super().__init__(args) self._stop_event = win32event.CreateEvent(None, 0, 0, None) self._running = True @@ -424,9 +424,9 @@ def SvcDoRun(self) -> None: # noqa: N802 pywin32 API return run_daemon(config) except ImportError: - _WindowsService = None # type: ignore + _WindowsService = None # type: ignore[misc, assignment] else: - _WindowsService = None # type: ignore + _WindowsService = None # --- CLI ----------------------------------------------------------------- @@ -481,20 +481,20 @@ def _build_arg_parser() -> argparse.ArgumentParser: return parser -def _cmd_init(args) -> int: +def _cmd_init(args: argparse.Namespace) -> int: path = write_default_config(args.config) print(f"Wrote stub config: {path}") print("Edit the file (token, server_url, host_id) before running 'run'.") return 0 -def _cmd_run(args) -> int: +def _cmd_run(args: argparse.Namespace) -> int: config = load_config(args.config) run_daemon(config) return 0 -def _cmd_available_codecs(_args) -> int: +def _cmd_available_codecs(_args: argparse.Namespace) -> int: from je_auto_control.utils.remote_desktop.hw_codec import ( available_hardware_codecs, ) @@ -508,11 +508,11 @@ def _cmd_available_codecs(_args) -> int: return 0 -def _cmd_install_windows_service(args) -> int: +def _cmd_install_windows_service(args: argparse.Namespace) -> int: return _install_windows_service(args.config or _default_config_path()) -def _cmd_generate_launchd(args) -> int: +def _cmd_generate_launchd(args: argparse.Namespace) -> int: _generate_launchd_plist(args.config or _default_config_path(), args.output) print(f"Wrote launchd plist: {args.output}") print("Activate with:") @@ -521,7 +521,7 @@ def _cmd_generate_launchd(args) -> int: return 0 -def _cmd_generate_systemd(args) -> int: +def _cmd_generate_systemd(args: argparse.Namespace) -> int: _generate_systemd_unit(args.config or _default_config_path(), args.output) print(f"Wrote systemd unit: {args.output}") print("Activate with:") @@ -547,7 +547,7 @@ def _cmd_generate_systemd(args) -> int: } -def main(argv: Optional[list] = None) -> int: +def main(argv: Optional[List[str]] = None) -> int: args = _build_arg_parser().parse_args(argv) logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") diff --git a/je_auto_control/utils/remote_desktop/lan_discovery.py b/je_auto_control/utils/remote_desktop/lan_discovery.py index 045fad3d5..dfefcfce7 100644 --- a/je_auto_control/utils/remote_desktop/lan_discovery.py +++ b/je_auto_control/utils/remote_desktop/lan_discovery.py @@ -14,7 +14,7 @@ import socket import threading -from typing import Callable, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -151,9 +151,9 @@ def stop(self) -> None: class _BrowseListener: """Adapter that pumps zeroconf events into the user callback.""" - def __init__(self, on_change: Callable[[Dict[str, dict]], None]) -> None: - self._on_change: Optional[Callable[[Dict[str, dict]], None]] = on_change - self._services: Dict[str, dict] = {} + def __init__(self, on_change: Callable[[Dict[str, Dict[str, Any]]], None]) -> None: + self._on_change: Optional[Callable[[Dict[str, Dict[str, Any]]], None]] = on_change + self._services: Dict[str, Dict[str, Any]] = {} self._lock = threading.Lock() self._publishing = 0 @@ -168,7 +168,7 @@ def idle(self) -> bool: with self._lock: return self._publishing == 0 - def _publish(self, snapshot: Dict[str, dict]) -> None: + def _publish(self, snapshot: Dict[str, Dict[str, Any]]) -> None: with self._lock: callback = self._on_change if callback is None: @@ -196,7 +196,7 @@ def add_service(self, zc: "Zeroconf", type_: str, name: str) -> None: self._publish(snapshot) @staticmethod - def _service_record(info: "ServiceInfo", name: str) -> dict: + def _service_record(info: "ServiceInfo", name: str) -> Dict[str, Any]: props = info.properties or {} host_id = (props.get(b"host_id") or b"").decode( "utf-8", errors="replace", @@ -236,7 +236,7 @@ class HostBrowser: Cancel via :meth:`stop`. """ - def __init__(self, on_change: Callable[[Dict[str, dict]], None]) -> None: + def __init__(self, on_change: Callable[[Dict[str, Dict[str, Any]]], None]) -> None: if not _AVAILABLE: raise ImportError( "LAN discovery needs the 'discovery' extra: " @@ -357,13 +357,13 @@ def _observe_browser(self, failures: list[BaseException]) -> None: self._failures.discard("browser.observe") -def list_local_services(timeout_s: float = 2.0) -> List[dict]: +def list_local_services(timeout_s: float = 2.0) -> List[Dict[str, Any]]: """One-shot synchronous browse (collects whatever shows up in ``timeout``).""" if not _AVAILABLE: return [] - snapshot: Dict[str, dict] = {} + snapshot: Dict[str, Dict[str, Any]] = {} done = threading.Event() - def _on(services: Dict[str, dict]) -> None: + def _on(services: Dict[str, Dict[str, Any]]) -> None: snapshot.clear() snapshot.update(services) browser = HostBrowser(on_change=_on) diff --git a/je_auto_control/utils/remote_desktop/webrtc_stats.py b/je_auto_control/utils/remote_desktop/webrtc_stats.py index 5165a8076..7e12ce446 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_stats.py +++ b/je_auto_control/utils/remote_desktop/webrtc_stats.py @@ -12,10 +12,13 @@ from concurrent.futures import Future from enum import Enum, auto from dataclasses import asdict, dataclass -from typing import Callable, Optional +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional from je_auto_control.utils.logging.logging_instance import autocontrol_logger +if TYPE_CHECKING: + from aiortc import RTCPeerConnection + _DEFAULT_INTERVAL_S = 1.0 @@ -29,7 +32,7 @@ class StatsSnapshot: packet_loss_pct: Optional[float] = None jitter_ms: Optional[float] = None - def to_dict(self) -> dict: + def to_dict(self) -> Dict[str, Optional[float]]: return asdict(self) @@ -43,7 +46,7 @@ class _PollState(Enum): class StatsPoller: """Drive a periodic ``getStats()`` poll on the asyncio bridge.""" - def __init__(self, pc, callback: Callable[[StatsSnapshot], None], + def __init__(self, pc: RTCPeerConnection, callback: Callable[[StatsSnapshot], None], interval_s: float = _DEFAULT_INTERVAL_S) -> None: self._pc = pc self._callback: Optional[Callable[[StatsSnapshot], None]] = callback @@ -156,7 +159,7 @@ async def _sample(self) -> Optional[StatsSnapshot]: self._absorb_entry(entry, delta_t, snap) return snap - def _absorb_entry(self, entry, delta_t, + def _absorb_entry(self, entry: Any, delta_t: Optional[float], snap: StatsSnapshot) -> None: stat_type = getattr(entry, "type", None) if stat_type == "inbound-rtp" and getattr(entry, "kind", "") == "video": @@ -169,7 +172,7 @@ def _absorb_entry(self, entry, delta_t, snap.rtt_ms = float(rtt) * 1000.0 @staticmethod - def _absorb_remote_inbound(entry, snap: StatsSnapshot) -> None: + def _absorb_remote_inbound(entry: Any, snap: StatsSnapshot) -> None: rtt = getattr(entry, "roundTripTime", None) if rtt is not None: snap.rtt_ms = float(rtt) * 1000.0 @@ -178,11 +181,11 @@ def _absorb_remote_inbound(entry, snap: StatsSnapshot) -> None: snap.jitter_ms = float(jitter) * 1000.0 @staticmethod - def _int_attr(entry, name: str) -> int: + def _int_attr(entry: Any, name: str) -> int: """Read a numeric WebRTC stat attribute as an int (missing -> 0).""" return int(getattr(entry, name, 0) or 0) - def _update_inbound(self, entry, delta_t, snap: StatsSnapshot) -> None: + def _update_inbound(self, entry: Any, delta_t: Optional[float], snap: StatsSnapshot) -> None: bytes_received = self._int_attr(entry, "bytesReceived") frames_decoded = self._int_attr(entry, "framesDecoded") packets_received = self._int_attr(entry, "packetsReceived") @@ -195,7 +198,7 @@ def _update_inbound(self, entry, delta_t, snap: StatsSnapshot) -> None: self._prev_packets_lost = packets_lost def _update_rates(self, bytes_received: int, frames_decoded: int, - delta_t, snap: StatsSnapshot) -> None: + delta_t: Optional[float], snap: StatsSnapshot) -> None: """Derive bitrate + fps from inter-sample deltas.""" if not delta_t or delta_t <= 0: return diff --git a/je_auto_control/utils/remote_desktop/webrtc_transport.py b/je_auto_control/utils/remote_desktop/webrtc_transport.py index 71baadb9b..30ee48880 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_transport.py +++ b/je_auto_control/utils/remote_desktop/webrtc_transport.py @@ -14,7 +14,7 @@ import time from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import dataclass, field -from typing import Dict, List, Optional, Sequence, Tuple, TypedDict +from typing import Any, Callable, Coroutine, Dict, List, Optional, Sequence, Tuple, TypedDict, TypeVar from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -33,7 +33,7 @@ ) from exc try: - import mss # type: ignore # noqa: F401 # reason: annotations + install probe + import mss # noqa: F401 # reason: annotations + install probe except ImportError as exc: # pragma: no cover - mss is a base dep raise ImportError("mss is required for screen capture") from exc @@ -51,6 +51,7 @@ "stun:openrelay.metered.ca:80", ) _ICE_GATHER_TIMEOUT_S = 8.0 +_T = TypeVar("_T") # Maps bandwidth preset names to (fps, jpeg-equivalent quality hint). @@ -141,11 +142,11 @@ def _run(self, loop: asyncio.AbstractEventLoop) -> None: asyncio.set_event_loop(loop) loop.run_forever() - def submit(self, coro) -> Future: + def submit(self, coro: Coroutine[Any, Any, _T]) -> Future[_T]: """Schedule a coroutine; returns ``concurrent.futures.Future``.""" return asyncio.run_coroutine_threadsafe(coro, self.start()) - def call_soon(self, callback, *args) -> None: + def call_soon(self, callback: Callable[..., object], *args: Any) -> None: """Schedule a sync callable from any thread.""" self.start().call_soon_threadsafe(callback, *args) @@ -207,11 +208,11 @@ def _get_cursor_position() -> Optional[Tuple[int, int]]: return point.x, point.y return None if sys.platform == "darwin": - from Quartz import CGEventSourceGetMouseState # type: ignore + from Quartz import CGEventSourceGetMouseState location = CGEventSourceGetMouseState(0) return int(location.x), int(location.y) try: - from Xlib import display as _xdisplay # type: ignore + from Xlib import display as _xdisplay data = _xdisplay.Display().screen().root.query_pointer()._data return data["root_x"], data["root_y"] except ImportError: @@ -240,7 +241,7 @@ def _draw_cursor_overlay(arr_bgr: "np.ndarray", x: int, y: int) -> None: region[core] = black -def _resolve_monitor(sct: "mss.base.MSSBase", index: int) -> dict: +def _resolve_monitor(sct: "mss.base.MSSBase", index: int) -> Dict[str, int]: monitors = sct.monitors if not monitors: raise RuntimeError("mss reported no monitors") @@ -249,7 +250,7 @@ def _resolve_monitor(sct: "mss.base.MSSBase", index: int) -> dict: return monitors[index] -def _capture_frame(monitor: dict) -> "np.ndarray": +def _capture_frame(monitor: Dict[str, int]) -> "np.ndarray": sct = getattr(_capture_local, "sct", None) if sct is None: sct = mss_grabber() @@ -275,7 +276,7 @@ def __init__(self, monitor_index: int = 1, fps: int = 24, self._period = 1.0 / self._fps self._region = region self._show_cursor = show_cursor - self._monitor: Optional[dict] = None + self._monitor: Optional[Dict[str, int]] = None # The last resolved monitor's corner, kept across set_target_monitor # so input in between still maps somewhere sensible. self._origin: Tuple[int, int] = ( @@ -317,7 +318,7 @@ def set_target_monitor(self, index: int) -> None: self._monitor_index = int(index) self._monitor = None # invalidate cache - def _resolve(self) -> dict: + def _resolve(self) -> Dict[str, int]: if self._monitor is not None: return self._monitor if self._region is not None: @@ -349,7 +350,7 @@ def _frame_timestamp(self) -> Tuple[int, fractions.Fraction]: self._last_pts = pts return pts, fractions.Fraction(1, VIDEO_CLOCK_RATE) - async def recv(self): + async def recv(self) -> av.VideoFrame: if self._last_emit is None: self._last_emit = time.monotonic() else: @@ -391,7 +392,7 @@ async def wait_for_ice_gathering( """Block until the PeerConnection has gathered all local ICE candidates.""" if pc.iceGatheringState == "complete": return - future: asyncio.Future = asyncio.get_running_loop().create_future() + future: asyncio.Future[None] = asyncio.get_running_loop().create_future() @pc.on("icegatheringstatechange") def _on_change() -> None: diff --git a/je_auto_control/utils/secrets/secret_store.py b/je_auto_control/utils/secrets/secret_store.py index 50306fef2..074ecfd9b 100644 --- a/je_auto_control/utils/secrets/secret_store.py +++ b/je_auto_control/utils/secrets/secret_store.py @@ -28,20 +28,23 @@ import threading from contextlib import contextmanager from pathlib import Path -from typing import Any, Dict, Iterator, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, Type from je_auto_control.utils.exception.exceptions import ( AutoControlException, CryptographyUnavailableError, ) from je_auto_control.utils.json_store.json_store import _file_lock, atomic_write_text +if TYPE_CHECKING: + from cryptography.fernet import Fernet, InvalidToken + _VERIFIER_PLAINTEXT = b"autocontrol-vault-v1" _KEY_ITERATIONS = 600_000 _SALT_BYTES = 16 -def _fernet_types() -> tuple: +def _fernet_types() -> Tuple[Type["Fernet"], Type["InvalidToken"]]: """Return ``(Fernet, InvalidToken)``, or explain why the vault cannot open. ``cryptography`` publishes no ``win_arm64`` wheel, so on Windows arm64 it @@ -84,7 +87,7 @@ def _derive_key(passphrase: str, salt: bytes, iterations: int) -> bytes: return base64.urlsafe_b64encode(raw) -def _load_vault(path: Path) -> Optional[dict]: +def _load_vault(path: Path) -> Optional[Dict[str, Any]]: if not path.exists(): return None try: @@ -98,7 +101,7 @@ def _load_vault(path: Path) -> Optional[dict]: return data -def _check_vault_fields(data: dict) -> None: +def _check_vault_fields(data: Dict[str, Any]) -> None: """Raise ``SecretStoreError`` for a vault whose fields cannot be used. A missing salt raised ``KeyError`` from :meth:`SecretManager.unlock`, and @@ -120,7 +123,7 @@ def _check_vault_fields(data: dict) -> None: raise SecretStoreError("vault salt is not base64") from error -def _atomic_write(path: Path, payload: dict) -> None: +def _atomic_write(path: Path, payload: Dict[str, Any]) -> None: """Replace the vault file; the temp file is unique and 0600 from creation. A fixed ``vault.json.tmp`` let two writers truncate each other's temp file @@ -135,7 +138,7 @@ def _atomic_write(path: Path, payload: dict) -> None: pass -def _new_vault(passphrase: str) -> Tuple[Any, dict]: +def _new_vault(passphrase: str) -> Tuple[Any, Dict[str, Any]]: """Return ``(fernet, payload)`` for an empty vault keyed by ``passphrase``.""" fernet_cls, _ = _fernet_types() salt = os.urandom(_SALT_BYTES) @@ -166,8 +169,9 @@ def __init__(self, path: Optional[Path] = None) -> None: self._explicit_path: Optional[Path] = ( Path(path) if path is not None else None) self._lock = threading.RLock() - self._fernet = None # type: ignore[assignment] - self._vault: Optional[dict] = None + self._fernet: Optional["Fernet"] = None + + self._vault: Optional[Dict[str, Any]] = None @property def _path(self) -> Path: @@ -329,7 +333,8 @@ def _vault_locked(self) -> Iterator[None]: finally: lock.__exit__(None, None, None) - def _require_unlocked(self) -> Tuple[Any, dict]: + def _require_unlocked(self) -> Tuple[Any, Dict[str, Any]]: + """Return the key and the vault as it is on disk now, or raise if locked. Every operation re-reads the file: each manager used to write back its diff --git a/je_auto_control/utils/shell_process/shell_exec.py b/je_auto_control/utils/shell_process/shell_exec.py index b6ddd0dd6..3116c0e1f 100644 --- a/je_auto_control/utils/shell_process/shell_exec.py +++ b/je_auto_control/utils/shell_process/shell_exec.py @@ -6,7 +6,7 @@ import subprocess # nosec B404 # reason: ShellManager intentionally invokes user-supplied subprocesses without shell import sys from threading import Thread -from typing import List, Optional +from typing import IO, List, Optional from je_auto_control.utils.exception.exceptions import AutoControlActionException from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -84,7 +84,7 @@ def _taskkill_path() -> str: return os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "taskkill.exe") -def _kill_tree(process: subprocess.Popen) -> None: +def _kill_tree(process: subprocess.Popen[bytes]) -> None: """Kill ``process`` and everything it started.""" if sys.platform == "win32": taskkill = [_taskkill_path(), "/T", "/F", "/PID", str(process.pid)] @@ -101,7 +101,7 @@ def _kill_tree(process: subprocess.Popen) -> None: def run_captured(argv: str | List[str], timeout_s: float, - input_bytes: Optional[bytes] = None) -> subprocess.CompletedProcess: + input_bytes: Optional[bytes] = None) -> subprocess.CompletedProcess[bytes]: """Run ``argv`` (no shell), capturing stdout and stderr as bytes, for at most ``timeout_s``. ``subprocess.run(timeout=...)`` kills only the program itself and then @@ -136,7 +136,7 @@ class ShellManager: - 將輸出放入 queue,供 pull_text() 取出 """ - def __init__(self, shell_encoding: Optional[str] = None, program_buffer: int = 10240000): + def __init__(self, shell_encoding: Optional[str] = None, program_buffer: int = 10240000) -> None: """ :param shell_encoding: shell command read output encoding; by default the locale's, which is what a console program writes on Windows @@ -146,9 +146,9 @@ def __init__(self, shell_encoding: Optional[str] = None, program_buffer: int = 1 self.read_program_error_output_from_thread: Thread | None = None self.read_program_output_from_thread: Thread | None = None self.still_run_shell: bool = False - self.process: subprocess.Popen | None = None - self.run_output_queue: queue.Queue = queue.Queue() - self.run_error_queue: queue.Queue = queue.Queue() + self.process: subprocess.Popen[bytes] | None = None + self.run_output_queue: queue.Queue[str] = queue.Queue() + self.run_error_queue: queue.Queue[str] = queue.Queue() self.program_encoding: str = shell_encoding or console_encoding() self.program_buffer: int = program_buffer @@ -235,7 +235,7 @@ def exit_program(self) -> None: self.log_and_clear_queue() - def _terminate_and_reap(self, process: subprocess.Popen) -> None: + def _terminate_and_reap(self, process: subprocess.Popen[bytes]) -> None: """Terminate ``process``, wait for the real exit code, and reap it.""" process.terminate() try: @@ -264,7 +264,8 @@ def log_and_clear_queue(self) -> None: self.run_output_queue = queue.Queue() self.run_error_queue = queue.Queue() - def _read_stream(self, stream, target_queue: queue.Queue) -> None: + def _read_stream(self, stream: Optional[IO[bytes]], target_queue: queue.Queue[str]) -> None: + """ Read stream line by line and put into queue. 讀取輸出流並放入 queue diff --git a/je_auto_control/utils/triggers/email_trigger.py b/je_auto_control/utils/triggers/email_trigger.py index ec5016678..28c42e3e4 100644 --- a/je_auto_control/utils/triggers/email_trigger.py +++ b/je_auto_control/utils/triggers/email_trigger.py @@ -23,7 +23,8 @@ import uuid from dataclasses import dataclass, field from email.header import decode_header, make_header -from typing import Any, Callable, Dict, Iterable, List, Optional +from email.message import EmailMessage +from typing import Any, Callable, Dict, Iterable, List, Optional, Set from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.json.json_file import read_executable_action_json @@ -65,8 +66,8 @@ class EmailTrigger: enabled: bool = True fired: int = 0 last_error: Optional[str] = None - _seen_uids: set = field(default_factory=set, repr=False) - _inflight: set = field(default_factory=set, repr=False) + _seen_uids: Set[str] = field(default_factory=set, repr=False) + _inflight: Set[str] = field(default_factory=set, repr=False) _uidvalidity: Optional[str] = field(default=None, repr=False) _authorization: DeferredAuthorization = field( default_factory=DeferredAuthorization.capture, init=False, repr=False, compare=False) @@ -84,7 +85,7 @@ def _decode_header_value(value: Optional[str]) -> str: return str(value) -def _part_text(part) -> Optional[str]: +def _part_text(part: EmailMessage) -> Optional[str]: """A text part's content, or ``None`` when its bytes cannot be read. A charset Python does not know (``unknown-8bit``, ``x-user-defined``, @@ -102,7 +103,7 @@ def _part_text(part) -> Optional[str]: return None -def _extract_text_body(msg) -> str: +def _extract_text_body(msg: EmailMessage) -> str: """Return the first text/plain part as a string, falling back to the body.""" if msg.is_multipart(): for part in msg.walk(): @@ -115,7 +116,7 @@ def _extract_text_body(msg) -> str: return _part_text(msg) or "" -def _header(msg, name: str) -> str: +def _header(msg: EmailMessage, name: str) -> str: """A header's decoded value, or its raw text when it does not parse. ``email.policy.default`` parses a header when it is read, and a @@ -131,7 +132,7 @@ def _header(msg, name: str) -> str: return _decode_header_value(value) -def _build_payload(uid: str, msg) -> Dict[str, Any]: +def _build_payload(uid: str, msg: EmailMessage) -> Dict[str, Any]: return { "email.uid": uid, "email.from": _header(msg, "From"), @@ -179,7 +180,7 @@ def _search_uids(client: imaplib.IMAP4, criteria: str) -> List[str]: return [chunk.decode("ascii", "replace") for chunk in data[0].split()] -def _fetch_message(client: imaplib.IMAP4, uid: str): +def _fetch_message(client: imaplib.IMAP4, uid: str) -> Optional[EmailMessage]: # BODY.PEEK[]: a plain RFC822 fetch sets \Seen on the server (RFC 3501), # so messages were marked read with mark_seen=False, and before the # script had run -- one lost for good if the process died mid-run. @@ -247,14 +248,14 @@ class EmailTriggerWatcher: """Polls registered IMAP triggers from a single background thread.""" def __init__(self, - executor: Optional[Callable[[list, Dict[str, Any]], Any]] = None, + executor: Optional[Callable[[List[Any], Dict[str, Any]], Any]] = None, ) -> None: self._lock = threading.RLock() self._fire_lock = threading.Lock() self._triggers: Dict[str, EmailTrigger] = {} self._stop = threading.Event() self._thread: Optional[threading.Thread] = None - self._executor: Callable[[list, Dict[str, Any]], Any] = ( + self._executor: Callable[[List[Any], Dict[str, Any]], Any] = ( self._default_executor if executor is None else executor ) @@ -515,7 +516,7 @@ def _execute_with_history(self, trigger: EmailTrigger, trigger.fired += 1 @staticmethod - def _default_executor(actions: list, variables: Dict[str, Any]) -> Any: + def _default_executor(actions: List[Any], variables: Dict[str, Any]) -> Any: from je_auto_control.utils.executor.action_executor import ( execute_action_with_vars, ) diff --git a/je_auto_control/utils/usb/passthrough/acl.py b/je_auto_control/utils/usb/passthrough/acl.py index ea011f2a4..b9251737b 100644 --- a/je_auto_control/utils/usb/passthrough/acl.py +++ b/je_auto_control/utils/usb/passthrough/acl.py @@ -88,7 +88,7 @@ import threading from dataclasses import asdict, dataclass, field from pathlib import Path -from typing import Iterator, List, Optional, Tuple +from typing import Any, Dict, Iterator, List, Optional, Tuple from je_auto_control.utils.exception.exceptions import AutoControlException from je_auto_control.utils.json_store.json_store import ( @@ -112,13 +112,13 @@ class UsbAclBusyError(AutoControlException, TimeoutError): """Another process held the ACL's lock for too long; the change was not made.""" -def _canonical(body: dict) -> bytes: +def _canonical(body: Dict[str, Any]) -> bytes: """The bytes an embedded signature covers: ``body`` without formatting choices.""" return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") -def _parse(raw: bytes) -> Tuple[Optional[dict], object]: +def _parse(raw: bytes) -> Tuple[Optional[Dict[str, Any]], object]: """``(body, embedded signature)`` of a file; ``(None, None)`` when it is not an object.""" try: payload = json.loads(raw.decode("utf-8")) @@ -191,11 +191,11 @@ def matches(self, *, vendor_id: str, product_id: str, return True return self.serial == serial - def to_dict(self) -> dict: + def to_dict(self) -> Dict[str, Any]: return asdict(self) @classmethod - def from_dict(cls, payload: dict) -> "AclRule": + def from_dict(cls, payload: Dict[str, Any]) -> "AclRule": return cls( vendor_id=str(payload["vendor_id"]), product_id=str(payload["product_id"]), @@ -318,7 +318,7 @@ def remove_rule(self, *, vendor_id: str, product_id: str, self._save() return removed - def export_rules(self) -> dict: + def export_rules(self) -> Dict[str, Any]: """Return a portable snapshot (no signature/key) for sharing/backup.""" with self._lock: return { @@ -327,7 +327,7 @@ def export_rules(self) -> dict: "rules": [r.to_dict() for r in self._state.rules], } - def import_rules(self, payload: dict, *, replace: bool = False, + def import_rules(self, payload: Dict[str, Any], *, replace: bool = False, persist: bool = True) -> int: """Merge (or replace) rules from an exported snapshot. @@ -430,7 +430,7 @@ def _resolve_key(self, *, create: bool) -> Optional[bytes]: def _compute_sig(data: bytes, key: bytes) -> str: return hmac.new(key, data, hashlib.sha256).hexdigest() - def _verified(self, raw: bytes, body: Optional[dict], embedded: object) -> bool: + def _verified(self, raw: bytes, body: Optional[Dict[str, Any]], embedded: object) -> bool: """Whether the file is intact: by its own signature, else the sidecar's rules.""" if embedded is None or body is None: return self._verify_signature(raw) @@ -488,7 +488,7 @@ def _verify_signature(self, raw: bytes) -> bool: return False return hmac.compare_digest(expected, self._compute_sig(raw, key)) - def _signed(self, body: dict) -> dict: + def _signed(self, body: Dict[str, Any]) -> Dict[str, Any]: """``body`` with its signature embedded; unsigned when no key can be had.""" key = self._resolve_key(create=True) if key is None: diff --git a/je_auto_control/windows/record/win32_input_hook.py b/je_auto_control/windows/record/win32_input_hook.py index fb7970606..9deac5136 100644 --- a/je_auto_control/windows/record/win32_input_hook.py +++ b/je_auto_control/windows/record/win32_input_hook.py @@ -27,7 +27,7 @@ import threading import time from ctypes import wintypes -from typing import Any, Dict, List, Optional +from typing import Any, Callable, Dict, List, Optional from je_auto_control.utils.exception.exception_tags import ( windows_import_error_message, @@ -144,7 +144,7 @@ def _run(self) -> None: finally: self._unhook(user32) - def _install(self, user32) -> None: + def _install(self, user32: Any) -> None: kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined] # reason: win32-only ctypes self._thread_id = kernel32.GetCurrentThreadId() proto = ctypes.WINFUNCTYPE( # type: ignore[attr-defined] # reason: win32-only ctypes @@ -167,7 +167,7 @@ def _install(self, user32) -> None: raise OSError(f"SetWindowsHookExW failed for {hook_id}") self._hooks.append(handle) - def _unhook(self, user32) -> None: + def _unhook(self, user32: Any) -> None: for handle in self._hooks: try: user32.UnhookWindowsHookEx(handle) @@ -183,8 +183,8 @@ def _put(self, event: Dict[str, Any]) -> None: event["time"] = time.monotonic() self.events.append(event) - def _keyboard_proc(self, user32): - def _proc(code, w_param, l_param): + def _keyboard_proc(self, user32: Any) -> Callable[[int, int, int], int]: + def _proc(code: int, w_param: int, l_param: int) -> int: # Called by the OS on this thread: an exception must not escape, # and it must not be slow — all desktop input queues behind it. try: @@ -201,8 +201,8 @@ def _proc(code, w_param, l_param): return _proc - def _mouse_proc(self, user32): - def _proc(code, w_param, l_param): + def _mouse_proc(self, user32: Any) -> Callable[[int, int, int], int]: + def _proc(code: int, w_param: int, l_param: int) -> int: try: if code >= 0: self._mouse_event(l_param, int(w_param)) @@ -212,7 +212,7 @@ def _proc(code, w_param, l_param): return _proc - def _mouse_event(self, l_param, message: int) -> None: + def _mouse_event(self, l_param: int, message: int) -> None: data = ctypes.cast(l_param, ctypes.POINTER(_MSLLHOOKSTRUCT)).contents button = _MOUSE_BUTTONS.get(message) if button is not None: diff --git a/je_auto_control/wrapper/auto_control_keyboard.py b/je_auto_control/wrapper/auto_control_keyboard.py index f24bfee8d..5aa61b064 100644 --- a/je_auto_control/wrapper/auto_control_keyboard.py +++ b/je_auto_control/wrapper/auto_control_keyboard.py @@ -12,7 +12,7 @@ import sys import warnings from contextlib import contextmanager -from typing import Iterator, Optional, Tuple +from typing import Iterator, Optional, Sequence, Tuple from je_auto_control.utils.exception.exception_tags import ( keyboard_press_key_error_message, keyboard_release_key_error_message, @@ -32,7 +32,7 @@ ) from je_auto_control.wrapper._input_observer import input_event, has_input_observer -def get_keyboard_keys_table() -> dict: +def get_keyboard_keys_table() -> dict[str, int]: """ 取得鍵盤對應表 Get keyboard keys table @@ -105,7 +105,7 @@ def _shift_held(is_shift: bool) -> Iterator[None]: if not is_shift or sys.platform == "darwin": yield return - still_held: list = [] + still_held: list[int | str] = [] try: press_keyboard_key("shift", skip_record=True) still_held.append("shift") @@ -195,7 +195,7 @@ def release_keyboard_key(keycode: int | str, is_shift: bool = False, raise AutoControlKeyboardException(f"{keyboard_release_key_error_message} {repr(error)}") from error -def _release_still_held(still_held: list, is_shift: bool) -> None: +def _release_still_held(still_held: list[int | str], is_shift: bool) -> None: """把「已經按下去、還沒放開」的鍵**倒著**放開。清空 ``still_held``。 Release keys that are still held down, in reverse order. @@ -232,7 +232,7 @@ def type_keyboard(keycode: int | str, is_shift: bool = False, of every subsequent click and keystroke. """ autocontrol_logger.info(f"type_keyboard, keycode={keycode}, is_shift={is_shift}, skip_record={skip_record}") - still_held: list = [] + still_held: list[int | str] = [] backend_shift = _backend_shift(is_shift) try: with _shift_held(is_shift): @@ -463,7 +463,7 @@ def write_secret(secret: str) -> None: record_action_to_list("write_secret", {"secret": _RECORD_MASK}) -def hotkey(key_code_list: list, is_shift: bool = False) -> Tuple[str, str]: +def hotkey(key_code_list: Sequence[int | str], is_shift: bool = False) -> Tuple[str, str]: """ 模擬組合鍵 (依序按下,再反向放開) Simulate hotkey (press all keys, then release in reverse order) @@ -474,7 +474,7 @@ def hotkey(key_code_list: list, is_shift: bool = False) -> Tuple[str, str]: """ autocontrol_logger.info(f"hotkey, key_code_list={key_code_list}, is_shift={is_shift}") # 已經按下去、還沒放開的鍵,**依按下的順序**。放開時倒著走。 - still_held: list = [] + still_held: list[int | str] = [] backend_shift = _backend_shift(is_shift) try: press_list = [] @@ -559,7 +559,7 @@ def send_key_event_to_window(window_title: str, keycode: int | str) -> None: ) -def __getattr__(name: str) -> dict: +def __getattr__(name: str) -> dict[str, int]: """Preserve explicit table access and caller replacement of that attribute.""" if name == "keyboard_keys_table": return get_keyboard_keys_table() diff --git a/je_auto_control/wrapper/window_backends/x11_backend.py b/je_auto_control/wrapper/window_backends/x11_backend.py index feaedcb73..dceb612e8 100644 --- a/je_auto_control/wrapper/window_backends/x11_backend.py +++ b/je_auto_control/wrapper/window_backends/x11_backend.py @@ -19,11 +19,15 @@ """ import sys import time -from typing import Any, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.wrapper.window_backends.base import WindowManageBackend +if TYPE_CHECKING: + from Xlib.display import Display + from Xlib.xobject.drawable import Window + #: ``ShowWindow`` codes this backend can honour, mapped to what X11 calls the #: same idea. The Win32 numbering is the project's cross-platform spelling of #: show-state; the codes with no X11 meaning are refused rather than guessed. @@ -60,8 +64,8 @@ class X11WindowBackend(WindowManageBackend): name = "x11-ewmh" def __init__(self) -> None: - self._connection = None - self._atoms: dict = {} + self._connection: Optional["Display"] = None + self._atoms: Dict[str, int] = {} self.available = _is_linux() and self._probe() # --- connection -------------------------------------------------------- @@ -75,7 +79,7 @@ def _probe(self) -> bool: "X11 window backend unavailable: %r", error) return False - def _display(self): + def _display(self) -> "Display": """The X connection, opened once and kept. Its own connection rather than the input backend's: this module is @@ -95,13 +99,13 @@ def _atom(self, name: str) -> int: self._atoms[name] = self._display().intern_atom(name) return self._atoms[name] - def _root(self): + def _root(self) -> "Window": return self._display().screen().root - def _window(self, window_id: int): + def _window(self, window_id: int) -> "Window": return self._display().create_resource_object("window", int(window_id)) - def _property(self, window, name: str, kind: Optional[int] = None): + def _property(self, window: "Window", name: str, kind: Optional[int] = None) -> Any: """Read a property's value list, or ``None`` when it is absent.""" from Xlib import X @@ -109,7 +113,7 @@ def _property(self, window, name: str, kind: Optional[int] = None): self._atom(name), X.AnyPropertyType if kind is None else kind) return None if found is None else found.value - def _client_message(self, window, name: str, data: List[int]) -> None: + def _client_message(self, window: "Window", name: str, data: List[int]) -> None: """Send an EWMH client message to the root window. EWMH requests are addressed to the root with @@ -166,7 +170,7 @@ def foreground_window(self) -> int: # --- reading one window ------------------------------------------------ - def _frame(self, window_id: int): + def _frame(self, window_id: int) -> "Window": """The window manager's frame around a client, or the client itself. A reparenting window manager makes the client a grandchild of the diff --git a/pyproject.toml b/pyproject.toml index 5d797f535..e1970f722 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -377,6 +377,7 @@ module = [ "je_auto_control.gui._i18n_helpers", "je_auto_control.gui._image_detect_tab", "je_auto_control.gui._qt_typed", + "je_auto_control.gui._record_tab", "je_auto_control.gui._report_tab", "je_auto_control.gui._screen_geometry", "je_auto_control.gui._screenshot_tab", @@ -411,8 +412,7 @@ module = [ "je_auto_control.gui.failed_stops_view", "je_auto_control.gui.flakiness_tab", "je_auto_control.gui.flow_editor", - "je_auto_control.gui.flow_editor.scene", - "je_auto_control.gui.flow_editor.tab", + "je_auto_control.gui.flow_editor.*", "je_auto_control.gui.healing_evaluation_panel", "je_auto_control.gui.healing_evaluation_worker", "je_auto_control.gui.hotkeys_tab", @@ -445,8 +445,10 @@ module = [ "je_auto_control.gui.remote_desktop._host_ops", "je_auto_control.gui.remote_desktop._webrtc_types", "je_auto_control.gui.remote_desktop.advanced_group", + "je_auto_control.gui.remote_desktop.annotation_overlay", "je_auto_control.gui.remote_desktop.blanking_overlay", "je_auto_control.gui.remote_desktop.connection_recent", + "je_auto_control.gui.remote_desktop.connection_screen", "je_auto_control.gui.remote_desktop.folder_sync_controls", "je_auto_control.gui.remote_desktop.folder_sync_io", "je_auto_control.gui.remote_desktop.frame_display", @@ -467,6 +469,7 @@ module = [ "je_auto_control.gui.remote_desktop.webrtc_host_sessions", "je_auto_control.gui.remote_desktop.webrtc_host_trust", "je_auto_control.gui.remote_desktop.webrtc_host_ui", + "je_auto_control.gui.remote_desktop.webrtc_known_hosts", "je_auto_control.gui.remote_desktop.webrtc_panel", "je_auto_control.gui.remote_desktop.webrtc_panel_common", "je_auto_control.gui.remote_desktop.webrtc_panel_state", @@ -495,6 +498,7 @@ module = [ "je_auto_control.gui.test_suite_tab", "je_auto_control.gui.theme", "je_auto_control.gui.trace_replay_tab", + "je_auto_control.gui.triggers_tab", "je_auto_control.gui.usb_browser_tab", "je_auto_control.gui.usb_devices_tab", "je_auto_control.gui.usb_passthrough_panel", @@ -536,19 +540,7 @@ module = [ "je_auto_control.linux_wayland.record", "je_auto_control.linux_wayland.screen", "je_auto_control.linux_with_x11", - "je_auto_control.linux_with_x11.core", - "je_auto_control.linux_with_x11.core.*", - "je_auto_control.linux_with_x11.keyboard", - "je_auto_control.linux_with_x11.keyboard.*", - "je_auto_control.linux_with_x11.listener", - "je_auto_control.linux_with_x11.mouse", - "je_auto_control.linux_with_x11.mouse.*", - "je_auto_control.linux_with_x11.record", - "je_auto_control.linux_with_x11.record.*", - "je_auto_control.linux_with_x11.screen", - "je_auto_control.linux_with_x11.screen.*", - "je_auto_control.linux_with_x11.uinput", - "je_auto_control.linux_with_x11.uinput.*", + "je_auto_control.linux_with_x11.*", "je_auto_control.osx", "je_auto_control.osx.*", "je_auto_control.utils", @@ -566,6 +558,8 @@ module = [ "je_auto_control.utils.accessibility.backends.null_backend", "je_auto_control.utils.accessibility.backends.windows_automation", "je_auto_control.utils.accessibility.backends.windows_events", + "je_auto_control.utils.accessibility.backends.windows_query", + "je_auto_control.utils.accessibility.backends.windows_reads", "je_auto_control.utils.accessibility.backends.windows_state", "je_auto_control.utils.accessibility.element", "je_auto_control.utils.accessibility.recorder", @@ -606,6 +600,7 @@ module = [ "je_auto_control.utils.agent_runtime.android_commands", "je_auto_control.utils.agent_runtime.android_control", "je_auto_control.utils.agent_runtime.android_geometry", + "je_auto_control.utils.agent_runtime.android_hierarchy", "je_auto_control.utils.agent_runtime.android_input_evidence", "je_auto_control.utils.agent_runtime.android_input_windows", "je_auto_control.utils.agent_runtime.android_scope", @@ -616,6 +611,7 @@ module = [ "je_auto_control.utils.agent_runtime.browser_environment", "je_auto_control.utils.agent_runtime.browser_readonly_scope", "je_auto_control.utils.agent_runtime.browser_retirement", + "je_auto_control.utils.agent_runtime.browser_target", "je_auto_control.utils.agent_runtime.browser_transfers", "je_auto_control.utils.agent_runtime.browser_validation", "je_auto_control.utils.agent_runtime.browser_verification", @@ -628,10 +624,13 @@ module = [ "je_auto_control.utils.agent_runtime.control_admission", "je_auto_control.utils.agent_runtime.dag_admission", "je_auto_control.utils.agent_runtime.dag_batch_recording", + "je_auto_control.utils.agent_runtime.dag_continuation_plan", "je_auto_control.utils.agent_runtime.dag_jobs", "je_auto_control.utils.agent_runtime.dag_local", "je_auto_control.utils.agent_runtime.dag_retention", "je_auto_control.utils.agent_runtime.dag_service_client", + "je_auto_control.utils.agent_runtime.dag_transfer_checks", + "je_auto_control.utils.agent_runtime.dag_transfer_stop", "je_auto_control.utils.agent_runtime.delegation", "je_auto_control.utils.agent_runtime.dialog_scope", "je_auto_control.utils.agent_runtime.document_launch", @@ -640,6 +639,7 @@ module = [ "je_auto_control.utils.agent_runtime.evidence_cache", "je_auto_control.utils.agent_runtime.file_dialog_scope", "je_auto_control.utils.agent_runtime.file_target", + "je_auto_control.utils.agent_runtime.handoff_records", "je_auto_control.utils.agent_runtime.helper_environment", "je_auto_control.utils.agent_runtime.helper_owner_linux", "je_auto_control.utils.agent_runtime.images", @@ -654,6 +654,8 @@ module = [ "je_auto_control.utils.agent_runtime.native_job", "je_auto_control.utils.agent_runtime.native_recovery", "je_auto_control.utils.agent_runtime.native_scope", + "je_auto_control.utils.agent_runtime.native_target", + "je_auto_control.utils.agent_runtime.observation_refs", "je_auto_control.utils.agent_runtime.ollama", "je_auto_control.utils.agent_runtime.origin_policy", "je_auto_control.utils.agent_runtime.owned_channel_factory", @@ -666,6 +668,7 @@ module = [ "je_auto_control.utils.agent_runtime.presence_broker", "je_auto_control.utils.agent_runtime.presence_channel_linux", "je_auto_control.utils.agent_runtime.presence_endpoint_linux", + "je_auto_control.utils.agent_runtime.presence_frames", "je_auto_control.utils.agent_runtime.presence_handshake", "je_auto_control.utils.agent_runtime.presence_host", "je_auto_control.utils.agent_runtime.presence_messages_linux", @@ -683,6 +686,7 @@ module = [ "je_auto_control.utils.agent_runtime.presence_session_windows", "je_auto_control.utils.agent_runtime.presence_state", "je_auto_control.utils.agent_runtime.presence_win32", + "je_auto_control.utils.agent_runtime.presence_windows", "je_auto_control.utils.agent_runtime.presence_worker", "je_auto_control.utils.agent_runtime.presence_x11", "je_auto_control.utils.agent_runtime.readiness", @@ -691,9 +695,13 @@ module = [ "je_auto_control.utils.agent_runtime.receipts", "je_auto_control.utils.agent_runtime.recovery_authorization", "je_auto_control.utils.agent_runtime.remote_effect", + "je_auto_control.utils.agent_runtime.remote_journal", "je_auto_control.utils.agent_runtime.remote_target", + "je_auto_control.utils.agent_runtime.remote_worker", "je_auto_control.utils.agent_runtime.resume_gate", + "je_auto_control.utils.agent_runtime.retained_browser", "je_auto_control.utils.agent_runtime.retained_browser_runtime", + "je_auto_control.utils.agent_runtime.retained_browser_target", "je_auto_control.utils.agent_runtime.retention", "je_auto_control.utils.agent_runtime.runner", "je_auto_control.utils.agent_runtime.runtime", @@ -701,18 +709,23 @@ module = [ "je_auto_control.utils.agent_runtime.service", "je_auto_control.utils.agent_runtime.skill_parameters", "je_auto_control.utils.agent_runtime.skill_reauthorization", + "je_auto_control.utils.agent_runtime.skill_recording", + "je_auto_control.utils.agent_runtime.store", "je_auto_control.utils.agent_runtime.submission", "je_auto_control.utils.agent_runtime.target_config", "je_auto_control.utils.agent_runtime.target_continuity", "je_auto_control.utils.agent_runtime.target_factory", + "je_auto_control.utils.agent_runtime.target_profiles", "je_auto_control.utils.agent_runtime.targets", "je_auto_control.utils.agent_runtime.task_handoff", "je_auto_control.utils.agent_runtime.transfer_adoption", "je_auto_control.utils.agent_runtime.transfer_cache", "je_auto_control.utils.agent_runtime.transfer_destination_scope", + "je_auto_control.utils.agent_runtime.transfer_evidence_contract", "je_auto_control.utils.agent_runtime.transfer_evidence_management", "je_auto_control.utils.agent_runtime.transfer_files", "je_auto_control.utils.agent_runtime.transfer_import_contract", + "je_auto_control.utils.agent_runtime.transfer_import_files", "je_auto_control.utils.agent_runtime.transfer_import_jobs", "je_auto_control.utils.agent_runtime.transfer_import_ledger", "je_auto_control.utils.agent_runtime.transfer_management", @@ -721,10 +734,16 @@ module = [ "je_auto_control.utils.agent_runtime.transfer_privacy", "je_auto_control.utils.agent_runtime.transfer_protocol", "je_auto_control.utils.agent_runtime.transfer_records", + "je_auto_control.utils.agent_runtime.transfer_routing", + "je_auto_control.utils.agent_runtime.transfer_selection", + "je_auto_control.utils.agent_runtime.transfer_staging", + "je_auto_control.utils.agent_runtime.transfer_transport", "je_auto_control.utils.agent_runtime.transport", "je_auto_control.utils.agent_runtime.trigger_config", "je_auto_control.utils.agent_runtime.trigger_history", + "je_auto_control.utils.agent_runtime.trigger_reauthorization", "je_auto_control.utils.agent_runtime.trigger_registration", + "je_auto_control.utils.agent_runtime.verification", "je_auto_control.utils.agent_runtime.window_pixels", "je_auto_control.utils.agent_runtime.wire_data", "je_auto_control.utils.agent_runtime.workflow_desktop", @@ -766,6 +785,7 @@ module = [ "je_auto_control.utils.bulkhead", "je_auto_control.utils.bulkhead.*", "je_auto_control.utils.callback", + "je_auto_control.utils.callback.*", "je_auto_control.utils.cancellable_process", "je_auto_control.utils.canonical_log", "je_auto_control.utils.canonical_log.*", @@ -895,6 +915,7 @@ module = [ "je_auto_control.utils.executor.action_schema", "je_auto_control.utils.executor.dispatch", "je_auto_control.utils.executor.flags", + "je_auto_control.utils.executor.flow_control", "je_auto_control.utils.executor.flow_data_commands", "je_auto_control.utils.executor.mouse_aliases", "je_auto_control.utils.executor.result_hook", @@ -949,11 +970,7 @@ module = [ "je_auto_control.utils.heal_analytics", "je_auto_control.utils.heal_analytics.*", "je_auto_control.utils.hotkey", - "je_auto_control.utils.hotkey.backends", - "je_auto_control.utils.hotkey.backends.base", - "je_auto_control.utils.hotkey.backends.macos_backend", - "je_auto_control.utils.hotkey.backends.windows_backend", - "je_auto_control.utils.hotkey.hotkey_daemon", + "je_auto_control.utils.hotkey.*", "je_auto_control.utils.hsv_segment", "je_auto_control.utils.http_cassette", "je_auto_control.utils.http_cassette.*", @@ -983,6 +1000,7 @@ module = [ "je_auto_control.utils.ime_state.*", "je_auto_control.utils.img_histogram", "je_auto_control.utils.input_macro", + "je_auto_control.utils.input_macro.*", "je_auto_control.utils.input_reach", "je_auto_control.utils.input_reach.*", "je_auto_control.utils.json", @@ -1194,6 +1212,7 @@ module = [ "je_auto_control.utils.remote_desktop._optional", "je_auto_control.utils.remote_desktop._optional.*", "je_auto_control.utils.remote_desktop.adaptive_bitrate", + "je_auto_control.utils.remote_desktop.address_book", "je_auto_control.utils.remote_desktop.audio", "je_auto_control.utils.remote_desktop.audio_retirement", "je_auto_control.utils.remote_desktop.audit_log", @@ -1205,14 +1224,17 @@ module = [ "je_auto_control.utils.remote_desktop.file_sync", "je_auto_control.utils.remote_desktop.file_transfer", "je_auto_control.utils.remote_desktop.fingerprint", + "je_auto_control.utils.remote_desktop.host", "je_auto_control.utils.remote_desktop.host_access", "je_auto_control.utils.remote_desktop.host_capture", "je_auto_control.utils.remote_desktop.host_client", "je_auto_control.utils.remote_desktop.host_id", + "je_auto_control.utils.remote_desktop.host_service", "je_auto_control.utils.remote_desktop.input_dispatch", "je_auto_control.utils.remote_desktop.input_send_queue", "je_auto_control.utils.remote_desktop.jpeg_recorder", "je_auto_control.utils.remote_desktop.jpeg_recorder_encrypted", + "je_auto_control.utils.remote_desktop.lan_discovery", "je_auto_control.utils.remote_desktop.media_retirement", "je_auto_control.utils.remote_desktop.permissions", "je_auto_control.utils.remote_desktop.presence", @@ -1246,6 +1268,8 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_mic", "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", "je_auto_control.utils.remote_desktop.webrtc_retirement", + "je_auto_control.utils.remote_desktop.webrtc_stats", + "je_auto_control.utils.remote_desktop.webrtc_transport", "je_auto_control.utils.remote_desktop.ws_host", "je_auto_control.utils.remote_desktop.ws_protocol", "je_auto_control.utils.remote_desktop.ws_viewer", @@ -1287,6 +1311,7 @@ module = [ "je_auto_control.utils.secret_ref", "je_auto_control.utils.secret_ref.*", "je_auto_control.utils.secrets", + "je_auto_control.utils.secrets.*", "je_auto_control.utils.secrets_scan", "je_auto_control.utils.secrets_scan.*", "je_auto_control.utils.selection_view", @@ -1307,6 +1332,7 @@ module = [ "je_auto_control.utils.shell_open", "je_auto_control.utils.shell_open.*", "je_auto_control.utils.shell_process", + "je_auto_control.utils.shell_process.*", "je_auto_control.utils.skill_library", "je_auto_control.utils.skill_library.*", "je_auto_control.utils.slo", @@ -1384,31 +1410,13 @@ module = [ "je_auto_control.utils.trash", "je_auto_control.utils.trash.*", "je_auto_control.utils.triggers", - "je_auto_control.utils.triggers.trigger_engine", - "je_auto_control.utils.triggers.webhook_server", + "je_auto_control.utils.triggers.*", "je_auto_control.utils.tween_drag", "je_auto_control.utils.tween_drag.*", "je_auto_control.utils.url_canon", "je_auto_control.utils.url_canon.*", "je_auto_control.utils.usb", - "je_auto_control.utils.usb.passthrough", - "je_auto_control.utils.usb.passthrough._client_requests", - "je_auto_control.utils.usb.passthrough.backend", - "je_auto_control.utils.usb.passthrough.client_errors", - "je_auto_control.utils.usb.passthrough.client_handle", - "je_auto_control.utils.usb.passthrough.commands", - "je_auto_control.utils.usb.passthrough.descriptor", - "je_auto_control.utils.usb.passthrough.flags", - "je_auto_control.utils.usb.passthrough.iokit_backend", - "je_auto_control.utils.usb.passthrough.key_provider", - "je_auto_control.utils.usb.passthrough.loopback", - "je_auto_control.utils.usb.passthrough.protocol", - "je_auto_control.utils.usb.passthrough.session", - "je_auto_control.utils.usb.passthrough.viewer_client", - "je_auto_control.utils.usb.passthrough.webrtc_channel", - "je_auto_control.utils.usb.passthrough.winusb_backend", - "je_auto_control.utils.usb.usb_devices", - "je_auto_control.utils.usb.usb_watcher", + "je_auto_control.utils.usb.*", "je_auto_control.utils.usbip", "je_auto_control.utils.usbip.*", "je_auto_control.utils.verify_field", @@ -1452,22 +1460,7 @@ module = [ "je_auto_control.utils.xml", "je_auto_control.utils.xml.*", "je_auto_control.windows", - "je_auto_control.windows.core", - "je_auto_control.windows.core.*", - "je_auto_control.windows.interception", - "je_auto_control.windows.interception.*", - "je_auto_control.windows.keyboard", - "je_auto_control.windows.keyboard.*", - "je_auto_control.windows.message", - "je_auto_control.windows.message.*", - "je_auto_control.windows.mouse", - "je_auto_control.windows.mouse.*", - "je_auto_control.windows.record", - "je_auto_control.windows.record.win32_record", - "je_auto_control.windows.screen", - "je_auto_control.windows.screen.*", - "je_auto_control.windows.window", - "je_auto_control.windows.window.*", + "je_auto_control.windows.*", "je_auto_control.wrapper", "je_auto_control.wrapper._input_observer", "je_auto_control.wrapper._platform_linux", @@ -1475,6 +1468,7 @@ module = [ "je_auto_control.wrapper._platform_wayland", "je_auto_control.wrapper._platform_windows", "je_auto_control.wrapper.auto_control_image", + "je_auto_control.wrapper.auto_control_keyboard", "je_auto_control.wrapper.auto_control_mouse", "je_auto_control.wrapper.auto_control_record", "je_auto_control.wrapper.auto_control_screen", @@ -1489,6 +1483,7 @@ module = [ "je_auto_control.wrapper.window_backends.base", "je_auto_control.wrapper.window_backends.null_backend", "je_auto_control.wrapper.window_backends.windows_backend", + "je_auto_control.wrapper.window_backends.x11_backend", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index a8d1aee0a..6a7dc8e88 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -6,50 +6,25 @@ # shrink. Move a module into the strict block once mypy passes it there, and # delete its line. je_auto_control.gui.agent_tasks_tab -je_auto_control.utils.agent_runtime.android_hierarchy -je_auto_control.utils.agent_runtime.browser_target je_auto_control.utils.agent_runtime.browser_workflows je_auto_control.utils.agent_runtime.completion_recovery je_auto_control.utils.agent_runtime.dag_batches je_auto_control.utils.agent_runtime.dag_continuation je_auto_control.utils.agent_runtime.dag_continuation_evidence -je_auto_control.utils.agent_runtime.dag_continuation_plan -je_auto_control.utils.agent_runtime.dag_transfer_checks -je_auto_control.utils.agent_runtime.dag_transfer_stop je_auto_control.utils.agent_runtime.evidence_handoff -je_auto_control.utils.agent_runtime.handoff_records je_auto_control.utils.agent_runtime.input_ledger -je_auto_control.utils.agent_runtime.native_target je_auto_control.utils.agent_runtime.native_worker -je_auto_control.utils.agent_runtime.observation_refs -je_auto_control.utils.agent_runtime.presence_frames je_auto_control.utils.agent_runtime.presence_pool -je_auto_control.utils.agent_runtime.presence_windows -je_auto_control.utils.agent_runtime.remote_journal -je_auto_control.utils.agent_runtime.remote_worker -je_auto_control.utils.agent_runtime.retained_browser -je_auto_control.utils.agent_runtime.retained_browser_target je_auto_control.utils.agent_runtime.routes je_auto_control.utils.agent_runtime.skill_completion je_auto_control.utils.agent_runtime.skill_execution -je_auto_control.utils.agent_runtime.skill_recording -je_auto_control.utils.agent_runtime.store -je_auto_control.utils.agent_runtime.target_profiles je_auto_control.utils.agent_runtime.task_authority je_auto_control.utils.agent_runtime.task_recovery je_auto_control.utils.agent_runtime.task_skills je_auto_control.utils.agent_runtime.task_triggers je_auto_control.utils.agent_runtime.transfer_evidence -je_auto_control.utils.agent_runtime.transfer_evidence_contract je_auto_control.utils.agent_runtime.transfer_host je_auto_control.utils.agent_runtime.transfer_import -je_auto_control.utils.agent_runtime.transfer_import_files je_auto_control.utils.agent_runtime.transfer_lineage -je_auto_control.utils.agent_runtime.transfer_routing -je_auto_control.utils.agent_runtime.transfer_selection je_auto_control.utils.agent_runtime.transfer_source -je_auto_control.utils.agent_runtime.transfer_staging -je_auto_control.utils.agent_runtime.transfer_transport -je_auto_control.utils.agent_runtime.trigger_reauthorization -je_auto_control.utils.agent_runtime.verification je_auto_control.utils.agent_runtime.workflow_specs diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index c54f654a7..577e675db 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -14,41 +14,27 @@ # written later under the same name is new and therefore strict. # je_auto_control.android.client -je_auto_control.gui._record_tab je_auto_control.gui.dag_tab -je_auto_control.gui.flow_editor.layout -je_auto_control.gui.remote_desktop.annotation_overlay -je_auto_control.gui.remote_desktop.connection_screen je_auto_control.gui.remote_desktop.webrtc_dialogs -je_auto_control.gui.remote_desktop.webrtc_known_hosts -je_auto_control.gui.triggers_tab je_auto_control.gui.vlm_tab je_auto_control.ios.client je_auto_control.linux_wayland.libei -je_auto_control.linux_with_x11.listener.x11_linux_listener je_auto_control.utils.accessibility.accessibility_api je_auto_control.utils.accessibility.backends.windows_backend -je_auto_control.utils.accessibility.backends.windows_query -je_auto_control.utils.accessibility.backends.windows_reads je_auto_control.utils.actionability.actionability je_auto_control.utils.barcode.barcode -je_auto_control.utils.callback.callback_function_executor je_auto_control.utils.codegen.codegen je_auto_control.utils.color_match.color_match je_auto_control.utils.color_region.color_region je_auto_control.utils.edge_lines.edge_lines je_auto_control.utils.edge_match.edge_match je_auto_control.utils.executor.action_executor -je_auto_control.utils.executor.flow_control je_auto_control.utils.feature_match.feature_match je_auto_control.utils.grid_locator.grid_locator je_auto_control.utils.grounding_consensus.grounding_consensus -je_auto_control.utils.hotkey.backends.linux_backend je_auto_control.utils.hsv_segment.hsv_segment je_auto_control.utils.image_quality.image_quality je_auto_control.utils.img_histogram.img_histogram -je_auto_control.utils.input_macro.input_macro -je_auto_control.utils.input_macro.recorder_base je_auto_control.utils.json_schema.json_schema je_auto_control.utils.logging.logging_instance je_auto_control.utils.match_autothresh.match_autothresh @@ -64,36 +50,23 @@ je_auto_control.utils.motion_regions.motion_regions je_auto_control.utils.perceptual_diff.perceptual_diff je_auto_control.utils.preprocess.preprocess je_auto_control.utils.recording_edit.editor -je_auto_control.utils.remote_desktop.address_book -je_auto_control.utils.remote_desktop.host -je_auto_control.utils.remote_desktop.host_service je_auto_control.utils.remote_desktop.hw_codec -je_auto_control.utils.remote_desktop.lan_discovery je_auto_control.utils.remote_desktop.multi_viewer je_auto_control.utils.remote_desktop.signaling_server je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host -je_auto_control.utils.remote_desktop.webrtc_stats -je_auto_control.utils.remote_desktop.webrtc_transport je_auto_control.utils.remote_desktop.webrtc_viewer je_auto_control.utils.rotated_match.rotated_match je_auto_control.utils.saliency.saliency je_auto_control.utils.scale_detect.scale_detect -je_auto_control.utils.secrets.secret_store je_auto_control.utils.shape_locator.shape_locator -je_auto_control.utils.shell_process.shell_exec je_auto_control.utils.ssim.ssim je_auto_control.utils.subpixel_match.subpixel_match je_auto_control.utils.table_grid_fill.table_grid_fill je_auto_control.utils.text_regions.text_regions je_auto_control.utils.tool_use_schema.schema -je_auto_control.utils.triggers.email_trigger -je_auto_control.utils.usb.passthrough.acl je_auto_control.utils.vision.backends.anthropic_backend je_auto_control.utils.vision.backends.openai_backend je_auto_control.utils.visual_match.visual_match -je_auto_control.windows.record.win32_input_hook -je_auto_control.wrapper.auto_control_keyboard je_auto_control.wrapper.backend_contract je_auto_control.wrapper.window_backends.macos_backend -je_auto_control.wrapper.window_backends.x11_backend From 74258c5e17313de5395d464c4a5f4b82e8c2a783 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 13:37:23 +0800 Subject: [PATCH 127/161] Bind ImageSource once and hold 22 image modules to the strict tier Each matching module spelt its own ImageSource = Any, which the typing contract allows only in a registered adapter. One adapter now owns the alias, so the modules that otherwise passed can join the tier. --- Progress.md | 2 +- architecture_explore.md | 36 +++++++++---------- docs/updates/2026-11-b.md | 8 +++++ docs/updates/README.md | 1 + je_auto_control/utils/barcode/barcode.py | 2 +- .../utils/color_match/color_match.py | 2 +- .../utils/color_region/color_region.py | 3 +- .../utils/edge_lines/edge_lines.py | 2 +- .../utils/edge_match/edge_match.py | 2 +- .../utils/feature_match/feature_match.py | 3 +- .../utils/hsv_segment/hsv_segment.py | 3 +- .../utils/image_quality/image_quality.py | 3 +- .../utils/img_histogram/img_histogram.py | 2 +- .../match_autothresh/match_autothresh.py | 3 +- .../utils/match_ensemble/match_ensemble.py | 3 +- .../utils/match_stability/match_stability.py | 3 +- .../utils/match_trust/match_trust.py | 3 +- .../utils/motion_regions/motion_regions.py | 3 +- .../utils/perceptual_diff/perceptual_diff.py | 2 +- .../utils/preprocess/preprocess.py | 2 +- .../utils/rotated_match/rotated_match.py | 3 +- je_auto_control/utils/saliency/saliency.py | 3 +- .../utils/scale_detect/scale_detect.py | 2 +- .../utils/shape_locator/shape_locator.py | 2 +- je_auto_control/utils/ssim/ssim.py | 2 +- .../utils/subpixel_match/subpixel_match.py | 3 +- .../utils/text_regions/text_regions.py | 2 +- .../utils/visual_match/image_source.py | 16 +++++++++ .../utils/visual_match/visual_match.py | 2 +- pyproject.toml | 23 ++++++++++++ .../test_typing_modernization_contract.py | 3 ++ test/verify/typing_strict_baseline.txt | 22 ------------ 32 files changed, 94 insertions(+), 77 deletions(-) create mode 100644 je_auto_control/utils/visual_match/image_source.py diff --git a/Progress.md b/Progress.md index 5d854d055..f99f9e1e8 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~09,共 1,444 個)。仍缺:`test/verify/typing_strict_baseline.txt` 57 個與 `typing_not_yet_strict.txt` 23 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:43 個每檔 11 個以上錯誤的大檔(三平台約 1,150 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),25 個影像/定位模組只差模組層級的 `ImageSource = Any` 之類的別名(要先定一個共用型別),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~10,共 1,467 個)。仍缺:`test/verify/typing_strict_baseline.txt` 35 個與 `typing_not_yet_strict.txt` 23 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:43 個每檔 11 個以上錯誤的大檔(三平台約 1,150 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),3 個只差模組層級的 `Any` 別名(`grid_locator` 的 `Box`、`grounding_consensus` 的 `Candidate`、`wrapper/backend_contract` 的 `MouseKeycode`),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 03f7b536e..f1256e766 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,544 | -| 程式碼總行數 | 237,841 | +| Python 模組總數(含周邊子專案) | 1,545 | +| 程式碼總行數 | 237,845 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -393,46 +393,46 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,572 行。 +> 37 個套件、約 6,576 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/annotate/` | 123 | 截圖標註:畫框、highlight、箭頭、標籤 | | `utils/barcode/` | 59 | 一維條碼(EAN/UPC)解碼,解碼器可注入 | | `utils/color_match/` | 151 | 在 HSV 通道上做顏色感知的樣板比對 | -| `utils/color_region/` | 107 | 以顏色定位畫面區域(遮罩 + 連通元件) | +| `utils/color_region/` | 106 | 以顏色定位畫面區域(遮罩 + 連通元件) | | `utils/color_stats/` | 103 | 區域顏色統計:平均色與主色 | | `utils/coordinate_space/` | 93 | 模型網格座標與實體像素之間的座標空間對映 | | `utils/cv2_utils/` | 1,091 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | | `utils/edge_lines/` | 131 | 以 Hough 轉換偵測線條/格線/分隔線 | | `utils/edge_match/` | 116 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | -| `utils/feature_match/` | 147 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | -| `utils/hsv_segment/` | 104 | HSV 色彩空間分割(抗光照的顏色遮罩 + blob 框) | +| `utils/feature_match/` | 146 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | +| `utils/hsv_segment/` | 103 | HSV 色彩空間分割(抗光照的顏色遮罩 + blob 框) | | `utils/icon_classify/` | 151 | 從像素形狀判斷一個框是哪一類元件 | | `utils/image_dedup/` | 100 | 感知雜湊影像去重(Pillow aHash/dHash) | -| `utils/image_quality/` | 82 | 在 OCR/比對前評分影像品質(銳利度/對比/亮度) | +| `utils/image_quality/` | 81 | 在 OCR/比對前評分影像品質(銳利度/對比/亮度) | | `utils/img_histogram/` | 112 | 顏色直方圖指紋與變化偵測(抗光照) | | `utils/marks_layout/` | 175 | Set-of-Marks 標籤的不重疊排版與可讀配色 | -| `utils/match_autothresh/` | 114 | Otsu 自動門檻,免去手動調 `min_score` | -| `utils/match_ensemble/` | 67 | 多樣板共識比對(多張參考圖投票到同一位置) | -| `utils/match_stability/` | 70 | 比對前的靜止閘門與跨影格的比對持續性 | -| `utils/match_trust/` | 155 | 樣板比對可信度評分(次峰比 + peak-to-sidelobe) | +| `utils/match_autothresh/` | 113 | Otsu 自動門檻,免去手動調 `min_score` | +| `utils/match_ensemble/` | 66 | 多樣板共識比對(多張參考圖投票到同一位置) | +| `utils/match_stability/` | 69 | 比對前的靜止閘門與跨影格的比對持續性 | +| `utils/match_trust/` | 154 | 樣板比對可信度評分(次峰比 + peak-to-sidelobe) | | `utils/monitor_layout/` | 558 | 多螢幕/虛擬桌面幾何(在哪個螢幕、位置、重映射)+ `logical_frame` 以滑鼠座標空間擷取畫面 | -| `utils/motion_regions/` | 78 | 兩影格間的局部變化/活動偵測(absdiff) | +| `utils/motion_regions/` | 77 | 兩影格間的局部變化/活動偵測(absdiff) | | `utils/perceptual_diff/` | 203 | 感知式(YIQ)影像差異,抑制反鋸齒邊緣誤報 | | `utils/preprocess/` | 276 | OCR/比對前的影像前處理(灰階、二值化、去傾斜…) | | `utils/qr/` | 59 | 從影像或螢幕區域解碼 QR code(OpenCV) | -| `utils/rotated_match/` | 203 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | -| `utils/saliency/` | 114 | 頻譜殘差視覺顯著性:顯著圖與排序後的顯著區域 | +| `utils/rotated_match/` | 202 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | +| `utils/saliency/` | 113 | 頻譜殘差視覺顯著性:顯著圖與排序後的顯著區域 | | `utils/scale_detect/` | 105 | 偵測樣板實際渲染的顯示縮放/視覺 DPI | | `utils/screen_grid/` | 146 | 供 VLM 接地用的粗粒度標號網格(點 ↔ 格對映) | | `utils/set_of_marks/` | 169 | Set-of-Marks 疊圖:為畫面元素編號供 VLM 指認 | | `utils/shape_locator/` | 108 | 以邊緣/輪廓偵測定位元件(矩形/形狀,免樣板) | | `utils/ssim/` | 162 | 結構相似度比較:感知分數 + 變化區域 | -| `utils/subpixel_match/` | 109 | 以二次曲面擬合做次像素級比對精修 | +| `utils/subpixel_match/` | 108 | 以二次曲面擬合做次像素級比對精修 | | `utils/theme_normalize/` | 94 | 主題無關的影像正規化,讓亮色樣板能配對深色模式 | | `utils/video_report/` | 171 | 影片步驟疊圖報告:把截圖加字幕串成操作導覽影片 | -| `utils/visual_match/` | 515 | 會回傳信心值的樣板比對(分數、多尺度、find-all + NMS);擷取走 `grab_logical`,命中座標已加回虛擬桌面原點,單色樣板直接拒收 | +| `utils/visual_match/` | 531 | 會回傳信心值的樣板比對(分數、多尺度、find-all + NMS);擷取走 `grab_logical`,命中座標已加回虛擬桌面原點,單色樣板直接拒收;`image_source.py` 是比對與影像分析模組共用的 `ImageSource` 別名(型別契約允許的 numpy 陣列 `Any` 邊界,列在 `SDK_ANY_ADAPTERS`) | | `utils/visual_regression/` | 251 | 桌面 GUI 的視覺回歸測試(黃金圖比對) | ### 5.4.6 OCR 與文字理解 @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,007 | 103,621 | -| **總計** | **1,532** | **237,096** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,625 | +| **總計** | **1,533** | **237,100** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 068e89446..b2f54828c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -713,3 +713,11 @@ - **Tests:** mypy with both flags: 1,154 errors in 56 files on each of win32 / linux / darwin, from 1,613 / 1,605 / 1,605 in 109 / 108 / 108, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; headless tests of the touched modules (accessibility, flow editor, triggers, remote desktop, agent runtime, callback, flow control, hotkey, shell, X11): every run passed, and the host-service, installer, WebRTC-transport and shell tests 79 passed after the follow-up edits; doc, file-length and complexity gates 41 passed. - **Files:** 57 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. - **Open items:** `Progress.md` › H (80 modules still outside the tier). + +## U-20261115-10 · 2026-11-15 · One shared ImageSource alias; 22 image modules join the strict tier · #done #typing + +- **What:** 24 matching and image-analysis modules each bound `ImageSource = Any`, which the typing contract allows only in a registered SDK adapter, so U-20261115-06 to -09 held 25 of them out of the strict tier although mypy passed them. +- **Change:** new `utils/visual_match/image_source.py` binds the alias once and says what a source is (a path, a PIL image, a numpy array or anything `numpy.asarray` accepts; numpy is read as `Any` by the contract); it is in `SDK_ANY_ADAPTERS` in `test_typing_modernization_contract.py` beside `_webrtc_types` and in the strict tier. The 24 modules import it instead of binding their own (line endings kept). 22 are promoted (strict tier 1,444 → 1,467 with the adapter; baseline 57 → 35); `visual_match.py` and the others still carrying other errors stay listed. Three modules still bind a different alias (`Box`, `Candidate`, `MouseKeycode`). +- **Tests:** every importer imports; mypy with both flags unchanged at 1,154 errors in 56 files on each platform; `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; the image modules' tests 180 passed; doc, file-length and complexity gates passed. +- **Files:** `utils/visual_match/image_source.py`, the 24 modules, `test/unit_test/headless/test_typing_modernization_contract.py`, `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › H (58 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index 89915f8b3..fd4069475 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-10 | 2026-11-15 | One shared ImageSource alias; 22 image modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-09 | 2026-11-15 | 52 more modules join the strict typing tier (seven to ten fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-08 | 2026-11-15 | 83 more modules join the strict typing tier (four to six fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-07 | 2026-11-15 | 127 more modules join the strict typing tier (two or three fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/barcode/barcode.py b/je_auto_control/utils/barcode/barcode.py index 1607492ec..1cb50f6b4 100644 --- a/je_auto_control/utils/barcode/barcode.py +++ b/je_auto_control/utils/barcode/barcode.py @@ -13,8 +13,8 @@ from typing import Any, Callable, Dict, List, Optional, Sequence from je_auto_control.utils.visual_match.visual_match import _haystack_gray_with_origin +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any Decoder = Callable[[Any], List[Dict[str, Any]]] diff --git a/je_auto_control/utils/color_match/color_match.py b/je_auto_control/utils/color_match/color_match.py index fd289cdb0..670f2c82e 100644 --- a/je_auto_control/utils/color_match/color_match.py +++ b/je_auto_control/utils/color_match/color_match.py @@ -21,8 +21,8 @@ from je_auto_control.utils.visual_match.visual_match import ( Match, _contain_cv2_error, _nms, _resize, _select_candidates, ) +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any _CHANNEL_INDEX = {"h": 0, "s": 1, "v": 2} # Saturation from which a template pixel carries colour; below it, hue is noise. _MIN_SATURATION = 40 diff --git a/je_auto_control/utils/color_region/color_region.py b/je_auto_control/utils/color_region/color_region.py index 403a5c8bb..b62b1901c 100644 --- a/je_auto_control/utils/color_region/color_region.py +++ b/je_auto_control/utils/color_region/color_region.py @@ -12,8 +12,7 @@ imported lazily. Imports no ``PySide6``. """ from typing import Any, Dict, List, Optional, Sequence, Tuple - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def _array_as_rgb(array: Any) -> Any: diff --git a/je_auto_control/utils/edge_lines/edge_lines.py b/je_auto_control/utils/edge_lines/edge_lines.py index 38ae48c1b..f3f0a1133 100644 --- a/je_auto_control/utils/edge_lines/edge_lines.py +++ b/je_auto_control/utils/edge_lines/edge_lines.py @@ -19,8 +19,8 @@ from je_auto_control.utils.visual_match.visual_match import ( _contain_cv2_error, _haystack_gray_with_origin, _to_screen, ) +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any _CANNY_LOW = 50 _CANNY_HIGH = 150 # Hough accumulator votes a segment needs, bounded around min_length / 2. diff --git a/je_auto_control/utils/edge_match/edge_match.py b/je_auto_control/utils/edge_match/edge_match.py index 680435a64..40d7e165f 100644 --- a/je_auto_control/utils/edge_match/edge_match.py +++ b/je_auto_control/utils/edge_match/edge_match.py @@ -20,8 +20,8 @@ Match, _contain_cv2_error, _haystack_gray, _haystack_gray_with_origin, _nms, _resize, _to_gray, _to_screen, ) +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any _DEFAULT_CANNY = (50, 150) diff --git a/je_auto_control/utils/feature_match/feature_match.py b/je_auto_control/utils/feature_match/feature_match.py index bd4c256a6..9f2a3aa7e 100644 --- a/je_auto_control/utils/feature_match/feature_match.py +++ b/je_auto_control/utils/feature_match/feature_match.py @@ -21,12 +21,11 @@ from je_auto_control.utils.visual_match.visual_match import ( _contain_cv2_error, _haystack_gray_with_origin, _to_gray, ) +from je_auto_control.utils.visual_match.image_source import ImageSource if TYPE_CHECKING: import cv2 -ImageSource = Any - @dataclass(frozen=True) class FeatureMatch: diff --git a/je_auto_control/utils/hsv_segment/hsv_segment.py b/je_auto_control/utils/hsv_segment/hsv_segment.py index df92651bd..d80d0bcf9 100644 --- a/je_auto_control/utils/hsv_segment/hsv_segment.py +++ b/je_auto_control/utils/hsv_segment/hsv_segment.py @@ -15,8 +15,7 @@ # Reuse the RGB loader / screen grab from color_region (single source of truth). from je_auto_control.utils.color_region.color_region import _grab_rgb, _origin, _to_rgb - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def _hsv(haystack: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: diff --git a/je_auto_control/utils/image_quality/image_quality.py b/je_auto_control/utils/image_quality/image_quality.py index fbbd15ed1..1693d276a 100644 --- a/je_auto_control/utils/image_quality/image_quality.py +++ b/je_auto_control/utils/image_quality/image_quality.py @@ -19,8 +19,7 @@ from typing import Any, Dict, Optional, Sequence, Tuple from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: diff --git a/je_auto_control/utils/img_histogram/img_histogram.py b/je_auto_control/utils/img_histogram/img_histogram.py index 9317cb49a..7442c6854 100644 --- a/je_auto_control/utils/img_histogram/img_histogram.py +++ b/je_auto_control/utils/img_histogram/img_histogram.py @@ -15,8 +15,8 @@ # Reuse the RGB loader / screen grab (single source of truth, no copy). from je_auto_control.utils.color_region.color_region import _grab_rgb, _to_rgb +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any _SIMILARITY_METHODS = ("correlation", "intersection") diff --git a/je_auto_control/utils/match_autothresh/match_autothresh.py b/je_auto_control/utils/match_autothresh/match_autothresh.py index 9d61fdc1a..adbdb6966 100644 --- a/je_auto_control/utils/match_autothresh/match_autothresh.py +++ b/je_auto_control/utils/match_autothresh/match_autothresh.py @@ -18,8 +18,7 @@ from je_auto_control.utils.visual_match.visual_match import ( Match, _score_map, _score_map_with_origin, ) - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def _separability(scaled: Any, threshold: float) -> float: diff --git a/je_auto_control/utils/match_ensemble/match_ensemble.py b/je_auto_control/utils/match_ensemble/match_ensemble.py index 7db34d909..0854f307e 100644 --- a/je_auto_control/utils/match_ensemble/match_ensemble.py +++ b/je_auto_control/utils/match_ensemble/match_ensemble.py @@ -13,8 +13,7 @@ no ``PySide6``. """ from typing import Any, Dict, List, Optional, Sequence - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def vote_centers(centers: Sequence[Sequence[int]], *, agree_px: float = 10, diff --git a/je_auto_control/utils/match_stability/match_stability.py b/je_auto_control/utils/match_stability/match_stability.py index 14957d920..4feec6d43 100644 --- a/je_auto_control/utils/match_stability/match_stability.py +++ b/je_auto_control/utils/match_stability/match_stability.py @@ -13,8 +13,7 @@ (ndarray / path / PIL); OpenCV + NumPy arrive lazily via those modules. Imports no ``PySide6``. """ from typing import Any, Dict, List, Optional, Sequence - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def region_stability(frames: Sequence[ImageSource], *, diff --git a/je_auto_control/utils/match_trust/match_trust.py b/je_auto_control/utils/match_trust/match_trust.py index 0beb5beed..74a7b13f1 100644 --- a/je_auto_control/utils/match_trust/match_trust.py +++ b/je_auto_control/utils/match_trust/match_trust.py @@ -19,8 +19,7 @@ from je_auto_control.utils.visual_match.visual_match import ( _contain_cv2_error, _score_map_with_origin, ) - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource @dataclass(frozen=True) diff --git a/je_auto_control/utils/motion_regions/motion_regions.py b/je_auto_control/utils/motion_regions/motion_regions.py index 6d6f016bd..f41457177 100644 --- a/je_auto_control/utils/motion_regions/motion_regions.py +++ b/je_auto_control/utils/motion_regions/motion_regions.py @@ -15,8 +15,7 @@ from typing import Any, Dict, List from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error, _to_gray - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def _diff_mask(before: ImageSource, after: ImageSource, threshold: int, blur: int) -> Any: diff --git a/je_auto_control/utils/perceptual_diff/perceptual_diff.py b/je_auto_control/utils/perceptual_diff/perceptual_diff.py index 02e825ce0..625da0140 100644 --- a/je_auto_control/utils/perceptual_diff/perceptual_diff.py +++ b/je_auto_control/utils/perceptual_diff/perceptual_diff.py @@ -20,8 +20,8 @@ # Reuse the RGB loader (single source of truth, no copy). from je_auto_control.utils.color_region.color_region import _to_rgb from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any _MAX_YIQ_DELTA = 35215.0 # pixelmatch: max possible YIQ delta for 255 diff _LUMA = (0.29889531, 0.58662247, 0.11448223) #: The eight neighbours as (dx, dy), in pixelmatch's scan order (x outer, y diff --git a/je_auto_control/utils/preprocess/preprocess.py b/je_auto_control/utils/preprocess/preprocess.py index d491d32ac..50471fb0c 100644 --- a/je_auto_control/utils/preprocess/preprocess.py +++ b/je_auto_control/utils/preprocess/preprocess.py @@ -18,8 +18,8 @@ from typing import Any, Callable, Dict, Optional, Sequence from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any _INTERP = ("nearest", "linear", "cubic", "lanczos") diff --git a/je_auto_control/utils/rotated_match/rotated_match.py b/je_auto_control/utils/rotated_match/rotated_match.py index 64f5506fa..899d15197 100644 --- a/je_auto_control/utils/rotated_match/rotated_match.py +++ b/je_auto_control/utils/rotated_match/rotated_match.py @@ -23,8 +23,7 @@ _haystack_gray_with_origin, _method, _nms, _reject_flat_template, _resize, _to_gray, _to_screen, ) - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource @dataclass(frozen=True) diff --git a/je_auto_control/utils/saliency/saliency.py b/je_auto_control/utils/saliency/saliency.py index f5f05cfac..cf508083b 100644 --- a/je_auto_control/utils/saliency/saliency.py +++ b/je_auto_control/utils/saliency/saliency.py @@ -14,8 +14,7 @@ region extraction. cv2 / numpy are lazily imported. Imports no ``PySide6``. """ from typing import Any, Dict, List, Optional, Sequence, Tuple - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource def _gray(source: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: diff --git a/je_auto_control/utils/scale_detect/scale_detect.py b/je_auto_control/utils/scale_detect/scale_detect.py index dcf502870..508ea2c8e 100644 --- a/je_auto_control/utils/scale_detect/scale_detect.py +++ b/je_auto_control/utils/scale_detect/scale_detect.py @@ -20,8 +20,8 @@ from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.preprocess.preprocess import _eight_bit from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any # Common Windows display scales (100% / 125% / 150% / 175% / 200%). _DEFAULT_SCALES = (1.0, 1.25, 1.5, 1.75, 2.0) diff --git a/je_auto_control/utils/shape_locator/shape_locator.py b/je_auto_control/utils/shape_locator/shape_locator.py index 49ec7eca4..3ea7d7bfd 100644 --- a/je_auto_control/utils/shape_locator/shape_locator.py +++ b/je_auto_control/utils/shape_locator/shape_locator.py @@ -17,8 +17,8 @@ from je_auto_control.utils.visual_match.visual_match import ( _haystack_gray_with_origin, _to_screen, ) +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any AspectRange = Optional[Tuple[float, float]] _CANNY_LOW = 50 _CANNY_HIGH = 150 diff --git a/je_auto_control/utils/ssim/ssim.py b/je_auto_control/utils/ssim/ssim.py index 049f31693..5b2e6d246 100644 --- a/je_auto_control/utils/ssim/ssim.py +++ b/je_auto_control/utils/ssim/ssim.py @@ -13,8 +13,8 @@ imported lazily. Imports no ``PySide6``. """ from typing import Any, Dict, List, Optional, Sequence, Tuple +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any IgnoreBoxes = Optional[Sequence[Sequence[int]]] _WINDOW = (11, 11) _SIGMA = 1.5 diff --git a/je_auto_control/utils/subpixel_match/subpixel_match.py b/je_auto_control/utils/subpixel_match/subpixel_match.py index 9df641141..53754b0e3 100644 --- a/je_auto_control/utils/subpixel_match/subpixel_match.py +++ b/je_auto_control/utils/subpixel_match/subpixel_match.py @@ -15,8 +15,7 @@ from typing import Any, Dict, List, Optional, Sequence, Tuple from je_auto_control.utils.visual_match.visual_match import _contain_cv2_error, _score_map_with_origin - -ImageSource = Any +from je_auto_control.utils.visual_match.image_source import ImageSource @dataclass(frozen=True) diff --git a/je_auto_control/utils/text_regions/text_regions.py b/je_auto_control/utils/text_regions/text_regions.py index 72b723337..c7b60246e 100644 --- a/je_auto_control/utils/text_regions/text_regions.py +++ b/je_auto_control/utils/text_regions/text_regions.py @@ -17,8 +17,8 @@ from je_auto_control.utils.visual_match.visual_match import ( _contain_cv2_error, _haystack_gray_with_origin, _to_screen, ) +from je_auto_control.utils.visual_match.image_source import ImageSource -ImageSource = Any Rect = Tuple[int, int, int, int] diff --git a/je_auto_control/utils/visual_match/image_source.py b/je_auto_control/utils/visual_match/image_source.py new file mode 100644 index 000000000..c2597cedd --- /dev/null +++ b/je_auto_control/utils/visual_match/image_source.py @@ -0,0 +1,16 @@ +"""The image argument the matching and analysis modules accept, as one shared alias. + +A source is a path (``str``, ``bytes`` or ``os.PathLike``), a PIL image, a +numpy array, or anything else ``numpy.asarray`` turns into one; ``None`` where a +parameter allows it means the live screen. numpy is read as ``Any`` by the +typing contract (``follow_imports = "skip"`` in ``pyproject.toml``), so the +array half of that union could not be spelt precisely anyway. This module is +the one place the alias is bound, as ``SDK_ANY_ADAPTERS`` in +``test_typing_modernization_contract.py`` records; the modules around it import +it instead of each writing ``ImageSource = Any``. Imports nothing at run time. +""" +from typing import Any + +ImageSource = Any + +__all__ = ["ImageSource"] diff --git a/je_auto_control/utils/visual_match/visual_match.py b/je_auto_control/utils/visual_match/visual_match.py index 238692929..15ffc515a 100644 --- a/je_auto_control/utils/visual_match/visual_match.py +++ b/je_auto_control/utils/visual_match/visual_match.py @@ -20,10 +20,10 @@ from je_auto_control.utils.exception.exceptions import ( AutoControlFlatTemplateException, AutoControlScreenException, ) +from je_auto_control.utils.visual_match.image_source import ImageSource # cv2 method name -> the OpenCV constant is resolved lazily in _method(). _METHOD_NAMES = ("ccoeff_normed", "ccorr_normed", "sqdiff_normed") -ImageSource = Any def _contain_cv2_error(fn): diff --git a/pyproject.toml b/pyproject.toml index e1970f722..e0f881d49 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -780,6 +780,7 @@ module = [ "je_auto_control.utils.baggage", "je_auto_control.utils.baggage.*", "je_auto_control.utils.barcode", + "je_auto_control.utils.barcode.*", "je_auto_control.utils.bidi_check", "je_auto_control.utils.bidi_check.*", "je_auto_control.utils.bulkhead", @@ -824,7 +825,9 @@ module = [ "je_auto_control.utils.codegen.journal_steps", "je_auto_control.utils.codegen.robot_check", "je_auto_control.utils.color_match", + "je_auto_control.utils.color_match.*", "je_auto_control.utils.color_region", + "je_auto_control.utils.color_region.*", "je_auto_control.utils.color_stats", "je_auto_control.utils.color_stats.*", "je_auto_control.utils.column_layout", @@ -889,7 +892,9 @@ module = [ "je_auto_control.utils.dotenv", "je_auto_control.utils.dotenv.*", "je_auto_control.utils.edge_lines", + "je_auto_control.utils.edge_lines.*", "je_auto_control.utils.edge_match", + "je_auto_control.utils.edge_match.*", "je_auto_control.utils.egress", "je_auto_control.utils.egress.*", "je_auto_control.utils.element_diff", @@ -931,6 +936,7 @@ module = [ "je_auto_control.utils.feature_flags", "je_auto_control.utils.feature_flags.*", "je_auto_control.utils.feature_match", + "je_auto_control.utils.feature_match.*", "je_auto_control.utils.field_entry", "je_auto_control.utils.field_entry.*", "je_auto_control.utils.file_assoc", @@ -972,6 +978,7 @@ module = [ "je_auto_control.utils.hotkey", "je_auto_control.utils.hotkey.*", "je_auto_control.utils.hsv_segment", + "je_auto_control.utils.hsv_segment.*", "je_auto_control.utils.http_cassette", "je_auto_control.utils.http_cassette.*", "je_auto_control.utils.http_client", @@ -996,9 +1003,11 @@ module = [ "je_auto_control.utils.image_dedup", "je_auto_control.utils.image_dedup.*", "je_auto_control.utils.image_quality", + "je_auto_control.utils.image_quality.*", "je_auto_control.utils.ime_state", "je_auto_control.utils.ime_state.*", "je_auto_control.utils.img_histogram", + "je_auto_control.utils.img_histogram.*", "je_auto_control.utils.input_macro", "je_auto_control.utils.input_macro.*", "je_auto_control.utils.input_reach", @@ -1050,9 +1059,13 @@ module = [ "je_auto_control.utils.marks_layout", "je_auto_control.utils.marks_layout.*", "je_auto_control.utils.match_autothresh", + "je_auto_control.utils.match_autothresh.*", "je_auto_control.utils.match_ensemble", + "je_auto_control.utils.match_ensemble.*", "je_auto_control.utils.match_stability", + "je_auto_control.utils.match_stability.*", "je_auto_control.utils.match_trust", + "je_auto_control.utils.match_trust.*", "je_auto_control.utils.mcp_registry", "je_auto_control.utils.mcp_registry.*", "je_auto_control.utils.mcp_server", @@ -1122,6 +1135,7 @@ module = [ "je_auto_control.utils.monitor_layout", "je_auto_control.utils.monitor_layout.*", "je_auto_control.utils.motion_regions", + "je_auto_control.utils.motion_regions.*", "je_auto_control.utils.mouse_path", "je_auto_control.utils.mouse_path.*", "je_auto_control.utils.mouse_relative", @@ -1163,6 +1177,7 @@ module = [ "je_auto_control.utils.percentiles", "je_auto_control.utils.percentiles.*", "je_auto_control.utils.perceptual_diff", + "je_auto_control.utils.perceptual_diff.*", "je_auto_control.utils.pii_text", "je_auto_control.utils.pii_text.*", "je_auto_control.utils.platform_id", @@ -1282,6 +1297,7 @@ module = [ "je_auto_control.utils.rich_clipboard", "je_auto_control.utils.rich_clipboard.*", "je_auto_control.utils.rotated_match", + "je_auto_control.utils.rotated_match.*", "je_auto_control.utils.run_diff", "je_auto_control.utils.run_diff.*", "je_auto_control.utils.run_history", @@ -1289,11 +1305,13 @@ module = [ "je_auto_control.utils.saga", "je_auto_control.utils.saga.*", "je_auto_control.utils.saliency", + "je_auto_control.utils.saliency.*", "je_auto_control.utils.sarif", "je_auto_control.utils.sarif.*", "je_auto_control.utils.sbom", "je_auto_control.utils.sbom.*", "je_auto_control.utils.scale_detect", + "je_auto_control.utils.scale_detect.*", "je_auto_control.utils.scheduler", "je_auto_control.utils.scheduler.*", "je_auto_control.utils.schema_compat", @@ -1329,6 +1347,7 @@ module = [ "je_auto_control.utils.settle_detector", "je_auto_control.utils.settle_detector.*", "je_auto_control.utils.shape_locator", + "je_auto_control.utils.shape_locator.*", "je_auto_control.utils.shell_open", "je_auto_control.utils.shell_open.*", "je_auto_control.utils.shell_process", @@ -1351,6 +1370,7 @@ module = [ "je_auto_control.utils.sse_client", "je_auto_control.utils.sse_client.*", "je_auto_control.utils.ssim", + "je_auto_control.utils.ssim.*", "je_auto_control.utils.start_exe", "je_auto_control.utils.start_exe.*", "je_auto_control.utils.state_machine", @@ -1364,6 +1384,7 @@ module = [ "je_auto_control.utils.stubs", "je_auto_control.utils.stubs.*", "je_auto_control.utils.subpixel_match", + "je_auto_control.utils.subpixel_match.*", "je_auto_control.utils.system_volume", "je_auto_control.utils.system_volume.*", "je_auto_control.utils.table_grid_fill", @@ -1386,6 +1407,7 @@ module = [ "je_auto_control.utils.text_normalize", "je_auto_control.utils.text_normalize.*", "je_auto_control.utils.text_regions", + "je_auto_control.utils.text_regions.*", "je_auto_control.utils.text_similarity", "je_auto_control.utils.text_similarity.*", "je_auto_control.utils.text_unicode", @@ -1435,6 +1457,7 @@ module = [ "je_auto_control.utils.vision.frame_capture", "je_auto_control.utils.vision.vlm_api", "je_auto_control.utils.visual_match", + "je_auto_control.utils.visual_match.image_source", "je_auto_control.utils.visual_regression", "je_auto_control.utils.visual_regression.*", "je_auto_control.utils.voice", diff --git a/test/unit_test/headless/test_typing_modernization_contract.py b/test/unit_test/headless/test_typing_modernization_contract.py index fd407ae78..15f8c3bc7 100644 --- a/test/unit_test/headless/test_typing_modernization_contract.py +++ b/test/unit_test/headless/test_typing_modernization_contract.py @@ -54,6 +54,9 @@ # av.VideoFrame and the aiortc-backed host / viewer / recorder classes, # which are ``None`` at run time without the ``webrtc`` extra. "je_auto_control.gui.remote_desktop._webrtc_types", + # The image argument of the matching and analysis modules: a path, a PIL + # image or anything ``numpy.asarray`` accepts, with numpy itself read as Any. + "je_auto_control.utils.visual_match.image_source", } _BARE_IGNORE = re.compile(r"#\s*type:\s*ignore(?!\[)") diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 577e675db..0f85807b7 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -22,32 +22,17 @@ je_auto_control.linux_wayland.libei je_auto_control.utils.accessibility.accessibility_api je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.actionability.actionability -je_auto_control.utils.barcode.barcode je_auto_control.utils.codegen.codegen -je_auto_control.utils.color_match.color_match -je_auto_control.utils.color_region.color_region -je_auto_control.utils.edge_lines.edge_lines -je_auto_control.utils.edge_match.edge_match je_auto_control.utils.executor.action_executor -je_auto_control.utils.feature_match.feature_match je_auto_control.utils.grid_locator.grid_locator je_auto_control.utils.grounding_consensus.grounding_consensus -je_auto_control.utils.hsv_segment.hsv_segment -je_auto_control.utils.image_quality.image_quality -je_auto_control.utils.img_histogram.img_histogram je_auto_control.utils.json_schema.json_schema je_auto_control.utils.logging.logging_instance -je_auto_control.utils.match_autothresh.match_autothresh -je_auto_control.utils.match_ensemble.match_ensemble -je_auto_control.utils.match_stability.match_stability -je_auto_control.utils.match_trust.match_trust je_auto_control.utils.mcp_server.tools._handlers je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations je_auto_control.utils.mcp_server.tools._handlers_system je_auto_control.utils.message_format.message_format -je_auto_control.utils.motion_regions.motion_regions -je_auto_control.utils.perceptual_diff.perceptual_diff je_auto_control.utils.preprocess.preprocess je_auto_control.utils.recording_edit.editor je_auto_control.utils.remote_desktop.hw_codec @@ -56,14 +41,7 @@ je_auto_control.utils.remote_desktop.signaling_server je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host je_auto_control.utils.remote_desktop.webrtc_viewer -je_auto_control.utils.rotated_match.rotated_match -je_auto_control.utils.saliency.saliency -je_auto_control.utils.scale_detect.scale_detect -je_auto_control.utils.shape_locator.shape_locator -je_auto_control.utils.ssim.ssim -je_auto_control.utils.subpixel_match.subpixel_match je_auto_control.utils.table_grid_fill.table_grid_fill -je_auto_control.utils.text_regions.text_regions je_auto_control.utils.tool_use_schema.schema je_auto_control.utils.vision.backends.anthropic_backend je_auto_control.utils.vision.backends.openai_backend From aa376eb097e51d70b9ca6907916017ddb5ed9837 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 13:43:31 +0800 Subject: [PATCH 128/161] Type grid boxes and grounding candidates instead of aliasing Any Both shapes are what the code already narrows on, so the two locator modules can join the strict tier. MouseKeycode keeps its Any: typing it per platform exposes mismatched key tables in the wrapper layer. --- Progress.md | 2 +- architecture_explore.md | 14 +++++++------- docs/updates/2026-11-b.md | 8 ++++++++ docs/updates/README.md | 1 + je_auto_control/utils/grid_locator/grid_locator.py | 7 +++++-- .../grounding_consensus/grounding_consensus.py | 5 +++-- pyproject.toml | 2 ++ test/verify/typing_strict_baseline.txt | 2 -- 8 files changed, 27 insertions(+), 14 deletions(-) diff --git a/Progress.md b/Progress.md index f99f9e1e8..5bce7bc09 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~10,共 1,467 個)。仍缺:`test/verify/typing_strict_baseline.txt` 35 個與 `typing_not_yet_strict.txt` 23 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:43 個每檔 11 個以上錯誤的大檔(三平台約 1,150 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),3 個只差模組層級的 `Any` 別名(`grid_locator` 的 `Box`、`grounding_consensus` 的 `Candidate`、`wrapper/backend_contract` 的 `MouseKeycode`),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~11,共 1,469 個)。仍缺:`test/verify/typing_strict_baseline.txt` 33 個與 `typing_not_yet_strict.txt` 23 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:43 個每檔 11 個以上錯誤的大檔(三平台約 1,150 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),`wrapper/backend_contract` 的 `MouseKeycode = Any`(依平台寫成 tuple/int 會露出 `platform_wrapper` 各分支匯入的 `mouse_keys_table` 型別不同,其中一個是 `dict[str, str]`,要先重整 wrapper 層),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index f1256e766..36ae765f5 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 237,845 | +| 程式碼總行數 | 237,849 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -437,7 +437,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.6 OCR 與文字理解 -> 19 個套件、約 3,829 行。 +> 19 個套件、約 3,832 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -446,7 +446,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/confusables/` | 146 | 易混淆/同形字偵測(Unicode 欺騙骨架) | | `utils/form_fields/` | 134 | 多方向關聯表單標籤與值,並讀取核取方塊狀態 | | `utils/fuzzy/` | 111 | 模糊字串比對與去重(預設 difflib,有 rapidfuzz 則優先) | -| `utils/grid_locator/` | 100 | 以 (row, column) 從邊界框定址表格/網格儲存格 | +| `utils/grid_locator/` | 103 | 以 (row, column) 從邊界框定址表格/網格儲存格 | | `utils/guardrail/` | 117 | 針對畫面/OCR 文字的啟發式 prompt-injection 防護 | | `utils/heading_segment/` | 71 | 判定 OCR 行是標題或內文,建出文件大綱 | | `utils/near_dup/` | 108 | 近似重複文字偵測(SimHash/MinHash) | @@ -486,7 +486,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.8 元素定位、自我修復與智慧等待 -> 23 個套件、約 6,343 行。 +> 23 個套件、約 6,344 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -501,7 +501,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/element_proposal/` | 92 | 免樣板、免模型地從原始像素提出乾淨元素清單 | | `utils/element_scoring/` | 105 | 加權候選評分(角色 + 名稱相似度 + 鄰近度 + 啟用狀態) | | `utils/expect_poll/` | 150 | 反覆取值直到符合條件(Playwright `expect.poll` 風格) | -| `utils/grounding_consensus/` | 173 | 對同一目標的多個接地提案做自我一致性投票 | +| `utils/grounding_consensus/` | 174 | 對同一目標的多個接地提案做自我一致性投票 | | `utils/heal_analytics/` | 120 | 自癒事件記錄的分析(治癒率、脆弱定位器) | | `utils/locator_chain/` | 112 | 可組合/可過濾的候選定位器(chained-locator 慣用法) | | `utils/locator_repair/` | 147 | 自癒回寫:把修正後的定位器持久化 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,625 | -| **總計** | **1,533** | **237,100** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,629 | +| **總計** | **1,533** | **237,104** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index b2f54828c..922adf11e 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -721,3 +721,11 @@ - **Tests:** every importer imports; mypy with both flags unchanged at 1,154 errors in 56 files on each platform; `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; the image modules' tests 180 passed; doc, file-length and complexity gates passed. - **Files:** `utils/visual_match/image_source.py`, the 24 modules, `test/unit_test/headless/test_typing_modernization_contract.py`, `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › H (58 modules still outside the tier). + +## U-20261115-11 · 2026-11-15 · Box and Candidate get real types; two locator modules join the strict tier · #done #typing + +- **What:** the three modules U-20261115-10 left out for binding a module-level name to `Any`. +- **Change:** `grid_locator.Box` is `object` (a list / tuple box in `BOX_FORMATS` or anything `element_box` reads -- which is what `_as_xywh` already narrows with `isinstance`), and `_center` takes the `Sequence[int]` it is always given; `grounding_consensus.Candidate` is `Union[Dict[str, Any], Sequence[float]]`, the two shapes `_xyw` handles. Both pass mypy on all three platforms and join the strict tier (1,469 modules; baseline 35 → 33). `wrapper/backend_contract.MouseKeycode` stays `Any`: a union fails every backend's `click_mouse`, and a per-platform alias (`Tuple[int, int, int]` on win32, `int` elsewhere) exposes that `platform_wrapper` imports a `mouse_keys_table` of a different type in each branch, one `dict[str, str]`, which `auto_control_mouse` then mixes -- a wrapper-layer refactor, recorded in `Progress.md`. +- **Tests:** mypy on all three platforms: no issues; `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the grid-locator and grounding-consensus tests 15 passed. +- **Files:** `utils/grid_locator/grid_locator.py`, `utils/grounding_consensus/grounding_consensus.py`, `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `architecture_explore.md` (line counts), `Progress.md`. +- **Open items:** `Progress.md` › H (56 modules still outside the tier). diff --git a/docs/updates/README.md b/docs/updates/README.md index fd4069475..a7ca66981 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-11 | 2026-11-15 | Box and Candidate get real types; two locator modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-10 | 2026-11-15 | One shared ImageSource alias; 22 image modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-09 | 2026-11-15 | 52 more modules join the strict typing tier (seven to ten fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-08 | 2026-11-15 | 83 more modules join the strict typing tier (four to six fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/grid_locator/grid_locator.py b/je_auto_control/utils/grid_locator/grid_locator.py index 3ac73a246..927c685c9 100644 --- a/je_auto_control/utils/grid_locator/grid_locator.py +++ b/je_auto_control/utils/grid_locator/grid_locator.py @@ -12,7 +12,10 @@ """ from typing import Any, Dict, List, Sequence, Tuple -Box = Any +#: A list / tuple box in one of :data:`BOX_FORMATS`, or anything +#: :func:`~je_auto_control.utils.accessibility.element.element_box` reads +#: (a dict, a match object, an accessibility element). +Box = object #: How a list box is laid out: ``locate_all_image`` answers ``ltrb``. BOX_FORMATS = ("xywh", "ltrb") @@ -40,7 +43,7 @@ def _checked_format(box_format: str) -> str: return box_format -def _center(box: Box) -> Tuple[int, int]: +def _center(box: Sequence[int]) -> Tuple[int, int]: """Return the integer centre ``(x, y)`` of an ``(x, y, w, h)`` box.""" x, y, width, height = (int(value) for value in box[:4]) return x + width // 2, y + height // 2 diff --git a/je_auto_control/utils/grounding_consensus/grounding_consensus.py b/je_auto_control/utils/grounding_consensus/grounding_consensus.py index 767d90486..fda663bac 100644 --- a/je_auto_control/utils/grounding_consensus/grounding_consensus.py +++ b/je_auto_control/utils/grounding_consensus/grounding_consensus.py @@ -13,11 +13,12 @@ """ import math from dataclasses import asdict, dataclass -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from je_auto_control.utils.accessibility.element import element_box -Candidate = Any +#: A proposed point: ``{"x", "y"[, "weight"]}`` or ``[x, y[, weight]]``. +Candidate = Union[Dict[str, Any], Sequence[float]] Element = Dict[str, Any] diff --git a/pyproject.toml b/pyproject.toml index e0f881d49..54c48e266 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -968,7 +968,9 @@ module = [ "je_auto_control.utils.governance", "je_auto_control.utils.governance.*", "je_auto_control.utils.grid_locator", + "je_auto_control.utils.grid_locator.*", "je_auto_control.utils.grounding_consensus", + "je_auto_control.utils.grounding_consensus.*", "je_auto_control.utils.guardrail", "je_auto_control.utils.guardrail.*", "je_auto_control.utils.heading_segment", diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 0f85807b7..37652cd62 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -24,8 +24,6 @@ je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.actionability.actionability je_auto_control.utils.codegen.codegen je_auto_control.utils.executor.action_executor -je_auto_control.utils.grid_locator.grid_locator -je_auto_control.utils.grounding_consensus.grounding_consensus je_auto_control.utils.json_schema.json_schema je_auto_control.utils.logging.logging_instance je_auto_control.utils.mcp_server.tools._handlers From 95ef4f45f8c225f1dabe491d277707a728235bdd Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 14:05:12 +0800 Subject: [PATCH 129/161] Annotate 25 modules with 11 to 20 gaps and hold them to the strict tier Mostly agent_runtime. The cv2 error decorator now keeps the signatures of what it wraps, and the signaling routes declare the response shapes they already returned. --- Progress.md | 2 +- architecture_explore.md | 52 +++++++++---------- docs/updates/2026-11-b.md | 8 +++ docs/updates/README.md | 1 + je_auto_control/gui/agent_tasks_tab.py | 28 +++++----- je_auto_control/gui/dag_tab.py | 29 ++++++----- .../utils/agent_runtime/browser_workflows.py | 27 +++++----- .../dag_continuation_evidence.py | 30 ++++++----- .../utils/agent_runtime/input_ledger.py | 22 ++++---- .../utils/agent_runtime/native_worker.py | 37 ++++++------- .../utils/agent_runtime/presence_pool.py | 24 ++++----- je_auto_control/utils/agent_runtime/routes.py | 26 +++++----- .../utils/agent_runtime/skill_completion.py | 33 +++++++----- .../utils/agent_runtime/skill_execution.py | 29 ++++++----- .../utils/agent_runtime/task_triggers.py | 25 ++++----- .../utils/agent_runtime/transfer_evidence.py | 24 ++++----- .../utils/agent_runtime/transfer_import.py | 36 ++++++------- .../utils/agent_runtime/transfer_lineage.py | 42 +++++++++------ .../utils/agent_runtime/transfer_source.py | 29 ++++++----- .../utils/agent_runtime/workflow_specs.py | 22 ++++---- je_auto_control/utils/codegen/codegen.py | 26 +++++----- .../utils/message_format/message_format.py | 2 +- .../utils/preprocess/preprocess.py | 32 ++++++------ .../utils/recording_edit/editor.py | 38 +++++++------- .../utils/remote_desktop/multi_viewer.py | 34 ++++++------ .../utils/remote_desktop/signaling_server.py | 30 +++++------ .../utils/remote_desktop/webrtc_files.py | 40 ++++++++------ .../utils/visual_match/visual_match.py | 37 +++++++------ .../wrapper/window_backends/macos_backend.py | 33 ++++++------ pyproject.toml | 40 ++++++++------ test/verify/typing_not_yet_strict.txt | 15 ------ test/verify/typing_strict_baseline.txt | 10 ---- 32 files changed, 451 insertions(+), 412 deletions(-) diff --git a/Progress.md b/Progress.md index 5bce7bc09..0b90960b7 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~11,共 1,469 個)。仍缺:`test/verify/typing_strict_baseline.txt` 33 個與 `typing_not_yet_strict.txt` 23 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:43 個每檔 11 個以上錯誤的大檔(三平台約 1,150 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),`wrapper/backend_contract` 的 `MouseKeycode = Any`(依平台寫成 tuple/int 會露出 `platform_wrapper` 各分支匯入的 `mouse_keys_table` 型別不同,其中一個是 `dict[str, str]`,要先重整 wrapper 層),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~12,共 1,494 個)。仍缺:`test/verify/typing_strict_baseline.txt` 23 個與 `typing_not_yet_strict.txt` 8 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:18 個每檔 20 個以上錯誤的大檔(三平台約 780 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),`wrapper/backend_contract` 的 `MouseKeycode = Any`(依平台寫成 tuple/int 會露出 `platform_wrapper` 各分支匯入的 `mouse_keys_table` 型別不同,其中一個是 `dict[str, str]`,要先重整 wrapper 層),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 36ae765f5..5eee3cd3f 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 237,849 | +| 程式碼總行數 | 237,894 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -198,7 +198,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `wrapper/auto_control_image.py` | 89 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | | `wrapper/auto_control_record.py` | 124 | 錄製 API:`record`/`stop_record`/`record_to_json`(支援 stop event 與逾時)。 | | `wrapper/auto_control_window.py` | 338 | 視窗管理門面:列舉、尋找、聚焦、等待、關閉、顯示狀態、幾何、所屬行程 PID、依行程列舉/最小化視窗、不搶焦點的投遞式輸入(目前僅 Windows 實作)。 | -| `wrapper/window_backends/` | 1,153 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | +| `wrapper/window_backends/` | 1,156 | 視窗管理的平台縫(`base` / `windows_backend` / `x11_backend` / `macos_backend` / `null_backend`)。放在 `wrapper/` 而不是 `utils/`,因為它必須 import `windows/`、`linux_with_x11/`、`osx/`,而 `utils/` 在分層上在那三者之上。 | ### 5.3 平台後端 @@ -393,7 +393,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,576 行。 +> 37 個套件、約 6,579 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -432,7 +432,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/subpixel_match/` | 108 | 以二次曲面擬合做次像素級比對精修 | | `utils/theme_normalize/` | 94 | 主題無關的影像正規化,讓亮色樣板能配對深色模式 | | `utils/video_report/` | 171 | 影片步驟疊圖報告:把截圖加字幕串成操作導覽影片 | -| `utils/visual_match/` | 531 | 會回傳信心值的樣板比對(分數、多尺度、find-all + NMS);擷取走 `grab_logical`,命中座標已加回虛擬桌面原點,單色樣板直接拒收;`image_source.py` 是比對與影像分析模組共用的 `ImageSource` 別名(型別契約允許的 numpy 陣列 `Any` 邊界,列在 `SDK_ANY_ADAPTERS`) | +| `utils/visual_match/` | 534 | 會回傳信心值的樣板比對(分數、多尺度、find-all + NMS);擷取走 `grab_logical`,命中座標已加回虛擬桌面原點,單色樣板直接拒收;`image_source.py` 是比對與影像分析模組共用的 `ImageSource` 別名(型別契約允許的 numpy 陣列 `Any` 邊界,列在 `SDK_ANY_ADAPTERS`) | | `utils/visual_regression/` | 251 | 桌面 GUI 的視覺回歸測試(黃金圖比對) | ### 5.4.6 OCR 與文字理解 @@ -516,13 +516,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 53,003 行。 +> 14 個套件、約 53,031 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,254 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 26,002 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 26,030 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,245 行。 +> 6 個套件、約 32,255 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,917 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,927 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,917 行/77 檔) +#### `utils/remote_desktop/`(16,927 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -837,7 +837,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `host_client.py` | 466 | TCP 主機的每連線處理器:一個檢視端一個實例,擁有它的認證交換、sender/audio/receiver 三條執行緒,以及入站訊息的路由表。 | | `registry.py` | 581 | `AC_remote_*` 指令使用的行程級單例。 | | `webrtc_transport.py` | 422 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | -| `multi_viewer.py` | 519 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | +| `multi_viewer.py` | 523 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | | `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 324 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | @@ -857,7 +857,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_file_receive.py` | 101 | Bind file receivers to one authenticated peer and channel, retiring partial bytes when ownership ends. | | `webrtc_file_write.py` | 209 | Bounded observable DataChannel writes preserve caller cancellation and serialize file producers. | | `webrtc_file_tasks.py` | 147 | Run remote inbox pushes outside the event loop while preserving connection ownership and cooperative cancellation. | -| `webrtc_files.py` | 416 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | +| `webrtc_files.py` | 422 | 專屬 DataChannel 的分塊檔案傳輸、可選校驗與原子發布確認。 | | `webrtc_host_auth.py` | 255 | 檢視端認證與核准:token 檢查、信任清單/IP 白名單自動放行、手動接受/拒絕、SAS、逾時關閉。 | | `lan_discovery.py` | 387 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | @@ -1045,7 +1045,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(26,002 行/182 檔) +#### `utils/agent_runtime/`(26,030 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1073,7 +1073,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `browser_transfers.py` | 101 | Rooted file snapshots and atomic publication around WebRunner-owned browser transfers. | | `browser_validation.py` | 35 | Pure browser text and URL bounds shared without loading SDK or command dispatch. | | `browser_verification.py` | 91 | Pinned browser completion clauses use fresh bounded SDK reads, never agent claims or previews. | -| `browser_workflows.py` | 181 | Compile rooted CSV forms and captured field transfers into reviewed WebRunner task actions. | +| `browser_workflows.py` | 182 | Compile rooted CSV forms and captured field transfers into reviewed WebRunner task actions. | | `budget_clock.py` | 35 | Persistent monotonic task budgets that cannot be extended by wall-clock rollback or restart. | | `cli.py` | 132 | Managed-task CLI parsing; the existing CLI owns terminal output. | | `client.py` | 93 | Shared local service client for GUI, CLI, MCP and Python task operations. | @@ -1086,7 +1086,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `dag_batch_recording.py` | 93 | Durable dispatch claims and independent destination verification for one managed DAG batch. | | `dag_batches.py` | 366 | Owner-scoped graph lifecycle and runtime-owned task/artifact host adapters. | | `dag_continuation.py` | 339 | Whole-graph review and one-shot continuation approval never replay a possible delivery. | -| `dag_continuation_evidence.py` | 169 | Bounded read-only destination evidence for explicit whole-batch continuation decisions. | +| `dag_continuation_evidence.py` | 171 | Bounded read-only destination evidence for explicit whole-batch continuation decisions. | | `dag_continuation_plan.py` | 91 | Explicit per-node decisions preserve graph scope and never reset a possible delivery claim. | | `dag_jobs.py` | 140 | Service-owned durable DAG deliveries never replay an interrupted coordinator attempt. | | `dag_local.py` | 98 | Closed local-node transport admits claimed DAG work under the original owner's authority. | @@ -1118,7 +1118,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `native_recovery.py` | 36 | Host-only input recovery checks never replay persisted keys or signal persisted PIDs. | | `native_scope.py` | 111 | Scope native window and control targets before their existing backend performs an action. | | `native_target.py` | 310 | Native desktop proxy with private IPC, host input ledger and cross-database ownership. | -| `native_worker.py` | 349 | Private native helper entry point; stdout is a bounded owner-only JSON protocol. | +| `native_worker.py` | 350 | Private native helper entry point; stdout is a bounded owner-only JSON protocol. | | `observation_refs.py` | 155 | Resolve observation-local elements and thumbnail points into host-checked native coordinates. | | `ollama.py` | 82 | Local-only Ollama decisions over bounded HTTP, without an SDK or remote fallback. | | `origin_policy.py` | 193 | Live origin path ceilings remain restrictive across accepted tasks, workers and service processes. | @@ -1173,8 +1173,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `runtime.py` | 750 | Shared managed-task lifecycle with fenced dispatch and evidence-based completion. | | `runtime_lock.py` | 75 | Cross-process ownership for one runtime database; imports never acquire locks. | | `service.py` | 115 | Explicit local runtime service lifecycle over the existing authenticated REST server. | -| `skill_completion.py` | 120 | Private read-only evidence for skill recording and publication preserves original workflow identity. | -| `skill_execution.py` | 110 | Exact original skill effects across real reviewed recovery, without granting input or replacing trials. | +| `skill_completion.py` | 129 | Private read-only evidence for skill recording and publication preserves original workflow identity. | +| `skill_execution.py` | 115 | Exact original skill effects across real reviewed recovery, without granting input or replacing trials. | | `skill_parameters.py` | 110 | Explicit typed parameter slots modify data values without widening a skill's authority. | | `skill_reauthorization.py` | 107 | Review origin renewal into a new immutable candidate without inheriting skill publication. | | `skill_recording.py` | 107 | Semantic skill drafts retain verified actions, original scope and independent completion evidence. | @@ -1189,7 +1189,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `task_handoff.py` | 82 | Real non-DAG source identity for explicit completion evidence, without fabricated admission. | | `task_recovery.py` | 484 | Review stopped tasks and create one explicitly approved successor without replay. | | `task_skills.py` | 373 | Immutable managed skill candidates require a verified trial and explicit version publication. | -| `task_triggers.py` | 271 | Durable preauthorized task bindings with owner refresh, bounded backlog and event deduplication. | +| `task_triggers.py` | 272 | Durable preauthorized task bindings with owner refresh, bounded backlog and event deduplication. | | `transfer_destination_scope.py` | 33 | Injected destination profiles and live origin ceilings confine reviewed import directories. | | `transfer_import_contract.py` | 83 | Closed destination management envelopes carry opaque foreign paths without forwarding local authority. | | `transfer_import.py` | 342 | Destination-owned consent and fenced recovery bind source manifests to immutable local files profiles. | @@ -1200,7 +1200,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `transfer_cache.py` | 34 | One runtime-derived private blob cache never accepts a public path or configuration account selector. | | `transfer_files.py` | 111 | Bounded source-file descriptors and verified chunks remain private until export consent commits. | | `transfer_host.py` | 202 | Host-injected source authority and destination scope keep task policy out of transfer leaves. | -| `transfer_lineage.py` | 148 | Bind artifact authority to real bounded recovery ancestry and original accepted DAG admission. | +| `transfer_lineage.py` | 156 | Bind artifact authority to real bounded recovery ancestry and original accepted DAG admission. | | `transfer_models.py` | 191 | Portable criterion selections and immutable descriptors for reviewed outcome transfers. | | `transfer_privacy.py` | 53 | Exclude actual host private stores and evidence roots without reserving ordinary output basenames. | | `transfer_protocol.py` | 171 | Runtime-owned transfer serialization coordinates source consent and service-owned destination imports. | @@ -1210,7 +1210,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `transfer_routing.py` | 136 | Coordinator-owned routed consent persists exact approval before forwarding source or destination creation. | | `transfer_records.py` | 292 | Private transfer reservations bind consent and retain capacity until owned cleanup is confirmed. | | `transfer_selection.py` | 136 | Resolve only source-owned passed file criteria and their explicitly selected manifest names. | -| `transfer_source.py` | 273 | Explicitly reviewed source artifacts publish immutable blobs under live host-derived authority. | +| `transfer_source.py` | 274 | Explicitly reviewed source artifacts publish immutable blobs under live host-derived authority. | | `transport.py` | 128 | Bounded HTTP requests; cancellation discards late inference replies before any input. | | `trigger_config.py` | 69 | Validate durable trigger schedules and rooted file-version notifications without side effects. | | `trigger_history.py` | 89 | Renewed trigger lineages share accepted event tombstones and outstanding-task limits. | @@ -1388,7 +1388,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | window_manager | `window_tab.py` | 152 | 列出、聚焦、關閉視窗。 | | plugins | `plugins_tab.py` | 85 | 從使用者目錄載入額外 `AC_` 指令。 | | webrunner | `webrunner_tab.py` | 203 | 從 GUI 驅動 `je_web_runner`。 | -| dag_runner | `dag_tab.py` | 366 | 編輯、驗證、執行跨主機 DAG。 | +| dag_runner | `dag_tab.py` | 367 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | | remote_desktop | `remote_desktop/`(40 檔) | 8,573 | 見下。 | @@ -1549,14 +1549,14 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,927 | +| `gui/` | 166 | 43,928 | | `utils/mcp_server/` | 63 | 22,241 | -| `utils/remote_desktop/` | 77 | 16,917 | +| `utils/remote_desktop/` | 77 | 16,927 | | `utils/executor/` | 11 | 10,756 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | | `utils/accessibility/` | 16 | 3,375 | -| `wrapper/` | 25 | 6,050 | +| `wrapper/` | 25 | 6,053 | | `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,228 | | `utils/agent/` | 13 | 2,254 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,629 | -| **總計** | **1,533** | **237,104** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,660 | +| **總計** | **1,533** | **237,149** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 922adf11e..54d1623bc 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -729,3 +729,11 @@ - **Tests:** mypy on all three platforms: no issues; `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the grid-locator and grounding-consensus tests 15 passed. - **Files:** `utils/grid_locator/grid_locator.py`, `utils/grounding_consensus/grounding_consensus.py`, `pyproject.toml`, `test/verify/typing_strict_baseline.txt`, `architecture_explore.md` (line counts), `Progress.md`. - **Open items:** `Progress.md` › H (56 modules still outside the tier). + +## U-20261115-12 · 2026-11-15 · 25 more modules join the strict typing tier (11 to 20 fixes each) · #done #typing + +- **What:** the next stage of `Progress.md` › H: the 25 files with 11 to 20 strict errors (373 by a fresh count), most of them in `agent_runtime`, plus `visual_match`, `preprocess`, `codegen`, `message_format`, `recording_edit`, `multi_viewer`, `signaling_server`, `webrtc_files`, the macOS window backend and two GUI tabs. +- **Change:** annotation-only edits in all 25. Worth knowing: `visual_match._contain_cv2_error` is typed with `ParamSpec` / `TypeVar`, so the functions it decorates (in `preprocess`, `color_match`, `edge_match`, `edge_lines`, `feature_match`) keep their real signatures for callers, with no new error anywhere; the signaling server's routes now declare `dict[str, str]` / `dict[str, bool]` where they said `dict` -- FastAPI reads a return annotation as the response model, so the OpenAPI schema is more precise, and every value those routes return is a `str` or `bool` (the `None` cases raise 404 first), so response validation cannot newly fail; its middleware is `Callable[[Request], Awaitable[Response]] -> Response`; `message_format.Node` is `Tuple[Any, ...]` (nodes differ in length); aiortc types in `multi_viewer` come in under `TYPE_CHECKING`. The bare `# type: ignore`s on `from aiortc.contrib.media import MediaRelay` and `import uvicorn` go, as the forced-`Any` override covers both (and `--extras`, which reads aiortc's real types, passes). 25 modules are promoted (strict tier 1,469 → 1,494; baseline 33 → 23, not-yet-strict 23 → 8). +- **Tests:** mypy with both flags: 781 errors in 31 files on each of win32 / linux / darwin, from 1,154 in 56, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; 22 related headless test files 429 passed, 1 skipped, and the multi-viewer and signaling tests 62 passed, 2 skipped after the ignores went; doc, file-length and complexity gates 41 passed. +- **Files:** 25 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. +- **Open items:** `Progress.md` › H (31 modules still outside the tier: 18 large ones, 12 with a real type error behind the annotation, and `wrapper/backend_contract`). diff --git a/docs/updates/README.md b/docs/updates/README.md index a7ca66981..9a03f84b4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-12 | 2026-11-15 | 25 more modules join the strict typing tier (11 to 20 fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-11 | 2026-11-15 | Box and Candidate get real types; two locator modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-10 | 2026-11-15 | One shared ImageSource alias; 22 image modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-09 | 2026-11-15 | 52 more modules join the strict typing tier (seven to ten fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/agent_tasks_tab.py b/je_auto_control/gui/agent_tasks_tab.py index 0b14e28ff..2b62ccf65 100644 --- a/je_auto_control/gui/agent_tasks_tab.py +++ b/je_auto_control/gui/agent_tasks_tab.py @@ -3,7 +3,7 @@ import json from functools import partial -from typing import Any +from typing import Any, Callable from pathlib import Path from PySide6.QtWidgets import ( # pylint: disable=no-name-in-module # reason: compiled Qt exports, tested offscreen @@ -44,7 +44,7 @@ def _translate(key: str) -> str: return language_wrapper.translate(key, key) -def _request(operation: str, payload: dict, token: CancellationToken) -> dict: +def _request(operation: str, payload: dict[str, Any], token: CancellationToken) -> dict[str, Any]: token.checkpoint() if operation == "start": return start_agent_runtime() @@ -167,7 +167,7 @@ def _setup_pages(self) -> None: raise RuntimeError("the observation page was built without a layout") page_layout.addWidget(self._observation) - def _page(self, key: str, fields: tuple) -> None: + def _page(self, key: str, fields: tuple[tuple[str, QWidget], ...]) -> None: page = QWidget() page.setProperty("role", "bare") form = QFormLayout() @@ -207,7 +207,7 @@ def retranslate(self) -> None: text = _translate("agent_target_" + self._target_operation.itemData(index)) self._target_operation.setItemText(index, text) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose lifecycle commands through the common Actions menu.""" return [("agent_start", partial(self._dispatch, "start")), ("agent_stop_service", partial(self._dispatch, "stop")), @@ -345,7 +345,7 @@ def _clear_observation(self, _task_id: str = "") -> None: self._observation.clear() self._remainder_request.setPlainText("{}") - def _pick_reference(self, reference: dict) -> None: + def _pick_reference(self, reference: dict[str, Any]) -> None: try: action = json.loads(self._action.toPlainText()) if not isinstance(action, dict) or not isinstance(action.get("arguments", {}), dict): @@ -468,7 +468,7 @@ def _submit(self) -> None: return self._dispatch("submit", payload) - def _task_spec(self) -> dict: + def _task_spec(self) -> dict[str, Any]: spec = json.loads(self._scope.toPlainText()) return AgentTaskSpec.from_dict({**spec, "goal": self._goal.text(), "target": self._target.text(), "mode": self._mode.currentText()}).to_dict() @@ -484,7 +484,7 @@ def _trigger_apply(self) -> None: self._trigger_config.setPlainText("{}") self._dispatch("trigger", {"operation": operation, "request": request}) - def _trigger_request(self, operation: str) -> dict: + def _trigger_request(self, operation: str) -> dict[str, Any]: if operation == "list": return {} if operation == "register": @@ -500,7 +500,7 @@ def _trigger_request(self, operation: str) -> dict: request.update(event_key=self._event_key.text(), payload=json.loads(self._trigger_config.toPlainText())) return request - def _dispatch(self, operation: str, payload: dict | None = None) -> None: + def _dispatch(self, operation: str, payload: dict[str, Any] | None = None) -> None: if self._handle is not None and self._handle.outcome is None: if operation not in {"pause", "cancel", "stop", "stop_all"}: return @@ -514,7 +514,7 @@ def _dispatch(self, operation: str, payload: dict | None = None) -> None: self._handle = self._controller.submit(partial(_request, operation, data), owner=self) self._handle.finished.connect(self._completed) - def _select_request_view(self, operation: str, data: dict) -> None: + def _select_request_view(self, operation: str, data: dict[str, Any]) -> None: self._view_task = str(data.get("task_id", "")) self._handoff_view = None if operation == "recovery": @@ -548,7 +548,7 @@ def _view_current(self) -> bool: return self._view_task == _TRIGGER_VIEW_PREFIX + self._trigger_id.text() return not self._view_task or self._view_task == self._task_id.text() - def _present_result(self, result: dict) -> None: + def _present_result(self, result: dict[str, Any]) -> None: self._present_lookup(result) if not self._present_trigger_authorization(result): return @@ -572,14 +572,14 @@ def _present_result(self, result: dict) -> None: for column, name in enumerate(("task_id", "goal", "state", "reason")): self._table.setItem(index, column, QTableWidgetItem(str(row.get(name, "")))) - def _present_observation(self, result: dict) -> None: + def _present_observation(self, result: dict[str, Any]) -> None: if "observation_id" in result: try: self._observation.present(result) except AgentTaskError as error: self._status.setText(str(error)) - def _present_trigger_authorization(self, result: dict) -> bool: + def _present_trigger_authorization(self, result: dict[str, Any]) -> bool: if "trigger_id" not in result or "approval_required" not in result: return True if result["trigger_id"] != self._trigger_id.text(): @@ -592,12 +592,12 @@ def _present_trigger_authorization(self, result: dict) -> bool: self._pages.setCurrentIndex(self._page_keys.index("agent_page_triggers")) return True - def _present_lookup(self, result: dict) -> None: + def _present_lookup(self, result: dict[str, Any]) -> None: found = result.get("task") if result.get("found") is True and isinstance(found, dict) and isinstance(found.get("task_id"), str): self._task_id.setText(found["task_id"]) - def _present_remainder(self, result: dict) -> None: + def _present_remainder(self, result: dict[str, Any]) -> None: draft = result.get("draft") if not isinstance(draft, dict): draft = result.get("review_template") diff --git a/je_auto_control/gui/dag_tab.py b/je_auto_control/gui/dag_tab.py index b89c0bfd9..d161bcee6 100644 --- a/je_auto_control/gui/dag_tab.py +++ b/je_auto_control/gui/dag_tab.py @@ -9,7 +9,7 @@ import threading from functools import partial from contextvars import copy_context -from typing import Any, Optional +from typing import Any, Callable, Optional from PySide6.QtCore import Qt from PySide6.QtWidgets import ( @@ -45,21 +45,21 @@ def _t(key: str) -> str: class _DagWorker: """One DAG request: built on the GUI thread, whose context it keeps, and called on the worker thread.""" - def __init__(self, definition: dict, max_parallel: int, + def __init__(self, definition: dict[str, Any], max_parallel: int, stop_event: Optional[threading.Event] = None, *, inspect_only: bool = False, - batch_id: str = "", batch_operation: str | dict = "") -> None: + batch_id: str = "", batch_operation: str | dict[str, Any] = "") -> None: self._definition = definition self._max_parallel = max_parallel self._stop_event = stop_event if stop_event is not None else threading.Event() self._context = copy_context() self._mode = (inspect_only, batch_id, batch_operation) - def __call__(self, stop_event: threading.Event) -> DagRunResult | dict: + def __call__(self, stop_event: threading.Event) -> DagRunResult | dict[str, Any]: """Run the request; setting ``stop_event`` stops scheduling, and managed nodes are asked to pause.""" self._stop_event = stop_event return self._context.run(self._execute) - def _execute(self) -> DagRunResult | dict: + def _execute(self) -> DagRunResult | dict[str, Any]: inspect_only, batch_id, batch_operation = self._mode if batch_operation: return self._execute_batch(batch_id, batch_operation) @@ -73,7 +73,7 @@ def _execute(self) -> DagRunResult | dict: stop_event=self._stop_event, batch_id=batch_id) return run_dag(self._definition, max_parallel=self._max_parallel, stop_event=self._stop_event) - def _execute_batch(self, batch_id: str, operation: str | dict) -> DagRunResult | dict: + def _execute_batch(self, batch_id: str, operation: str | dict[str, Any]) -> DagRunResult | dict[str, Any]: action = operation["operation"] if isinstance(operation, dict) else operation payload = operation.get("request", {}) if isinstance(operation, dict) else {} if action in {"run_background", "continue_background"}: @@ -90,7 +90,7 @@ def _execute_batch(self, batch_id: str, operation: str | dict) -> DagRunResult | request.update({key: payload[key] for key in ("decisions", "timeout_seconds") if key in payload}) return manage_agent_dag(action, request) - def _submit_background(self, batch_id: str, action: str, payload: dict) -> dict: + def _submit_background(self, batch_id: str, action: str, payload: dict[str, Any]) -> dict[str, Any]: request = {"batch_id": batch_id, "definition": self._definition, "max_parallel": self._max_parallel} if action == "continue_background": approved = manage_agent_dag("approve_continuation", { @@ -168,7 +168,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> list[tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("dag_load_btn", self._on_load), @@ -243,8 +243,9 @@ def _request_run(self, *, inspect_only: bool, batch_operation: str = "") -> None self._status_label.setText(_t("dag_inspecting" if inspect_only else "dag_running")) self._spawn_worker(definition, inspect_only=inspect_only, batch_operation=batch_operation) - def _spawn_worker(self, definition: dict, *, inspect_only: bool = False, batch_operation: str = "") -> None: - operation: str | dict = batch_operation + def _spawn_worker(self, definition: dict[str, Any], *, inspect_only: bool = False, + batch_operation: str = "") -> None: + operation: str | dict[str, Any] = batch_operation if batch_operation in {"review_continuation", "run_continuation", "continue_background"}: try: payload = json.loads(self._continuation_request.toPlainText()) @@ -281,7 +282,7 @@ def _show_outcome(self, result: Any) -> None: else: self._on_worker_finished(result) - def _parse_editor(self) -> Optional[dict]: + def _parse_editor(self) -> Optional[dict[str, Any]]: raw = self._editor.toPlainText().strip() if not raw: self._status_label.setText(_t("dag_empty")) @@ -292,7 +293,7 @@ def _parse_editor(self) -> Optional[dict]: self._status_label.setText(f"{_t('dag_invalid')}: {error}") return None - def _on_inspection_finished(self, result: dict) -> None: + def _on_inspection_finished(self, result: dict[str, Any]) -> None: if not self._inspection_current(): self._status_label.setText(_t("dag_inspection_stale")) return @@ -303,7 +304,7 @@ def _on_inspection_finished(self, result: dict) -> None: row.get("task_id") or "", "", row.get("error", "")) for row in rows] self._render_rows(values) - def _on_batch_finished(self, result: dict) -> None: + def _on_batch_finished(self, result: dict[str, Any]) -> None: if not self._inspection_current(): self._status_label.setText(_t("dag_inspection_stale")) return @@ -353,7 +354,7 @@ def _populate_table(self, result: DagRunResult) -> None: )) self._render_rows(rows) - def _render_rows(self, rows: list[tuple]) -> None: + def _render_rows(self, rows: list[tuple[Any, ...]]) -> None: self._table.setRowCount(len(rows)) for row, values in enumerate(rows): for col, text in enumerate(values): diff --git a/je_auto_control/utils/agent_runtime/browser_workflows.py b/je_auto_control/utils/agent_runtime/browser_workflows.py index 2b4c20f36..ff432b22a 100644 --- a/je_auto_control/utils/agent_runtime/browser_workflows.py +++ b/je_auto_control/utils/agent_runtime/browser_workflows.py @@ -14,14 +14,14 @@ ) -def browser_options(config: dict) -> dict: +def browser_options(config: dict[str, Any]) -> dict[str, Any]: """Require explicit task origins and refuse a desktop-app fallback in a browser draft.""" if config.get("apps"): raise AgentTaskError("browser workflow cannot grant desktop applications") return {"backend": "browser", "allowed_origins": browser_origins(config.get("allowed_origins", []))} -def browser_workflow(workflow: str, config: dict, policy: TaskPolicy) -> dict: +def browser_workflow(workflow: str, config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: """Build only supported browser workflows without opening a session or starting a task.""" if workflow == "batch_form": return {"actions": _forms(config, policy)} @@ -32,7 +32,7 @@ def browser_workflow(workflow: str, config: dict, policy: TaskPolicy) -> dict: raise AgentTaskError("browser backend currently supports batch_form, transfer and download_archive") -def _downloads(config: dict, policy: TaskPolicy) -> dict: +def _downloads(config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: from je_auto_control.utils.agent_runtime.workflow_specs import _items from je_auto_control.utils.agent_runtime.workflow_files import _destination from je_auto_control.utils.agent_runtime.browser_transfers import _expected @@ -71,26 +71,26 @@ def _text(value: Any, name: str, *, empty: bool = False, maximum: int = 8000) -> return value -def _locator(selector: Any, frame: Any = "") -> dict: +def _locator(selector: Any, frame: Any = "") -> dict[str, Any]: return {"selector": _text(selector, "selector", maximum=4096), "frame": _text(frame, "frame", empty=True, maximum=4096)} -def _action(tool: str, arguments: dict, expected: Any = None) -> dict: +def _action(tool: str, arguments: dict[str, Any], expected: Any = None) -> dict[str, Any]: result = {"tool": tool, "arguments": arguments} if expected is not None: result["expect_result"] = expected return result -def _navigate(url: Any, policy: TaskPolicy) -> dict: +def _navigate(url: Any, policy: TaskPolicy) -> dict[str, Any]: _text(url, "URL", maximum=4096) if _url_origin(url) not in policy.spec.options["allowed_origins"]: raise AgentTaskError("browser workflow navigation is outside its reviewed origins") return _action("AC_browser_navigate", {"url": url}, True) -def _forms(config: dict, policy: TaskPolicy) -> list[dict]: +def _forms(config: dict[str, Any], policy: TaskPolicy) -> list[dict[str, Any]]: from je_auto_control.utils.agent_runtime.workflow_specs import _items, _rows rows, fields = _rows(config, policy), _items(config, "fields") if 1 + len(rows) * (len(fields) * 2 + 4) > 1000: @@ -110,7 +110,8 @@ def _forms(config: dict, policy: TaskPolicy) -> list[dict]: return actions -def _form_field(actions: list[dict], field: dict, row: dict, config: dict) -> None: +def _form_field(actions: list[dict[str, Any]], field: dict[str, Any], row: dict[str, Any], + config: dict[str, Any]) -> None: if set(field) - {"column", "selector", "frame", "transform"} or field.get("column") not in row: raise AgentTaskError("browser field requires a mapped table column and reviewed locator") locator = _locator(field.get("selector"), field.get("frame", "")) @@ -122,7 +123,7 @@ def _form_field(actions: list[dict], field: dict, row: dict, config: dict) -> No actions.append(_action("AC_browser_wait", _wait_arguments(config, locator, "value", value), value)) -def _row_confirmation(config: dict, row: dict) -> str | None: +def _row_confirmation(config: dict[str, Any], row: dict[str, Any]) -> str | None: column = config.get("confirmation_column") if column is None: return None @@ -131,7 +132,7 @@ def _row_confirmation(config: dict, row: dict) -> str | None: return _text(row[column], "row confirmation") -def _commit(actions: list[dict], config: dict, confirmation: Any = None) -> None: +def _commit(actions: list[dict[str, Any]], config: dict[str, Any], confirmation: Any = None) -> None: expected = _text(confirmation if confirmation is not None else config.get("confirmation_value"), "confirmation") locator = _locator(config.get("confirmation_selector"), config.get("confirmation_frame", "")) submit = _locator(config.get("submit_selector"), config.get("submit_frame", "")) @@ -142,14 +143,14 @@ def _commit(actions: list[dict], config: dict, confirmation: Any = None) -> None ]) -def _wait_arguments(config: dict, locator: dict, operation: str, expected: Any) -> dict: +def _wait_arguments(config: dict[str, Any], locator: dict[str, Any], operation: str, expected: Any) -> dict[str, Any]: from je_auto_control.utils.agent_runtime.models import positive timeout = config.get("wait_seconds", 5) positive(timeout, "browser workflow wait", 60) return {**locator, "operation": operation, "expected": expected, "timeout_seconds": timeout} -def _transfer(config: dict, policy: TaskPolicy) -> list[dict]: +def _transfer(config: dict[str, Any], policy: TaskPolicy) -> list[dict[str, Any]]: from je_auto_control.utils.agent_runtime.workflow_specs import _items fields = _items(config, "fields") if len(fields) * 3 + 5 > 1000: @@ -174,7 +175,7 @@ def _transfer(config: dict, policy: TaskPolicy) -> list[dict]: return actions -def _transfer_field(field: dict) -> None: +def _transfer_field(field: dict[str, Any]) -> None: allowed = {"source", "source_frame", "source_operation", "destination", "destination_frame", "transform"} if set(field) - allowed or field.get("source_operation", "value") not in {"text", "value"}: raise AgentTaskError("browser transfer field contains unreviewed settings") diff --git a/je_auto_control/utils/agent_runtime/dag_continuation_evidence.py b/je_auto_control/utils/agent_runtime/dag_continuation_evidence.py index ddaea426c..9693cfa70 100644 --- a/je_auto_control/utils/agent_runtime/dag_continuation_evidence.py +++ b/je_auto_control/utils/agent_runtime/dag_continuation_evidence.py @@ -18,7 +18,7 @@ class ContinuationEvidence: """Use captured matching host endpoints, bounded deadlines and no submit/resume/control operation.""" - def __init__(self, batch: dict, timeout: float = 30, runtime: Any = None) -> None: + def __init__(self, batch: dict[str, Any], timeout: float = 30, runtime: Any = None) -> None: positive(timeout, "DAG continuation timeout_seconds", 300) self.batch = batch self.deadline = time.monotonic() + timeout @@ -26,7 +26,7 @@ def __init__(self, batch: dict, timeout: float = 30, runtime: Any = None) -> Non self.calls: dict[str, Any] = {} self.runtime = runtime - def query(self, node: dict, operation: str, body: dict) -> dict: + def query(self, node: dict[str, Any], operation: str, body: dict[str, Any]) -> dict[str, Any]: """Refresh authority around one pinned lookup/get, hiding transport diagnostics.""" host = node["host"] managed_tasks.authorize_task_host(self.owner, host) @@ -48,7 +48,7 @@ def query(self, node: dict, operation: str, body: dict) -> dict: raise AgentTaskError("DAG continuation destination evidence is malformed") return reply - def _read(self, host: str, operation: str, body: dict, timeout: float) -> dict: + def _read(self, host: str, operation: str, body: dict[str, Any], timeout: float) -> dict[str, Any]: if host == "local" and self.runtime is not None: return self._local(operation, body) return self.connection(host)(operation, body, timeout) @@ -59,7 +59,7 @@ def connection(self, host: str) -> Any: self.calls[host] = managed_tasks.bound_task_connection(host, self.batch['hosts'][host]) return self.calls[host] - def _local(self, operation: str, body: dict) -> dict: + def _local(self, operation: str, body: dict[str, Any]) -> dict[str, Any]: with self.owner.scope(): if operation == "lookup": return self.runtime.lookup(body["idempotency_key"], body.get("spec")) @@ -67,7 +67,7 @@ def _local(self, operation: str, body: dict) -> dict: return self.runtime.get(body["task_id"]).to_dict() raise AgentTaskError("continuation evidence accepts read-only lookup/get only") - def original(self, node: dict) -> dict | None: + def original(self, node: dict[str, Any]) -> dict[str, Any] | None: """Identify the accepted original spec through a submission witness or live legacy matching.""" key = {"idempotency_key": node["task"]["idempotency_key"]} reply = self.query(node, "lookup", key) @@ -88,14 +88,15 @@ def original(self, node: dict) -> dict | None: task = matched["task"] return task - def successor(self, node: dict, original: dict, identifier: str, - handoff_id: str | None = None) -> tuple[dict, list[dict]]: + def successor(self, node: dict[str, Any], original: dict[str, Any], identifier: str, + handoff_id: str | None = None) -> tuple[dict[str, Any], list[dict[str, Any]]]: """Follow only real runtime recovery provenance; every candidate must independently complete.""" if handoff_id is not None: return self._handoff(node, original, identifier, handoff_id) return self._ordinary_successor(node, original, identifier) - def _handoff(self, node: dict, original: dict, identifier: str, handoff_id: str) -> tuple[dict, list[dict]]: + def _handoff(self, node: dict[str, Any], original: dict[str, Any], identifier: str, + handoff_id: str) -> tuple[dict[str, Any], list[dict[str, Any]]]: if node['host'] != 'local': binding = {'source_task': original['task_id'], 'request_key_hash': sha256(node['task']['idempotency_key'].encode('utf-8')).hexdigest(), @@ -115,13 +116,14 @@ def _handoff(self, node: dict, original: dict, identifier: str, handoff_id: str) completion(candidate, node) return candidate, chain - def _ordinary_successor(self, node: dict, original: dict, identifier: str) -> tuple[dict, list[dict]]: + def _ordinary_successor(self, node: dict[str, Any], original: dict[str, Any], + identifier: str) -> tuple[dict[str, Any], list[dict[str, Any]]]: candidate = self.query(node, "get", {"task_id": identifier}) if candidate.get("task_id") != identifier: raise AgentTaskError("DAG continuation successor identity changed") completion(candidate, node) current, seen = candidate, set() - chain: list[dict] = [] + chain: list[dict[str, Any]] = [] for _index in range(16): current_id = current.get("task_id") if not isinstance(current_id, str) or current_id in seen: @@ -130,7 +132,7 @@ def _ordinary_successor(self, node: dict, original: dict, identifier: str) -> tu metadata = current.get("metadata") recovery = metadata.get("recovery") if isinstance(metadata, dict) else None source = recovery.get("source_task") if isinstance(recovery, dict) else None - chain.append(cast(dict, semantic_task(current))) + chain.append(cast(dict[str, Any], semantic_task(current))) if source == original.get("task_id"): return candidate, chain if not isinstance(source, str): @@ -141,7 +143,7 @@ def _ordinary_successor(self, node: dict, original: dict, identifier: str) -> tu raise AgentTaskError("DAG continuation successor has no verified source recovery chain") -def _legacy_match(reply: dict, initial: dict) -> None: +def _legacy_match(reply: dict[str, Any], initial: dict[str, Any]) -> None: version = reply.get("spec_match_contract") # pylint: disable-next=unidiomatic-typecheck # reason: exact legacy protocol integer excludes bool if type(version) is not int or version != 1 or reply.get("spec_match") != "matches": @@ -151,12 +153,12 @@ def _legacy_match(reply: dict, initial: dict) -> None: raise AgentTaskError("DAG continuation original request identity changed") -def completion(task: dict, node: dict) -> None: +def completion(task: dict[str, Any], node: dict[str, Any]) -> None: """Share strict independent clauses and input retirement without interpreting historical screen state.""" managed_tasks.validate_recorded_completion(task, node["task"]["spec"]) -def semantic_task(task: dict | None) -> dict | None: +def semantic_task(task: dict[str, Any] | None) -> dict[str, Any] | None: """Bind stable evidence only, excluding elapsed time, private paths and raw diagnostics.""" if task is None: return None diff --git a/je_auto_control/utils/agent_runtime/input_ledger.py b/je_auto_control/utils/agent_runtime/input_ledger.py index 42079dc60..4786808b1 100644 --- a/je_auto_control/utils/agent_runtime/input_ledger.py +++ b/je_auto_control/utils/agent_runtime/input_ledger.py @@ -10,7 +10,7 @@ _RELEASES = frozenset({"key_release", "key_released", "mouse_release", "mouse_released"}) -def _key(event: dict) -> str: +def _key(event: dict[str, Any]) -> str: value = event.get("keycode") if isinstance(value, bool) or not isinstance(value, (str, int)): raise AgentTaskError("native input requires a concrete key code") @@ -21,8 +21,8 @@ class InputLedger: """Keep only keys/buttons this owner authorized, never another task's state.""" def __init__(self) -> None: - self._keys: dict[str, dict] = {} - self._buttons: dict[str, dict] = {} + self._keys: dict[str, dict[str, Any]] = {} + self._buttons: dict[str, dict[str, Any]] = {} @property def empty(self) -> bool: @@ -33,7 +33,7 @@ def snapshot(self) -> dict[str, Any]: """Copy only the owned input needed for narrowly scoped cleanup.""" return detached({"keys": list(self._keys.values()), "buttons": list(self._buttons.values())}) - def consume(self, event: dict, *, cleanup: bool = False) -> None: + def consume(self, event: dict[str, Any], *, cleanup: bool = False) -> None: """Check an event before acknowledging it to the helper.""" kind = event.get("kind") if cleanup and kind not in _RELEASES: @@ -46,7 +46,7 @@ def consume(self, event: dict, *, cleanup: bool = False) -> None: raise AgentTaskError("unrecognized native input event") handlers[kind](event) - def _key_press(self, event: dict) -> None: + def _key_press(self, event: dict[str, Any]) -> None: key = _key(event) if key in self._keys: raise AgentTaskError("key is already held by this task") @@ -57,17 +57,17 @@ def _key_press(self, event: dict) -> None: if event.get("unicode"): self._keys[key]["unicode"] = True - def _key_release(self, event: dict) -> None: + def _key_release(self, event: dict[str, Any]) -> None: if _key(event) not in self._keys: raise AgentTaskError("cannot release a key this task does not own") if self._keys[_key(event)]["is_shift"] != event.get("is_shift", False): raise AgentTaskError("cannot change a held key's modifier ownership") - def _key_released(self, event: dict) -> None: + def _key_released(self, event: dict[str, Any]) -> None: self._key_release(event) self._keys.pop(_key(event)) - def _mouse_press(self, event: dict) -> None: + def _mouse_press(self, event: dict[str, Any]) -> None: key = _key(event) if key in self._buttons: raise AgentTaskError("button is already held by this task") @@ -75,14 +75,14 @@ def _mouse_press(self, event: dict) -> None: raise AgentTaskError("native pointer requires integer coordinates") self._buttons[key] = {name: event[name] for name in ("keycode", "x", "y")} - def _mouse_release(self, event: dict) -> None: + def _mouse_release(self, event: dict[str, Any]) -> None: if _key(event) not in self._buttons: raise AgentTaskError("cannot release a button this task does not own") - def _mouse_released(self, event: dict) -> None: + def _mouse_released(self, event: dict[str, Any]) -> None: self._mouse_release(event) self._buttons.pop(_key(event)) @staticmethod - def _nonholding(_event: dict) -> None: + def _nonholding(_event: dict[str, Any]) -> None: return None diff --git a/je_auto_control/utils/agent_runtime/native_worker.py b/je_auto_control/utils/agent_runtime/native_worker.py index f589a5071..9e62359d3 100644 --- a/je_auto_control/utils/agent_runtime/native_worker.py +++ b/je_auto_control/utils/agent_runtime/native_worker.py @@ -42,7 +42,7 @@ def __init__(self, source: Any, sink: Any, *, target: Any = None) -> None: self._activity: Any = None self._control_event = threading.Event() self._sink_lock = threading.Lock() - self._presence_binding: dict | None = None + self._presence_binding: dict[str, Any] | None = None self._presence_endpoint: Any = None self._notice_stop = threading.Event() self._notice_thread: threading.Thread | None = None @@ -51,7 +51,7 @@ def __init__(self, source: Any, sink: Any, *, target: Any = None) -> None: def _browser_readonly(self) -> bool: return isinstance(self._target, BrowserTarget) and self._target.input_retired - def _reply(self, payload: dict) -> None: + def _reply(self, payload: dict[str, Any]) -> None: packet = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8") + b"\n" if len(packet) > _LIMIT: raise AgentTaskError("native response is too large") @@ -65,7 +65,7 @@ def _physical_takeover(self) -> None: self._reply({"control": "physical_input"}) return - def _validate_input(self, event: dict) -> None: + def _validate_input(self, event: dict[str, Any]) -> None: """Recheck live permission; cleanup may acknowledge owned release boundaries only.""" if self._cleanup: if event.get("kind") not in {"key_release", "key_released", "mouse_release", "mouse_released"}: @@ -74,7 +74,7 @@ def _validate_input(self, event: dict) -> None: self._check_activity() self._target.validate_input(event) - def _input(self, event: dict) -> None: + def _input(self, event: dict[str, Any]) -> None: if self._browser_readonly: raise AgentTaskError("read-only browser cannot acknowledge native input") self._validate_input(event) @@ -116,7 +116,7 @@ def _serve(self) -> None: self._reply(durable_payload({"id": self._request_id, "error": f"{type(error).__name__}: {error}", "error_type": type(error).__name__})) - def _dispatch(self, operation: str, payload: dict) -> Any: + def _dispatch(self, operation: str, payload: dict[str, Any]) -> Any: if self._browser_readonly: with input_observer(self._input): return self._dispatch_browser_readonly(operation, payload) @@ -132,7 +132,7 @@ def _dispatch(self, operation: str, payload: dict) -> Any: self._configure_scope(payload) return self._scoped_operation(operation, payload) - def _bootstrap(self) -> dict: + def _bootstrap(self) -> dict[str, Any]: """Advertise optional retirement only on the built-in original configured browser worker.""" result = {"protocol": 1} # pylint: disable-next=unidiomatic-typecheck # reason: read-only/custom worker subclasses cannot claim this API @@ -140,7 +140,7 @@ def _bootstrap(self) -> dict: result["browser_readonly"] = 1 return result - def _scoped_operation(self, operation: str, payload: dict) -> Any: + def _scoped_operation(self, operation: str, payload: dict[str, Any]) -> Any: if self._spec is None: raise AgentTaskError("native worker must be configured by its owner") definition = self._target.readonly_spec if self._browser_readonly else self._spec @@ -155,7 +155,7 @@ def _scoped_operation(self, operation: str, payload: dict) -> Any: stack.enter_context(operation_scope(TaskOperation(definition, self._check_activity, self._owner))) return self._operation(operation, payload) - def _retire_browser(self, payload: dict) -> dict: + def _retire_browser(self, payload: dict[str, Any]) -> dict[str, Any]: if payload != {} or self._profile_kind != "browser" or self._spec is None: raise AgentTaskError("browser retirement requires the configured original scope") with command_guard(refuse_browser_tool), input_observer(self._input): @@ -163,7 +163,7 @@ def _retire_browser(self, payload: dict) -> dict: return {"supported": False} return self._target.freeze_readonly() - def _dispatch_browser_readonly(self, operation: str, payload: dict) -> Any: + def _dispatch_browser_readonly(self, operation: str, payload: dict[str, Any]) -> Any: if operation == "cleanup": return self._cleanup_browser_readonly(payload) _readonly_browser_payload(operation, payload) @@ -175,21 +175,21 @@ def _dispatch_browser_readonly(self, operation: str, payload: dict) -> Any: return self._target.bind_readonly(payload["spec"], validate=TaskPolicy) return self._scoped_operation(operation, payload) - def _cleanup_browser_readonly(self, payload: dict) -> dict: + def _cleanup_browser_readonly(self, payload: dict[str, Any]) -> dict[str, Any]: if payload != {"keys": [], "buttons": []}: raise AgentTaskError("read-only browser cleanup cannot inject input") with command_guard(refuse_browser_tool), input_observer(self._input): self._target.cleanup() return {"cleaned": True} - def _probe_browser(self, payload: dict) -> dict: + def _probe_browser(self, payload: dict[str, Any]) -> dict[str, Any]: if self._spec is not None or not isinstance(payload, dict) or set(payload) != {"transfer"}: raise AgentTaskError("dependency probing requires an unconfigured owned helper") # pylint: disable-next=import-outside-toplevel # reason: only an explicit unconfigured probe loads this seam from je_auto_control.utils.agent_runtime.browser_environment import inspect_browser_dependencies return inspect_browser_dependencies(payload["transfer"]) - def _configure_scope(self, payload: dict) -> None: + def _configure_scope(self, payload: dict[str, Any]) -> None: spec = AgentTaskSpec.from_dict(payload["spec"]) owner = AuthorizationContext(**payload["owner"]) if payload.get("owner") else None self._check_presence_pin(spec, owner, payload) @@ -203,7 +203,8 @@ def _configure_scope(self, payload: dict) -> None: self._target = BrowserTarget() self._configure_presence(payload) - def _check_presence_pin(self, spec: AgentTaskSpec, owner: AuthorizationContext | None, payload: dict) -> None: + def _check_presence_pin(self, spec: AgentTaskSpec, owner: AuthorizationContext | None, + payload: dict[str, Any]) -> None: if self._presence_binding is not None and (spec != self._spec or owner != self._owner or payload.get('presence') != self._presence_binding or payload.get('presence_endpoint') != ( @@ -211,7 +212,7 @@ def _check_presence_pin(self, spec: AgentTaskSpec, owner: AuthorizationContext | if self._presence_endpoint is not None else None)): raise AgentTaskError('configured desktop presence cannot change capability or owner scope') - def _configure_presence(self, payload: dict) -> None: + def _configure_presence(self, payload: dict[str, Any]) -> None: if self._requires_presence(): binding = payload.get('presence') if not isinstance(binding, dict): @@ -225,7 +226,7 @@ def _requires_presence(self) -> bool: return (not self._custom_target and self._spec is not None and self._spec.target != 'local-files' and self._profile_kind not in {'files', 'browser'}) - def _configure_profile(self, payload: dict) -> None: + def _configure_profile(self, payload: dict[str, Any]) -> None: if "profile" not in payload: return from je_auto_control.utils.agent_runtime.target_config import AgentTargetProfile, check_host_platform @@ -249,7 +250,7 @@ def _guard(self, policy: TaskPolicy, name: str, arguments: Any) -> None: self._check_activity() policy.check(name, arguments) - def _operation(self, operation: str, payload: dict) -> Any: + def _operation(self, operation: str, payload: dict[str, Any]) -> Any: if operation == "configure": if self._spec is None: raise AgentTaskError("native worker has no configured scope") @@ -297,14 +298,14 @@ def close(self) -> None: raise AgentTaskError('physical presence notice has not retired; owned helper must retire') @staticmethod - def _release_key(key: dict) -> None: + def _release_key(key: dict[str, Any]) -> None: from je_auto_control.wrapper.auto_control_keyboard import release_keyboard_key, _release_unicode_unit if key.get('unicode'): _release_unicode_unit(key['keycode']) else: release_keyboard_key(key['keycode'], key['is_shift'], skip_record=True) - def _release_owned(self, payload: dict) -> dict: + def _release_owned(self, payload: dict[str, Any]) -> dict[str, Any]: from je_auto_control.wrapper.auto_control_mouse import release_mouse if set(payload) != {"keys", "buttons"}: raise AgentTaskError("cleanup payload is invalid") diff --git a/je_auto_control/utils/agent_runtime/presence_pool.py b/je_auto_control/utils/agent_runtime/presence_pool.py index 9a0f4a130..0e9989e03 100644 --- a/je_auto_control/utils/agent_runtime/presence_pool.py +++ b/je_auto_control/utils/agent_runtime/presence_pool.py @@ -36,7 +36,7 @@ class _Ticket: @dataclass class _Grant: ticket: _Ticket - binding: dict + binding: dict[str, Any] released: threading.Event = field(default_factory=threading.Event) @@ -76,19 +76,19 @@ def retired(self) -> bool: """Report actual shared process/thread retirement, never a native-input cleanup proof.""" return self._pool.retired - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Inspect this reference's shared source without creating resources or granting input.""" return self._pool.status() - def acquire(self, check: Callable[[], None], timeout: float) -> dict: + def acquire(self, check: Callable[[], None], timeout: float) -> dict[str, Any]: """Wait within this caller's budget; cancellation abandons only this caller's grant.""" return self._pool.acquire_reference(self._owner, check, timeout) - def endpoint(self, binding: dict) -> dict | None: + def endpoint(self, binding: dict[str, Any]) -> dict[str, Any] | None: """Snapshot launch metadata for this reference's exact live grant, without discovery.""" return self._pool.endpoint_reference(self._owner, binding) - def release(self, binding: dict) -> None: + def release(self, binding: dict[str, Any]) -> None: """Schedule negative-only retirement of a token issued to this exact reference.""" self._pool.release_reference(self._owner, binding) @@ -114,7 +114,7 @@ def retired(self) -> bool: thread = self._owner.thread return self._owner.retired.is_set() and (thread is None or not thread.is_alive()) - def status(self) -> dict: + def status(self) -> dict[str, Any]: """Return passive connection availability, never an input permission or native evidence claim.""" with self._mutex: if self._owner.stop.is_set() or self._owner.failure is not None: @@ -142,7 +142,7 @@ def _live(self, ticket: _Ticket) -> bool: return (not ticket.owner.closed.is_set() and not ticket.abandoned.is_set() and time.monotonic() < ticket.deadline) - def acquire_reference(self, owner: _Reference, check: Callable[[], None], timeout: float) -> dict: + def acquire_reference(self, owner: _Reference, check: Callable[[], None], timeout: float) -> dict[str, Any]: """Queue a bounded ticket; caller checkpoints are never passed into the shared owned RPC.""" ticket = _Ticket(owner, _deadline(timeout)) check() @@ -181,7 +181,7 @@ def _start_thread(self, target: Callable[[], None], name: str) -> None: self._owner.retired.set() raise AgentTaskError('shared presence thread could not start') from error - def _wait(self, ticket: _Ticket, check: Callable[[], None]) -> dict: + def _wait(self, ticket: _Ticket, check: Callable[[], None]) -> dict[str, Any]: while True: check() self._check_owner() @@ -204,7 +204,7 @@ def _wait(self, ticket: _Ticket, check: Callable[[], None]) -> dict: ticket.accepted.set() return dict(value.binding) - def endpoint_reference(self, owner: _Reference, binding: dict) -> dict | None: + def endpoint_reference(self, owner: _Reference, binding: dict[str, Any]) -> dict[str, Any] | None: """Check ownership and copy the pinned endpoint atomically with reference/grant retirement.""" binding = presence_body('check', binding) with self._mutex: @@ -217,7 +217,7 @@ def endpoint_reference(self, owner: _Reference, binding: dict) -> dict | None: endpoint = self._owner.endpoint return endpoint_to_wire(endpoint) if endpoint is not None else None - def release_reference(self, owner: _Reference, binding: dict) -> None: + def release_reference(self, owner: _Reference, binding: dict[str, Any]) -> None: """Mark only a recorded owned grant; the I/O owner performs its negative release.""" binding = presence_body('release', binding) with self._mutex: @@ -275,7 +275,7 @@ def _ensure(self) -> None: self._owner.generation = identifier(value['generation']) self._owner.endpoint = endpoint - def _rpc(self, operation: str, body: dict) -> dict: + def _rpc(self, operation: str, body: dict[str, Any]) -> dict[str, Any]: self._check_owner() generation = self._owner.generation if generation is None: @@ -396,7 +396,7 @@ def shared_reference() -> PresenceReference: return _SHARED.pool.reference() -def shared_status() -> dict: +def shared_status() -> dict[str, Any]: """Inspect the default host pool without creating a reference, broker or native observer.""" with _SHARED.mutex: if _SHARED.pool is None: diff --git a/je_auto_control/utils/agent_runtime/routes.py b/je_auto_control/utils/agent_runtime/routes.py index 09c9712cb..6d4f5a0b2 100644 --- a/je_auto_control/utils/agent_runtime/routes.py +++ b/je_auto_control/utils/agent_runtime/routes.py @@ -57,20 +57,20 @@ def dispatch(runtime: Any, operation: str, body: Any = None, task_id: str | None return _task_operation(runtime, operation, body) -def _transfer(runtime: Any, body: dict, *, peer: bool = False) -> dict: +def _transfer(runtime: Any, body: dict[str, Any], *, peer: bool = False) -> dict[str, Any]: if set(body) != {'operation', 'request'}: raise AgentTaskError('transfer requires operation and request') handler = runtime.transfers.peer if peer else runtime.transfers.control return handler(body['operation'], body['request']) -def _dag(runtime: Any, body: dict) -> dict: +def _dag(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if "operation" not in body or set(body) - {"operation", "request"}: raise AgentTaskError("dag accepts operation and an optional request object") return runtime.batches.control(body["operation"], body.get("request")) -def _lookup(runtime: Any, body: dict) -> dict: +def _lookup(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if "idempotency_key" not in body or set(body) - {"idempotency_key", "spec"}: raise AgentTaskError("lookup requires idempotency_key and accepts an optional spec") if "spec" in body and not isinstance(body["spec"], dict): @@ -78,7 +78,7 @@ def _lookup(runtime: Any, body: dict) -> dict: return runtime.lookup(body["idempotency_key"], body.get("spec")) -def _submit(runtime: Any, body: dict) -> dict: +def _submit(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if "spec" not in body or set(body) - {"spec", "idempotency_key"}: raise AgentTaskError("submit requires spec and accepts an optional idempotency_key") task = runtime.submit(body["spec"], idempotency_key=body.get("idempotency_key")) @@ -87,51 +87,51 @@ def _submit(runtime: Any, body: dict) -> dict: return {"task_id": task.task_id, "state": task.state} -def _recover_target(runtime: Any, body: dict) -> dict: +def _recover_target(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if set(body) != {"target", "note"} or not isinstance(body["target"], str): raise AgentTaskError("recover_target requires target and operator note") from je_auto_control.utils.agent_runtime.native_recovery import recover_target return recover_target(runtime, body["target"], body["note"]) -def _stop_all(runtime: Any, body: dict) -> dict: +def _stop_all(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if body: raise AgentTaskError("stop_all requires an empty body") return runtime.stop_all() -def _draft(body: dict) -> dict: +def _draft(body: dict[str, Any]) -> dict[str, Any]: if set(body) != {"workflow", "config"}: raise AgentTaskError("draft requires workflow and config") from je_auto_control.utils.agent_runtime.workflow_specs import draft_agent_workflow return {"draft": draft_agent_workflow(body["workflow"], body["config"])} -def _prune(runtime: Any, body: dict) -> dict: +def _prune(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if set(body) - {"keep_days"}: raise AgentTaskError("prune accepts only keep_days") return runtime.prune(body.get("keep_days", 30)) -def _trigger(runtime: Any, body: dict) -> dict: +def _trigger(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if "operation" not in body or set(body) - {"operation", "request"}: raise AgentTaskError("trigger accepts operation and an optional request object") return runtime.triggers.control(body["operation"], body.get("request")) -def _skill(runtime: Any, body: dict) -> dict: +def _skill(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if "operation" not in body or set(body) - {"operation", "request"}: raise AgentTaskError("skill accepts operation and an optional request object") return runtime.skills.control(body["operation"], body.get("request")) -def _target(runtime: Any, body: dict) -> dict: +def _target(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if "operation" not in body or set(body) - {"operation", "request"}: raise AgentTaskError("target accepts operation and an optional request object") return runtime.target_profiles.control(body["operation"], body.get("request")) -def _recovery(runtime: Any, body: dict) -> dict: +def _recovery(runtime: Any, body: dict[str, Any]) -> dict[str, Any]: if set(body) != {"operation", "request"}: raise AgentTaskError("recovery requires operation and request") result = runtime.recovery.control(body["operation"], body["request"]) @@ -158,7 +158,7 @@ def _task_operation(runtime: Any, operation: str, body: dict[str, Any]) -> dict[ return result -def _check_task_fields(operation: str, body: dict) -> None: +def _check_task_fields(operation: str, body: dict[str, Any]) -> None: required = {"task_id"} | {"act": {"action"}, "reconcile": {"review"}}.get(operation, set()) optional = {"offset", "limit"} if operation == "receipts" else set() if not required <= set(body) or set(body) - required - optional or not isinstance(body.get("task_id"), str): diff --git a/je_auto_control/utils/agent_runtime/skill_completion.py b/je_auto_control/utils/agent_runtime/skill_completion.py index bb4bac7dc..3314f658e 100644 --- a/je_auto_control/utils/agent_runtime/skill_completion.py +++ b/je_auto_control/utils/agent_runtime/skill_completion.py @@ -2,7 +2,7 @@ from __future__ import annotations import json -from typing import Any, Callable +from typing import TYPE_CHECKING, Any, Callable from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.handoff_records import HandoffAccess @@ -11,11 +11,18 @@ ) -def _decode_binding(value: str) -> dict: +if TYPE_CHECKING: + from je_auto_control.utils.agent_runtime.models import AgentTaskSpec + +_Authority = Callable[..., dict[str, Any] | None] +_Template = Callable[[Any, dict[str, Any]], 'AgentTaskSpec'] + + +def _decode_binding(value: str) -> dict[str, Any]: return decode_completion_binding(value) -def publication_details(connection: Any, publication: Any) -> dict | None: +def publication_details(connection: Any, publication: Any) -> dict[str, Any] | None: """Expose historical adoption IDs and hashes, never private principal stores or live-evidence claims.""" if publication is None: return None @@ -31,7 +38,7 @@ def publication_details(connection: Any, publication: Any) -> dict | None: return result -def _binding(connection: Any, task_id: str, trial_id: str) -> dict: +def _binding(connection: Any, task_id: str, trial_id: str) -> dict[str, Any]: row = connection.execute('SELECT c.details,r.source_task,r.snapshot FROM agent_readonly_completions c ' 'JOIN agent_task_recoveries r ON r.task_id=c.task_id WHERE c.task_id=?', (task_id,)).fetchone() if row is None: @@ -43,7 +50,7 @@ def _binding(connection: Any, task_id: str, trial_id: str) -> dict: return details -def _lineage(connection: Any, task_id: str, trial_id: str) -> dict: +def _lineage(connection: Any, task_id: str, trial_id: str) -> dict[str, Any]: details = _binding(connection, task_id, trial_id) current, seen = details['source_task'], {task_id} for _index in range(16): @@ -56,8 +63,8 @@ def _lineage(connection: Any, task_id: str, trial_id: str) -> dict: raise AgentTaskError('skill completion has no bounded verified recovery chain') -def _verification_scope(runtime: Any, connection: Any, trial: dict, task_id: str, - authority_check: Callable, verification_spec: Callable) -> tuple[dict, str | None]: +def _verification_scope(runtime: Any, connection: Any, trial: dict[str, Any], task_id: str, + authority_check: _Authority, verification_spec: _Template) -> tuple[dict[str, Any], str | None]: renewed = connection.execute('SELECT 1 FROM agent_task_authorizations WHERE task_id=?', (task_id,)).fetchone() scope = (authority_check(runtime, task_id, connection=connection) if renewed is not None else authority_check(runtime, task_id)) @@ -66,13 +73,14 @@ def _verification_scope(runtime: Any, connection: Any, trial: dict, task_id: str return verification_spec(runtime, trial).to_dict(), None -def _completion_identifier(task_id: Any, trial: dict) -> None: +def _completion_identifier(task_id: Any, trial: dict[str, Any]) -> None: if not isinstance(task_id, str) or not 1 <= len(task_id) <= 256 or task_id == trial['id']: raise AgentTaskError('completion_task_id must identify a separate reviewed completion task') -def _selected_completion(runtime: Any, connection: Any, trial: dict, selected: Any, - authority_check: Callable, verification_spec: Callable) -> tuple[dict, Any, Any, dict]: +def _selected_completion(runtime: Any, connection: Any, trial: dict[str, Any], selected: Any, + authority_check: _Authority, verification_spec: _Template + ) -> tuple[dict[str, Any], Any, Any, dict[str, Any]]: access = selected if isinstance(selected, HandoffAccess) else None task_id = access.projection['task_id'] if access is not None else selected _completion_identifier(task_id, trial) @@ -92,8 +100,9 @@ def _selected_completion(runtime: Any, connection: Any, trial: dict, selected: A return row, access, authorization_review, details -def check_skill_completion(runtime: Any, connection: Any, trial: dict, task_id: Any, - authority_check: Callable, verification_spec: Callable, snapshot_digest: Callable) -> dict: +def check_skill_completion(runtime: Any, connection: Any, trial: dict[str, Any], task_id: Any, + authority_check: _Authority, verification_spec: _Template, + snapshot_digest: Callable[[Any], str]) -> dict[str, Any]: """Revalidate a separately succeeded reader under the skill library's SQLite write transaction.""" row, access, authorization_review, details = _selected_completion(runtime, connection, trial, task_id, authority_check, verification_spec) diff --git a/je_auto_control/utils/agent_runtime/skill_execution.py b/je_auto_control/utils/agent_runtime/skill_execution.py index d835ea957..970ee78b2 100644 --- a/je_auto_control/utils/agent_runtime/skill_execution.py +++ b/je_auto_control/utils/agent_runtime/skill_execution.py @@ -9,16 +9,19 @@ from je_auto_control.utils.agent_runtime.errors import AgentTaskError from je_auto_control.utils.agent_runtime.handoff_records import HandoffAccess +_Link = tuple[dict[str, Any], dict[str, Any], dict[str, Any]] +_Review = Callable[[Any, dict[str, Any], dict[str, Any], dict[str, Any]], dict[str, Any]] -def _execution_row(runtime: Any, identifier: str, access: HandoffAccess | None) -> dict: + +def _execution_row(runtime: Any, identifier: str, access: HandoffAccess | None) -> dict[str, Any]: if access is not None: return access.read(identifier) # pylint: disable-next=protected-access # reason: ungranted evidence retains ordinary caller ownership checks return runtime._row(identifier) -def _chain(runtime: Any, connection: Any, root: dict, identifier: Any, - access: HandoffAccess | None = None) -> list[tuple[dict, dict, dict]]: +def _chain(runtime: Any, connection: Any, root: dict[str, Any], identifier: Any, + access: HandoffAccess | None = None) -> list[_Link]: if not isinstance(identifier, str) or not 1 <= len(identifier) <= 256 or identifier == root['id']: raise AgentTaskError('execution_task_id must identify a separate reviewed executable successor') result, seen = [], {root['id']} @@ -47,7 +50,7 @@ def _same(first: Any, second: Any) -> bool: == json.dumps(second, sort_keys=True, separators=(',', ':'), allow_nan=False)) -def _scope(parent: dict, child: dict, *, renewed: bool = False) -> None: +def _scope(parent: dict[str, Any], child: dict[str, Any], *, renewed: bool = False) -> None: fixed = set(parent) - {'goal', 'actions', 'roots', 'options'} if set(parent) != set(child) or not _same({key: parent[key] for key in fixed}, {key: child[key] for key in fixed}): @@ -58,7 +61,7 @@ def _scope(parent: dict, child: dict, *, renewed: bool = False) -> None: _scope_options(parent['options'], child['options'], renewed=renewed) -def _scope_options(parent: dict, child: dict, *, renewed: bool) -> None: +def _scope_options(parent: dict[str, Any], child: dict[str, Any], *, renewed: bool) -> None: before, after = dict(parent), dict(child) before.pop('skill_pin', None) origins = set(before.pop('origin_policies', [])) @@ -67,11 +70,12 @@ def _scope_options(parent: dict, child: dict, *, renewed: bool) -> None: raise AgentTaskError('execution recovery removed original restrictions or changed fixed options') -def _execution_segments(connection: Any, links: list, root: dict, review: Callable, - verify_plan: Callable) -> tuple[list[dict], list[dict]]: - combined: list[dict] = [] - segments: list[dict] = [] - actions: list[dict] = [] +def _execution_segments(connection: Any, links: list[_Link], root: dict[str, Any], review: _Review, + verify_plan: Callable[..., list[dict[str, Any]]] + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + combined: list[dict[str, Any]] = [] + segments: list[dict[str, Any]] = [] + actions: list[dict[str, Any]] = [] for parent, child, link in links: evidence = review(connection, parent, child, link) _scope(parent['spec'], child['spec'], renewed=isinstance(review, HandoffAccess) and review.renewed) @@ -88,8 +92,9 @@ def _execution_segments(connection: Any, links: list, root: dict, review: Callab return segments, actions -def check_skill_execution(runtime: Any, connection: Any, root: dict, request: dict, - review: Callable, verify_plan: Callable, completion: Callable) -> dict: +def check_skill_execution(runtime: Any, connection: Any, root: dict[str, Any], request: dict[str, Any], + review: _Review, verify_plan: Callable[..., list[dict[str, Any]]], + completion: Callable[[Any, dict[str, Any], Any], dict[str, Any]]) -> dict[str, Any]: """Combine only exact confirmed semantic effects and independently completed final verification.""" access = review if isinstance(review, HandoffAccess) else None links = _chain(runtime, connection, root, request['execution_task_id'], access) diff --git a/je_auto_control/utils/agent_runtime/task_triggers.py b/je_auto_control/utils/agent_runtime/task_triggers.py index 4bc04d002..426a933ac 100644 --- a/je_auto_control/utils/agent_runtime/task_triggers.py +++ b/je_auto_control/utils/agent_runtime/task_triggers.py @@ -68,7 +68,8 @@ def register(self, request: Mapping[str, Any]) -> dict[str, Any]: self._insert(identifier, value, spec, config, metadata, now) return {"trigger_id": identifier, "enabled": True, "kind": value["kind"]} - def _insert(self, identifier: str, value: dict, spec: AgentTaskSpec, config: dict, owner: dict, now: float) -> None: + def _insert(self, identifier: str, value: dict[str, Any], spec: AgentTaskSpec, config: dict[str, Any], + owner: dict[str, Any], now: float) -> None: with self.runtime.store.connection(write=True) as connection: insert_registration(connection, identifier, value, spec, config, owner, now) @@ -104,7 +105,7 @@ def control(self, operation: str, request: Mapping[str, Any] | None = None) -> d return self.list() return self._control_existing(operation, value) - def _control_existing(self, operation: str, value: dict) -> dict: + def _control_existing(self, operation: str, value: dict[str, Any]) -> dict[str, Any]: _existing_fields(operation, value) row = self._row(value["trigger_id"]) if operation == "fire": @@ -121,7 +122,7 @@ def _control_existing(self, operation: str, value: dict) -> dict: return self._remove(row) raise AgentTaskError("unknown trigger operation") - def _enabled(self, row: dict, enabled: bool) -> dict: + def _enabled(self, row: dict[str, Any], enabled: bool) -> dict[str, Any]: owner = AuthorizationContext(**row["owner"]) if row["owner"] else None if enabled: with self.runtime.store.connection() as connection: @@ -130,7 +131,7 @@ def _enabled(self, row: dict, enabled: bool) -> dict: return self._set_enabled(row, True) return self._set_enabled(row, False) - def _set_enabled(self, row: dict, enabled: bool) -> dict: + def _set_enabled(self, row: dict[str, Any], enabled: bool) -> dict[str, Any]: if enabled: spec = self.runtime._validated_spec(row["spec"]) validate_config(row["kind"], row["config"], TaskPolicy(spec)) @@ -141,7 +142,7 @@ def _set_enabled(self, row: dict, enabled: bool) -> dict: (int(enabled), next_due(row["kind"], row["config"], time.time()), row["id"])) return {"trigger_id": row["id"], "enabled": enabled} - def _remove(self, row: dict) -> dict: + def _remove(self, row: dict[str, Any]) -> dict[str, Any]: with self.runtime.store.connection(write=True) as connection: connection.execute("DELETE FROM agent_trigger_events WHERE trigger_id=?", (row["id"],)) connection.execute("DELETE FROM agent_triggers WHERE id=?", (row["id"],)) @@ -149,7 +150,7 @@ def _remove(self, row: dict) -> dict: self._stable.pop(row["id"], None) return {"trigger_id": row["id"], "removed": True} - def fire(self, row: dict, event_key: str, payload: Any = None) -> dict[str, Any]: + def fire(self, row: dict[str, Any], event_key: str, payload: Any = None) -> dict[str, Any]: """Deduplicate an event and queue a fresh task within its preauthorized template only.""" if not row["enabled"] or not isinstance(event_key, str) or not event_key or len(event_key) > 256: raise AgentTaskError("trigger is disabled or event_key is invalid") @@ -161,7 +162,7 @@ def fire(self, row: dict, event_key: str, payload: Any = None) -> dict[str, Any] with DeferredAuthorization(owner).scope(), self.runtime._lock(_TRIGGER_PREFIX + row["id"]): return self._fire_owned(row, digest, payload) - def _fire_owned(self, row: dict, digest: str, payload: Any) -> dict: + def _fire_owned(self, row: dict[str, Any], digest: str, payload: Any) -> dict[str, Any]: with self.runtime.store.connection() as connection: live = connection.execute("SELECT enabled FROM agent_triggers WHERE id=?", (row["id"],)).fetchone() if live is None or not live["enabled"]: @@ -180,7 +181,7 @@ def _fire_owned(self, row: dict, digest: str, payload: Any) -> dict: return {"deferred": True, "reason": "trigger pending-task limit reached"} return self._queue(row, digest, payload) - def _queue(self, row: dict, digest: str, payload: Any) -> dict: + def _queue(self, row: dict[str, Any], digest: str, payload: Any) -> dict[str, Any]: spec = detached(row["spec"]) spec["inputs"] = {**spec.get("inputs", {}), "event": {"key": digest, "payload": payload}} spec["options"] = {**spec.get("options", {}), "trigger": {"id": row["id"], "event": digest}} @@ -191,7 +192,7 @@ def _queue(self, row: dict, digest: str, payload: Any) -> dict: self.runtime.background.start(task.task_id) return self._event_result(task.task_id, duplicate=False) - def _event_result(self, task_id: str, *, duplicate: bool) -> dict: + def _event_result(self, task_id: str, *, duplicate: bool) -> dict[str, Any]: with self.runtime.store.connection() as connection: row = connection.execute("SELECT state FROM agent_tasks WHERE id=?", (task_id,)).fetchone() return {"task_id": task_id, "duplicate": duplicate, "state": row[0] if row else "expired"} @@ -212,7 +213,7 @@ def poll(self) -> None: except (AutoControlException, OSError, ValueError, TypeError) as error: self._fault(row["id"], f"trigger needs review: {type(error).__name__}") - def _poll_one(self, row: dict) -> None: + def _poll_one(self, row: dict[str, Any]) -> None: if row["kind"] == "event": return if row["kind"] == "file": @@ -227,7 +228,7 @@ def _poll_one(self, row: dict) -> None: connection.execute("UPDATE agent_triggers SET next_run=? WHERE id=?", (next_due(row["kind"], row["config"], now), row["id"])) - def _poll_file(self, row: dict) -> None: + def _poll_file(self, row: dict[str, Any]) -> None: spec = AgentTaskSpec.from_dict(row["spec"]) path = Path(TaskPolicy(spec).path(row["config"]["path"])) if not path.is_file(): @@ -264,7 +265,7 @@ def _register_fields(value: Any) -> None: raise AgentTaskError("trigger name must be nonempty text of at most two hundred characters") -def _existing_fields(operation: str, value: dict) -> None: +def _existing_fields(operation: str, value: dict[str, Any]) -> None: required = {"trigger_id", "event_key"} if operation == "fire" else {"trigger_id"} optional = {"payload"} if operation == "fire" else set() if not required <= set(value) or set(value) - required - optional: diff --git a/je_auto_control/utils/agent_runtime/transfer_evidence.py b/je_auto_control/utils/agent_runtime/transfer_evidence.py index 1e7383fa6..96f3b4066 100644 --- a/je_auto_control/utils/agent_runtime/transfer_evidence.py +++ b/je_auto_control/utils/agent_runtime/transfer_evidence.py @@ -18,7 +18,7 @@ from je_auto_control.utils.exception.cancellation import cancellation_checkpoint -def _summary(context: dict, identifier: str, source: str, task: str) -> dict: +def _summary(context: dict[str, Any], identifier: str, source: str, task: str) -> dict[str, Any]: proof = context['proof'] result = {'contract': 1, 'grant_id': identifier, 'source_task': source, 'task_id': task, 'source_snapshot': context['source_snapshot'], 'completion_snapshot': context['completion_snapshot'], @@ -30,12 +30,12 @@ def _summary(context: dict, identifier: str, source: str, task: str) -> dict: return portable_evidence(result, resolved=False) -def _public(record: dict) -> dict: +def _public(record: dict[str, Any]) -> dict[str, Any]: state = 'expired' if record['state'] == 'active' and record['expires'] <= time.time() else record['state'] return {'grant_id': record['id'], 'state': state, 'summary': deepcopy(record['scope']['summary'])} -def _bound_summary(context: dict, record: dict, expected: dict) -> dict: +def _bound_summary(context: dict[str, Any], record: dict[str, Any], expected: dict[str, Any]) -> dict[str, Any]: if (expected['source_task'] != record['scope']['source_task'] or expected['submitted_spec_digest'] != context['submitted_spec_digest'] or expected['request_key_hash'] not in {item['key_hash'] for item in context['requests']}): @@ -56,7 +56,7 @@ class RemoteEvidenceSource: def __init__(self, runtime: Any, records: Any, host: Any, checkpoint: Any) -> None: self.runtime, self.records, self.host, self.checkpoint = runtime, records, host, checkpoint - self.reviews: dict[str, dict] = {} + self.reviews: dict[str, dict[str, Any]] = {} self.initialized = False def _initialize(self) -> None: @@ -65,7 +65,7 @@ def _initialize(self) -> None: self.records.initialize(connection) self.initialized = True - def control(self, operation: str, request: Mapping) -> dict: + def control(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Review and manage finite source-owned grants without adding foreign task-read authority.""" self.host.check_open() self.checkpoint() @@ -95,12 +95,12 @@ def control(self, operation: str, request: Mapping) -> dict: row = self.records.find(connection, row['id']) return {'evidence': _public(row)} - def _manager(self, record: dict, actor: dict) -> None: + def _manager(self, record: dict[str, Any], actor: dict[str, Any]) -> None: if record['kind'] != 'evidence': raise AgentTaskError('identity does not select a portable evidence grant') self.host.managed(record['scope']['source_task'], actor) - def _review(self, request: dict, actor: dict) -> dict: + def _review(self, request: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: _text(request['idempotency_key'], 256, 'idempotency key') if request['recipient_policy'] not in ('caller', 'source_owner'): raise AgentTaskError('evidence recipient must derive caller or original source owner') @@ -123,8 +123,8 @@ def _review(self, request: dict, actor: dict) -> dict: return {'review': review, 'digest': sha256(_canonical(summary)).hexdigest(), 'evidence': summary, 'review_expires': record['review_expires'], 'approval_required': True} - def _check(self, record: dict, *, connection: Any = None, issuing: bool = False, - checkpoint: Callable | None = None) -> dict: + def _check(self, record: dict[str, Any], *, connection: Any = None, issuing: bool = False, + checkpoint: Callable[[], None] | None = None) -> dict[str, Any]: check = self.checkpoint if checkpoint is None else checkpoint check() scope = record['scope'] @@ -159,7 +159,7 @@ def skill_access(self, connection: Any, source_task: str, task_id: str, grant_id raise AgentTaskError('portable skill evidence recipient changed') return access - def _create(self, request: dict, actor: dict) -> dict: + def _create(self, request: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: _hex(request['review'], 32) note = _text(request['note'], 4000, 'approval note') key = _text(request['idempotency_key'], 256, 'idempotency key') @@ -183,7 +183,7 @@ def _create(self, request: dict, actor: dict) -> dict: self._check(created, connection=connection, issuing=True) return {'evidence': _public(created)} - def resolve(self, grant_id: str, binding: Mapping) -> dict: + def resolve(self, grant_id: str, binding: Mapping[str, Any]) -> dict[str, Any]: """Revalidate one exact original accepted witness under the actual receiving account every time.""" self.host.check_open() self.checkpoint() @@ -224,7 +224,7 @@ def close(self) -> None: def resolve_remote_evidence(peer: Any, host: str, host_binding: str, grant_id: str, - binding: Mapping, timeout: float = 30) -> dict: + binding: Mapping[str, Any], timeout: float = 30) -> dict[str, Any]: """Resolve fresh authenticated evidence without interpreting foreign principals or local paths.""" request = {'grant_id': grant_id, 'binding': evidence_binding(binding)} return peer.call(host, host_binding, 'evidence', request, timeout) diff --git a/je_auto_control/utils/agent_runtime/transfer_import.py b/je_auto_control/utils/agent_runtime/transfer_import.py index 0840ff09c..538cf43d4 100644 --- a/je_auto_control/utils/agent_runtime/transfer_import.py +++ b/je_auto_control/utils/agent_runtime/transfer_import.py @@ -23,7 +23,7 @@ class _ImportState: """Unapproved reviews belong only to the current runtime; approved intents will be durable.""" - reviews: dict[str, dict] = field(default_factory=dict) + reviews: dict[str, dict[str, Any]] = field(default_factory=dict) enabled: bool = False jobs: Any = None @@ -50,7 +50,7 @@ def __init__(self, runtime: Any, records: TransferRecords, host: Any, peer: Any, self.remaining = remaining self._state = _ImportState() - def control(self, operation: str, request: Mapping) -> dict: + def control(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Review only exact destination management envelopes under actual current local authority.""" value = dict(_object(request, IMPORT_FIELDS[operation])) actor = principal() @@ -97,11 +97,11 @@ def _jobs(self) -> TransferImportJobs: return self._state.jobs @staticmethod - def _owner(row: dict, actor: dict) -> None: + def _owner(row: dict[str, Any], actor: dict[str, Any]) -> None: if row['kind'] != 'import' or row['actor'] != actor_key(actor): raise AgentTaskError('destination import belongs to another recipient') - def _local(self, row: dict, *, connection: Any = None) -> dict: + def _local(self, row: dict[str, Any], *, connection: Any = None) -> dict[str, Any]: with _refresh(row['scope']['issuer']).scope(): destination = row['scope']['destination'] current = self.host.destination_context(destination['profile']['name'], destination['directory'], @@ -110,12 +110,12 @@ def _local(self, row: dict, *, connection: Any = None) -> dict: raise AgentTaskError('destination import receipt has expired') return current - def _current(self, row: dict) -> None: + def _current(self, row: dict[str, Any]) -> None: self._local(row) if self.runtime.batches.transfer_binding(row['scope']['source_host']) != row['scope']['binding']: raise AgentTaskError('destination source registration changed') - def _manifest(self, row: dict, timeout: float) -> TransferManifest: + def _manifest(self, row: dict[str, Any], timeout: float) -> TransferManifest: self._current(row) scope = row['scope'] with _refresh(scope['issuer']).scope(): @@ -126,7 +126,7 @@ def _manifest(self, row: dict, timeout: float) -> TransferManifest: raise AgentTaskError('source export differs from the reviewed manifest') return manifest - def _create(self, request: dict, actor: dict) -> dict: + def _create(self, request: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: _hex(request['review'], 32) note_hash = _text(request['note'], 4000, 'approval note') key_hash = _text(request['idempotency_key'], 256, 'idempotency key') @@ -160,14 +160,14 @@ def _create(self, request: dict, actor: dict) -> dict: jobs.wake() return reply - def _public(self, row: dict, connection: Any) -> dict: + def _public(self, row: dict[str, Any], connection: Any) -> dict[str, Any]: delivery = self._state.jobs.ledger.read(connection, row['id']) state = delivery['state'] if row['expires'] > time.time() else 'expired' return {'import_id': row['id'], 'state': state, 'expires': row['expires'], 'manifest_digest': row['scope']['digest'], 'files_directory': delivery['files_directory'] if state == 'published' else None} - def _run(self, row: dict) -> None: + def _run(self, row: dict[str, Any]) -> None: jobs = self._state.jobs with self.runtime.store.connection() as connection: retained = jobs.ledger.read(connection, row['id']) @@ -189,11 +189,11 @@ def _run(self, row: dict) -> None: self._current(row) @staticmethod - def _delivery_scope(row: dict, delivery: dict) -> None: + def _delivery_scope(row: dict[str, Any], delivery: dict[str, Any]) -> None: row['scope']['destination']['origins'] = list(dict.fromkeys([ *row['scope']['destination']['origins'], *delivery['ceilings']])) - def deliver(self, import_id: str, generation: int, check: Callable[[], None]) -> dict: + def deliver(self, import_id: str, generation: int, check: Callable[[], None]) -> dict[str, Any]: """Receive and independently verify real source bytes under the persisted original local issuer.""" jobs = self._state.jobs with self.runtime.store.connection() as connection: @@ -224,11 +224,11 @@ def budget() -> float: self._local(row, connection=connection) return {'import_id': import_id, 'state': 'published'} - def _receive(self, row: dict, manifest: TransferManifest, generation: int, checkpoint: Callable, - budget: Callable) -> Any: + def _receive(self, row: dict[str, Any], manifest: TransferManifest, generation: int, + checkpoint: Callable[[], None], budget: Callable[[], float]) -> Any: jobs = self._state.jobs cache = PrivateTransferCache(self.runtime.store.path) - def read(digest: str) -> dict: + def read(digest: str) -> dict[str, Any]: scope = row['scope'] return self.remote.call(scope['source_host'], scope['binding'], 'chunk', {'export_id': manifest.export_id, 'sha256': digest}, budget()) @@ -238,12 +238,12 @@ def read(digest: str) -> dict: self._local(row, connection=connection) jobs.ledger.advance(connection, row['id'], generation, 'verified') self._local(row, connection=connection) - def publication(value: dict) -> None: + def publication(value: dict[str, Any]) -> None: with self.runtime.store.connection(write=True) as connection: self._local(row, connection=connection) jobs.ledger.advance(connection, row['id'], generation, 'verified', publication=value) self._local(row, connection=connection) - def staging_retired(witness: dict) -> None: + def staging_retired(witness: dict[str, Any]) -> None: with self.runtime.store.connection(write=True) as connection: jobs.ledger.staging_retired(connection, row['id'], witness) return publish_import(row, manifest, cache, checkpoint, publication, staging_retired) @@ -278,7 +278,7 @@ def maintain(self) -> None: for identifier in pending: self._cleanup_account(identifier) - def _cleanup_candidate(self, record: dict, delivery: dict) -> bool: + def _cleanup_candidate(self, record: dict[str, Any], delivery: dict[str, Any]) -> bool: if not record['held']: return False if record['expires'] <= time.time(): @@ -305,7 +305,7 @@ def _cleanup_account(self, identifier: str) -> None: with self.runtime.store.connection(write=True) as connection: self.records.release(connection, identifier) - def _review(self, request: dict, actor: dict) -> dict: + def _review(self, request: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: _text(request['idempotency_key'], 256, 'idempotency key') destination = self.host.destination_context(request['target'], request['directory']) if self.remote is None: diff --git a/je_auto_control/utils/agent_runtime/transfer_lineage.py b/je_auto_control/utils/agent_runtime/transfer_lineage.py index aebabf67d..f4abb2429 100644 --- a/je_auto_control/utils/agent_runtime/transfer_lineage.py +++ b/je_auto_control/utils/agent_runtime/transfer_lineage.py @@ -9,19 +9,22 @@ from je_auto_control.utils.rbac.authorization import AuthorizationContext from je_auto_control.utils.rbac.deferred import DeferredAuthorization +_Link = tuple[dict[str, Any], dict[str, Any], dict[str, Any]] + @dataclass(frozen=True) class SourceLineage: """Reuse host recovery witnesses without issuing completion grants or fabricating child admission.""" runtime: Any - digest: Callable - submitted: Callable - manager: Callable - retired: Callable - ownership: Callable + digest: Callable[[Any], str] + submitted: Callable[[dict[str, Any]], str] + manager: Callable[[dict[str, Any], dict[str, Any]], None] + retired: Callable[[str], bool] + ownership: Callable[[Any, str], dict[str, Any] | None] - def context(self, connection: Any, leaf: dict, issuer: dict, origins: list[str] | None) -> dict: + def context(self, connection: Any, leaf: dict[str, Any], issuer: dict[str, Any], + origins: list[str] | None) -> dict[str, Any]: """Check original requests, current owners and every real historical recovery segment.""" rows, links = self._chain(connection, leaf, issuer) root = rows[0] @@ -39,7 +42,8 @@ def context(self, connection: Any, leaf: dict, issuer: dict, origins: list[str] 'submission_digest': accepted if accepted is not None else self.submitted(root['spec'])} @staticmethod - def _principals(rows: list, context: dict, ownership: list) -> tuple[dict, ...]: + def _principals(rows: list[dict[str, Any]], context: dict[str, Any], + ownership: list[dict[str, Any] | None]) -> tuple[dict[str, Any], ...]: owners = tuple(row['owner'] for row in rows) admission = context['binding'].get('admission') if admission is not None: @@ -49,8 +53,8 @@ def _principals(rows: list, context: dict, ownership: list) -> tuple[dict, ...]: owners += (value['actor'], value['owner']) return owners - def _segments(self, connection: Any, context: dict, links: list, issuer: dict, - origins: list[str] | None) -> tuple[tuple, list]: + def _segments(self, connection: Any, context: dict[str, Any], links: list[_Link], issuer: dict[str, Any], + origins: list[str] | None) -> tuple[tuple[Any, ...], list[dict[str, Any]]]: if not links: return (), [] context['issuer'] = issuer @@ -61,9 +65,10 @@ def _segments(self, connection: Any, context: dict, links: list, issuer: dict, for parent, child, link in links] return (context['policy'],), segments - def _chain(self, connection: Any, leaf: dict, issuer: dict) -> tuple[list, list]: + def _chain(self, connection: Any, leaf: dict[str, Any], + issuer: dict[str, Any]) -> tuple[list[dict[str, Any]], list[_Link]]: rows, seen, row = [leaf], set(), leaf - links: list[tuple[dict, dict, dict]] = [] + links: list[_Link] = [] for _index in range(17): if row['id'] in seen or not self.retired(row['id']): raise AgentTaskError('source recovery ancestry is cyclic or input has not retired') @@ -84,7 +89,8 @@ def _chain(self, connection: Any, leaf: dict, issuer: dict) -> tuple[list, list] row = parent raise AgentTaskError('source exceeds sixteen real recovery links') - def _root(self, connection: Any, root: dict, origins: list[str] | None) -> tuple[dict, str | None]: + def _root(self, connection: Any, root: dict[str, Any], + origins: list[str] | None) -> tuple[dict[str, Any], str | None]: accepted = connection.execute('SELECT spec_digest FROM agent_task_submissions WHERE task_id=?', (root['id'],)).fetchone() admitted = connection.execute('SELECT * FROM agent_dag_local_tasks WHERE task_id=?', @@ -101,7 +107,7 @@ def _root(self, connection: Any, root: dict, origins: list[str] | None) -> tuple return context, accepted[0] if accepted is not None else None @staticmethod - def _tag(root: dict, accepted: Any, admitted: Any) -> dict | None: + def _tag(root: dict[str, Any], accepted: Any, admitted: Any) -> dict[str, Any] | None: tag = root['spec']['options'].get('dag_batch') if (accepted is not None or admitted is not None) and tag is None: raise AgentTaskError('source original DAG tag is missing') @@ -109,7 +115,8 @@ def _tag(root: dict, accepted: Any, admitted: Any) -> dict | None: raise AgentTaskError('tagged source original submission witness is unavailable') return tag - def _local_context(self, connection: Any, root: dict, binding: dict | None, origins: list[str] | None) -> dict: + def _local_context(self, connection: Any, root: dict[str, Any], binding: dict[str, Any] | None, + origins: list[str] | None) -> dict[str, Any]: if binding is None: raise AgentTaskError('source original local DAG binding is unavailable') context = self.runtime.batches.handoff_context(binding['batch_id'], binding['node_id'], @@ -119,7 +126,7 @@ def _local_context(self, connection: Any, root: dict, binding: dict | None, orig self.manager(json.loads(context['binding']['admission']['actor']), root['owner']) return context - def _requests(self, connection: Any, row: dict) -> list: + def _requests(self, connection: Any, row: dict[str, Any]) -> list[dict[str, Any]]: requests = [dict(item) for item in connection.execute( 'SELECT * FROM agent_request_keys WHERE task_id=? ORDER BY owner_key,key_hash', (row['id'],))] owner = json.dumps([row['owner'].get('user_id'), row['owner'].get('store_path')]) @@ -127,11 +134,12 @@ def _requests(self, connection: Any, row: dict) -> list: raise AgentTaskError('source original accepted request witness changed') return requests - def accepted_requests(self, connection: Any, row: dict) -> list: + def accepted_requests(self, connection: Any, row: dict[str, Any]) -> list[dict[str, Any]]: """Expose only actual validated private request witnesses to another host-owned proof builder.""" return self._requests(connection, row) - def evidence_context(self, connection: Any, source: dict, issuer: dict, origins: list[str] | None) -> dict: + def evidence_context(self, connection: Any, source: dict[str, Any], issuer: dict[str, Any], + origins: list[str] | None) -> dict[str, Any]: """Preserve actual local DAG admission; remote accepted nodes keep their real task-only context.""" lineage = self.context(connection, source, issuer, origins) rows, _links = self._chain(connection, source, issuer) diff --git a/je_auto_control/utils/agent_runtime/transfer_source.py b/je_auto_control/utils/agent_runtime/transfer_source.py index f6f0739ad..487930892 100644 --- a/je_auto_control/utils/agent_runtime/transfer_source.py +++ b/je_auto_control/utils/agent_runtime/transfer_source.py @@ -16,12 +16,12 @@ from je_auto_control.utils.agent_runtime.transfer_records import TransferRecords, _text from je_auto_control.utils.agent_runtime.transfer_selection import TextCriterion, check_source_paths, selected_files -def _binding(context: dict) -> dict: +def _binding(context: dict[str, Any]) -> dict[str, Any]: return {key: context[key] for key in ('source_snapshot', 'completion_snapshot', 'submission_digest', 'origin_scope', 'expires', 'lineage_digest')} -def _public(record: dict) -> dict: +def _public(record: dict[str, Any]) -> dict[str, Any]: state = record['state'] if state == 'active' and record['expires'] <= time.time(): state = 'expired' @@ -47,7 +47,7 @@ class TransferSource: def __init__(self, runtime: Any, records: TransferRecords, host: Any, checkpoint: Any) -> None: self.runtime, self.records, self.host = runtime, records, host - self._reviews: dict[str, dict] = {} + self._reviews: dict[str, dict[str, Any]] = {} self._cache = PrivateTransferCache(runtime.store.path) self._initialized = False self._checkpoint = checkpoint @@ -58,7 +58,7 @@ def _initialize(self) -> None: self.records.initialize(connection) self._initialized = True - def control(self, operation: str, request: Mapping[str, Any]) -> dict: + def control(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Execute only exact local management envelopes; none accept paths or foreign principals.""" self.host.check_open() self._checkpoint() @@ -85,12 +85,12 @@ def control(self, operation: str, request: Mapping[str, Any]) -> dict: row = self.records.find(connection, row['id']) return {'export': _public(row)} - def _manage(self, record: dict, actor: dict) -> None: + def _manage(self, record: dict[str, Any], actor: dict[str, Any]) -> None: if record['kind'] != 'export': raise AgentTaskError('identity is not an export') self.host.managed(record['scope']['source_task'], actor) - def _review(self, request: dict, actor: dict) -> dict: + def _review(self, request: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: _text(request['idempotency_key'], 256, 'idempotency key') if request['recipient_policy'] not in ('caller', 'source_owner'): raise AgentTaskError('recipient_policy must derive caller or original source owner') @@ -120,7 +120,7 @@ def checkpoint() -> None: return {'review': review, 'digest': manifest.digest, 'manifest': manifest.to_dict(), 'review_expires': now + 300, 'approval_required': True} - def _scan(self, context: dict, selected: list, checkpoint: Any, *, + def _scan(self, context: dict[str, Any], selected: list[tuple[str, dict[str, Any]]], checkpoint: Any, *, account: str | None = None) -> tuple[SourceFile, ...]: result, remaining = [], MAX_TRANSFER_BYTES for path, clause in selected: @@ -134,7 +134,7 @@ def _scan(self, context: dict, selected: list, checkpoint: Any, *, return tuple(result) @staticmethod - def _criterion(item: SourceFile, clause: dict, text: TextCriterion | None) -> None: + def _criterion(item: SourceFile, clause: dict[str, Any], text: TextCriterion | None) -> None: if clause['kind'] == 'file_sha256' and item.file.blob.sha256 != clause['value']: raise AgentTaskError('source bytes no longer satisfy the selected hash criterion') if 'expected_size' in clause and item.file.blob.size != clause['expected_size']: @@ -144,7 +144,7 @@ def _criterion(item: SourceFile, clause: dict, text: TextCriterion | None) -> No if text is not None: text.finish() - def _check(self, context: dict, issuer: dict, *, connection: Any = None) -> None: + def _check(self, context: dict[str, Any], issuer: dict[str, Any], *, connection: Any = None) -> None: self._checkpoint() self._cache.check() current = self.host.context(context['row']['id'], issuer, connection=connection, @@ -153,7 +153,7 @@ def _check(self, context: dict, issuer: dict, *, connection: Any = None) -> None raise AgentTaskError('source evidence or reviewed authority changed') self._checkpoint() - def _create(self, request: dict, actor: dict) -> dict: + def _create(self, request: dict[str, Any], actor: dict[str, Any]) -> dict[str, Any]: _hex(request['review'], 32) note_hash = _text(request['note'], 4000, 'approval note') key_hash = _text(request['idempotency_key'], 256, 'idempotency key') @@ -197,7 +197,8 @@ def _create(self, request: dict, actor: dict) -> dict: if not accepted: self._cleanup(record) - def _retry(self, request: dict, actor: dict, note_hash: str, key_hash: str) -> dict | None: + def _retry(self, request: dict[str, Any], actor: dict[str, Any], note_hash: str, + key_hash: str) -> dict[str, Any] | None: with self.runtime.store.connection() as connection: previous = self.records.review(connection, request['review']) if previous is None: @@ -208,7 +209,7 @@ def _retry(self, request: dict, actor: dict, note_hash: str, key_hash: str) -> d self._live(previous) return previous - def _live(self, record: dict) -> dict: + def _live(self, record: dict[str, Any]) -> dict[str, Any]: self._checkpoint() with self.runtime.store.connection() as connection: active = self.records.active(connection, record['id']) @@ -221,7 +222,7 @@ def _live(self, record: dict) -> dict: self._cache.check() return current - def peer(self, operation: str, request: Mapping[str, Any]) -> dict: + def peer(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: """Read only exact committed manifests or selected content hashes as their actual local recipient.""" fields = {'export_id'} if operation == 'export' else {'export_id', 'sha256'} if not isinstance(operation, str) or operation not in {'export', 'chunk'}: @@ -265,7 +266,7 @@ def maintain(self) -> None: for record in pending: self._cleanup(record) - def _cleanup(self, record: dict) -> None: + def _cleanup(self, record: dict[str, Any]) -> None: with self.runtime.store.connection(write=True) as connection: self.records.revoke(connection, record['id']) self._cache.delete_account(record['account']) diff --git a/je_auto_control/utils/agent_runtime/workflow_specs.py b/je_auto_control/utils/agent_runtime/workflow_specs.py index 172b383ca..f3564eba4 100644 --- a/je_auto_control/utils/agent_runtime/workflow_specs.py +++ b/je_auto_control/utils/agent_runtime/workflow_specs.py @@ -50,7 +50,7 @@ def draft_agent_workflow(workflow: str, config: Mapping[str, Any]) -> dict[str, return validated.to_dict() -def _base(workflow: str, config: dict) -> dict: +def _base(workflow: str, config: dict[str, Any]) -> dict[str, Any]: options = {"workflow": workflow} default = "local-files" if workflow == "download_archive" else "local-desktop" if config.get("backend") == "browser": @@ -64,7 +64,7 @@ def _base(workflow: str, config: dict) -> dict: "actions": [], "options": options} -def _items(config: dict, name: str) -> list[dict]: +def _items(config: dict[str, Any], name: str) -> list[dict[str, Any]]: value = config.get(name) if not isinstance(value, list) or not value or len(value) > 500: raise AgentTaskError(f"{name} requires between 1 and 500 items") @@ -73,14 +73,14 @@ def _items(config: dict, name: str) -> list[dict]: return value -def _action(tool: str, arguments: dict, expected: Any = None) -> dict: +def _action(tool: str, arguments: dict[str, Any], expected: Any = None) -> dict[str, Any]: result = {"tool": tool, "arguments": arguments} if expected is not None: result["expect_result"] = expected return result -def _downloads(config: dict, policy: TaskPolicy) -> dict: +def _downloads(config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: directory = policy.path(config.get("directory")) entries = _items(config, "files") from je_auto_control.utils.agent_runtime.workflow_files import _destination @@ -114,7 +114,7 @@ def url_origin(url: str) -> str: return f"{parsed.scheme}://{hostname}:{port}" -def _rows(config: dict, policy: TaskPolicy) -> list[dict]: +def _rows(config: dict[str, Any], policy: TaskPolicy) -> list[dict[str, Any]]: source = Path(policy.path(config.get("source"))) if source.stat().st_size > 8_000_000: raise AgentTaskError("workflow table exceeds eight megabytes") @@ -134,14 +134,14 @@ def _rows(config: dict, policy: TaskPolicy) -> list[dict]: return rows -def _focus(config: dict) -> dict: +def _focus(config: dict[str, Any]) -> dict[str, Any]: title = config.get("window_title") if not isinstance(title, str) or not title: raise AgentTaskError("workflow application requires an explicit window_title") return _action("AC_focus_window", {"title_substring": title}) -def _forms(config: dict, policy: TaskPolicy) -> dict: +def _forms(config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: rows, fields = _rows(config, policy), _items(config, "fields") if len(rows) * (len(fields) * 2 + 2) > 1000: raise AgentTaskError("batch form requires at most one thousand actions") @@ -165,7 +165,7 @@ def _forms(config: dict, policy: TaskPolicy) -> dict: return {"actions": actions} -def _commit_actions(actions: list[dict], config: dict, row: str) -> None: +def _commit_actions(actions: list[dict[str, Any]], config: dict[str, Any], row: str) -> None: if not config.get("submit_selector") or not config.get("confirmation_selector"): raise AgentTaskError("submission requires a button and a read-back confirmation selector") if "confirmation_value" not in config: @@ -181,7 +181,7 @@ def _commit_actions(actions: list[dict], config: dict, row: str) -> None: ]) -def _transfer(config: dict, _policy: TaskPolicy) -> dict: +def _transfer(config: dict[str, Any], _policy: TaskPolicy) -> dict[str, Any]: actions = [_focus(config["source_app"])] fields = _items(config, "fields") for index, field in enumerate(fields): @@ -199,7 +199,7 @@ def _transfer(config: dict, _policy: TaskPolicy) -> dict: return {"actions": actions} -def _workspace(config: dict, policy: TaskPolicy) -> dict: +def _workspace(config: dict[str, Any], policy: TaskPolicy) -> dict[str, Any]: actions = [] launches = [] for document in config.get("documents", []): @@ -217,7 +217,7 @@ def _workspace(config: dict, policy: TaskPolicy) -> dict: return {"actions": actions, "options": {"workflow": "workspace", "approved_documents": launches}} -def _dirty_document_check(entry: dict) -> list[dict]: +def _dirty_document_check(entry: dict[str, Any]) -> list[dict[str, Any]]: if not entry.get("unsaved_selector"): return [] if "unsaved_value" not in entry: diff --git a/je_auto_control/utils/codegen/codegen.py b/je_auto_control/utils/codegen/codegen.py index f817e85ec..30370e1bb 100644 --- a/je_auto_control/utils/codegen/codegen.py +++ b/je_auto_control/utils/codegen/codegen.py @@ -19,7 +19,7 @@ import pprint import re import textwrap -from typing import Any, Dict, Sequence, Tuple +from typing import Any, Callable, Dict, Sequence, Set, Tuple from je_auto_control.utils.json.json_file import read_action_json from je_auto_control.utils.json_store.json_store import atomic_write_text @@ -62,7 +62,7 @@ def _non_finite(value: Any) -> bool: return False -def _math_import(actions: Sequence) -> str: +def _math_import(actions: Sequence[Sequence[Any]]) -> str: """The import ``repr`` output needs when the actions hold NaN or infinity. ``json`` reads ``NaN`` / ``Infinity``, and ``repr`` writes them as the @@ -78,14 +78,14 @@ def _unwrapped(actions: Any) -> Any: return actions -def _call_context() -> Tuple[dict, set]: +def _call_context() -> Tuple[Dict[str, Callable[..., Any]], Set[str]]: """Return ``(event_dict, public_names)`` for mapping commands to calls.""" import je_auto_control as ac from je_auto_control.utils.executor.action_executor import executor return executor.event_dict, set(getattr(ac, "__all__", ())) -def _action_to_call(action: Sequence, event_dict: dict, public: set) -> str: +def _action_to_call(action: Sequence[Any], event_dict: Dict[str, Callable[..., Any]], public: Set[str]) -> str: """Render one action as a Python statement (call or executor fall-back).""" name = action[0] params = action[1] if len(action) == 2 else None @@ -148,13 +148,13 @@ def _keyword_safe(params: object) -> bool: for key in params) -def _calls_body(actions: Sequence) -> str: +def _calls_body(actions: Sequence[Sequence[Any]]) -> str: event_dict, public = _call_context() return "\n".join( _action_to_call(action, event_dict, public) for action in actions) -def _actions_body(actions: Sequence) -> str: +def _actions_body(actions: Sequence[Sequence[Any]]) -> str: # sort_dicts=False: the replay is meant to be exact, and a dict value's # key order is what str() of it -- text a script may type -- shows. literal = pprint.pformat([list(action) for action in actions], @@ -162,7 +162,7 @@ def _actions_body(actions: Sequence) -> str: return f"actions = {literal}\n" + _REPLAY.format("actions") -def _body(actions: Sequence, style: str) -> str: +def _body(actions: Sequence[Sequence[Any]], style: str) -> str: if style == "actions": return _actions_body(actions) if style == "calls": @@ -170,7 +170,7 @@ def _body(actions: Sequence, style: str) -> str: raise ValueError(f"unknown codegen style: {style!r}") -def _render_pytest(actions: Sequence, name: str, style: str, +def _render_pytest(actions: Sequence[Sequence[Any]], name: str, style: str, failure_bundle: bool = False) -> str: raw_body = _body(actions, style) if failure_bundle: @@ -190,7 +190,7 @@ def _render_pytest(actions: Sequence, name: str, style: str, + f"def test_{_slug(name)}():\n{body}\n") -def _render_python(actions: Sequence, name: str, style: str, +def _render_python(actions: Sequence[Sequence[Any]], name: str, style: str, _failure_bundle: bool = False) -> str: slug = _slug(name) body = textwrap.indent(_body(actions, style), " ") @@ -202,7 +202,7 @@ def _render_python(actions: Sequence, name: str, style: str, f" {slug}()\n") -def _render_robot(actions: Sequence, name: str, _style: str, +def _render_robot(actions: Sequence[Sequence[Any]], name: str, _style: str, _failure_bundle: bool = False) -> str: # Base64, not a raw-string literal: ''' in any value closed the literal # and the rest ran as Python inside Evaluate, and Robot itself splits @@ -237,7 +237,7 @@ def _robot_test_name(name: str) -> str: return text.title() or "Recorded Flow" -def _check_shapes(actions: list) -> None: +def _check_shapes(actions: list[Any]) -> None: """Refuse what the executor would refuse to run, before rendering it. ``[1]`` or ``[[]]`` ended in a traceback, and ``["AC_click_mouse", {...}, @@ -255,7 +255,7 @@ def _check_shapes(actions: list) -> None: } -def generate_code(actions: Sequence | Dict[str, Any], target: str = "pytest", +def generate_code(actions: Sequence[Sequence[Any]] | Dict[str, Any], target: str = "pytest", name: str = "recorded_flow", style: str = "calls", failure_bundle: bool = False) -> str: """Render ``actions`` as source code for ``target`` (pytest/python/robot). @@ -281,7 +281,7 @@ def generate_code(actions: Sequence | Dict[str, Any], target: str = "pytest", return code -def generate_code_file(source, output_path: str, target: str = "pytest", +def generate_code_file(source: list[Any] | Dict[str, Any] | str, output_path: str, target: str = "pytest", name: str = "recorded_flow", style: str = "calls", failure_bundle: bool = False) -> str: """Generate code from a list or JSON action-file path; write and return it.""" diff --git a/je_auto_control/utils/message_format/message_format.py b/je_auto_control/utils/message_format/message_format.py index 179a8a813..f8f0a05bd 100644 --- a/je_auto_control/utils/message_format/message_format.py +++ b/je_auto_control/utils/message_format/message_format.py @@ -24,7 +24,7 @@ from je_auto_control.utils.exception.exceptions import AutoControlException -Node = Tuple +Node = Tuple[Any, ...] PluralRule = Callable[[Any], str] _Operands = Callable[[float, int, bool], str] diff --git a/je_auto_control/utils/preprocess/preprocess.py b/je_auto_control/utils/preprocess/preprocess.py index 50471fb0c..22f427086 100644 --- a/je_auto_control/utils/preprocess/preprocess.py +++ b/je_auto_control/utils/preprocess/preprocess.py @@ -23,7 +23,7 @@ _INTERP = ("nearest", "linear", "cubic", "lanczos") -def _pil_to_bgr(image: Any): +def _pil_to_bgr(image: Any) -> Any: """A PIL image as an OpenCV array: ``L`` stays single-channel, colour becomes BGR(A). ``np.asarray`` on a palette image gives palette *indices*, and RGB order @@ -39,7 +39,7 @@ def _pil_to_bgr(image: Any): return cv2.cvtColor(np.asarray(image.convert("RGB")), cv2.COLOR_RGB2BGR) -def _to_array(source: ImageSource): +def _to_array(source: ImageSource) -> Any: """Load a path / ndarray / PIL image as a uint8 ndarray in OpenCV's BGR order.""" import cv2 import numpy as np @@ -51,7 +51,7 @@ def _to_array(source: ImageSource): return _pil_to_bgr(source) -def _resolve(haystack: Optional[ImageSource], region: Optional[Sequence[int]]): +def _resolve(haystack: Optional[ImageSource], region: Optional[Sequence[int]]) -> Any: if haystack is not None: return _as_uint8(_to_array(haystack)) from je_auto_control.utils.cv2_utils.region_capture import grab_screen_region @@ -78,7 +78,7 @@ def _eight_bit(source: Any) -> Any: return Image.fromarray(_as_uint8(array)) -def _as_uint8(array): +def _as_uint8(array: Any) -> Any: """``array`` as uint8, which every step assumes. A 16-bit PNG stayed 16-bit: Otsu then wrote 0 and 255 into a uint16 image, @@ -96,7 +96,7 @@ def _as_uint8(array): return np.clip(np.rint(values), 0, 255).astype(np.uint8) -def _gray(array): +def _gray(array: Any) -> Any: import cv2 if array.ndim == 3 and array.shape[2] == 1: array = array[:, :, 0] @@ -108,7 +108,7 @@ def _gray(array): @_contain_cv2_error def to_grayscale(haystack: Optional[ImageSource] = None, *, - region: Optional[Sequence[int]] = None): + region: Optional[Sequence[int]] = None) -> Any: """Return the image as a single-channel grayscale ndarray.""" return _gray(_resolve(haystack, region)) @@ -116,7 +116,7 @@ def to_grayscale(haystack: Optional[ImageSource] = None, *, @_contain_cv2_error def upscale(haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, scale: float = 2.0, - interp: str = "cubic"): + interp: str = "cubic") -> Any: """Return the image resized by ``scale`` — enlarge small UI text before OCR.""" import cv2 if interp not in _INTERP: @@ -136,7 +136,7 @@ def upscale(haystack: Optional[ImageSource] = None, *, @_contain_cv2_error def binarize(haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, method: str = "otsu", - block_size: int = 31, c: int = 11): + block_size: int = 31, c: int = 11) -> Any: """Return a black/white image. ``method``: otsu / adaptive_mean / adaptive_gaussian.""" import cv2 gray = _gray(_resolve(haystack, region)) @@ -157,7 +157,7 @@ def binarize(haystack: Optional[ImageSource] = None, *, @_contain_cv2_error def denoise(haystack: Optional[ImageSource] = None, *, - region: Optional[Sequence[int]] = None, strength: int = 7): + region: Optional[Sequence[int]] = None, strength: int = 7) -> Any: """Return a denoised grayscale image (non-local means).""" import cv2 return cv2.fastNlMeansDenoising(_gray(_resolve(haystack, region)), None, @@ -167,7 +167,7 @@ def denoise(haystack: Optional[ImageSource] = None, *, @_contain_cv2_error def enhance_contrast(haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, clip: float = 2.0, - grid: int = 8): + grid: int = 8) -> Any: """Return a CLAHE contrast-enhanced grayscale image (rescues dark/low-contrast UI).""" import cv2 if int(grid) < 1: @@ -201,7 +201,7 @@ def detect_skew_angle(haystack: Optional[ImageSource] = None, *, @_contain_cv2_error def deskew(haystack: Optional[ImageSource] = None, *, - region: Optional[Sequence[int]] = None, max_angle: float = 15.0): + region: Optional[Sequence[int]] = None, max_angle: float = 15.0) -> Any: """Return the image rotated to remove text skew (no-op when none is detected).""" import cv2 array = _resolve(haystack, region) @@ -214,20 +214,20 @@ def deskew(haystack: Optional[ImageSource] = None, *, flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) -def _step_grayscale(array, **_kwargs): +def _step_grayscale(array: Any, **_kwargs: Any) -> Any: return to_grayscale(array) -def _step_upscale(array, *, scale: float, **_kwargs): +def _step_upscale(array: Any, *, scale: float, **_kwargs: Any) -> Any: return upscale(array, scale=scale) -def _step_binarize(array, **_kwargs): +def _step_binarize(array: Any, **_kwargs: Any) -> Any: return binarize(array) def _step_adaptive(method: str) -> Callable[..., Any]: - def _step(array, *, block_size: int, c: int, **_kwargs): + def _step(array: Any, *, block_size: int, c: int, **_kwargs: Any) -> Any: return binarize(array, method=method, block_size=block_size, c=c) return _step @@ -249,7 +249,7 @@ def _step(array, *, block_size: int, c: int, **_kwargs): def preprocess_image(haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, steps: Sequence[str] = ("grayscale", "upscale", "binarize"), - scale: float = 2.0, block_size: int = 31, c: int = 11): + scale: float = 2.0, block_size: int = 31, c: int = 11) -> Any: """Apply a pipeline of named preprocessing ``steps`` in order, returning the result. Steps: ``grayscale``, ``upscale`` (by ``scale``), ``binarize`` (Otsu), diff --git a/je_auto_control/utils/recording_edit/editor.py b/je_auto_control/utils/recording_edit/editor.py index 2621b415e..94dc3838b 100644 --- a/je_auto_control/utils/recording_edit/editor.py +++ b/je_auto_control/utils/recording_edit/editor.py @@ -6,14 +6,14 @@ from typing import Any, Callable, List, Optional -def trim_actions(actions: List[list], start: int = 0, - end: Optional[int] = None) -> List[list]: +def trim_actions(actions: List[List[Any]], start: int = 0, + end: Optional[int] = None) -> List[List[Any]]: """Return a slice ``actions[start:end]`` (end=None means to the end).""" return list(actions[start:end]) -def insert_action(actions: List[list], index: int, new_action: list - ) -> List[list]: +def insert_action(actions: List[List[Any]], index: int, new_action: List[Any] + ) -> List[List[Any]]: """Return a new list with ``new_action`` inserted at ``index``.""" result = list(actions) if index < 0 or index > len(result): @@ -22,28 +22,28 @@ def insert_action(actions: List[list], index: int, new_action: list return result -def remove_action(actions: List[list], index: int) -> List[list]: +def remove_action(actions: List[List[Any]], index: int) -> List[List[Any]]: """Return a new list with the entry at ``index`` removed.""" if index < 0 or index >= len(actions): raise IndexError(f"remove_action: index {index} out of range") return actions[:index] + actions[index + 1:] -def filter_actions(actions: List[list], - predicate: Callable[[list], bool]) -> List[list]: +def filter_actions(actions: List[List[Any]], + predicate: Callable[[List[Any]], bool]) -> List[List[Any]]: """Return only actions for which ``predicate(action)`` is true.""" return [action for action in actions if predicate(action)] -def adjust_delays(actions: List[list], factor: float = 1.0, - clamp_ms: int = 0) -> List[list]: +def adjust_delays(actions: List[List[Any]], factor: float = 1.0, + clamp_ms: int = 0) -> List[List[Any]]: """Scale every ``AC_sleep`` delay by ``factor`` (and clamp to ``clamp_ms``). :param factor: multiplier for ``seconds`` values (<1 speeds up). :param clamp_ms: floor for each resulting delay, in milliseconds. """ floor_seconds = max(0.0, float(clamp_ms) / 1000.0) - adjusted: List[list] = [] + adjusted: List[List[Any]] = [] for action in actions: original = _numeric_seconds(action) if original is not None: @@ -56,10 +56,10 @@ def adjust_delays(actions: List[list], factor: float = 1.0, return adjusted -def scale_coordinates(actions: List[list], - x_factor: float, y_factor: float) -> List[list]: +def scale_coordinates(actions: List[List[Any]], + x_factor: float, y_factor: float) -> List[List[Any]]: """Multiply every ``x`` / ``y`` parameter; useful when replaying on a new resolution.""" - scaled: List[list] = [] + scaled: List[List[Any]] = [] for action in actions: if len(action) < 2 or not isinstance(action[1], dict): scaled.append(action) @@ -83,8 +83,8 @@ def _action_name(action: object) -> object: return None -def dedupe_moves(actions: List[list], - move_commands: Optional[List[str]] = None) -> List[list]: +def dedupe_moves(actions: List[List[Any]], + move_commands: Optional[List[str]] = None) -> List[List[Any]]: """Collapse each run of consecutive mouse-move actions into its last one. A raw recording captures one action per cursor sample, so a single @@ -98,7 +98,7 @@ def dedupe_moves(actions: List[list], ``("AC_set_mouse_position",)``. """ moves = set(move_commands) if move_commands else set(_DEFAULT_MOVE_COMMANDS) - result: List[list] = [] + result: List[List[Any]] = [] for action in actions: name = _action_name(action) prev_name = _action_name(result[-1]) if result else None @@ -109,7 +109,7 @@ def dedupe_moves(actions: List[list], return result -def merge_sleeps(actions: List[list]) -> List[list]: +def merge_sleeps(actions: List[List[Any]]) -> List[List[Any]]: """Collapse each run of consecutive ``AC_sleep`` actions into one sleep. A recording often emits several back-to-back idle delays; replaying @@ -118,7 +118,7 @@ def merge_sleeps(actions: List[list]) -> List[list]: single sleep, leaving every other action untouched. Returns a new list; the input is not mutated. """ - result: List[list] = [] + result: List[List[Any]] = [] for action in actions: seconds = _numeric_seconds(action) previous = _numeric_seconds(result[-1]) if result else None @@ -146,7 +146,7 @@ def _numeric_seconds(action: Any) -> Optional[float]: return None -def _is_sleep(action: list) -> bool: +def _is_sleep(action: List[Any]) -> bool: return ( isinstance(action, list) and len(action) == 2 diff --git a/je_auto_control/utils/remote_desktop/multi_viewer.py b/je_auto_control/utils/remote_desktop/multi_viewer.py index 73c5b0254..efb0dfbbf 100644 --- a/je_auto_control/utils/remote_desktop/multi_viewer.py +++ b/je_auto_control/utils/remote_desktop/multi_viewer.py @@ -8,15 +8,16 @@ """ from __future__ import annotations +import os import secrets from dataclasses import dataclass from functools import partial import threading from datetime import datetime, timezone -from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Union try: - from aiortc.contrib.media import MediaRelay # type: ignore + from aiortc.contrib.media import MediaRelay except ImportError as exc: # pragma: no cover raise ImportError( "Multi-viewer host requires the 'webrtc' extra (aiortc).", @@ -32,6 +33,9 @@ ScreenVideoTrack, WebRTCConfig, ) +if TYPE_CHECKING: + from aiortc import MediaStreamTrack, RTCPeerConnection + SessionStateCallback = Callable[[str, str], None] SessionAuthCallback = Callable[[str], None] @@ -50,7 +54,7 @@ def __init__(self, config: WebRTCConfig) -> None: ) self._relay = MediaRelay() - def subscribe(self): + def subscribe(self) -> MediaStreamTrack: return self._relay.subscribe(self._track) @property @@ -103,8 +107,8 @@ def __init__(self, *, token: str, read_only: bool = False, permissions: Optional[SessionPermissions] = None, input_dispatcher: Optional[Callable[[Mapping[str, Any]], Any]] = None, - ip_whitelist: Optional[list] = None, - on_annotation: Optional[Callable[[dict], None]] = None, + ip_whitelist: Optional[List[str]] = None, + on_annotation: Optional[Callable[[Dict[str, Any]], None]] = None, on_session_state: Optional[SessionStateCallback] = None, on_session_authenticated: Optional[SessionAuthCallback] = None, on_pending_viewer: Optional[SessionPendingCallback] = None, @@ -126,7 +130,7 @@ def __init__(self, *, token: str, self._on_session_authenticated = on_session_authenticated self._on_pending_viewer = on_pending_viewer self._sessions: Dict[str, WebRTCDesktopHost] = {} - self._session_meta: Dict[str, dict] = {} + self._session_meta: Dict[str, Dict[str, str]] = {} self._session_tokens: Dict[str, object] = {} self._retiring: Dict[str, WebRTCDesktopHost] = {} self._creating: set[WebRTCDesktopHost] = set() @@ -140,7 +144,7 @@ def _capture_origin(self) -> Tuple[int, int]: source = self._source return source.capture_origin if source is not None else (0, 0) - def _annotate(self, data: dict) -> None: + def _annotate(self, data: Dict[str, Any]) -> None: """Pass a session's annotation on with the shared track's origin. A session relays the shared track, so its own origin is (0, 0). @@ -373,7 +377,7 @@ def disable_accept_viewer_audio_opus(self) -> None: except (RuntimeError, OSError) as error: autocontrol_logger.debug("disable accept audio: %r", error) - def broadcast_file(self, local_path, remote_name=None) -> int: + def broadcast_file(self, local_path: Union[str, os.PathLike[str]], remote_name: Optional[str] = None) -> int: """Push a file to every authenticated viewer; returns recipient count.""" with self._lock: sessions = list(self._sessions.values()) @@ -390,7 +394,7 @@ def broadcast_file(self, local_path, remote_name=None) -> int: # --- introspection ------------------------------------------------------ - def list_sessions(self) -> List[dict]: + def list_sessions(self) -> List[Dict[str, Any]]: with self._lock: return [ { @@ -409,12 +413,12 @@ def session_count(self) -> int: with self._lock: return len(self._sessions) - def screen_track(self): + def screen_track(self) -> Optional[ScreenVideoTrack]: """Return the underlying ``ScreenVideoTrack`` (or None if no source).""" with self._lock: return None if self._source is None else self._source._track - def first_session_pc(self): + def first_session_pc(self) -> Optional[RTCPeerConnection]: """Return the first session's RTCPeerConnection, or None.""" with self._lock: for host in self._sessions.values(): @@ -422,7 +426,7 @@ def first_session_pc(self): return host._pc return None - def session_pc(self, session_id: str): + def session_pc(self, session_id: str) -> Optional[RTCPeerConnection]: """Return the named session's RTCPeerConnection, or None if gone.""" with self._lock: host = self._sessions.get(session_id) @@ -439,7 +443,7 @@ def _require_session(self, session_id: str) -> WebRTCDesktopHost: # --- callback wrappers -------------------------------------------------- - def _wrap_state_callback(self, session_id: str, token: object = None): + def _wrap_state_callback(self, session_id: str, token: object = None) -> Callable[[str], None]: cb = self._on_session_state def _emit(state: str) -> None: if token is not None and self._session_tokens.get(session_id) is not token: @@ -478,7 +482,7 @@ def retire() -> None: autocontrol_logger.warning("session retirement remains pending") threading.Thread(target=retire, name="webrtc-prune", daemon=True).start() - def _wrap_auth_callback(self, session_id: str, token: object = None): + def _wrap_auth_callback(self, session_id: str, token: object = None) -> Callable[[], None]: cb = self._on_session_authenticated def _emit() -> None: with self._lock: @@ -494,7 +498,7 @@ def _emit() -> None: autocontrol_logger.debug("session auth cb: %r", error) return _emit - def _wrap_pending_callback(self, session_id: str, token: object = None): + def _wrap_pending_callback(self, session_id: str, token: object = None) -> Optional[Callable[[], None]]: cb = self._on_pending_viewer if cb is None: return None diff --git a/je_auto_control/utils/remote_desktop/signaling_server.py b/je_auto_control/utils/remote_desktop/signaling_server.py index 862352ae2..d44442be2 100644 --- a/je_auto_control/utils/remote_desktop/signaling_server.py +++ b/je_auto_control/utils/remote_desktop/signaling_server.py @@ -36,10 +36,10 @@ import time from dataclasses import dataclass, field from pathlib import Path -from typing import Annotated, Dict, List, Optional +from typing import Annotated, Awaitable, Callable, Dict, List, Optional try: - from fastapi import Depends, FastAPI, Header, HTTPException, Request + from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.staticfiles import StaticFiles @@ -159,7 +159,7 @@ class _AnswerIn(BaseModel): } -def _build_secret_dependency(shared_secret: Optional[str]): +def _build_secret_dependency(shared_secret: Optional[str]) -> Callable[[Optional[str]], None]: """Return a FastAPI dependency that enforces ``X-Signaling-Secret``.""" def _check( x_signaling_secret: Annotated[ @@ -206,7 +206,7 @@ def _maybe_mount_viewer(app: FastAPI, serve_web_viewer: bool) -> None: def _register_routes(app: FastAPI, store: "_SessionStore", - secret_dep) -> None: + secret_dep: Callable[..., object]) -> None: # Apply the auth dependency at the route layer so each handler's # signature stays free of plumbing parameters. The dependency # itself uses the recommended ``Annotated[Optional[str], Header(...)]`` @@ -215,12 +215,12 @@ def _register_routes(app: FastAPI, store: "_SessionStore", auth_only = [Depends(secret_dep)] @app.get("/health") - def _health() -> dict: + def _health() -> dict[str, str]: return {"status": "ok"} @app.post("/sessions/{host_id}/offer", responses=_OFFER_RESPONSES, dependencies=auth_only) - def _post_offer(host_id: str, body: _OfferIn) -> dict: + def _post_offer(host_id: str, body: _OfferIn) -> dict[str, bool]: _validate_host_id(host_id) _validate_sdp(body.sdp) if not store.upsert_offer(host_id, body.sdp): @@ -229,7 +229,7 @@ def _post_offer(host_id: str, body: _OfferIn) -> dict: @app.get("/sessions/{host_id}/offer", responses=_NOT_FOUND_RESPONSES, dependencies=auth_only) - def _get_offer(host_id: str) -> dict: + def _get_offer(host_id: str) -> dict[str, str]: _validate_host_id(host_id) sdp = store.fetch_offer(host_id) if sdp is None: @@ -239,7 +239,7 @@ def _get_offer(host_id: str) -> dict: @app.post("/sessions/{host_id}/answer", responses={**_VALIDATION_RESPONSES, **_NOT_FOUND_RESPONSES}, dependencies=auth_only) - def _post_answer(host_id: str, body: _AnswerIn) -> dict: + def _post_answer(host_id: str, body: _AnswerIn) -> dict[str, bool]: _validate_host_id(host_id) _validate_sdp(body.sdp) if not store.upsert_answer(host_id, body.sdp): @@ -249,7 +249,7 @@ def _post_answer(host_id: str, body: _AnswerIn) -> dict: @app.get("/sessions/{host_id}/answer", responses=_NOT_FOUND_RESPONSES, dependencies=auth_only) - def _get_answer(host_id: str) -> dict: + def _get_answer(host_id: str) -> dict[str, str]: _validate_host_id(host_id) sdp = store.fetch_answer(host_id) if sdp is None: @@ -258,7 +258,7 @@ def _get_answer(host_id: str) -> dict: @app.delete("/sessions/{host_id}", responses=_AUTH_RESPONSES, dependencies=auth_only) - def _delete(host_id: str) -> dict: + def _delete(host_id: str) -> dict[str, bool]: _validate_host_id(host_id) return {"deleted": store.delete(host_id)} @@ -302,14 +302,14 @@ def _guard_refusal(request: Request, shared_secret: Optional[str]) -> Optional[J def _register_body_guard(app: FastAPI, shared_secret: Optional[str]) -> None: @app.middleware("http") - async def _guard(request: Request, call_next): + async def _guard(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: refusal = _guard_refusal(request, shared_secret) return refusal if refusal is not None else await call_next(request) def _register_request_logging(app: FastAPI) -> None: @app.middleware("http") - async def _log_request(request: Request, call_next): + async def _log_request(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: response = await call_next(request) _LOG.info("%s %s -> %d", request.method, request.scope.get("path", ""), response.status_code) @@ -319,7 +319,7 @@ async def _log_request(request: Request, call_next): def create_app(shared_secret: Optional[str] = None, ttl_s: float = _DEFAULT_TTL_S, serve_web_viewer: bool = True, - cors_origins: Optional[list] = None, + cors_origins: Optional[List[str]] = None, config_store_path: Optional[str | Path] = None, allow_legacy_config_writes: bool = False, asset_store_path: Optional[str | Path] = None) -> FastAPI: @@ -364,10 +364,10 @@ def _build_arg_parser() -> argparse.ArgumentParser: return parser -def main(argv: Optional[list] = None) -> None: +def main(argv: Optional[List[str]] = None) -> None: """Entry point: parse args and start uvicorn.""" try: - import uvicorn # type: ignore + import uvicorn except ImportError as exc: # pragma: no cover raise SystemExit( "uvicorn missing; install with pip install " diff --git a/je_auto_control/utils/remote_desktop/webrtc_files.py b/je_auto_control/utils/remote_desktop/webrtc_files.py index db153d256..9df2d66c5 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_files.py +++ b/je_auto_control/utils/remote_desktop/webrtc_files.py @@ -31,7 +31,7 @@ from dataclasses import dataclass, field from hashlib import sha256 from pathlib import Path -from typing import Callable, Optional +from typing import Any, Callable, Optional from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.exception.exceptions import AutoControlException @@ -42,7 +42,7 @@ ) from je_auto_control.utils.remote_desktop.webrtc_transport import get_bridge from je_auto_control.utils.remote_desktop.webrtc_file_write import ( - _PinnedBridge, _channel_transfer, _checkpoint, _send_confirmed, + _Channel, _PinnedBridge, _channel_transfer, _checkpoint, _send_confirmed, ) @@ -84,7 +84,7 @@ def _redirected_on_windows(base: str) -> bool: return base[-1] in ". " or base.split(".")[0].upper() in _WINDOWS_DEVICE_NAMES -def _announced_size(raw) -> int: +def _announced_size(raw: Any) -> int: """Validate the envelope's ``size``: an int in 0..4 GiB.""" try: size = int(raw) @@ -95,7 +95,7 @@ def _announced_size(raw) -> int: return size -def _confirmed_begin(data: dict) -> bool: +def _confirmed_begin(data: dict[str, Any]) -> bool: version = data.get('commit') if version is None: return False @@ -106,7 +106,7 @@ def _confirmed_begin(data: dict) -> bool: return True -def _confirmed_end(current: dict, data: dict) -> None: +def _confirmed_end(current: dict[str, Any], data: dict[str, Any]) -> None: if not current['commit']: return if (data.get('transfer_id') != current['transfer_id'] or not valid_hex(data.get('sha256'), 64) @@ -123,7 +123,7 @@ def __init__(self, inbox_dir: Optional[Path] = None) -> None: self._inbox = (Path(inbox_dir) if inbox_dir else default_inbox_dir()).absolute() self._inbox.mkdir(parents=True, exist_ok=True) self._lock = threading.Lock() - self._current: Optional[dict] = None + self._current: Optional[dict[str, Any]] = None self._closed = False def abort(self, reason: str = 'receive permission ended') -> None: @@ -136,7 +136,7 @@ def close(self) -> None: self._closed = True self._abort_locked('receiver closed') - def handle_message(self, message, + def handle_message(self, message: object, on_progress: Optional[Callable[[int, int], None]] = None, on_done: Optional[Callable[[Path], None]] = None, on_error: Optional[Callable[[str], None]] = None, *, @@ -165,7 +165,9 @@ def handle_message(self, message, raise def _handle_envelope(self, raw: str, - on_done, on_error, on_receipt) -> None: + on_done: Optional[Callable[[Path], None]], + on_error: Optional[Callable[[str], None]], + on_receipt: Optional[Callable[[FileReceiveReceipt], None]]) -> None: try: data = json.loads(raw) except json.JSONDecodeError as error: @@ -183,7 +185,7 @@ def _handle_envelope(self, raw: str, if on_error is not None: on_error(reason) - def _handle_chunk(self, chunk: bytes, on_progress) -> None: + def _handle_chunk(self, chunk: bytes, on_progress: Optional[Callable[[int, int], None]]) -> None: with self._lock: current = self._current if self._closed or current is None: @@ -203,7 +205,7 @@ def _handle_chunk(self, chunk: bytes, on_progress) -> None: if on_progress is not None: on_progress(written, size) - def _begin(self, data: dict) -> None: + def _begin(self, data: dict[str, Any]) -> None: with self._lock: if self._closed: return @@ -229,7 +231,8 @@ def _begin(self, data: dict) -> None: "file transfer: receiving %s (%d bytes)", target, size, ) - def _finish(self, on_done, on_receipt, data) -> None: + def _finish(self, on_done: Optional[Callable[[Path], None]], + on_receipt: Optional[Callable[[FileReceiveReceipt], None]], data: dict[str, Any]) -> None: with self._lock: current = self._current if self._closed or current is None: @@ -266,7 +269,7 @@ def _abort_locked(self, reason: str) -> None: autocontrol_logger.warning("file transfer aborted: %s", reason) -def _discard_partial(current: dict) -> None: +def _discard_partial(current: dict[str, Any]) -> None: """Attempt both cleanup operations before preserving the first original interruption.""" failures = [] for operation in (current['fh'].close, lambda: current['part'].unlink(missing_ok=True)): @@ -300,7 +303,8 @@ def _send_options(channel: object, chunk_size: int, require_commit: bool) -> Non raise FileTransferError('require_commit must be a boolean') -def _source_plan(local_path, remote_name, chunk_size, peer) -> _SendPlan: +def _source_plan(local_path: str | os.PathLike[str], remote_name: Optional[str], chunk_size: int, + peer: Optional[ConfirmedPeer]) -> _SendPlan: path = Path(local_path) if not path.is_file(): raise FileTransferError(f'not a file: {local_path}') @@ -313,12 +317,12 @@ def _source_plan(local_path, remote_name, chunk_size, peer) -> _SendPlan: class FileTransferSender: """Send a single file from the caller side via the DataChannel.""" - def __init__(self, channel) -> None: + def __init__(self, channel: Optional[_Channel]) -> None: if channel is None: raise ValueError("file sender requires a DataChannel") self._channel = channel - def send(self, local_path, + def send(self, local_path: str | os.PathLike[str], remote_name: Optional[str] = None, chunk_size: int = _DEFAULT_CHUNK_SIZE, on_progress: Optional[Callable[[int, int], None]] = None, *, @@ -339,7 +343,8 @@ def send(self, local_path, except BaseException as error: # reason: preserve signals while containing ordinary channel failures raise _send_failure(error, require_commit=require_commit) from error - def _transfer(self, plan, on_progress, bridge, cancelled) -> None: + def _transfer(self, plan: _SendPlan, on_progress: Optional[Callable[[int, int], None]], + bridge: _PinnedBridge, cancelled: Optional[Callable[[], bool]]) -> None: guard = plan.peer.guard if plan.peer is not None else cancelled try: with commit_request(plan.peer, plan.transfer_id, plan.size) as request: @@ -367,7 +372,8 @@ def _transfer(self, plan, on_progress, bridge, cancelled) -> None: raise raise converted from error - def _chunks(self, plan, on_progress, bridge, cancelled) -> str: + def _chunks(self, plan: _SendPlan, on_progress: Optional[Callable[[int, int], None]], + bridge: _PinnedBridge, cancelled: Optional[Callable[[], bool]]) -> str: sent = 0 digest = sha256() try: diff --git a/je_auto_control/utils/visual_match/visual_match.py b/je_auto_control/utils/visual_match/visual_match.py index 15ffc515a..c58956855 100644 --- a/je_auto_control/utils/visual_match/visual_match.py +++ b/je_auto_control/utils/visual_match/visual_match.py @@ -15,7 +15,7 @@ import dataclasses import functools from dataclasses import asdict, dataclass -from typing import Any, Dict, List, Optional, Protocol, Sequence, TypeVar +from typing import Any, Callable, Dict, List, Optional, ParamSpec, Protocol, Sequence, Tuple, TypeVar from je_auto_control.utils.exception.exceptions import ( AutoControlFlatTemplateException, AutoControlScreenException, @@ -25,8 +25,11 @@ # cv2 method name -> the OpenCV constant is resolved lazily in _method(). _METHOD_NAMES = ("ccoeff_normed", "ccorr_normed", "sqdiff_normed") +_P = ParamSpec("_P") +_R = TypeVar("_R") -def _contain_cv2_error(fn): + +def _contain_cv2_error(fn: Callable[_P, _R]) -> Callable[_P, _R]: """Convert OpenCV's ``cv2.error`` into a contained AutoControlScreenException. A degenerate template/mask makes ``cv2.matchTemplate``/``minMaxLoc`` raise @@ -35,7 +38,7 @@ def _contain_cv2_error(fn): instead of being recorded as a failed match step. """ @functools.wraps(fn) - def wrapper(*args, **kwargs): + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: import cv2 try: return fn(*args, **kwargs) @@ -86,7 +89,7 @@ def _gray_code(channels: int, is_bgr: bool) -> int: return cv2.COLOR_BGR2GRAY if is_bgr else cv2.COLOR_RGB2GRAY -def _to_gray(source: ImageSource): +def _to_gray(source: ImageSource) -> Any: """Load a path / ndarray / PIL image as a 2-D grayscale ndarray. The channel order is tracked so luminance weights stay correct: images @@ -119,11 +122,11 @@ def _to_gray(source: ImageSource): return cv2.cvtColor(array, _gray_code(array.shape[2], is_bgr)) -def _grab_gray(region: Optional[Sequence[int]]): +def _grab_gray(region: Optional[Sequence[int]]) -> Any: return _grab_gray_with_origin(region)[0] -def _grab_gray_with_origin(region: Optional[Sequence[int]]): +def _grab_gray_with_origin(region: Optional[Sequence[int]]) -> Tuple[Any, int, int]: """``(gray screen, origin_x, origin_y)`` in the coordinate space of the mouse. Goes through ``monitor_layout.grab_logical`` rather than a plain screenshot: @@ -168,12 +171,12 @@ def _move_dict(moved: Dict[str, Any], origin_x: int, origin_y: int) -> Dict[str, def _haystack_gray(haystack: Optional[ImageSource], - region: Optional[Sequence[int]]): + region: Optional[Sequence[int]]) -> Any: return _haystack_gray_with_origin(haystack, region)[0] def _haystack_gray_with_origin(haystack: Optional[ImageSource], - region: Optional[Sequence[int]]): + region: Optional[Sequence[int]]) -> Tuple[Any, int, int]: """``(gray haystack, origin_x, origin_y)``. A caller-supplied ``haystack`` is its own coordinate space, so its origin is @@ -184,7 +187,7 @@ def _haystack_gray_with_origin(haystack: Optional[ImageSource], return _grab_gray_with_origin(region) -def _imread(path: str, flags: int): +def _imread(path: str, flags: int) -> Any: """Read an image file, tolerating non-ASCII paths. ``cv2.imread`` goes through the C locale on Windows and simply returns @@ -210,7 +213,7 @@ def _imread(path: str, flags: int): FLAT_TEMPLATE_STD = 1.0 -def _reject_flat_template(template) -> None: +def _reject_flat_template(template: Any) -> None: """Raise if ``template`` is too uniform for normalised correlation.""" import numpy as np if float(np.asarray(template, dtype=np.float64).std()) < FLAT_TEMPLATE_STD: @@ -219,7 +222,7 @@ def _reject_flat_template(template) -> None: "cannot locate it; crop a region with a pattern or text in it") -def _resize(template, scale: float): +def _resize(template: Any, scale: float) -> Any: import cv2 if abs(scale - 1.0) < 1e-9: return template @@ -231,7 +234,7 @@ def _resize(template, scale: float): @_contain_cv2_error def _score_map(template: ImageSource, haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, - method: str = "ccoeff_normed", scale: float = 1.0): + method: str = "ccoeff_normed", scale: float = 1.0) -> Tuple[Any, Any]: """Return ``(full correlation score map, scaled gray template)``. The map is oriented so higher = better for every method (``sqdiff_normed`` @@ -248,7 +251,7 @@ def _score_map(template: ImageSource, haystack: Optional[ImageSource] = None, *, def _score_map_with_origin(template: ImageSource, haystack: Optional[ImageSource] = None, *, region: Optional[Sequence[int]] = None, - method: str = "ccoeff_normed", scale: float = 1.0): + method: str = "ccoeff_normed", scale: float = 1.0) -> Tuple[Any, Any, int, int]: """:func:`_score_map` plus the frame's origin: ``(map, template, origin_x, origin_y)``. Add the origin to a map position to get a screen coordinate. Without it @@ -351,7 +354,7 @@ def _nms(matches: List[_BoxT], iou_threshold: float) -> List[_BoxT]: _NMS_CANDIDATE_MIN = 200 -def _select_candidates(result, min_score: float, width: int, height: int, +def _select_candidates(result: Any, min_score: float, width: int, height: int, max_results: int, origin: Sequence[int] = (0, 0), ) -> List[Match]: """Candidate matches >= ``min_score``, capped to the top scorers. @@ -409,7 +412,7 @@ def best_matches(template: ImageSource, *, min_score=-1.0, max_results=int(top_n)) -def _load_unchanged(source: ImageSource): +def _load_unchanged(source: ImageSource) -> Tuple[Any, bool]: """Return ``(array, is_bgr)`` keeping an alpha channel if present. ``is_bgr`` is True only for ``cv2.imread`` paths so the caller converts to @@ -427,7 +430,7 @@ def _load_unchanged(source: ImageSource): return np.asarray(source), False -def _template_and_mask(template: ImageSource, mask: Optional[ImageSource]): +def _template_and_mask(template: ImageSource, mask: Optional[ImageSource]) -> Tuple[Any, Any]: """Return (gray_template, uint8_mask_or_None); alpha is the implicit mask.""" import cv2 import numpy as np @@ -451,7 +454,7 @@ def _template_and_mask(template: ImageSource, mask: Optional[ImageSource]): def _masked_scores(template: ImageSource, mask: Optional[ImageSource], haystack: Optional[ImageSource], - region: Optional[Sequence[int]]): + region: Optional[Sequence[int]]) -> Tuple[Any, Any, int, int]: """Return (score_map, gray_template, origin_x, origin_y) for masked correlation. NaNs are zeroed. The origin is what to add to a map position; dropping it diff --git a/je_auto_control/wrapper/window_backends/macos_backend.py b/je_auto_control/wrapper/window_backends/macos_backend.py index 806186fce..6dfd7125d 100644 --- a/je_auto_control/wrapper/window_backends/macos_backend.py +++ b/je_auto_control/wrapper/window_backends/macos_backend.py @@ -29,11 +29,14 @@ so that half asks the accessibility API and is empty without the grant. """ import sys -from typing import Any, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.wrapper.window_backends.base import WindowManageBackend +if TYPE_CHECKING: + from je_auto_control.utils.exception.exceptions import AutoControlUnsupportedOperationException + #: ``ShowWindow`` codes with a macOS meaning; see the X11 backend for why the #: project spells show-state in Win32's numbering. SW_SHOWNORMAL = 1 @@ -62,7 +65,7 @@ def _probe(self) -> bool: # --- listing, via Quartz ----------------------------------------------- - def _window_info(self) -> List[dict]: + def _window_info(self) -> List[Dict[str, Any]]: """Every on-screen window Quartz will admit to, front-most first.""" import Quartz @@ -71,7 +74,7 @@ def _window_info(self) -> List[dict]: found = Quartz.CGWindowListCopyWindowInfo(options, Quartz.kCGNullWindowID) return list(found or []) - def _off_screen_info(self, on_screen: List[dict]) -> List[dict]: + def _off_screen_info(self, on_screen: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Application-layer windows Quartz knows of that are not on screen. Far more than the minimised ones: hidden applications, other Spaces @@ -87,7 +90,7 @@ def _off_screen_info(self, on_screen: List[dict]) -> List[dict]: if _number(info) and _number(info) not in shown and _is_application_layer(info)] - def _minimized_info(self, on_screen: List[dict]) -> List[dict]: + def _minimized_info(self, on_screen: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """The off-screen windows whose accessibility element says minimised. One ``AXWindows`` query per owning process, not per window. Without @@ -97,7 +100,7 @@ def _minimized_info(self, on_screen: List[dict]) -> List[dict]: import Quartz minimized = [] - elements: dict = {} + elements: Dict[int, List[Any]] = {} for info in self._off_screen_info(on_screen): pid = int(info.get(Quartz.kCGWindowOwnerPID, 0) or 0) if not pid: @@ -128,7 +131,7 @@ def list_windows(self) -> List[Tuple[int, str]]: windows.append((number, str(info.get(Quartz.kCGWindowName, "") or ""))) return windows - def _info_for(self, window_id: int) -> Optional[dict]: + def _info_for(self, window_id: int) -> Optional[Dict[str, Any]]: """Quartz's description of one window, on screen or not, or None. Asked for by id rather than searched for in the on-screen list, which @@ -192,7 +195,7 @@ def window_process_id(self, window_id: int) -> int: # --- acting, via the accessibility API --------------------------------- - def _ax_windows_for(self, pid: int) -> list: + def _ax_windows_for(self, pid: int) -> List[Any]: """Every accessibility window belonging to a process.""" import ApplicationServices as ax @@ -201,7 +204,7 @@ def _ax_windows_for(self, pid: int) -> list: application, "AXWindows", None) return [] if error or not windows else list(windows) - def _ax_window(self, window_id: int): + def _ax_window(self, window_id: int) -> Any: """The ``AXUIElement`` for a ``CGWindowID``, or None. Quartz ids and accessibility elements are separate namespaces with no @@ -218,7 +221,7 @@ def _ax_window(self, window_id: int): return None return _match_info(self._ax_windows_for(pid), info) - def _require_ax_window(self, window_id: int, operation: str): + def _require_ax_window(self, window_id: int, operation: str) -> Any: window = self._ax_window(window_id) if window is None: raise _refusal(operation, window_id) @@ -319,14 +322,14 @@ def move(self, window_id: int, x: int, y: int, # Refusing says so; a "success" that focused something else would not. -def _number(info: dict) -> int: +def _number(info: Dict[str, Any]) -> int: """The ``CGWindowID`` in a Quartz window-info dictionary, or 0.""" import Quartz return int(info.get(Quartz.kCGWindowNumber, 0) or 0) -def _is_application_layer(info: dict) -> bool: +def _is_application_layer(info: Dict[str, Any]) -> bool: """Whether a Quartz window sits on layer 0, where ordinary windows live.""" import Quartz @@ -342,7 +345,7 @@ def _ax_minimized(window: Any) -> bool: return bool(value) -def _match_info(candidates: list, info: dict): +def _match_info(candidates: List[Any], info: Dict[str, Any]) -> Any: """The accessibility window among ``candidates`` that ``info`` describes.""" import Quartz @@ -353,8 +356,8 @@ def _match_info(candidates: list, info: dict): str(info.get(Quartz.kCGWindowName, "") or "")) -def _best_match(candidates: list, wanted_origin: Tuple[int, int], - wanted_title: str): +def _best_match(candidates: List[Any], wanted_origin: Tuple[int, int], + wanted_title: str) -> Any: """Pick the accessibility window that is the Quartz window described. Frame is the stronger signal and is tried first: a title can be empty, or @@ -389,7 +392,7 @@ def _point(value: Any) -> Tuple[int, int]: return (int(point.x), int(point.y)) -def _refusal(operation: str, window_id: int): +def _refusal(operation: str, window_id: int) -> "AutoControlUnsupportedOperationException": from je_auto_control.utils.exception.exceptions import ( AutoControlUnsupportedOperationException, ) diff --git a/pyproject.toml b/pyproject.toml index 54c48e266..228406413 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -397,6 +397,7 @@ module = [ "je_auto_control.gui.adaptive_window", "je_auto_control.gui.admin_console_tab", "je_auto_control.gui.agent_observation_view", + "je_auto_control.gui.agent_tasks_tab", "je_auto_control.gui.agent_transfer_view", "je_auto_control.gui.assertions_tab", "je_auto_control.gui.audit_log_tab", @@ -404,6 +405,7 @@ module = [ "je_auto_control.gui.computer_use_tab", "je_auto_control.gui.config_sync_tab", "je_auto_control.gui.config_sync_worker", + "je_auto_control.gui.dag_tab", "je_auto_control.gui.data_source_tab", "je_auto_control.gui.device_matrix_tab", "je_auto_control.gui.diagnostics_capabilities", @@ -615,6 +617,7 @@ module = [ "je_auto_control.utils.agent_runtime.browser_transfers", "je_auto_control.utils.agent_runtime.browser_validation", "je_auto_control.utils.agent_runtime.browser_verification", + "je_auto_control.utils.agent_runtime.browser_workflows", "je_auto_control.utils.agent_runtime.budget_clock", "je_auto_control.utils.agent_runtime.cli", "je_auto_control.utils.agent_runtime.client", @@ -624,6 +627,7 @@ module = [ "je_auto_control.utils.agent_runtime.control_admission", "je_auto_control.utils.agent_runtime.dag_admission", "je_auto_control.utils.agent_runtime.dag_batch_recording", + "je_auto_control.utils.agent_runtime.dag_continuation_evidence", "je_auto_control.utils.agent_runtime.dag_continuation_plan", "je_auto_control.utils.agent_runtime.dag_jobs", "je_auto_control.utils.agent_runtime.dag_local", @@ -644,6 +648,7 @@ module = [ "je_auto_control.utils.agent_runtime.helper_owner_linux", "je_auto_control.utils.agent_runtime.images", "je_auto_control.utils.agent_runtime.input_journal", + "je_auto_control.utils.agent_runtime.input_ledger", "je_auto_control.utils.agent_runtime.jobs", "je_auto_control.utils.agent_runtime.local_evidence", "je_auto_control.utils.agent_runtime.manifest_evidence", @@ -655,6 +660,7 @@ module = [ "je_auto_control.utils.agent_runtime.native_recovery", "je_auto_control.utils.agent_runtime.native_scope", "je_auto_control.utils.agent_runtime.native_target", + "je_auto_control.utils.agent_runtime.native_worker", "je_auto_control.utils.agent_runtime.observation_refs", "je_auto_control.utils.agent_runtime.ollama", "je_auto_control.utils.agent_runtime.origin_policy", @@ -678,6 +684,7 @@ module = [ "je_auto_control.utils.agent_runtime.presence_pipe_linux", "je_auto_control.utils.agent_runtime.presence_pipe_windows", "je_auto_control.utils.agent_runtime.presence_platform", + "je_auto_control.utils.agent_runtime.presence_pool", "je_auto_control.utils.agent_runtime.presence_protocol", "je_auto_control.utils.agent_runtime.presence_quartz", "je_auto_control.utils.agent_runtime.presence_reader", @@ -703,10 +710,13 @@ module = [ "je_auto_control.utils.agent_runtime.retained_browser_runtime", "je_auto_control.utils.agent_runtime.retained_browser_target", "je_auto_control.utils.agent_runtime.retention", + "je_auto_control.utils.agent_runtime.routes", "je_auto_control.utils.agent_runtime.runner", "je_auto_control.utils.agent_runtime.runtime", "je_auto_control.utils.agent_runtime.runtime_lock", "je_auto_control.utils.agent_runtime.service", + "je_auto_control.utils.agent_runtime.skill_completion", + "je_auto_control.utils.agent_runtime.skill_execution", "je_auto_control.utils.agent_runtime.skill_parameters", "je_auto_control.utils.agent_runtime.skill_reauthorization", "je_auto_control.utils.agent_runtime.skill_recording", @@ -718,16 +728,20 @@ module = [ "je_auto_control.utils.agent_runtime.target_profiles", "je_auto_control.utils.agent_runtime.targets", "je_auto_control.utils.agent_runtime.task_handoff", + "je_auto_control.utils.agent_runtime.task_triggers", "je_auto_control.utils.agent_runtime.transfer_adoption", "je_auto_control.utils.agent_runtime.transfer_cache", "je_auto_control.utils.agent_runtime.transfer_destination_scope", + "je_auto_control.utils.agent_runtime.transfer_evidence", "je_auto_control.utils.agent_runtime.transfer_evidence_contract", "je_auto_control.utils.agent_runtime.transfer_evidence_management", "je_auto_control.utils.agent_runtime.transfer_files", + "je_auto_control.utils.agent_runtime.transfer_import", "je_auto_control.utils.agent_runtime.transfer_import_contract", "je_auto_control.utils.agent_runtime.transfer_import_files", "je_auto_control.utils.agent_runtime.transfer_import_jobs", "je_auto_control.utils.agent_runtime.transfer_import_ledger", + "je_auto_control.utils.agent_runtime.transfer_lineage", "je_auto_control.utils.agent_runtime.transfer_management", "je_auto_control.utils.agent_runtime.transfer_models", "je_auto_control.utils.agent_runtime.transfer_operations", @@ -736,6 +750,7 @@ module = [ "je_auto_control.utils.agent_runtime.transfer_records", "je_auto_control.utils.agent_runtime.transfer_routing", "je_auto_control.utils.agent_runtime.transfer_selection", + "je_auto_control.utils.agent_runtime.transfer_source", "je_auto_control.utils.agent_runtime.transfer_staging", "je_auto_control.utils.agent_runtime.transfer_transport", "je_auto_control.utils.agent_runtime.transport", @@ -748,6 +763,7 @@ module = [ "je_auto_control.utils.agent_runtime.wire_data", "je_auto_control.utils.agent_runtime.workflow_desktop", "je_auto_control.utils.agent_runtime.workflow_files", + "je_auto_control.utils.agent_runtime.workflow_specs", "je_auto_control.utils.agent_runtime.workflow_values", "je_auto_control.utils.agent_runtime.workflow_wait", "je_auto_control.utils.agent_runtime.workspace_scope", @@ -814,16 +830,7 @@ module = [ "je_auto_control.utils.clipboard_rich_formats", "je_auto_control.utils.clipboard_rich_formats.*", "je_auto_control.utils.codegen", - "je_auto_control.utils.codegen.candidate_archive", - "je_auto_control.utils.codegen.candidate_models", - "je_auto_control.utils.codegen.candidate_validation", - "je_auto_control.utils.codegen.journal_cli", - "je_auto_control.utils.codegen.journal_commands", - "je_auto_control.utils.codegen.journal_import", - "je_auto_control.utils.codegen.journal_selection", - "je_auto_control.utils.codegen.journal_source", - "je_auto_control.utils.codegen.journal_steps", - "je_auto_control.utils.codegen.robot_check", + "je_auto_control.utils.codegen.*", "je_auto_control.utils.color_match", "je_auto_control.utils.color_match.*", "je_auto_control.utils.color_region", @@ -1132,6 +1139,7 @@ module = [ "je_auto_control.utils.media_assert", "je_auto_control.utils.media_assert.*", "je_auto_control.utils.message_format", + "je_auto_control.utils.message_format.*", "je_auto_control.utils.modifier_state", "je_auto_control.utils.modifier_state.*", "je_auto_control.utils.monitor_layout", @@ -1191,6 +1199,7 @@ module = [ "je_auto_control.utils.postcondition", "je_auto_control.utils.postcondition.*", "je_auto_control.utils.preprocess", + "je_auto_control.utils.preprocess.*", "je_auto_control.utils.process_doc", "je_auto_control.utils.process_doc.*", "je_auto_control.utils.process_memory", @@ -1218,6 +1227,7 @@ module = [ "je_auto_control.utils.reading_flow", "je_auto_control.utils.reading_flow.*", "je_auto_control.utils.recording_edit", + "je_auto_control.utils.recording_edit.*", "je_auto_control.utils.recurrence", "je_auto_control.utils.recurrence.*", "je_auto_control.utils.redaction", @@ -1253,6 +1263,7 @@ module = [ "je_auto_control.utils.remote_desktop.jpeg_recorder_encrypted", "je_auto_control.utils.remote_desktop.lan_discovery", "je_auto_control.utils.remote_desktop.media_retirement", + "je_auto_control.utils.remote_desktop.multi_viewer", "je_auto_control.utils.remote_desktop.permissions", "je_auto_control.utils.remote_desktop.presence", "je_auto_control.utils.remote_desktop.protocol", @@ -1264,6 +1275,7 @@ module = [ "je_auto_control.utils.remote_desktop.session_quality_cache", "je_auto_control.utils.remote_desktop.session_recorder", "je_auto_control.utils.remote_desktop.signaling_client", + "je_auto_control.utils.remote_desktop.signaling_server", "je_auto_control.utils.remote_desktop.totp", "je_auto_control.utils.remote_desktop.transport", "je_auto_control.utils.remote_desktop.trust_list", @@ -1278,6 +1290,7 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_file_receive", "je_auto_control.utils.remote_desktop.webrtc_file_tasks", "je_auto_control.utils.remote_desktop.webrtc_file_write", + "je_auto_control.utils.remote_desktop.webrtc_files", "je_auto_control.utils.remote_desktop.webrtc_host_auth", "je_auto_control.utils.remote_desktop.webrtc_host_media", "je_auto_control.utils.remote_desktop.webrtc_inspector", @@ -1459,7 +1472,7 @@ module = [ "je_auto_control.utils.vision.frame_capture", "je_auto_control.utils.vision.vlm_api", "je_auto_control.utils.visual_match", - "je_auto_control.utils.visual_match.image_source", + "je_auto_control.utils.visual_match.*", "je_auto_control.utils.visual_regression", "je_auto_control.utils.visual_regression.*", "je_auto_control.utils.voice", @@ -1505,10 +1518,7 @@ module = [ "je_auto_control.wrapper.mobile_extensions", "je_auto_control.wrapper.platform_wrapper", "je_auto_control.wrapper.window_backends", - "je_auto_control.wrapper.window_backends.base", - "je_auto_control.wrapper.window_backends.null_backend", - "je_auto_control.wrapper.window_backends.windows_backend", - "je_auto_control.wrapper.window_backends.x11_backend", + "je_auto_control.wrapper.window_backends.*", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index 6a7dc8e88..f69a6fc7f 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -5,26 +5,11 @@ # (which may not grow). Each is debt, not an exemption: this list may only # shrink. Move a module into the strict block once mypy passes it there, and # delete its line. -je_auto_control.gui.agent_tasks_tab -je_auto_control.utils.agent_runtime.browser_workflows je_auto_control.utils.agent_runtime.completion_recovery je_auto_control.utils.agent_runtime.dag_batches je_auto_control.utils.agent_runtime.dag_continuation -je_auto_control.utils.agent_runtime.dag_continuation_evidence je_auto_control.utils.agent_runtime.evidence_handoff -je_auto_control.utils.agent_runtime.input_ledger -je_auto_control.utils.agent_runtime.native_worker -je_auto_control.utils.agent_runtime.presence_pool -je_auto_control.utils.agent_runtime.routes -je_auto_control.utils.agent_runtime.skill_completion -je_auto_control.utils.agent_runtime.skill_execution je_auto_control.utils.agent_runtime.task_authority je_auto_control.utils.agent_runtime.task_recovery je_auto_control.utils.agent_runtime.task_skills -je_auto_control.utils.agent_runtime.task_triggers -je_auto_control.utils.agent_runtime.transfer_evidence je_auto_control.utils.agent_runtime.transfer_host -je_auto_control.utils.agent_runtime.transfer_import -je_auto_control.utils.agent_runtime.transfer_lineage -je_auto_control.utils.agent_runtime.transfer_source -je_auto_control.utils.agent_runtime.workflow_specs diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 37652cd62..8e86d671e 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -14,7 +14,6 @@ # written later under the same name is new and therefore strict. # je_auto_control.android.client -je_auto_control.gui.dag_tab je_auto_control.gui.remote_desktop.webrtc_dialogs je_auto_control.gui.vlm_tab je_auto_control.ios.client @@ -22,7 +21,6 @@ je_auto_control.linux_wayland.libei je_auto_control.utils.accessibility.accessibility_api je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.actionability.actionability -je_auto_control.utils.codegen.codegen je_auto_control.utils.executor.action_executor je_auto_control.utils.json_schema.json_schema je_auto_control.utils.logging.logging_instance @@ -30,19 +28,11 @@ je_auto_control.utils.mcp_server.tools._handlers je_auto_control.utils.mcp_server.tools._handlers_locators je_auto_control.utils.mcp_server.tools._handlers_operations je_auto_control.utils.mcp_server.tools._handlers_system -je_auto_control.utils.message_format.message_format -je_auto_control.utils.preprocess.preprocess -je_auto_control.utils.recording_edit.editor je_auto_control.utils.remote_desktop.hw_codec -je_auto_control.utils.remote_desktop.multi_viewer -je_auto_control.utils.remote_desktop.signaling_server -je_auto_control.utils.remote_desktop.webrtc_files je_auto_control.utils.remote_desktop.webrtc_host je_auto_control.utils.remote_desktop.webrtc_viewer je_auto_control.utils.table_grid_fill.table_grid_fill je_auto_control.utils.tool_use_schema.schema je_auto_control.utils.vision.backends.anthropic_backend je_auto_control.utils.vision.backends.openai_backend -je_auto_control.utils.visual_match.visual_match je_auto_control.wrapper.backend_contract -je_auto_control.wrapper.window_backends.macos_backend From 1325f211b56bb2c13fdb2da7cea2b8487686c61f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 14:38:33 +0800 Subject: [PATCH 130/161] Declare that ac_wait_for_pixel needs three channels Annotating get_pixel let the contract sweep exercise this tool, and the sample it drew from the schema had one channel, which the handler has always refused. The schema now says so. --- CHANGELOG.md | 3 +++ docs/updates/2026-11-b.md | 8 ++++++++ docs/updates/README.md | 1 + je_auto_control/utils/mcp_server/tools/_factories.py | 3 ++- 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d1a6a31d..efe6c6a66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] +- MCP: `ac_wait_for_pixel`'s `target_rgb` schema declares `minItems: 3`, which the handler + already required (it raises on fewer channels and reads the first three of more). + - Approval gate: with RBAC on, the maker and the checker are the authenticated user. A `requester` or `approver` naming anyone else raises `AuthorizationError` (an empty one means that user), so one operator can no longer file a request and approve it under a second name. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 54d1623bc..c49de3dd9 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -737,3 +737,11 @@ - **Tests:** mypy with both flags: 781 errors in 31 files on each of win32 / linux / darwin, from 1,154 in 56, no file gaining an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; 22 related headless test files 429 passed, 1 skipped, and the multi-viewer and signaling tests 62 passed, 2 skipped after the ignores went; doc, file-length and complexity gates 41 passed. - **Files:** 25 modules under `je_auto_control/`, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `Progress.md`. - **Open items:** `Progress.md` › H (31 modules still outside the tier: 18 large ones, 12 with a real type error behind the annotation, and `wrapper/backend_contract`). + +## U-20261115-13 · 2026-11-15 · Dev CI red on ac_wait_for_pixel after get_pixel was annotated · #incident #mcp #typing + +- **What:** `test_adapter_registry_sweep.py::test_tool_result_survives_json[ac_wait_for_pixel]` failed on every `pytest-headless` square of `dev.yml` from 3711e013 (U-20261115-07) on: `ValueError: target_rgb must contain at least 3 channels`. That commit gave `wrapper.auto_control_screen.get_pixel` its return annotation, `Tuple[int, int, int]`, which is what lets the sweep stub a callee from its contract -- so the tool was swept for the first time, with arguments sampled from its schema, and `target_rgb` was declared as an array of any length: the sample had one item. The schema was wrong, not the annotation: `wait_for_pixel` refuses fewer than three channels and reads the first three of more. +- **Fix:** `target_rgb` declares `"minItems": 3` (not the shared `_RGB_SCHEMA`, which also caps it at three and would refuse an RGBA value the handler accepts). `CHANGELOG.md` records it. +- **Tests:** the sweep 1,898 passed, 6 skipped; `test_mcp_and_devices_audit.py`, `test_mcp_call_run.py`, `test_mcp_server.py` 147 passed. +- **Lesson:** an annotation can widen what a contract sweep covers. The typing stages ran the touched modules' own tests, not the sweeps that read annotations; the next stage runs `test_adapter_registry_sweep.py` too. +- **Files:** `utils/mcp_server/tools/_factories.py`, `CHANGELOG.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 9a03f84b4..1e9b4a3eb 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-13 | 2026-11-15 | Dev CI red on ac_wait_for_pixel after get_pixel was annotated | #incident #mcp #typing | [2026-11-b](2026-11-b.md) | | U-20261115-12 | 2026-11-15 | 25 more modules join the strict typing tier (11 to 20 fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-11 | 2026-11-15 | Box and Candidate get real types; two locator modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-10 | 2026-11-15 | One shared ImageSource alias; 22 image modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/mcp_server/tools/_factories.py b/je_auto_control/utils/mcp_server/tools/_factories.py index 00055256f..8b8ba60c1 100644 --- a/je_auto_control/utils/mcp_server/tools/_factories.py +++ b/je_auto_control/utils/mcp_server/tools/_factories.py @@ -241,7 +241,8 @@ def screen_tools() -> List[MCPTool]: input_schema=schema({ "x": {"type": "integer"}, "y": {"type": "integer"}, - "target_rgb": {"type": "array", + # wait_for_pixel refuses fewer than three channels (it reads the first three). + "target_rgb": {"type": "array", "minItems": 3, "items": {"type": "integer"}}, "tolerance": {"type": "integer"}, "timeout": {"type": "number"}, From fdf91d1015115b2aaaba9ccf8c49271111272cf3 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 14:39:52 +0800 Subject: [PATCH 131/161] Type the 18 largest modules and ignore non-string WebRTC control types The last annotation stage: 17 more modules join the strict tier and the not-yet-strict list is empty. Typing the WebRTC control dispatch showed that a peer sending a list as the message type crashed the callback. --- CHANGELOG.md | 4 + Progress.md | 2 +- architecture_explore.md | 80 +++--- docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + .../gui/remote_desktop/webrtc_dialogs.py | 52 ++-- .../accessibility/backends/windows_backend.py | 179 ++++++------- .../agent_runtime/completion_recovery.py | 114 +++++---- .../utils/agent_runtime/dag_batches.py | 47 ++-- .../utils/agent_runtime/dag_continuation.py | 58 +++-- .../utils/agent_runtime/evidence_handoff.py | 62 +++-- .../utils/agent_runtime/task_authority.py | 54 ++-- .../utils/agent_runtime/task_recovery.py | 70 ++--- .../utils/agent_runtime/task_skills.py | 72 +++--- .../utils/agent_runtime/transfer_host.py | 47 ++-- .../utils/executor/action_executor.py | 128 +++++----- .../utils/json_schema/json_schema.py | 60 ++--- .../utils/mcp_server/tools/_handlers.py | 169 ++++++------ .../mcp_server/tools/_handlers_locators.py | 81 +++--- .../mcp_server/tools/_handlers_operations.py | 217 +++++++++------- .../mcp_server/tools/_handlers_system.py | 121 ++++----- .../utils/remote_desktop/webrtc_host.py | 66 ++--- .../utils/remote_desktop/webrtc_viewer.py | 66 ++--- pyproject.toml | 241 +----------------- .../headless/test_webrtc_ctrl_message_type.py | 51 ++++ test/verify/typing_not_yet_strict.txt | 8 - test/verify/typing_strict_baseline.txt | 9 - 27 files changed, 1021 insertions(+), 1046 deletions(-) create mode 100644 test/unit_test/headless/test_webrtc_ctrl_message_type.py diff --git a/CHANGELOG.md b/CHANGELOG.md index efe6c6a66..2a0e97199 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- Remote desktop: a WebRTC control message whose `type` is not a string (`{"type": []}`) is + ignored by the host and the viewer; it raised `TypeError: unhashable type` from the data + channel's message callback. + - MCP: `ac_wait_for_pixel`'s `target_rgb` schema declares `minItems: 3`, which the handler already required (it raises on fewer channels and reads the first three of more). diff --git a/Progress.md b/Progress.md index 0b90960b7..b4ad60963 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層已收進三平台都通過的舊模組(U-20261115-05~12,共 1,494 個)。仍缺:`test/verify/typing_strict_baseline.txt` 23 個與 `typing_not_yet_strict.txt` 8 個模組要先修到通過`disallow_untyped_defs`/`disallow_any_generics`:18 個每檔 20 個以上錯誤的大檔(三平台約 780 個錯誤,最多的是 MCP handler 模組、`action_executor.py`、`agent_runtime` 的 recovery/skills 與 Windows accessibility backend),`wrapper/backend_contract` 的 `MouseKeycode = Any`(依平台寫成 tuple/int 會露出 `platform_wrapper` 各分支匯入的 `mouse_keys_table` 型別不同,其中一個是 `dict[str, str]`,要先重整 wrapper 層),另有 12 個補上正確註記會露出真的型別錯誤:`android/client.py`、`ios/client.py`、兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開)、`linux_wayland/libei.py`、`utils/logging/logging_instance.py`、`utils/accessibility/accessibility_api.py`、`utils/actionability/actionability.py`、`utils/table_grid_fill/table_grid_fill.py`、`utils/tool_use_schema/schema.py`、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`);以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層收進所有補註記就能通過的模組(U-20261115-05~14,共 1,511 個;`typing_not_yet_strict.txt` 已清空)。仍缺:`test/verify/typing_strict_baseline.txt` 剩 14 個,每個都要改程式碼而不只是補註記——`android/client.py`、`ios/client.py` 與兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開,mypy 只接受 `tuple[Any, ...]`,改成 `(OSError, ...) + _sdk_errors()` 才能精確)、`linux_wayland/libei.py`(`oeffis.connect_eis_fd` 的回傳型別)、`utils/logging/logging_instance.py`(`FileHandler._open` 與 `open()` 的 `IO[Any]`)、`utils/accessibility/accessibility_api.py`(`tuple(el.bounds)` 不是 4-tuple)、`utils/actionability/actionability.py`(`visible` 不收窄 `bbox`)、`utils/table_grid_fill/table_grid_fill.py`(`None in (...)` 不收窄)、`utils/tool_use_schema/schema.py`(`Mapping` 傳給宣告 `dict` 的 `execute_one`)、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None,真的可能除以 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`)、`utils/mcp_server/tools/_handlers.py` 的 `tween_drag`(`tuple(start)` 不是 `Tuple[int, int]`)、`wrapper/backend_contract.py` 的 `MouseKeycode = Any`(依平台寫成 tuple/int 會露出 `platform_wrapper` 各分支匯入的 `mouse_keys_table` 型別不同,其中一個是 `dict[str, str]`,要先重整 wrapper 層);以及完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 5eee3cd3f..a72909fbd 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 237,894 | +| 程式碼總行數 | 238,044 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,562 行。 +> 25 個套件、約 19,570 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -304,7 +304,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,756 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,764 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | | `utils/input_macro/` | 481 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | @@ -463,12 +463,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,926 行。 +> 16 個套件、約 4,929 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a11y_audit/` | 362 | 以無障礙樹 + OCR 進行無障礙與 i18n 稽核 | -| `utils/accessibility/` | 3,375 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | +| `utils/accessibility/` | 3,378 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | | `utils/ax_text/` | 105 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | @@ -516,13 +516,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 53,031 行。 +> 14 個套件、約 53,158 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,254 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 26,030 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 26,084 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -530,21 +530,21 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,241 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/mcp_server/` | 22,314 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | | `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 666 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,255 行。 +> 6 個套件、約 32,263 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,927 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,935 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -744,11 +744,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | | `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,756 行)— 執行核心 +#### `utils/executor/`(10,764 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `action_executor.py` | 8,679 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | +| `action_executor.py` | 8,687 | `Executor` 類別與 `event_dict` 分派表(774 個指令),另含數百個把 utils 能力接成指令的 adapter 函式;全域單例 `executor` 與 `add_command_to_executor()` 擴充點。 | | `flow_control.py` | 727 | 真正的流程控制:`AC_loop`/`AC_for_each`/`AC_while_*`/`AC_if_*`/`AC_try`/`AC_retry`/`AC_parallel`/`AC_define_macro`/`AC_call_macro`/變數指令(`AC_set_var`/`AC_get_var`/`AC_inc_var`)。`LoopBreak`/`LoopContinue` 以例外實作。34 個區塊指令的分派表 `BLOCK_COMMANDS` 也在這裡,含下一列匯入的資料來源指令。 | | `flow_data_commands.py` | 275 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | | `action_schema.py` | 225 | action list 的結構驗證:形狀、參數型別、未知指令拒絕。單一走訪同時支援兩種消費方式:`validate_actions()` 遇到第一個問題就拋、`unknown_command_names()` 收齊全部不認得的名字(REST `/execute` 用它回 400)。 | @@ -756,16 +756,16 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,241 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,314 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `tools/_factories.py` | 9,389 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | -| `tools/_handlers.py` | 547 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | +| `tools/_factories.py` | 9,390 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | +| `tools/_handlers.py` | 566 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | | `tools/_handlers_qa.py` | 619 | 同一種 adapter,QA 主題:斷言 DSL、資料驅動、SQL/PDF/郵件/HTTP 步驟、codegen、視覺回歸、狀態機、flaky 偵測與隔離、suite runner、無障礙稽核、裝置矩陣、媒體斷言。從 `_handlers.py` 依主題拆出的第一塊(750 行上限);兩者互不引用。 | | `tools/_handlers_input.py` | 221 | 同一種 adapter,輸入主題:滑鼠、鍵盤、虛擬手把(ViGEm)。 | | `tools/_handlers_screen.py` | 352 | 同一種 adapter,螢幕主題:擷取、像素、影像與文字搜尋、螢幕錄影。 | -| `tools/_handlers_system.py` | 592 | 同一種 adapter,桌面工作階段:視窗(狀態操作依正規化的後端成敗回覆)、行程與 shell、開檔、閒置與睡眠、音量、鎖定、輸入法狀態、欄位驗證與重試、色彩對比、變更排序、元件分類、剪貼簿。 | +| `tools/_handlers_system.py` | 599 | 同一種 adapter,桌面工作階段:視窗(狀態操作依正規化的後端成敗回覆)、行程與 shell、開檔、閒置與睡眠、音量、鎖定、輸入法狀態、欄位驗證與重試、色彩對比、變更排序、元件分類、剪貼簿。 | | `tools/_handlers_runs.py` | 124 | 同一種 adapter,執行主題:executor、執行歷史、錄製、動作檔。 | | `tools/_template_candidates.py` | 91 | 五個候選樣板工具,含縮圖、固定樣本驗證、路徑根目錄與取消。 | | `tools/_healing_source.py` | 41 | 原始步驟唯讀查閱工具,含進度、取消與目前路徑政策。 | @@ -788,8 +788,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `tools/_handlers_desktop_executor.py` | 225 | 35 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_mobile_executor.py` | 135 | 10 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | | `tools/_handlers_vision_executor.py` | 564 | 70 個領域委派;保留函式內 executor 匯入、參數預設與轉送契約,使用 strict typing。 | -| `tools/_handlers_locators.py` | 436 | 同一種 adapter,定位主題:無障礙樹、智慧等待、自我修復、螢幕觀察、座標空間、視覺與 OCR、影像去重、元件倉庫、A/B 定位。 | -| `tools/_handlers_operations.py` | 656 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | +| `tools/_handlers_locators.py` | 449 | 同一種 adapter,定位主題:無障礙樹、智慧等待、自我修復、螢幕觀察、座標空間、視覺與 OCR、影像去重、元件倉庫、A/B 定位。 | +| `tools/_handlers_operations.py` | 689 | 同一種 adapter,營運主題:agent 與其記憶/追蹤、治理與合規、成本與遙測、失敗掛鉤、看門狗、速率限制、檢查點、核可、產物與資產、測試選擇與分片、佇列與 saga。 | | `server.py` | 630 | JSON-RPC 2.0 over stdio 的最小 MCP 伺服器:連線範圍狀態、行內/併發分派、resource/prompt 處理器;`tools/call` 的准入、執行與稽核在 `_tool_calls.py`;握手時代的方法表(`_run_method`),兩個協定時代的逐請求分派在 `_stateless.py`;工具清單/session profile 在 `_disclosure_server.py`。 | | `_tool_calls.py` | 179 | `tools/call` 路徑(`ToolCallMixin`):請求、RBAC、揭露目錄、schema、參數政策、限流與破壞性確認的准入,以 `ToolCallContext` 執行、寫稽核並轉成結果;失敗截圖在呼叫時才向 `server` 取 `_capture_error_screenshot`。 | | `http_transport.py` | 623 | MCP 的 HTTP 傳輸;宣告 2026-07-28 的請求走 `_http_stateless.py` 的標頭規則,不發 session。 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,927 行/77 檔) +#### `utils/remote_desktop/`(16,935 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -826,8 +826,8 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `webrtc_host.py` | 746 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | -| `webrtc_viewer.py` | 736 | WebRTC 檢視端:接收視訊並送出輸入。 | +| `webrtc_host.py` | 750 | WebRTC 主機:串流螢幕視訊並接受檢視端輸入;session 生命週期、DataChannel 接線、檔案收發。 | +| `webrtc_viewer.py` | 740 | WebRTC 檢視端:接收視訊並送出輸入。 | | `webrtc_retirement.py` | 186 | 序列化 peer 世代、保留未完成的停止 future,區分待完成與失敗清理。 | | `webrtc_media_owners.py` | 249 | 保留 peer 媒體建構失敗及未完成子資源,提供快取的 slot 清理結果。 | | `webrtc_peer_cleanup.py` | 166 | 逐項清理 host/viewer 的原始資源,保留失敗項目並等候影格任務結束。 | @@ -1045,7 +1045,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(26,030 行/182 檔) +#### `utils/agent_runtime/`(26,084 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1079,13 +1079,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `client.py` | 93 | Shared local service client for GUI, CLI, MCP and Python task operations. | | `commands.py` | 135 | One command catalogue shared by executor, MCP and the visual script editor. | | `completion_contract.py` | 63 | Shared completion evidence and retirement checks without service or DAG transport dependencies. | -| `completion_recovery.py` | 660 | Explicit post-effect completion review with private lineage and permanent read-only targets. | +| `completion_recovery.py` | 672 | Explicit post-effect completion review with private lineage and permanent read-only targets. | | `context.py` | 74 | Host-owned operation context shared with local workers, never serialized model authority. | | `control_admission.py` | 29 | Closed runtime stop requests share a bounded reserve separate from ordinary HTTP polling. | | `dag_admission.py` | 80 | Trusted local DAG admission records bind original ownership, caller authority and a live attempt. | | `dag_batch_recording.py` | 93 | Durable dispatch claims and independent destination verification for one managed DAG batch. | -| `dag_batches.py` | 366 | Owner-scoped graph lifecycle and runtime-owned task/artifact host adapters. | -| `dag_continuation.py` | 339 | Whole-graph review and one-shot continuation approval never replay a possible delivery. | +| `dag_batches.py` | 369 | Owner-scoped graph lifecycle and runtime-owned task/artifact host adapters. | +| `dag_continuation.py` | 345 | Whole-graph review and one-shot continuation approval never replay a possible delivery. | | `dag_continuation_evidence.py` | 171 | Bounded read-only destination evidence for explicit whole-batch continuation decisions. | | `dag_continuation_plan.py` | 91 | Explicit per-node decisions preserve graph scope and never reset a possible delivery claim. | | `dag_jobs.py` | 140 | Service-owned durable DAG deliveries never replay an interrupted coordinator attempt. | @@ -1098,7 +1098,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `errors.py` | 23 | Typed failures for managed tasks, observations and control ownership. | | `evidence.py` | 215 | Service-owned task provenance, redacted artifacts and thirty-day metadata retention. | | `evidence_cache.py` | 92 | Database-bound evidence paths never turn historical journal references into filesystem ownership. | -| `evidence_handoff.py` | 368 | Explicit revocable evidence-only grants preserve ordinary task ownership and input isolation. | +| `evidence_handoff.py` | 376 | Explicit revocable evidence-only grants preserve ordinary task ownership and input isolation. | | `file_dialog_scope.py` | 62 | Bind the existing file-dialog executor to one task-owned window and rooted absolute path. | | `file_target.py` | 35 | A noninteractive target for rooted archive workflows, separate from desktop input. | | `handoff_records.py` | 116 | Fixed-family handoff records and host-only access to explicitly granted evidence. | @@ -1185,10 +1185,10 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `target_factory.py` | 27 | Create inert managed adapters from host profiles; SDKs and native resources stay lazy. | | `target_profiles.py` | 205 | Durable target profiles, live controls and explicit dependency diagnostics separate from native evidence. | | `targets.py` | 193 | Explicit target adapters; native imports occur only during requested operations. | -| `task_authority.py` | 316 | Trusted source-owner recovery admission and live owner/reviewer authority checks. | +| `task_authority.py` | 322 | Trusted source-owner recovery admission and live owner/reviewer authority checks. | | `task_handoff.py` | 82 | Real non-DAG source identity for explicit completion evidence, without fabricated admission. | -| `task_recovery.py` | 484 | Review stopped tasks and create one explicitly approved successor without replay. | -| `task_skills.py` | 373 | Immutable managed skill candidates require a verified trial and explicit version publication. | +| `task_recovery.py` | 494 | Review stopped tasks and create one explicitly approved successor without replay. | +| `task_skills.py` | 377 | Immutable managed skill candidates require a verified trial and explicit version publication. | | `task_triggers.py` | 272 | Durable preauthorized task bindings with owner refresh, bounded backlog and event deduplication. | | `transfer_destination_scope.py` | 33 | Injected destination profiles and live origin ceilings confine reviewed import directories. | | `transfer_import_contract.py` | 83 | Closed destination management envelopes carry opaque foreign paths without forwarding local authority. | @@ -1199,7 +1199,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `transfer_staging.py` | 171 | Journal exclusive staging identities and retire only recognized files and empty directories. | | `transfer_cache.py` | 34 | One runtime-derived private blob cache never accepts a public path or configuration account selector. | | `transfer_files.py` | 111 | Bounded source-file descriptors and verified chunks remain private until export consent commits. | -| `transfer_host.py` | 202 | Host-injected source authority and destination scope keep task policy out of transfer leaves. | +| `transfer_host.py` | 207 | Host-injected source authority and destination scope keep task policy out of transfer leaves. | | `transfer_lineage.py` | 156 | Bind artifact authority to real bounded recovery ancestry and original accepted DAG admission. | | `transfer_models.py` | 191 | Portable criterion selections and immutable descriptors for reviewed outcome transfers. | | `transfer_privacy.py` | 53 | Exclude actual host private stores and evidence roots without reserving ordinary output basenames. | @@ -1391,7 +1391,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 367 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,573 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,577 | 見下。 | | presence | `presence_tab.py` | 171 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | | admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | @@ -1409,7 +1409,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,573 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,577 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1421,7 +1421,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `folder_sync_io.py` | 130 | Bind confirmed folder sends, cancellation and frozen receipts to one captured GUI owner. | | `webrtc_panel_state.py` | 165 | 主機/檢視端 mixin 的具體 Qt 狀態與 slot 型別契約;不新增執行時預設值。 | | `webrtc_panel.py` | 423 | WebRTC 子分頁主體。 | -| `webrtc_dialogs.py` | 529 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | +| `webrtc_dialogs.py` | 533 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | | `connection_screen.py` | 723 | Quick Connect —— AnyDesk 風格單畫面入口。 | @@ -1549,13 +1549,13 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,928 | -| `utils/mcp_server/` | 63 | 22,241 | -| `utils/remote_desktop/` | 77 | 16,927 | -| `utils/executor/` | 11 | 10,756 | +| `gui/` | 166 | 43,932 | +| `utils/mcp_server/` | 63 | 22,314 | +| `utils/remote_desktop/` | 77 | 16,935 | +| `utils/executor/` | 11 | 10,764 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | -| `utils/accessibility/` | 16 | 3,375 | +| `utils/accessibility/` | 16 | 3,378 | | `wrapper/` | 25 | 6,053 | | `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,228 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,660 | -| **總計** | **1,533** | **237,149** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,714 | +| **總計** | **1,533** | **237,299** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c49de3dd9..53bc2b429 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -745,3 +745,11 @@ - **Tests:** the sweep 1,898 passed, 6 skipped; `test_mcp_and_devices_audit.py`, `test_mcp_call_run.py`, `test_mcp_server.py` 147 passed. - **Lesson:** an annotation can widen what a contract sweep covers. The typing stages ran the touched modules' own tests, not the sweeps that read annotations; the next stage runs `test_adapter_registry_sweep.py` too. - **Files:** `utils/mcp_server/tools/_factories.py`, `CHANGELOG.md`. + +## U-20261115-14 · 2026-11-15 · The 18 largest modules typed; a non-string WebRTC control type is ignored · #done #typing #remote-desktop + +- **What:** the last annotation stage of `Progress.md` › H: the 18 files with more than 20 strict errors (686): the MCP handler modules, `action_executor.py`, the `agent_runtime` recovery / DAG / evidence / authority modules, the Windows accessibility backend, the WebRTC host and viewer, `json_schema` and `gui/remote_desktop/webrtc_dialogs.py`. +- **Change:** annotation-only edits in all 18. Worth knowing: `action_executor` narrows public signatures to what callers pass (`execute_action(action_list: List[Any] | Dict[str, Any], step_callback: Optional[Callable[[List[Any]], None]])`, `execute_files(List[str])`, `known_commands() -> Set[str]`, `event_dict: Dict[str, Callable[..., Any]]`) and gains a `TYPE_CHECKING` block; `json_schema.Schema` is `Union[Dict[str, Any], bool]`, which is what a JSON Schema is; `windows_backend.py` reaches exactly 750 lines (an `_Opt = Optional[str]` alias and one joined `return` keep it there), `webrtc_host.py` 750 and `webrtc_viewer.py` 740; `webrtc_host._apply_renegotiate_answer` takes `peer: Any` (the precise type gives a false `union-attr` after the identity check). Two spots exposed a real defect: the WebRTC host's and viewer's control dispatch looked `data.get("type")` up in a dict, so `{"type": []}` from a peer raised `TypeError: unhashable type` inside the data channel's callback; both now ignore a non-string type, which lets their tables be typed `dict[str, Callable[[dict[str, Any]], ...]]`. `_handlers.tween_drag` stays unannotated (`tuple(start)` is not `Tuple[int, int]`). 17 modules are promoted (strict tier 1,494 → 1,511; baseline 23 → 14; `typing_not_yet_strict.txt` 8 → 0, now empty). +- **Tests:** mypy with both flags: 57 errors in 14 files on each of win32 / linux / darwin, from 781 in 31 -- the 14 are exactly the modules `Progress.md` › H lists, and no file gained an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; the agent's 36 related test files 1,044 passed, 2 skipped; new `test_webrtc_ctrl_message_type.py` (4 of 13 fail on the old code, 13 pass) with the WebRTC file-transfer, annotation-screen and retirement tests 147 passed; `test_adapter_registry_sweep.py` 1,911 passed, 6 skipped; doc, file-length and complexity gates passed. +- **Files:** 18 modules under `je_auto_control/`, the new test, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `CHANGELOG.md`, `Progress.md`. +- **Open items:** `Progress.md` › H (14 modules that need a code change, not an annotation). diff --git a/docs/updates/README.md b/docs/updates/README.md index 1e9b4a3eb..8f72e58cc 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-14 | 2026-11-15 | The 18 largest modules typed; a non-string WebRTC control type is ignored | #done #typing #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261115-13 | 2026-11-15 | Dev CI red on ac_wait_for_pixel after get_pixel was annotated | #incident #mcp #typing | [2026-11-b](2026-11-b.md) | | U-20261115-12 | 2026-11-15 | 25 more modules join the strict typing tier (11 to 20 fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-11 | 2026-11-15 | Box and Candidate get real types; two locator modules join the strict tier | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/remote_desktop/webrtc_dialogs.py b/je_auto_control/gui/remote_desktop/webrtc_dialogs.py index 162fc3e46..2f8a626a9 100644 --- a/je_auto_control/gui/remote_desktop/webrtc_dialogs.py +++ b/je_auto_control/gui/remote_desktop/webrtc_dialogs.py @@ -7,9 +7,10 @@ """ from __future__ import annotations -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, Callable, Optional -from PySide6.QtCore import Qt, Signal +from PySide6.QtCore import QPoint, Qt, Signal +from PySide6.QtGui import QCloseEvent, QDragEnterEvent, QDragMoveEvent, QDropEvent, QKeyEvent from PySide6.QtWidgets import ( QAbstractItemView, QDialog, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMenu, @@ -29,6 +30,9 @@ KnownHostsDialog, ) +if TYPE_CHECKING: + from je_auto_control.utils.remote_desktop.audit_log import AuditLog + class PendingViewerDialog(QDialog): """Three-button accept/reject prompt with an optional 'trust' choice. @@ -95,7 +99,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self.setSelectionMode(self.SelectionMode.SingleSelection) - def populate(self, entries: list) -> None: + def populate(self, entries: list[dict[str, Any]]) -> None: self.clear() for entry in entries: viewer_id = entry.get("viewer_id", "") @@ -107,7 +111,7 @@ def populate(self, entries: list) -> None: item.setData(Qt.ItemDataRole.UserRole, viewer_id) self.addItem(item) - def keyPressEvent(self, event) -> None: # noqa: N802 Qt override + def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802 Qt override if event.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace): item = self.currentItem() if item is not None: @@ -118,7 +122,7 @@ def keyPressEvent(self, event) -> None: # noqa: N802 Qt override super().keyPressEvent(event) -def _format_size(value) -> str: +def _format_size(value: Any) -> str: """``1,234`` for a byte count, or the value as the host sent it.""" try: return f"{int(value):,}" @@ -141,7 +145,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self._on_context_menu) - def _on_context_menu(self, position) -> None: + def _on_context_menu(self, position: QPoint) -> None: entry = self.selected_entry() if entry is None: return @@ -164,7 +168,7 @@ def _on_context_menu(self, position) -> None: elif chosen_act is delete_action: self.deleted.emit(entry) - def populate(self, entries: list, tag_filter: str = "") -> None: + def populate(self, entries: list[dict[str, Any]], tag_filter: str = "") -> None: if tag_filter: entries = [ e for e in entries @@ -185,7 +189,7 @@ def populate(self, entries: list, tag_filter: str = "") -> None: self.addItem(item) @staticmethod - def _format_entry(entry: dict) -> str: + def _format_entry(entry: dict[str, Any]) -> str: """Build the one-line display label for an address-book entry.""" label = entry.get("label", "") or "(unnamed)" host_id = entry.get("host_id", "") @@ -196,19 +200,19 @@ def _format_entry(entry: dict) -> str: suffix = f" ({last_used})" if last_used else "" return f"{star}{label} - {host_id}{tag_str}{suffix}" - def selected_entry(self) -> Optional[dict]: + def selected_entry(self) -> Optional[dict[str, Any]]: item = self.currentItem() if item is None: return None entry = item.data(Qt.ItemDataRole.UserRole) return dict(entry) if isinstance(entry, dict) else None - def _on_double_click(self, item) -> None: + def _on_double_click(self, item: QListWidgetItem) -> None: entry = item.data(Qt.ItemDataRole.UserRole) if isinstance(entry, dict): self.chosen.emit(dict(entry)) - def keyPressEvent(self, event) -> None: # noqa: N802 Qt override + def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802 Qt override if event.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace): entry = self.selected_entry() if entry is not None: @@ -254,15 +258,15 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self._show_context_menu) - def selected_names(self) -> list: - names = [] + def selected_names(self) -> list[str]: + names: list[str] = [] for row in sorted({i.row() for i in self.selectedIndexes()}): item = self.item(row, 0) if item is not None: names.append(item.text()) return names - def populate(self, files: list, format_mtime) -> None: + def populate(self, files: list[Any], format_mtime: Callable[[Any], str]) -> None: """Replace contents. ``format_mtime(value) -> str`` formats the column. ``files`` comes from the remote host: an entry that is not an object @@ -280,18 +284,18 @@ def populate(self, files: list, format_mtime) -> None: # --- drag-and-drop ------------------------------------------------------ - def _accept_url_drag(self, event) -> None: + def _accept_url_drag(self, event: QDragMoveEvent) -> None: """Shared drag handler: accept iff the payload carries file URLs.""" if event.mimeData().hasUrls(): event.acceptProposedAction() - def dragEnterEvent(self, event) -> None: # noqa: N802 Qt override + def dragEnterEvent(self, event: QDragEnterEvent) -> None: # noqa: N802 Qt override self._accept_url_drag(event) - def dragMoveEvent(self, event) -> None: # noqa: N802 Qt override + def dragMoveEvent(self, event: QDragMoveEvent) -> None: # noqa: N802 Qt override self._accept_url_drag(event) - def dropEvent(self, event) -> None: # noqa: N802 Qt override + def dropEvent(self, event: QDropEvent) -> None: # noqa: N802 Qt override urls = event.mimeData().urls() from pathlib import Path as _Path paths = [ @@ -305,7 +309,7 @@ def dropEvent(self, event) -> None: # noqa: N802 Qt override # --- context menu ------------------------------------------------------- - def _show_context_menu(self, position) -> None: + def _show_context_menu(self, position: QPoint) -> None: names = self.selected_names() if not names: return @@ -327,7 +331,7 @@ def _show_context_menu(self, position) -> None: class AuditLogDialog(QDialog): """Browse the SQLite audit log with filter on event_type / host_id.""" - def __init__(self, audit_log, parent: Optional[QWidget] = None) -> None: + def __init__(self, audit_log: AuditLog, parent: Optional[QWidget] = None) -> None: super().__init__(parent) self._log = audit_log self.setWindowTitle(_t("rd_webrtc_audit_title")) @@ -409,7 +413,7 @@ def __init__(self, parent: Optional[QWidget] = None) -> None: self._view = ViewLifetime(self) self.setWindowTitle(_t("rd_webrtc_lan_title")) self.setMinimumSize(620, 260) - self._services: dict = {} + self._services: dict[str, dict[str, Any]] = {} layout = QVBoxLayout(self) help_label = QLabel(_t("rd_webrtc_lan_help")) help_label.setWordWrap(True) @@ -463,11 +467,11 @@ def _start_browser(self) -> None: except (RuntimeError, OSError): self._browser = None - def _update_services(self, services: dict) -> None: + def _update_services(self, services: dict[str, dict[str, Any]]) -> None: """Any thread: report the hosts seen; the table is redrawn on the GUI thread.""" self._view.post("_on_services_changed", dict(services)) - def _on_services_changed(self, services: dict) -> None: + def _on_services_changed(self, services: dict[str, dict[str, Any]]) -> None: self._services = dict(services) self._refresh() @@ -517,7 +521,7 @@ def done(self, result: int) -> None: # noqa: D401 # Qt override self._stop_browser() super().done(result) - def closeEvent(self, event) -> None: # noqa: N802 Qt override + def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 Qt override self._stop_browser() super().closeEvent(event) diff --git a/je_auto_control/utils/accessibility/backends/windows_backend.py b/je_auto_control/utils/accessibility/backends/windows_backend.py index 9e30f1d75..54d97e86a 100644 --- a/je_auto_control/utils/accessibility/backends/windows_backend.py +++ b/je_auto_control/utils/accessibility/backends/windows_backend.py @@ -12,7 +12,8 @@ is initialised on that thread, and no raw element outlives the call that found it -- see :mod:`~je_auto_control.utils.accessibility.backends.windows_automation`. """ -from typing import Any, Dict, List, Optional +import queue +from typing import Any, Callable, Dict, List, Optional from je_auto_control.utils.accessibility.backends.base import ( AccessibilityBackend, @@ -37,6 +38,7 @@ from je_auto_control.utils.logging.logging_instance import autocontrol_logger _UIA_ERRORS = UIA_READ_ERRORS +_Opt = Optional[str] # an optional control filter: name / role / app / automation id _UIA_IS_CONTROL_ELEMENT_PROPERTY = 30016 _UIA_NAME_PROPERTY = 30005 @@ -79,7 +81,6 @@ } - class WindowsAccessibilityBackend(AccessibilityBackend): """UIAutomation-based flat element listing.""" @@ -95,7 +96,7 @@ def __init__(self) -> None: self._uia_module: Any = None self._event_lock = threading.Lock() - def _ensure_automation(self): + def _ensure_automation(self) -> Any: if self._automation is not None: return self._automation if not self.available: @@ -116,7 +117,7 @@ def _ensure_automation(self): self._uia_module = uia_module return automation - def _collect_from(self, automation, root, app_name, wanted, + def _collect_from(self, automation: Any, root: Any, app_name: _Opt, wanted: int, results: List[AccessibilityElement]) -> None: """Append this root's elements to ``results``, stopping at ``wanted``. @@ -176,7 +177,7 @@ def list_elements(self, app_name: Optional[str] = None, self._collect_from(automation, root, app_name, wanted, results) return results - def _raw_matches(self, raw, filters, cached: bool) -> bool: + def _raw_matches(self, raw: Any, filters: Dict[str, Any], cached: bool) -> bool: """Whether this element satisfies the caller's filters.""" element = _convert_uia(raw, cached=cached) if element is None: @@ -189,8 +190,8 @@ def _raw_matches(self, raw, filters, cached: bool) -> bool: app_name=filters.get("app_name"), contains=bool(filters.get("contains"))) - def _find_raw(self, name, role, app_name, automation_id, - window_title=None, contains=False): + def _find_raw(self, name: _Opt, role: _Opt, app_name: _Opt, automation_id: _Opt, + window_title: _Opt = None, contains: bool = False) -> Any: """Return the first matching raw UIA element, or ``None``. Every control-pattern call lands here, so this is the hot path for @@ -226,7 +227,7 @@ def _find_raw(self, name, role, app_name, automation_id, autocontrol_logger.error("UIA element search failed: %r", error) return None - def _pattern(self, raw, pattern_id, interface_name): + def _pattern(self, raw: Any, pattern_id: int, interface_name: str) -> Any: """Return a queried control pattern interface, or None.""" try: unknown = raw.GetCurrentPattern(pattern_id) @@ -237,9 +238,9 @@ def _pattern(self, raw, pattern_id, interface_name): except _UIA_ERRORS: return None - def get_value(self, name=None, role=None, app_name=None, - automation_id=None, window_title=None, - contains=False) -> Optional[str]: + def get_value(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None, window_title: _Opt = None, + contains: bool = False) -> Optional[str]: raw = self._find_raw(name, role, app_name, automation_id, window_title=window_title, contains=contains) if raw is not None and is_password(raw): @@ -257,8 +258,8 @@ def get_value(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def set_value(self, value, name=None, role=None, app_name=None, - automation_id=None) -> bool: + def set_value(self, value: str, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_VALUE_PATTERN_ID, "IUIAutomationValuePattern") if raw else None @@ -270,8 +271,8 @@ def set_value(self, value, name=None, role=None, app_name=None, except _UIA_ERRORS: return False - def invoke(self, name=None, role=None, app_name=None, - automation_id=None) -> bool: + def invoke(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_INVOKE_PATTERN_ID, "IUIAutomationInvokePattern") if raw else None @@ -283,8 +284,8 @@ def invoke(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return False - def toggle(self, name=None, role=None, app_name=None, - automation_id=None) -> bool: + def toggle(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_TOGGLE_PATTERN_ID, "IUIAutomationTogglePattern") if raw else None @@ -296,8 +297,8 @@ def toggle(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return False - def read_table(self, name=None, role=None, app_name=None, - automation_id=None): + def read_table(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> List[List[str]]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_GRID_PATTERN_ID, "IUIAutomationGridPattern") if raw else None @@ -310,8 +311,8 @@ def read_table(self, name=None, role=None, app_name=None, return [] return [self._read_row(pattern, r, cols) for r in range(rows)] - def _invoke_pattern_method(self, name, role, app_name, automation_id, - pattern_id, interface_name, action): + def _invoke_pattern_method(self, name: _Opt, role: _Opt, app_name: _Opt, automation_id: _Opt, + pattern_id: int, interface_name: str, action: Callable[[Any], Any]) -> bool: """Find a control, query a pattern, run ``action(pattern)`` → bool.""" raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, pattern_id, interface_name) if raw else None @@ -323,18 +324,18 @@ def _invoke_pattern_method(self, name, role, app_name, automation_id, except _UIA_ERRORS: return False - def expand(self, name=None, role=None, app_name=None, automation_id=None): + def expand(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_EXPANDCOLLAPSE_PATTERN_ID, "IUIAutomationExpandCollapsePattern", lambda p: p.Expand()) - def collapse(self, name=None, role=None, app_name=None, automation_id=None): + def collapse(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_EXPANDCOLLAPSE_PATTERN_ID, "IUIAutomationExpandCollapsePattern", lambda p: p.Collapse()) - def expand_state(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[str]: + def expand_state(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[str]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_EXPANDCOLLAPSE_PATTERN_ID, "IUIAutomationExpandCollapsePattern") if raw else None @@ -345,25 +346,26 @@ def expand_state(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def select_item(self, name=None, role=None, app_name=None, automation_id=None): + def select_item(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_SELECTIONITEM_PATTERN_ID, "IUIAutomationSelectionItemPattern", lambda p: p.Select()) - def set_range_value(self, value, name=None, role=None, app_name=None, - automation_id=None): + def set_range_value(self, value: float, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_RANGEVALUE_PATTERN_ID, "IUIAutomationRangeValuePattern", lambda p: p.SetValue(float(value))) - def scroll_into_view(self, name=None, role=None, app_name=None, - automation_id=None): + def scroll_into_view(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_SCROLLITEM_PATTERN_ID, "IUIAutomationScrollItemPattern", lambda p: p.ScrollIntoView()) - def get_range(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def get_range(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_RANGEVALUE_PATTERN_ID, "IUIAutomationRangeValuePattern") if raw else None @@ -376,7 +378,7 @@ def get_range(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def _realize(self, raw) -> None: + def _realize(self, raw: Any) -> None: """Realize a virtualized element so it materializes (VirtualizedItemPattern).""" pattern = self._pattern(raw, _UIA_VIRTUALIZEDITEM_PATTERN_ID, "IUIAutomationVirtualizedItemPattern") @@ -387,8 +389,9 @@ def _realize(self, raw) -> None: except _UIA_ERRORS: pass - def find_virtual_item(self, item_name=None, by="name", container_name=None, - container_role=None, app_name=None, automation_id=None): + def find_virtual_item(self, item_name: _Opt = None, by: str = "name", container_name: _Opt = None, + container_role: _Opt = None, app_name: _Opt = None, automation_id: _Opt = None, + ) -> Optional[AccessibilityElement]: container = self._find_raw(container_name, container_role, app_name, automation_id) pattern = self._pattern(container, _UIA_ITEMCONTAINER_PATTERN_ID, @@ -407,36 +410,36 @@ def find_virtual_item(self, item_name=None, by="name", container_name=None, self._realize(found) return _convert_uia(found) - def get_properties(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def get_properties(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id) if not raw: return None return _read_properties(raw) - def get_state(self, name=None, role=None, app_name=None, - automation_id=None, window_title=None, - contains=False) -> Optional[Dict[str, Any]]: + def get_state(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None, window_title: _Opt = None, + contains: bool = False) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id, window_title=window_title, contains=contains) return None if not raw else read_state(raw) - def move_element(self, x=0.0, y=0.0, name=None, role=None, app_name=None, - automation_id=None): + def move_element(self, x: float = 0.0, y: float = 0.0, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_TRANSFORM_PATTERN_ID, "IUIAutomationTransformPattern", lambda pattern: pattern.Move(float(x), float(y))) - def resize_element(self, width=0.0, height=0.0, name=None, role=None, - app_name=None, automation_id=None): + def resize_element(self, width: float = 0.0, height: float = 0.0, name: _Opt = None, role: _Opt = None, + app_name: _Opt = None, automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_TRANSFORM_PATTERN_ID, "IUIAutomationTransformPattern", lambda pattern: pattern.Resize(float(width), float(height))) - def set_window_state(self, state="normal", name=None, role=None, - app_name=None, automation_id=None): + def set_window_state(self, state: str = "normal", name: _Opt = None, role: _Opt = None, + app_name: _Opt = None, automation_id: _Opt = None) -> bool: visual = _WINDOW_VISUAL_STATES.get(str(state).lower()) if visual is None: return False @@ -445,8 +448,8 @@ def set_window_state(self, state="normal", name=None, role=None, "IUIAutomationWindowPattern", lambda pattern: pattern.SetWindowVisualState(visual)) - def window_interaction_state(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[str]: + def window_interaction_state(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[str]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_WINDOW_PATTERN_ID, "IUIAutomationWindowPattern") if raw else None @@ -458,8 +461,8 @@ def window_interaction_state(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def legacy_info(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def legacy_info(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_LEGACYIACCESSIBLE_PATTERN_ID, "IUIAutomationLegacyIAccessiblePattern" @@ -468,16 +471,16 @@ def legacy_info(self, name=None, role=None, app_name=None, return None return _read_legacy(pattern) - def legacy_default_action(self, name=None, role=None, app_name=None, - automation_id=None): + def legacy_default_action(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: return self._invoke_pattern_method( name, role, app_name, automation_id, _UIA_LEGACYIACCESSIBLE_PATTERN_ID, "IUIAutomationLegacyIAccessiblePattern", lambda pattern: pattern.DoDefaultAction()) - def get_selection(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def get_selection(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_SELECTION_PATTERN_ID, "IUIAutomationSelectionPattern") if raw else None @@ -492,13 +495,13 @@ def get_selection(self, name=None, role=None, app_name=None, return {"items": items, "can_select_multiple": can_multiple, "is_required": required} - def _multiple_view(self, name, role, app_name, automation_id): + def _multiple_view(self, name: _Opt, role: _Opt, app_name: _Opt, automation_id: _Opt) -> Any: raw = self._find_raw(name, role, app_name, automation_id) return self._pattern(raw, _UIA_MULTIPLEVIEW_PATTERN_ID, "IUIAutomationMultipleViewPattern") if raw else None - def list_views(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def list_views(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: pattern = self._multiple_view(name, role, app_name, automation_id) if pattern is None: return None @@ -510,8 +513,8 @@ def list_views(self, name=None, role=None, app_name=None, return {"current": _view_name(pattern, current), "views": [_view_name(pattern, view_id) for view_id in view_ids]} - def set_view(self, view="", name=None, role=None, app_name=None, - automation_id=None): + def set_view(self, view: str = "", name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: pattern = self._multiple_view(name, role, app_name, automation_id) if pattern is None: return False @@ -524,7 +527,7 @@ def set_view(self, view="", name=None, role=None, app_name=None, return False return False - def _make_focus_handler(self, sink): + def _make_focus_handler(self, sink: "queue.Queue[Dict[str, Any]]") -> Any: """Build a COM focus-changed event handler that puts events on ``sink``.""" try: import comtypes @@ -536,18 +539,18 @@ class _FocusHandler(comtypes.COMObject): _com_interfaces_ = [interface] def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent( - self, sender): # noqa: N802 # reason: comtypes callback name + self, sender: Any) -> int: # noqa: N802 # reason: comtypes callback name element = _convert_uia(sender) sink.put(element.to_dict() if element else {"focused": True}) return 0 return _FocusHandler() - def wait_for_focus_change(self, timeout=5.0) -> Optional[Dict[str, Any]]: + def wait_for_focus_change(self, timeout: float = 5.0) -> Optional[Dict[str, Any]]: import queue from je_auto_control.utils.accessibility.backends.windows_events import wait_for_event automation = self._ensure_automation() - events: "queue.Queue" = queue.Queue() + events: "queue.Queue[Dict[str, Any]]" = queue.Queue() handler = self._make_focus_handler(events) if handler is None: return None @@ -565,8 +568,8 @@ def wait_for_focus_change(self, timeout=5.0) -> Optional[Dict[str, Any]]: except _UIA_ERRORS: pass - def get_table_headers(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def get_table_headers(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id) pattern = self._pattern(raw, _UIA_TABLE_PATTERN_ID, "IUIAutomationTablePattern") if raw else None @@ -579,8 +582,8 @@ def get_table_headers(self, name=None, role=None, app_name=None, return None return {"columns": _header_names(columns), "rows": _header_names(rows)} - def get_grid_cell(self, row=0, column=0, name=None, role=None, - app_name=None, automation_id=None) -> Optional[Dict[str, Any]]: + def get_grid_cell(self, row: int = 0, column: int = 0, name: _Opt = None, role: _Opt = None, + app_name: _Opt = None, automation_id: _Opt = None) -> Optional[Dict[str, Any]]: raw = self._find_raw(name, role, app_name, automation_id) grid = self._pattern(raw, _UIA_GRID_PATTERN_ID, "IUIAutomationGridPattern") if raw else None @@ -596,7 +599,7 @@ def get_grid_cell(self, row=0, column=0, name=None, role=None, "IUIAutomationGridItemPattern"), cell, int(row), int(column)) - def _text_pattern(self, name, role, app_name, automation_id): + def _text_pattern(self, name: _Opt, role: _Opt, app_name: _Opt, automation_id: _Opt) -> Any: """Find a control and return its IUIAutomationTextPattern, or None.""" raw = self._find_raw(name, role, app_name, automation_id) if not raw: @@ -604,8 +607,8 @@ def _text_pattern(self, name, role, app_name, automation_id): return self._pattern(raw, _UIA_TEXT_PATTERN_ID, "IUIAutomationTextPattern") - def document_text(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[str]: + def document_text(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[str]: pattern = self._text_pattern(name, role, app_name, automation_id) if pattern is None: return None @@ -614,8 +617,8 @@ def document_text(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def selected_text(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[str]: + def selected_text(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[str]: pattern = self._text_pattern(name, role, app_name, automation_id) if pattern is None: return None @@ -627,8 +630,8 @@ def selected_text(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def visible_text(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[str]: + def visible_text(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[str]: pattern = self._text_pattern(name, role, app_name, automation_id) if pattern is None: return None @@ -640,7 +643,8 @@ def visible_text(self, name=None, role=None, app_name=None, except _UIA_ERRORS: return None - def _find_range(self, text, ignore_case, name, role, app_name, automation_id): + def _find_range(self, text: str, ignore_case: bool, name: _Opt, role: _Opt, app_name: _Opt, + automation_id: _Opt) -> Any: """Find ``text`` in the control's document range (TextPattern.FindText).""" pattern = self._text_pattern(name, role, app_name, automation_id) if pattern is None: @@ -651,13 +655,12 @@ def _find_range(self, text, ignore_case, name, role, app_name, automation_id): except _UIA_ERRORS: return None - def find_text(self, text="", ignore_case=True, name=None, role=None, - app_name=None, automation_id=None) -> bool: - return not _is_null(self._find_range(text, ignore_case, name, role, app_name, - automation_id)) + def find_text(self, text: str = "", ignore_case: bool = True, name: _Opt = None, role: _Opt = None, + app_name: _Opt = None, automation_id: _Opt = None) -> bool: + return not _is_null(self._find_range(text, ignore_case, name, role, app_name, automation_id)) - def select_text(self, text="", ignore_case=True, name=None, role=None, - app_name=None, automation_id=None) -> bool: + def select_text(self, text: str = "", ignore_case: bool = True, name: _Opt = None, role: _Opt = None, + app_name: _Opt = None, automation_id: _Opt = None) -> bool: found = self._find_range(text, ignore_case, name, role, app_name, automation_id) if not found: @@ -668,8 +671,8 @@ def select_text(self, text="", ignore_case=True, name=None, role=None, except _UIA_ERRORS: return False - def text_attributes(self, name=None, role=None, app_name=None, - automation_id=None) -> Optional[Dict[str, Any]]: + def text_attributes(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> Optional[Dict[str, Any]]: pattern = self._text_pattern(name, role, app_name, automation_id) if pattern is None: return None @@ -682,8 +685,8 @@ def text_attributes(self, name=None, role=None, app_name=None, return None return _read_text_attributes(text_range) - def set_focus(self, name=None, role=None, app_name=None, - automation_id=None) -> bool: + def set_focus(self, name: _Opt = None, role: _Opt = None, app_name: _Opt = None, + automation_id: _Opt = None) -> bool: raw = self._find_raw(name, role, app_name, automation_id) if not raw: return False @@ -698,9 +701,9 @@ def focused_element(self) -> Optional[AccessibilityElement]: return None if raw is None else _convert_uia(raw) @staticmethod - def _read_row(pattern, row: int, cols: int): + def _read_row(pattern: Any, row: int, cols: int) -> List[str]: """Read one grid row into a list of cell strings.""" - cells = [] + cells: List[str] = [] for col in range(cols): try: cell = pattern.GetItem(row, col) @@ -710,7 +713,7 @@ def _read_row(pattern, row: int, cols: int): return cells -def _convert_uia(raw, cached: bool = False) -> Optional[AccessibilityElement]: +def _convert_uia(raw: Any, cached: bool = False) -> Optional[AccessibilityElement]: """Convert one UIA element. ``cached`` reads the pre-fetched properties. Every ``Current*`` read is a cross-process call into the application that diff --git a/je_auto_control/utils/agent_runtime/completion_recovery.py b/je_auto_control/utils/agent_runtime/completion_recovery.py index 2df44cd66..372a553a9 100644 --- a/je_auto_control/utils/agent_runtime/completion_recovery.py +++ b/je_auto_control/utils/agent_runtime/completion_recovery.py @@ -26,9 +26,10 @@ _STOPPED = frozenset({"paused", "waiting_user", "recovering", "cancelled", "timed_out", "failed"}) _INDEPENDENT = frozenset({"file_exists", "file_text", "file_sha256", "file_manifest", "screen", "browser"}) +_Link = tuple[dict[str, Any], dict[str, Any], dict[str, Any]] -def retainable_browser(target: Any, row: dict, receipts: Callable[[], list[dict]]) -> bool: +def retainable_browser(target: Any, row: dict[str, Any], receipts: Callable[[], list[dict[str, Any]]]) -> bool: """Admit only the real built-in browser with confirmed effects and independent browser criteria.""" # pylint: disable-next=unidiomatic-typecheck # reason: custom flags cannot opt into private helper ownership if type(target) is not NativeDesktopTarget or not target.has_browser_context: @@ -46,7 +47,7 @@ def _connection(store: Any, connection: Any) -> Any: return store.connection() if connection is None else nullcontext(connection) -def completion_details(store: Any, task_id: str, *, connection: Any = None) -> dict | None: +def completion_details(store: Any, task_id: str, *, connection: Any = None) -> dict[str, Any] | None: """Read private host admission; user specification options never grant this authority.""" with _connection(store, connection) as reading: row = reading.execute("SELECT details FROM agent_readonly_completions WHERE task_id=?", (task_id,)).fetchone() @@ -65,7 +66,7 @@ def _missing_marker(connection: Any, task_id: str) -> None: raise AgentTaskError('private read-only completion marker is missing') -def _snapshot(runtime: Any, row: dict, *, connection: Any = None) -> str: +def _snapshot(runtime: Any, row: dict[str, Any], *, connection: Any = None) -> str: # pylint: disable-next=import-outside-toplevel # reason: share the exact existing receipt/review snapshot contract from je_auto_control.utils.agent_runtime.task_recovery import _snapshot as source_snapshot with _connection(runtime.store, connection) as reading: @@ -75,7 +76,7 @@ def _snapshot(runtime: Any, row: dict, *, connection: Any = None) -> str: return source_snapshot(row, actions, reviews) -def _stopped(runtime: Any, row: dict, *, allow_verified: bool = False, connection: Any = None) -> None: +def _stopped(runtime: Any, row: dict[str, Any], *, allow_verified: bool = False, connection: Any = None) -> None: # pylint: disable-next=protected-access # reason: completion cannot borrow live input or an unwinding operation if row['state'] not in _STOPPED and not (allow_verified and _retired_reader(runtime, row, connection)): raise AgentTaskError('completion review requires stopped, retired source input') @@ -84,7 +85,7 @@ def _stopped(runtime: Any, row: dict, *, allow_verified: bool = False, connectio raise AgentTaskError("completion review requires stopped, retired source input") -def _retired_reader(runtime: Any, row: dict, connection: Any) -> bool: +def _retired_reader(runtime: Any, row: dict[str, Any], connection: Any) -> bool: if row['state'] != 'succeeded': return False with _connection(runtime.store, connection) as reading: @@ -93,7 +94,7 @@ def _retired_reader(runtime: Any, row: dict, connection: Any) -> bool: and completion_details(runtime.store, row['id'], connection=reading) is not None) -def _principals(details: dict) -> None: +def _principals(details: dict[str, Any]) -> None: reviewer = details["reviewer"] for owner in (details["source_owner"], details["effect_owner"]): with DeferredAuthorization(AuthorizationContext(**reviewer) if reviewer else None).scope(): @@ -104,7 +105,7 @@ def _principals(details: dict) -> None: pass -def check_completion_authority(runtime: Any, task_id: str, *, connection: Any = None) -> dict | None: +def check_completion_authority(runtime: Any, task_id: str, *, connection: Any = None) -> dict[str, Any] | None: """Keep source/effect snapshots and both real principals live through reads and success publication.""" details = completion_details(runtime.store, task_id, connection=connection) if details is None: @@ -126,12 +127,12 @@ def check_completion_authority(runtime: Any, task_id: str, *, connection: Any = return None -def completion_metadata(store: Any, task_id: str, *, runtime: Any = None) -> dict: +def completion_metadata(store: Any, task_id: str, *, runtime: Any = None) -> dict[str, Any]: """Expose bounded public provenance without private principal stores or authority-bearing fields.""" details = completion_details(store, task_id) if details is None: return {} - result: dict = {"completion_review": {"contract": 1, "source_task": details["source_task"], + result: dict[str, Any] = {"completion_review": {"contract": 1, "source_task": details["source_task"], "effect_task": details["effect_task"], "snapshot": details["source_snapshot"]}} with store.connection() as reading: @@ -145,7 +146,7 @@ def completion_metadata(store: Any, task_id: str, *, runtime: Any = None) -> dic return result -def completion_target(runtime: Any, row: Mapping, original: Any, operation: Callable[[], Any]) -> Any: +def completion_target(runtime: Any, row: Mapping[str, Any], original: Any, operation: Callable[[], Any]) -> Any: """Select a separately owned read-only proxy from private admission, never from model-authored options.""" details = completion_details(runtime.store, row["id"]) if details is None: @@ -170,7 +171,7 @@ def completion_target(runtime: Any, row: Mapping, original: Any, operation: Call return cached -def completion_evidence(runtime: Any, row: dict) -> tuple[TaskPolicy, list[dict]]: +def completion_evidence(runtime: Any, row: dict[str, Any]) -> tuple[TaskPolicy, list[dict[str, Any]]]: """Verify original pinned action evidence, while the task's target supplies a fresh independent observation.""" details = completion_details(runtime.store, row["id"]) effect = runtime.store.get(details["effect_task"]) if details is not None else row @@ -192,7 +193,7 @@ def _require_target(adapter: Any) -> None: raise AgentTaskError("target has no supported permanent read-only completion helper") -def _effect(runtime: Any, row: dict, *, connection: Any = None) -> dict: +def _effect(runtime: Any, row: dict[str, Any], *, connection: Any = None) -> dict[str, Any]: details = completion_details(runtime.store, row["id"], connection=connection) with _connection(runtime.store, connection) as reading: effect = runtime.store.read_task(reading, details['effect_task']) if details is not None else row @@ -210,13 +211,13 @@ def _effect(runtime: Any, row: dict, *, connection: Any = None) -> dict: return effect -def completion_spec(runtime: Any, effect: dict) -> AgentTaskSpec: +def completion_spec(runtime: Any, effect: dict[str, Any]) -> AgentTaskSpec: """Derive the exact no-action verification scope shared by admission and evidence consumers.""" # pylint: disable-next=protected-access # reason: retain current host profile, scope and criteria validation return runtime._validated_spec(_verification_template(effect['spec'])) -def _verification_template(value: dict) -> dict: +def _verification_template(value: dict[str, Any]) -> dict[str, Any]: spec = detached(value) spec.update(goal="Reviewed completion: " + spec["goal"][:15940], mode="external", actions=[]) for key in ("dag_batch", "skill_pin"): @@ -224,7 +225,8 @@ def _verification_template(value: dict) -> dict: return spec -def _details(runtime: Any, source: dict, effect: dict, ownership: dict | None, *, connection: Any = None) -> dict: +def _details(runtime: Any, source: dict[str, Any], effect: dict[str, Any], ownership: dict[str, Any] | None, *, + connection: Any = None) -> dict[str, Any]: actor = current_authorization() if ownership is not None: reviewer = ownership["actor"] @@ -238,7 +240,7 @@ def _details(runtime: Any, source: dict, effect: dict, ownership: dict | None, * return details -def _review_mode(runtime: Any, row: dict, operation: str) -> bool: +def _review_mode(runtime: Any, row: dict[str, Any], operation: str) -> bool: renewal = operation in {'review_completion_authorization', 'create_authorized_completion'} _stopped(runtime, row, allow_verified=renewal) if (not renewal and completion_details(runtime.store, row['id']) is not None @@ -247,7 +249,8 @@ def _review_mode(runtime: Any, row: dict, operation: str) -> bool: return renewal -def control_completion(recovery: Any, operation: str, row: dict, request: dict, ownership: dict | None) -> dict: +def control_completion(recovery: Any, operation: str, row: dict[str, Any], request: dict[str, Any], + ownership: dict[str, Any] | None) -> dict[str, Any]: """Review a deterministic read-only successor or atomically admit its exact source snapshot once.""" runtime = recovery.runtime renewal = _review_mode(runtime, row, operation) @@ -277,8 +280,8 @@ def control_completion(recovery: Any, operation: str, row: dict, request: dict, return _create(recovery, row, request, spec, details, owned, authorization) -def _create(recovery: Any, row: dict, request: dict, spec: AgentTaskSpec, details: dict, owned: dict | None, - authorization: dict | None = None) -> dict: +def _create(recovery: Any, row: dict[str, Any], request: dict[str, Any], spec: AgentTaskSpec, details: dict[str, Any], + owned: dict[str, Any] | None, authorization: dict[str, Any] | None = None) -> dict[str, Any]: # pylint: disable-next=import-outside-toplevel # reason: reuse bounded human review and provenance projection from je_auto_control.utils.agent_runtime.task_recovery import _review_note, recovery_link note = _review_note(request["note"]) @@ -297,7 +300,8 @@ def validate(connection: Any) -> None: current = runtime.store.read_task(connection, row['id']) with DeferredAuthorization.capture().scope(): if authorization is not None: - actual = _renewal(runtime, current, owned, connection=connection) + actual: tuple[AgentTaskSpec, dict[str, Any], dict[str, Any] | None] = _renewal( + runtime, current, owned, connection=connection) else: effect = _effect(runtime, current, connection=connection) actual = (completion_spec(runtime, effect), @@ -310,7 +314,7 @@ def validate(connection: Any) -> None: return {"task_id": task.task_id, "state": task.state, "recovery": recovery_link(runtime.store, task.task_id)} -def _require_browser_context(runtime: Any, effect: dict) -> None: +def _require_browser_context(runtime: Any, effect: dict[str, Any]) -> None: # pylint: disable-next=protected-access # reason: the built-in target was checked before private completion admission if not runtime._targets[effect["spec"]["target"]].is_managed_browser: return @@ -319,7 +323,8 @@ def _require_browser_context(runtime: Any, effect: dict) -> None: require_source(runtime, effect) -def _renewal_base(runtime: Any, source: dict, effect: dict, *, connection: Any = None, depth: int = 0) -> dict: +def _renewal_base(runtime: Any, source: dict[str, Any], effect: dict[str, Any], *, connection: Any = None, + depth: int = 0) -> dict[str, Any]: base = detached(effect['spec']) details = completion_details(runtime.store, source['id'], connection=connection) if details is not None: @@ -330,13 +335,14 @@ def _renewal_base(runtime: Any, source: dict, effect: dict, *, connection: Any = return base -def _authorized_effect(base: dict, authorization: dict) -> dict: +def _authorized_effect(base: dict[str, Any], authorization: dict[str, Any]) -> dict[str, Any]: approved = authorized_template(base, authorization) approved.update(actions=base['actions'], mode=base['mode']) return approved -def _renewal(runtime: Any, source: dict, ownership: dict | None, *, connection: Any = None) -> tuple: +def _renewal(runtime: Any, source: dict[str, Any], ownership: dict[str, Any] | None, *, + connection: Any = None) -> tuple[AgentTaskSpec, dict[str, Any], dict[str, Any]]: _stopped(runtime, source, allow_verified=True, connection=connection) effect = _effect(runtime, source, connection=connection) details = _details(runtime, source, effect, ownership, connection=connection) @@ -347,7 +353,7 @@ def _renewal(runtime: Any, source: dict, ownership: dict | None, *, connection: return spec, details, authorization -def _authorization(store: Any, task_id: str, *, connection: Any = None) -> dict | None: +def _authorization(store: Any, task_id: str, *, connection: Any = None) -> dict[str, Any] | None: with _connection(store, connection) as reading: row = reading.execute('SELECT details FROM agent_task_authorizations WHERE task_id=?', (task_id,)).fetchone() if row is None: @@ -373,12 +379,12 @@ def _string_list(value: Any) -> bool: return isinstance(value, list) and all(isinstance(item, str) for item in value) -def _approval_shape(value: dict) -> bool: +def _approval_shape(value: dict[str, Any]) -> bool: return (_string_list(value['approved_roots']) and all(isinstance(value[key], str) for key in ('review', 'binding', 'actor'))) -def _context_lists(context: dict) -> bool: +def _context_lists(context: dict[str, Any]) -> bool: version = context['contract'] if not isinstance(version, int) or isinstance(version, bool) or version != 1: return False @@ -394,7 +400,7 @@ def _policy_shape(value: Any) -> bool: and isinstance(value['id'], str) and _string_list(value['roots'])) -def _effect_spec(runtime: Any, child: dict, details: dict, *, connection: Any = None, +def _effect_spec(runtime: Any, child: dict[str, Any], details: dict[str, Any], *, connection: Any = None, historical: bool = False, depth: int = 0) -> AgentTaskSpec: with _connection(runtime.store, connection) as reading: effect = runtime.store.read_task(reading, details['effect_task']) @@ -415,7 +421,7 @@ def _effect_spec(runtime: Any, child: dict, details: dict, *, connection: Any = return runtime._validated_spec(approved) -def _renewal_contract(authorization: dict, base: dict, binding: str) -> dict: +def _renewal_contract(authorization: dict[str, Any], base: dict[str, Any], binding: str) -> dict[str, Any]: context = authorization['context'] if (authorization['binding'] != binding or context['source_snapshot'] != binding or authorization['review'] != request_spec_digest(context) @@ -428,7 +434,7 @@ def _renewal_contract(authorization: dict, base: dict, binding: str) -> dict: return approved -def _renewal_binding(runtime: Any, details: dict, *, connection: Any = None) -> str: +def _renewal_binding(runtime: Any, details: dict[str, Any], *, connection: Any = None) -> str: admissions = [] with _connection(runtime.store, connection) as reading: for identifier in dict.fromkeys((details['source_task'], details['effect_task'])): @@ -445,7 +451,8 @@ def _renewal_binding(runtime: Any, details: dict, *, connection: Any = None) -> return request_spec_digest({'completion': details, 'admissions': admissions}) -def _completion_dag_context(runtime: Any, connection: Any, row: dict, admission: dict) -> dict: +def _completion_dag_context(runtime: Any, connection: Any, row: dict[str, Any], + admission: dict[str, Any]) -> dict[str, Any]: context = runtime.batches.handoff_context(admission['batch_id'], admission['node_id'], connection=connection, identity_only=True) if context['source']['id'] != row['id']: @@ -453,10 +460,10 @@ def _completion_dag_context(runtime: Any, connection: Any, row: dict, admission: return context -def _inherited_dag_binding(runtime: Any, connection: Any, effect: dict, source_id: str) -> dict: +def _inherited_dag_binding(runtime: Any, connection: Any, effect: dict[str, Any], source_id: str) -> dict[str, Any]: tag = _inherited_tag(effect['spec']['options']['dag_batch']) row = runtime.store.read_task(connection, source_id) - lineage: list[dict] = [] + lineage: list[dict[str, Any]] = [] seen: set[str] = set() for _index in range(16): if row['id'] in seen: @@ -473,22 +480,23 @@ def _inherited_dag_binding(runtime: Any, connection: Any, effect: dict, source_i raise AgentHumanReview('completion original DAG admission has no bounded real recovery chain') -def _inherited_tag(value: Any) -> dict: +def _inherited_tag(value: Any) -> dict[str, Any]: if (not isinstance(value, dict) or set(value) != {'batch_id', 'node_id', 'graph_hash'} or not all(isinstance(item, str) for item in value.values())): raise AgentHumanReview('completion inherited DAG identity is invalid') return value -def _inherited_origin(context: dict, tag: dict, effect_id: str, seen: set, - lineage: list, admitted: dict) -> dict: +def _inherited_origin(context: dict[str, Any], tag: dict[str, Any], effect_id: str, seen: set[str], + lineage: list[dict[str, Any]], admitted: dict[str, Any]) -> dict[str, Any]: if (effect_id not in seen or context['binding']['graph_hash'] != tag['graph_hash'] or (admitted['batch_id'], admitted['node_id']) != (tag['batch_id'], tag['node_id'])): raise AgentHumanReview('completion inherited DAG source identity changed') return {'kind': 'inherited_local_dag', 'binding': context['binding'], 'lineage': lineage} -def _inherited_parent(runtime: Any, connection: Any, row: dict, tag: dict) -> tuple[dict, dict]: +def _inherited_parent(runtime: Any, connection: Any, row: dict[str, Any], + tag: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: actual = row['spec']['options'].get('dag_batch') if actual != tag: if actual is not None or completion_details(runtime.store, row['id'], connection=connection) is None: @@ -504,7 +512,8 @@ def _inherited_parent(runtime: Any, connection: Any, row: dict, tag: dict) -> tu return parent, link -def _historical_reader(runtime: Any, reader: dict, details: dict, effect: dict, connection: Any, depth: int) -> None: +def _historical_reader(runtime: Any, reader: dict[str, Any], details: dict[str, Any], effect: dict[str, Any], + connection: Any, depth: int) -> None: if depth >= 15: raise AgentTaskError('completion authorization exceeds sixteen real recovery links') _principals(details) @@ -526,7 +535,8 @@ def _historical_reader(runtime: Any, reader: dict, details: dict, effect: dict, raise AgentHumanReview('completion historical verification scope changed') -def _historical_link(runtime: Any, connection: Any, reader: dict, details: dict, effect: dict) -> None: +def _historical_link(runtime: Any, connection: Any, reader: dict[str, Any], details: dict[str, Any], + effect: dict[str, Any]) -> None: link = connection.execute('SELECT source_task,snapshot FROM agent_task_recoveries WHERE task_id=?', (reader['id'],)).fetchone() if (link is None or link['source_task'] != details['source_task'] @@ -539,7 +549,7 @@ def _historical_link(runtime: Any, connection: Any, reader: dict, details: dict, raise AgentHumanReview('completion historical source snapshot changed') -def historical_handoff_reader(runtime: Any, connection: Any, row: dict) -> bool: +def historical_handoff_reader(runtime: Any, connection: Any, row: dict[str, Any]) -> bool: """Prove actual private historical reader scope without renewing an unavailable old origin.""" details = completion_details(runtime.store, row['id'], connection=connection) if details is None: @@ -550,8 +560,9 @@ def historical_handoff_reader(runtime: Any, connection: Any, row: dict) -> bool: return True -def handoff_completion_scope(runtime: Any, connection: Any, context: dict, links: list, *, - authorization: dict | None = None, issuing: bool = False) -> dict | None: +def handoff_completion_scope(runtime: Any, connection: Any, context: dict[str, Any], links: list[_Link], *, + authorization: dict[str, Any] | None = None, + issuing: bool = False) -> dict[str, Any] | None: """Review only already verified renewed readers under every original real recovery ceiling.""" rows = _handoff_rows(links) leaf = rows[-1] @@ -578,8 +589,8 @@ def handoff_completion_scope(runtime: Any, connection: Any, context: dict, links 'completion_task': leaf['id'], 'completion_review': renewal['review'], 'segments': segments}} -def _handoff_approvals(rows: list[dict], roots: list, binding: str, issuer: dict, - authorization: dict | None) -> tuple[list, list]: +def _handoff_approvals(rows: list[dict[str, Any]], roots: list[str], binding: str, issuer: dict[str, Any], + authorization: dict[str, Any] | None) -> tuple[list[dict[str, Any]], list[str]]: segments, origins = [], [] for index, row in enumerate(rows): previous = None if authorization is None else authorization['segments'][index]['authorization'] @@ -590,7 +601,7 @@ def _handoff_approvals(rows: list[dict], roots: list, binding: str, issuer: dict return segments, origins -def _handoff_rows(links: list) -> list[dict]: +def _handoff_rows(links: list[_Link]) -> list[dict[str, Any]]: if not links or len(links) > 16: raise AgentTaskError('handoff requires at most sixteen real recovery links') rows = [links[0][0], *(child for _source, child, _link in links)] @@ -599,7 +610,8 @@ def _handoff_rows(links: list) -> list[dict]: return rows -def _handoff_binding(runtime: Any, connection: Any, context: dict, rows: list[dict], review: str) -> str: +def _handoff_binding(runtime: Any, connection: Any, context: dict[str, Any], rows: list[dict[str, Any]], + review: str) -> str: snapshots = [] for row in rows: check_historical_admission(connection, row) @@ -618,7 +630,7 @@ def _handoff_bundle_header(value: Any) -> bool: and value['contract'] == 1 and value['kind'] == 'readonly_completion_handoff') -def _handoff_bundle(value: Any, rows: list[dict], binding: str, review: str) -> dict: +def _handoff_bundle(value: Any, rows: list[dict[str, Any]], binding: str, review: str) -> dict[str, Any]: if (not _handoff_bundle_header(value) or value['binding'] != binding or value['completion_task'] != rows[-1]['id'] or value['completion_review'] != review): raise AgentTaskError('handoff completion authorization changed') @@ -626,7 +638,7 @@ def _handoff_bundle(value: Any, rows: list[dict], binding: str, review: str) -> return value -def _handoff_segments(segments: Any, rows: list[dict]) -> None: +def _handoff_segments(segments: Any, rows: list[dict[str, Any]]) -> None: if not isinstance(segments, list) or len(segments) != len(rows): raise AgentTaskError('handoff completion authorization segments changed') for segment, row in zip(segments, rows): @@ -634,14 +646,14 @@ def _handoff_segments(segments: Any, rows: list[dict]) -> None: raise AgentTaskError('invalid private handoff completion authorization') -def _handoff_segment(value: Any, row: dict) -> bool: +def _handoff_segment(value: Any, row: dict[str, Any]) -> bool: return (isinstance(value, dict) and set(value) == {'task_id', 'authorization'} and value['task_id'] == row['id'] and _authorization_shape(value['authorization'], 'readonly_completion_handoff')) -def _handoff_authorization(row: dict, roots: list, binding: str, issuer: dict, - previous: dict | None) -> tuple[dict, dict]: +def _handoff_authorization(row: dict[str, Any], roots: list[str], binding: str, issuer: dict[str, Any], + previous: dict[str, Any] | None) -> tuple[dict[str, Any], dict[str, Any]]: validate_root_snapshot(row['spec']['roots']) if any(not any(Path(root).is_relative_to(Path(parent)) for parent in row['spec']['roots']) for root in roots): raise AgentTaskError('handoff reader roots exceed a historical task ceiling') diff --git a/je_auto_control/utils/agent_runtime/dag_batches.py b/je_auto_control/utils/agent_runtime/dag_batches.py index ce7b516c4..ef2021ef4 100644 --- a/je_auto_control/utils/agent_runtime/dag_batches.py +++ b/je_auto_control/utils/agent_runtime/dag_batches.py @@ -3,6 +3,7 @@ from contextlib import nullcontext import json +from pathlib import Path import time import uuid from typing import Any @@ -39,7 +40,7 @@ _FIELDS.update(CONTINUATION_FIELDS) -def _request(operation: Any, value: Any) -> dict: +def _request(operation: Any, value: Any) -> dict[str, Any]: request = durable_payload(detached({} if value is None else value)) if operation not in OPERATIONS or not isinstance(request, dict): raise AgentTaskError("invalid batch operation or request") @@ -55,7 +56,7 @@ def _request(operation: Any, value: Any) -> dict: return request -def _matching_handoff_submission(value: Any, accepted: dict, source: dict, expected: str) -> bool: +def _matching_handoff_submission(value: Any, accepted: dict[str, Any], source: dict[str, Any], expected: str) -> bool: return (value is not None and value['spec_digest'] == expected and accepted['spec_hash'] == request_spec_digest(source['spec'])) @@ -68,7 +69,7 @@ def __init__(self, runtime: Any) -> None: self.runtime = runtime @staticmethod - def transfer_private_files() -> tuple: + def transfer_private_files() -> tuple[Path, ...]: """Supply current host-owned credential paths without initializing a console or service.""" return registered_transfer_private_files() @@ -79,7 +80,7 @@ def transfer_binding(self, host: str) -> str: self.runtime.transfers.source.host.check_open() return binding - def transfer_call(self, host: str, binding: str, path: str, body: dict, timeout: float) -> dict: + def transfer_call(self, host: str, binding: str, path: str, body: dict[str, Any], timeout: float) -> dict[str, Any]: """Keep registered transfer I/O behind this runtime's existing host-owned adapter boundary.""" self.runtime.transfers.source.host.check_open() result = registered_host_transfer(host, binding, path, body, timeout) @@ -87,7 +88,7 @@ def transfer_call(self, host: str, binding: str, path: str, body: dict, timeout: return result def handoff_context(self, batch_id: str, node_id: str, *, origin_policies: list[str] | None = None, - connection: Any = None, identity_only: bool = False) -> dict: + connection: Any = None, identity_only: bool = False) -> dict[str, Any]: """Derive a local evidence recipient from a real original request and private DAG admission.""" batch = self._row(batch_id, connection=connection) node = bound_node(batch, node_id) @@ -100,7 +101,7 @@ def handoff_context(self, batch_id: str, node_id: str, *, origin_policies: list[ 'request': request_spec_digest(node['task']), 'admission': admission} return {'binding': binding, 'source': source, 'state': batch['state'], 'policy': policy} - def handoff_policy(self, source: dict, origin_policies: list[str] | None = None) -> TaskPolicy: + def handoff_policy(self, source: dict[str, Any], origin_policies: list[str] | None = None) -> TaskPolicy: """Preserve original effect policy for grants without a privately reviewed completion renewal.""" policy_spec = detached(source['spec']) if origin_policies is not None: @@ -109,7 +110,8 @@ def handoff_policy(self, source: dict, origin_policies: list[str] | None = None) # pylint: disable-next=protected-access # reason: original and issuing-session ceilings cover every actual effect return TaskPolicy(self.runtime._validated_spec(policy_spec)) - def _handoff_source(self, batch: dict, node: dict, *, connection: Any = None) -> tuple[dict, dict, str]: + def _handoff_source(self, batch: dict[str, Any], node: dict[str, Any], *, + connection: Any = None) -> tuple[dict[str, Any], dict[str, Any], str]: owner = batch['owner'] transaction = self.runtime.store.connection() if connection is None else nullcontext(connection) with transaction as active_connection: @@ -132,7 +134,7 @@ def _handoff_source(self, batch: dict, node: dict, *, connection: Any = None) -> raise AgentTaskError('handoff original source owner differs from its batch') return source, dict(found), expected - def control(self, operation: str, request: Any = None) -> dict: + def control(self, operation: str, request: Any = None) -> dict[str, Any]: """Operate on a closed batch protocol; inspection/registration never acquire an input target.""" request = _request(operation, request) if current_operation() is not None: @@ -156,7 +158,7 @@ def control(self, operation: str, request: Any = None) -> dict: return DagLocalTasks(self.runtime, batch, request, DeferredAuthorization.capture()).control() return self._existing(operation, batch, request) - def _existing(self, operation: str, batch: dict, request: dict) -> dict: + def _existing(self, operation: str, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: if operation == "get": return self._describe(batch) owner = AuthorizationContext(**batch["owner"]) if batch["owner"] else None @@ -180,7 +182,8 @@ def _existing(self, operation: str, batch: dict, request: dict) -> dict: return self._begin(batch, request) return self._execution(operation, batch, request) - def _background(self, batch: dict, request: dict, continuation: DagContinuation) -> dict: + def _background(self, batch: dict[str, Any], request: dict[str, Any], + continuation: DagContinuation) -> dict[str, Any]: jobs = getattr(self.runtime, "background_dags", None) if jobs is None: raise AgentTaskError("background DAG execution requires an explicitly started service") @@ -203,7 +206,7 @@ def stop_all(self) -> None: if owns_task(json.loads(row["owner"]), current_authorization()): self.control("pause_batch", {"batch_id": row["id"]}) - def _row(self, identifier: str, *, connection: Any = None) -> dict: + def _row(self, identifier: str, *, connection: Any = None) -> dict[str, Any]: # pylint: disable-next=protected-access # reason: closed runtimes cannot accept new coordinator work if self.runtime._closed: raise AgentTaskError("runtime is closed") @@ -227,7 +230,7 @@ def _row(self, identifier: str, *, connection: Any = None) -> dict: batch["input_definition"] = json.loads(original[0]) if original is not None else batch["definition"] return batch - def _normalize(self, value: Any) -> tuple[dict, dict]: + def _normalize(self, value: Any) -> tuple[dict[str, Any], dict[str, Any]]: definition = batch_definition(value) hosts = {} for node in definition["nodes"]: @@ -242,7 +245,7 @@ def _normalize(self, value: Any) -> tuple[dict, dict]: hosts[host] = task_host_binding(host) return definition, hosts - def _register(self, request: dict) -> dict: + def _register(self, request: dict[str, Any]) -> dict[str, Any]: original = batch_definition(request["definition"]) definition, hosts = self._normalize(request["definition"]) parallel = request.get("max_parallel", 4) @@ -262,14 +265,14 @@ def _register(self, request: dict) -> dict: (identifier, node["id"], "pending", "{}", now)) return self._describe(self._row(identifier)) - def _list(self) -> dict: + def _list(self) -> dict[str, Any]: with self.runtime.store.connection() as connection: rows = connection.execute("SELECT id,owner FROM agent_dag_batches " "ORDER BY created DESC LIMIT 200").fetchall() return {"batches": [self._describe(self._row(row["id"])) for row in rows if owns_task(json.loads(row["owner"]), current_authorization())]} - def _describe(self, batch: dict) -> dict: + def _describe(self, batch: dict[str, Any]) -> dict[str, Any]: with self.runtime.store.connection() as connection: rows = connection.execute("SELECT node_id,phase,receipt FROM agent_dag_nodes " "WHERE batch_id=? ORDER BY node_id", (batch["id"],)).fetchall() @@ -289,7 +292,7 @@ def _describe(self, batch: dict) -> dict: "nodes": [{"id": row["node_id"], "phase": row["phase"], "receipt": json.loads(row["receipt"])} for row in rows]} - def _begin(self, batch: dict, request: dict) -> dict: + def _begin(self, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: definition, hosts = self._normalize(request["definition"]) if (request_spec_digest(definition) != batch["graph_hash"] or hosts != batch["hosts"] or not isinstance(request["max_parallel"], int) or isinstance(request["max_parallel"], bool) @@ -304,18 +307,18 @@ def _begin(self, batch: dict, request: dict) -> dict: return {"batch_id": batch["id"], "attempt": attempt, "hosts": hosts, "max_parallel": batch["max_parallel"], "definition": bind_definition(definition, batch["id"], batch["graph_hash"])} - def _execution(self, operation: str, batch: dict, request: dict) -> dict: + def _execution(self, operation: str, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: with (self.runtime.transfers.activity() if self._remote_transfer_batch(batch) else nullcontext()): return self._execute_attempt(operation, batch, request) - def _remote_transfer_batch(self, batch: dict) -> bool: + def _remote_transfer_batch(self, batch: dict[str, Any]) -> bool: with self.runtime.store.connection() as connection: rows = connection.execute('SELECT a.details FROM agent_dag_adoptions d ' 'JOIN agent_dag_approvals a ON a.id=d.approval_id AND a.batch_id=d.batch_id ' 'WHERE d.batch_id=?', (batch['id'],)).fetchall() return any(remote_reports(batch, json.loads(row['details'])['reports']) for row in rows) - def _execute_attempt(self, operation: str, batch: dict, request: dict) -> dict: + def _execute_attempt(self, operation: str, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: if batch["state"] != "running" or request["attempt"] != batch["attempt"]: raise AgentTaskError("batch execution attempt is inactive") self._execution_checks(operation, batch, request) @@ -338,13 +341,13 @@ def _execute_attempt(self, operation: str, batch: dict, request: dict) -> dict: self._execution_checks(operation, batch, request) return self._describe(self._row(batch["id"])) - def _execution_checks(self, operation: str, batch: dict, request: dict) -> None: + def _execution_checks(self, operation: str, batch: dict[str, Any], request: dict[str, Any]) -> None: if operation in {'claim', 'record'}: self._validate_adopted_dependencies(batch, request) if operation == 'finish': self._validate_final_remote_adoptions(batch) - def _validate_final_remote_adoptions(self, batch: dict) -> None: + def _validate_final_remote_adoptions(self, batch: dict[str, Any]) -> None: with self.runtime.store.connection() as connection: rows = connection.execute('SELECT d.node_id,a.details FROM agent_dag_adoptions d ' 'JOIN agent_dag_approvals a ON a.id=d.approval_id AND a.batch_id=d.batch_id WHERE d.batch_id=?', @@ -355,7 +358,7 @@ def _validate_final_remote_adoptions(self, batch: dict) -> None: if any(report['decision']['node_id'] == row['node_id'] for report in reports): continuation.validate_node(batch, row['node_id'], batch['attempt']) - def _validate_adopted_dependencies(self, batch: dict, request: dict) -> None: + def _validate_adopted_dependencies(self, batch: dict[str, Any], request: dict[str, Any]) -> None: node = bound_node(batch, request["node_id"]) with self.runtime.store.connection() as connection: adopted = {row[0] for row in connection.execute( diff --git a/je_auto_control/utils/agent_runtime/dag_continuation.py b/je_auto_control/utils/agent_runtime/dag_continuation.py index 1f3fe5b90..4c50296b3 100644 --- a/je_auto_control/utils/agent_runtime/dag_continuation.py +++ b/je_auto_control/utils/agent_runtime/dag_continuation.py @@ -23,7 +23,7 @@ "validate_node": {"batch_id", "attempt", "node_id"}} -def _decisions(value: Any, batch: dict) -> dict[str, dict] | None: +def _decisions(value: Any, batch: dict[str, Any]) -> dict[str, dict[str, Any]] | None: if value is None: return None if not isinstance(value, list) or len(value) != len(batch["definition"]["nodes"]): @@ -40,13 +40,13 @@ def _decisions(value: Any, batch: dict) -> dict[str, dict] | None: return result -def _deadline(request: dict) -> float: +def _deadline(request: dict[str, Any]) -> float: timeout = request.get('timeout_seconds', 30) positive(timeout, 'DAG continuation timeout_seconds', 300) return time.monotonic() + timeout -def _input_matches(batch: dict, definition: Any) -> None: +def _input_matches(batch: dict[str, Any], definition: Any) -> None: if request_spec_digest(batch_definition(definition)) != request_spec_digest(batch["input_definition"]): raise AgentTaskError("DAG continuation input graph changed") @@ -55,10 +55,10 @@ def _input_matches(batch: dict, definition: Any) -> None: class DagContinuation: """Bind explicit decisions to local claims, current authority and fresh destination receipts.""" - def __init__(self, batches: Any, actor: dict) -> None: + def __init__(self, batches: Any, actor: dict[str, Any]) -> None: self.batches, self.actor = batches, actor - def control(self, operation: str, batch: dict, request: dict) -> dict: + def control(self, operation: str, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: """Review without writes, approve without dispatch, or acquire exactly one approved attempt.""" if operation == "pause_batch": return self._pause(batch) @@ -74,13 +74,13 @@ def control(self, operation: str, batch: dict, request: dict) -> dict: baseline = self._baseline(batch) return self._gather(baseline, request.get("decisions"), request.get("timeout_seconds", 30))["public"] - def _baseline(self, batch: dict) -> dict: + def _baseline(self, batch: dict[str, Any]) -> dict[str, Any]: with self.batches.runtime.store.connection() as connection: nodes = [dict(row) for row in connection.execute( "SELECT * FROM agent_dag_nodes WHERE batch_id=? ORDER BY node_id", (batch["id"],))] return detached({"batch": batch, "nodes": nodes, "actor": self.actor}) - def _gather(self, baseline: dict, decisions: Any, timeout: float) -> dict: + def _gather(self, baseline: dict[str, Any], decisions: Any, timeout: float) -> dict[str, Any]: batch = baseline["batch"] selected = _decisions(decisions, batch) evidence = ContinuationEvidence(batch, timeout, self.batches.runtime) @@ -99,8 +99,8 @@ def _gather(self, baseline: dict, decisions: Any, timeout: float) -> dict: "issue": item.get("issue", "")} for item in reports]} return {"public": public, "baseline": baseline, "reports": reports} - def _review_node(self, node: dict, phase: str, choice: dict | None, - evidence: ContinuationEvidence, snapshot: str) -> dict: + def _review_node(self, node: dict[str, Any], phase: str, choice: dict[str, Any] | None, + evidence: ContinuationEvidence, snapshot: str) -> dict[str, Any]: try: original = evidence.original(node) if choice is None: @@ -110,7 +110,8 @@ def _review_node(self, node: dict, phase: str, choice: dict | None, decision = choice or {"node_id": node["id"], "action": "wait"} return {"decision": decision, "ready": False, "issue": "destination_or_decision_requires_review"} - def _default(self, node: dict, phase: str, original: dict | None, snapshot: str) -> dict: + def _default(self, node: dict[str, Any], phase: str, original: dict[str, Any] | None, + snapshot: str) -> dict[str, Any]: if original is not None: completion(original, node) return {"node_id": node["id"], "action": "adopt", "task_id": original["task_id"]} @@ -119,7 +120,7 @@ def _default(self, node: dict, phase: str, original: dict | None, snapshot: str) return {"node_id": node["id"], "action": "dispatch", "spec": spec} return {"node_id": node["id"], "action": "wait"} - def _pause(self, batch: dict) -> dict: + def _pause(self, batch: dict[str, Any]) -> dict[str, Any]: with self.batches.runtime.store.connection(write=True) as connection: connection.execute("UPDATE agent_dag_batches SET state='waiting_review',attempt='',updated=? WHERE id=?", (time.time(), batch["id"])) @@ -129,7 +130,7 @@ def _pause(self, batch: dict) -> dict: # pylint: disable-next=protected-access # reason: preserve the registry's owner-scoped public projection return self.batches._describe(self.batches._row(batch["id"])) - def _approve(self, batch: dict, request: dict) -> dict: + def _approve(self, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: deadline = _deadline(request) note = request["note"] if not isinstance(note, str) or not note.strip() or len(note) > 4000: @@ -153,7 +154,8 @@ def _approve(self, batch: dict, request: dict) -> dict: raise AgentTaskError("DAG continuation evidence or decisions changed; review again") return self._save_approval(batch, request, review, plan_hash, deadline) - def _save_approval(self, batch: dict, request: dict, review: dict, plan_hash: str, deadline: float) -> dict: + def _save_approval(self, batch: dict[str, Any], request: dict[str, Any], review: dict[str, Any], plan_hash: str, + deadline: float) -> dict[str, Any]: identifier = uuid.uuid4().hex details = {**review, "note": request['note'], "actor": self.actor} checks = (DagTransferChecks(self.batches.runtime.store, batch, @@ -173,14 +175,16 @@ def _save_approval(self, batch: dict, request: dict, review: dict, plan_hash: st self._commit_approval(connection, batch, identifier, review['reports'])) return {"batch_id": batch["id"], "approval_id": identifier, "approval_state": "ready"} - def _commit_approval(self, connection: Any, batch: dict, identifier: str, reports: list) -> None: + def _commit_approval(self, connection: Any, batch: dict[str, Any], identifier: str, + reports: list[dict[str, Any]]) -> None: self._apply(connection, batch, identifier, reports) connection.execute("UPDATE agent_dag_approvals SET state='ready' WHERE id=?", (identifier,)) connection.execute("UPDATE agent_dag_batches SET state='approved',attempt='',updated=? WHERE id=?", (time.time(), batch['id'])) self._handoff_checks(connection, batch, reports) - def _resume_approval(self, batch: dict, request: dict, previous: dict, deadline: float) -> dict: + def _resume_approval(self, batch: dict[str, Any], request: dict[str, Any], previous: dict[str, Any], + deadline: float) -> dict[str, Any]: details = json.loads(previous['details']) if batch['state'] != 'waiting_review' or details['actor'] != self.actor or details['note'] != request['note']: raise AgentTaskError('provisional adoption requires its original explicit approval request') @@ -194,7 +198,7 @@ def _resume_approval(self, batch: dict, request: dict, previous: dict, deadline: return {'batch_id': batch['id'], 'approval_id': previous['id'], 'approval_state': 'ready'} @staticmethod - def _apply(connection: Any, batch: dict, identifier: str, reports: list[dict]) -> None: + def _apply(connection: Any, batch: dict[str, Any], identifier: str, reports: list[dict[str, Any]]) -> None: for report in reports: decision = report["decision"] node_id = decision["node_id"] @@ -212,7 +216,7 @@ def _apply(connection: Any, batch: dict, identifier: str, reports: list[dict]) - connection.execute("INSERT OR REPLACE INTO agent_dag_adoptions VALUES (?,?,?,?,?)", (batch["id"], node_id, decision["task_id"], report["original"]["task_id"], identifier)) - def _start(self, batch: dict, request: dict) -> dict: + def _start(self, batch: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: deadline = _deadline(request) with self.batches.runtime.store.connection() as connection: row = connection.execute("SELECT * FROM agent_dag_approvals WHERE id=? AND batch_id=?", @@ -232,7 +236,8 @@ def _start(self, batch: dict, request: dict) -> dict: "max_parallel": batch["max_parallel"], "definition": bind_definition(batch["definition"], batch["id"], batch["graph_hash"], batch["bindings"])} - def _activate(self, batch: dict, identifier: str, reports: list, deadline: float, baseline: dict | None) -> str: + def _activate(self, batch: dict[str, Any], identifier: str, reports: list[dict[str, Any]], deadline: float, + baseline: dict[str, Any] | None) -> str: attempt = uuid.uuid4().hex checks = (DagTransferChecks(self.batches.runtime.store, batch, lambda: self._remote_checks(batch, reports, deadline), baseline=baseline) @@ -250,19 +255,20 @@ def _activate(self, batch: dict, identifier: str, reports: list, deadline: float self._commit_start(connection, batch, identifier, attempt, reports)) return attempt - def _commit_start(self, connection: Any, batch: dict, identifier: str, attempt: str, reports: list) -> None: + def _commit_start(self, connection: Any, batch: dict[str, Any], identifier: str, attempt: str, + reports: list[dict[str, Any]]) -> None: connection.execute("UPDATE agent_dag_approvals SET state='used' WHERE id=?", (identifier,)) connection.execute("UPDATE agent_dag_batches SET state='running',attempt=?,updated=? WHERE id=?", (attempt, time.time(), batch['id'])) self._handoff_checks(connection, batch, reports) - def _start_context(self, batch: dict, request: dict, details: dict) -> None: + def _start_context(self, batch: dict[str, Any], request: dict[str, Any], details: dict[str, Any]) -> None: parallel = request["max_parallel"] if (details["actor"] != self.actor or not isinstance(parallel, int) or isinstance(parallel, bool) or parallel != batch["max_parallel"]): raise AgentTaskError("DAG continuation actor or parallelism changed") - def validate_node(self, batch: dict, node_id: str, attempt: str) -> dict: + def validate_node(self, batch: dict[str, Any], node_id: str, attempt: str) -> dict[str, Any]: """Recheck adopted dependency evidence under the active attempt without dispatch or input.""" if batch["state"] != "running" or batch["attempt"] != attempt: raise AgentTaskError("DAG continuation attempt is inactive") @@ -288,7 +294,7 @@ def validate_node(self, batch: dict, node_id: str, attempt: str) -> dict: return {"outcome": "completed", "task_id": adoption["task_id"], "task_state": "succeeded", "input_released": True} - def _validate_adoption(self, batch: dict, node_id: str, adoption: dict) -> None: + def _validate_adoption(self, batch: dict[str, Any], node_id: str, adoption: dict[str, Any]) -> None: node = bound_node(batch, node_id) evidence = ContinuationEvidence(batch, runtime=self.batches.runtime) original = evidence.original(node) @@ -303,13 +309,13 @@ def _validate_adoption(self, batch: dict, node_id: str, adoption: dict) -> None: if approval is None: raise AgentTaskError('DAG adoption approval evidence is missing') decisions = json.loads(approval[0])['public']['decisions'] - decision: dict = next((item for item in decisions if item['node_id'] == node_id), {}) + decision: dict[str, Any] = next((item for item in decisions if item['node_id'] == node_id), {}) if 'handoff_id' in decision: evidence.successor(node, original, adoption['task_id'], decision['handoff_id']) else: evidence.successor(node, original, adoption['task_id']) - def _remote_grant(self, batch: dict, node_id: str, adoption: dict) -> bool: + def _remote_grant(self, batch: dict[str, Any], node_id: str, adoption: dict[str, Any]) -> bool: if bound_node(batch, node_id)['host'] == 'local': return False with self.batches.runtime.store.connection() as connection: @@ -318,14 +324,14 @@ def _remote_grant(self, batch: dict, node_id: str, adoption: dict) -> bool: return row is not None and any(item['node_id'] == node_id and 'handoff_id' in item for item in json.loads(row['details'])['public']['decisions']) - def _handoff_checks(self, connection: Any, batch: dict, reports: list[dict]) -> None: + def _handoff_checks(self, connection: Any, batch: dict[str, Any], reports: list[dict[str, Any]]) -> None: for report in reports: decision = report['decision'] if 'handoff_id' in decision and bound_node(batch, decision['node_id'])['host'] == 'local': self.batches.runtime.recovery.handoff_evidence(batch['id'], decision['node_id'], report['original']['task_id'], decision['task_id'], decision['handoff_id'], connection=connection) - def _remote_checks(self, batch: dict, reports: list[dict], deadline: float) -> None: + def _remote_checks(self, batch: dict[str, Any], reports: list[dict[str, Any]], deadline: float) -> None: remaining = deadline - time.monotonic() if remaining <= 0: raise AgentTaskError('remote adoption confirmation deadline expired') diff --git a/je_auto_control/utils/agent_runtime/evidence_handoff.py b/je_auto_control/utils/agent_runtime/evidence_handoff.py index 8fbcebe87..934d91aba 100644 --- a/je_auto_control/utils/agent_runtime/evidence_handoff.py +++ b/je_auto_control/utils/agent_runtime/evidence_handoff.py @@ -28,11 +28,11 @@ def _digest(value: Any) -> str: return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest() -def _identity(value: dict) -> tuple[Any, Any]: +def _identity(value: dict[str, Any]) -> tuple[Any, Any]: return value.get('user_id'), value.get('store_path') -def _principal() -> dict: +def _principal() -> dict[str, Any]: actor = current_authorization() return asdict(actor) if actor is not None else {} @@ -43,7 +43,7 @@ def _identifier(value: Any) -> str: return value -def _manager(actor: dict, owner: dict) -> None: +def _manager(actor: dict[str, Any], owner: dict[str, Any]) -> None: try: authority = DeferredAuthorization(AuthorizationContext(**actor) if actor else None) except (TypeError, ValueError) as error: @@ -54,7 +54,7 @@ def _manager(actor: dict, owner: dict) -> None: raise AuthorizationError('handoff issuer can no longer manage the actual evidence owner') -def _expiry(rows: list[dict]) -> float: +def _expiry(rows: list[dict[str, Any]]) -> float: values = [row['updated'] for row in rows if row['state'] in _TERMINAL] if not values or any(isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) for value in values): @@ -65,12 +65,12 @@ def _expiry(rows: list[dict]) -> float: return deadline -def _retained_tasks(context: dict, tasks: list[dict]) -> list[dict]: +def _retained_tasks(context: dict[str, Any], tasks: list[dict[str, Any]]) -> list[dict[str, Any]]: rows = context.get('retained_rows', []) + tasks return list({row['id']: row for row in rows}.values()) -def _public(row: dict) -> dict: +def _public(row: dict[str, Any]) -> dict[str, Any]: fields = ('id', *(key for key in ('batch_id', 'node_id') if key in row), 'source_task', 'task_id', 'review', 'state', 'expires') result = {key: row[key] for key in fields} @@ -82,13 +82,14 @@ def _public(row: dict) -> dict: class EvidenceHandoffs: """Grant immutable task/DAG completion projections without ambient task-read capability.""" - def __init__(self, runtime: Any, context: Callable, witness: Callable, scope: Callable | None = None, + def __init__(self, runtime: Any, context: Callable[..., dict[str, Any]], witness: Callable[..., dict[str, Any]], + scope: Callable[..., dict[str, Any]] | None = None, records: HandoffRecords | None = None) -> None: self.runtime, self.context, self.witness = runtime, context, witness self.scope = scope self.records = records if records is not None else HandoffRecords() - def control(self, operation: str, request: dict) -> dict: + def control(self, operation: str, request: dict[str, Any]) -> dict[str, Any]: """Review, issue, inspect or revoke a closed caller-scoped evidence handoff.""" self._open() expected = _FIELDS[operation] @@ -117,14 +118,15 @@ def _open(self) -> None: if self.runtime._closed: raise AgentTaskError('runtime is closed') - def describe(self, connection: Any, request: dict, actor: dict, *, issuing: bool = False, - issuer_policies: list[str] | None = None, authorization: dict | None = None) -> tuple: + def describe(self, connection: Any, request: dict[str, Any], actor: dict[str, Any], *, issuing: bool = False, + issuer_policies: list[str] | None = None, authorization: dict[str, Any] | None = None + ) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]: """Supply current private proof to an owning host; this neither issues nor consumes a local grant.""" self._open() return self._proof(connection, request, actor, issuing=issuing, issuer_policies=issuer_policies, authorization=authorization) - def _issue(self, operation: str, request: dict) -> dict: + def _issue(self, operation: str, request: dict[str, Any]) -> dict[str, Any]: actor = _principal() with self.runtime.store.connection(write=True) as connection: proof, _tasks, _context = self._proof(connection, request, actor, issuing=True) @@ -152,18 +154,20 @@ def _issue(self, operation: str, request: dict) -> dict: return {'handoff': _public(row)} @staticmethod - def _insert(connection: Any, row: dict) -> None: + def _insert(connection: Any, row: dict[str, Any]) -> None: HandoffRecords('batch_id' not in row).insert(connection, row) - def _context(self, request: dict, *, connection: Any = None, issuer_policies: list[str] | None = None) -> dict: + def _context(self, request: dict[str, Any], *, connection: Any = None, + issuer_policies: list[str] | None = None) -> dict[str, Any]: options = {'identity_only': True} if self.scope is not None else {} identifiers = ((request['source_task'],) if self.records.standalone else (request['batch_id'], request['node_id'])) return self.context(*identifiers, origin_policies=issuer_policies, connection=connection, **options) - def _proof(self, connection: Any, request: dict, actor: dict, *, issuing: bool = False, + def _proof(self, connection: Any, request: dict[str, Any], actor: dict[str, Any], *, issuing: bool = False, issuer_policies: list[str] | None = None, - authorization: dict | None = None) -> tuple[dict, list[dict], dict]: + authorization: dict[str, Any] | None = None + ) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]: context = self._context(request, connection=connection, issuer_policies=issuer_policies) if self.records.standalone: allowed = {'paused', 'waiting_user', 'recovering', 'cancelled', 'timed_out', 'failed', 'succeeded'} @@ -193,7 +197,9 @@ def _proof(self, connection: Any, request: dict, actor: dict, *, issuing: bool = proof['completion_authorization'] = context['completion_authorization'] return proof, [self._task(connection, child, link) for _source, child, link in reversed(links)], context - def _segments(self, connection: Any, context: dict, links: list, actor: dict) -> tuple[list, list]: + def _segments(self, connection: Any, context: dict[str, Any], + links: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]], + actor: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: segments, tasks = [], [context['source']] for source, child, link in links: _manager(actor, source['owner']) @@ -209,7 +215,8 @@ def _segments(self, connection: Any, context: dict, links: list, actor: dict) -> **{key: evidence[key] for key in ('source_snapshot', 'snapshot', 'completion_snapshot')}}) return segments, tasks - def _chain(self, connection: Any, root: str, identifier: str, *, issuing: bool) -> list[tuple[dict, dict, dict]]: + def _chain(self, connection: Any, root: str, identifier: str, *, + issuing: bool) -> list[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]]: _identifier(identifier) chain, seen = [], {root} for _index in range(16): @@ -228,7 +235,7 @@ def _chain(self, connection: Any, root: str, identifier: str, *, issuing: bool) identifier = source['id'] raise AgentTaskError('handoff has no bounded real recovery chain to the original DAG source') - def _row(self, connection: Any, identifier: str, *, issuing: bool) -> dict: + def _row(self, connection: Any, identifier: str, *, issuing: bool) -> dict[str, Any]: if issuing: # pylint: disable-next=protected-access # reason: keep ordinary task ownership before reading issuance evidence self.runtime._row(identifier) @@ -237,7 +244,7 @@ def _row(self, connection: Any, identifier: str, *, issuing: bool) -> dict: _manager(_principal(), row['owner']) return row - def _task(self, connection: Any, row: dict, link: dict) -> dict: + def _task(self, connection: Any, row: dict[str, Any], link: dict[str, Any]) -> dict[str, Any]: completion = connection.execute('SELECT contract FROM agent_completion WHERE task_id=?', (row['id'],)).fetchone() return {'task_id': row['id'], 'state': row['state'], @@ -247,7 +254,7 @@ def _task(self, connection: Any, row: dict, link: dict) -> dict: 'source_task': link['source_task'], 'snapshot': link['snapshot']}}} @staticmethod - def _projection(proof: dict) -> dict: + def _projection(proof: dict[str, Any]) -> dict[str, Any]: binding = proof['binding'] result = {'contract': 1, **{key: binding[key] for key in ('batch_id', 'node_id', 'source_task') if key in binding}, @@ -264,7 +271,7 @@ def _projection(proof: dict) -> dict: for name in ('replaced_origins', 'retained_origins', 'current_origins')}} return result - def _load(self, connection: Any, identifier: str) -> tuple[dict, dict]: + def _load(self, connection: Any, identifier: str) -> tuple[dict[str, Any], dict[str, Any]]: _identifier(identifier) found = self.records.find(connection, identifier) if found is None: @@ -285,14 +292,14 @@ def _load(self, connection: Any, identifier: str) -> tuple[dict, dict]: return row, proof @staticmethod - def _audit_authority(proof: dict) -> None: + def _audit_authority(proof: dict[str, Any]) -> None: current = _principal() participants = (proof['issuer'], proof['binding']['owner'], proof['leaf_owner']) if current and current.get('role') != 'admin' and not any( _identity(current) == _identity(actor) for actor in participants): raise AgentTaskError('handoff does not exist or belongs to another caller') - def _inspect(self, operation: str, request: dict) -> dict: + def _inspect(self, operation: str, request: dict[str, Any]) -> dict[str, Any]: with self.runtime.store.connection() as connection: if operation == 'get_handoff': row, proof = self._load(connection, request['handoff_id']) @@ -302,7 +309,7 @@ def _inspect(self, operation: str, request: dict) -> dict: found = self.records.list(connection, context['binding']) return {'handoffs': [_public(dict(row)) for row in found]} - def _revoke(self, identifier: str) -> dict: + def _revoke(self, identifier: str) -> dict[str, Any]: with self.runtime.store.connection(write=True) as connection: row, proof = self._load(connection, identifier) self._audit_authority(proof) @@ -312,7 +319,7 @@ def _revoke(self, identifier: str) -> dict: row['state'] = 'revoked' return {'handoff': _public(row)} - def _active(self, connection: Any, row: dict) -> None: + def _active(self, connection: Any, row: dict[str, Any]) -> None: current, revoked = self.records.current(connection, row['id']) if current is None or current['state'] != 'active' or revoked or row['expires'] <= time.time(): raise AgentTaskError('handoff is revoked or expired') @@ -320,7 +327,7 @@ def _active(self, connection: Any, row: dict) -> None: raise AgentTaskError('handoff evidence changed') def consume(self, batch_id: str, node_id: str, source_task: str, task_id: str, handoff_id: str, - *, connection: Any = None) -> tuple[dict, list]: + *, connection: Any = None) -> tuple[dict[str, Any], list[dict[str, Any]]]: """Read only completion projections for the exact private grant under the current batch owner.""" request = {'batch_id': batch_id, 'node_id': node_id, 'source_task': source_task, 'task_id': task_id, 'handoff_id': handoff_id} @@ -338,7 +345,8 @@ def consume_task(self, source_task: str, task_id: str, handoff_id: str, authority = HandoffPolicy(context['policy'], context.get('completion_authorization') is not None) return HandoffAccess(projection, rows, links, authority, self.witness, grant) - def _consume(self, request: dict, *, connection: Any = None) -> tuple[dict, list, dict]: + def _consume(self, request: dict[str, Any], *, + connection: Any = None) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]: self._open() try: transaction = self.runtime.store.connection(write=True) if connection is None else nullcontext(connection) diff --git a/je_auto_control/utils/agent_runtime/task_authority.py b/je_auto_control/utils/agent_runtime/task_authority.py index 20a9607ac..714234a90 100644 --- a/je_auto_control/utils/agent_runtime/task_authority.py +++ b/je_auto_control/utils/agent_runtime/task_authority.py @@ -21,16 +21,16 @@ class RecoveryBinding: """An internal atomic envelope, never accepted as caller-authored JSON authority.""" - authorization: dict | None - ownership: dict + authorization: dict[str, Any] | None + ownership: dict[str, Any] @dataclass(frozen=True) class CompletionBinding: """Host-derived read-only proof admitted atomically with the real recovery lineage.""" - recovery: dict | RecoveryBinding | None - details: dict + recovery: dict[str, Any] | RecoveryBinding | None + details: dict[str, Any] validate: Callable[[Any], None] | None = None @@ -43,7 +43,7 @@ class HandoffScope: child_readonly: bool -def validate_ownership_request(operation: str, request: dict, fields: set[str]) -> None: +def validate_ownership_request(operation: str, request: dict[str, Any], fields: set[str]) -> None: """Accept an explicit source-owner policy and its reviewed token, never an arbitrary owner identity.""" expected = set(fields) if "owner_policy" in request: @@ -57,7 +57,7 @@ def validate_ownership_request(operation: str, request: dict, fields: set[str]) @contextmanager -def ownership_scope(row: dict, request: dict) -> Iterator[dict | None]: +def ownership_scope(row: dict[str, Any], request: dict[str, Any]) -> Iterator[dict[str, Any] | None]: """Bind explicit recovery to the current source owner, preserving the actual reviewer separately.""" if "owner_policy" not in request: yield None @@ -72,7 +72,7 @@ def ownership_scope(row: dict, request: dict) -> Iterator[dict | None]: yield value -def ownership_review(value: dict | None, snapshot: str) -> dict | None: +def ownership_review(value: dict[str, Any] | None, snapshot: str) -> dict[str, Any] | None: """Freeze both identities and current roles against the reviewed source snapshot.""" if value is None: return None @@ -81,13 +81,14 @@ def ownership_review(value: dict | None, snapshot: str) -> dict | None: return {**data, "review": digest} -def public_ownership(value: dict) -> dict: +def public_ownership(value: dict[str, Any]) -> dict[str, Any]: """Project audit identity without exposing private user-store paths or input capabilities.""" return {"contract": 1, "policy": value["policy"], "review": value["review"], "owner": value["owner"].get("user_id", "local"), "actor": value["actor"].get("user_id", "local")} -def recovery_binding(authorization: dict | None, ownership: dict | None) -> dict | RecoveryBinding | None: +def recovery_binding(authorization: dict[str, Any] | None, + ownership: dict[str, Any] | None) -> dict[str, Any] | RecoveryBinding | None: """Retain legacy authorization metadata while carrying trusted ownership into the same transaction.""" if ownership is None: return authorization @@ -97,7 +98,7 @@ def recovery_binding(authorization: dict | None, ownership: dict | None) -> dict def bind_recovery(connection: Any, task_id: str, - binding: dict | RecoveryBinding | CompletionBinding | None, owner: dict) -> None: + binding: dict[str, Any] | RecoveryBinding | CompletionBinding | None, owner: dict[str, Any]) -> None: """Atomically record ownership beside lineage and any separately reviewed origin renewal.""" validate = binding.validate if isinstance(binding, CompletionBinding) else None if isinstance(binding, CompletionBinding): @@ -116,7 +117,7 @@ def bind_recovery(connection: Any, task_id: str, validate(connection) -def require_matching_ownership(store: Any, task_id: str, expected: dict | None) -> None: +def require_matching_ownership(store: Any, task_id: str, expected: dict[str, Any] | None) -> None: """A retry cannot change the ownership policy, reviewer or source-owner review of an accepted child.""" with store.connection() as connection: row = connection.execute("SELECT details FROM agent_recovery_owners WHERE task_id=?", (task_id,)).fetchone() @@ -149,7 +150,7 @@ def _principal(value: Any) -> None: raise AgentTaskError(_INVALID_PRINCIPAL) -def recorded_recovery_owner(connection: Any, task_id: str) -> dict | None: +def recorded_recovery_owner(connection: Any, task_id: str) -> dict[str, Any] | None: """Decode actual host-owned recovery principals and validate their complete reviewed binding.""" row = connection.execute('SELECT details FROM agent_recovery_owners WHERE task_id=?', (task_id,)).fetchone() if row is None: @@ -178,7 +179,8 @@ def _ownership_contract(value: Any) -> None: raise AgentTaskError('invalid recovery execution ownership contract') -def check_recovery_authority(runtime: Any, connection: Any, source: dict, child: dict, link: dict) -> None: +def check_recovery_authority(runtime: Any, connection: Any, source: dict[str, Any], child: dict[str, Any], + link: dict[str, Any]) -> None: """Keep actual legacy/explicit reviewers, both owners and current effect scopes live.""" _principal(source['owner']) _principal(child['owner']) @@ -193,7 +195,7 @@ def check_recovery_authority(runtime: Any, connection: Any, source: dict, child: _task_effect_authority(runtime, connection, row) -def _task_effect_identity(runtime: Any, connection: Any, row: dict, historical: bool) -> None: +def _task_effect_identity(runtime: Any, connection: Any, row: dict[str, Any], historical: bool) -> None: recorded = recorded_recovery_owner(connection, row['id']) if recorded is not None and actor_identity(recorded['owner']) != actor_identity(row['owner']): raise AgentTaskError('recovery execution task ownership changed') @@ -206,12 +208,13 @@ def _task_effect_identity(runtime: Any, connection: Any, row: dict, historical: pass -def _task_effect_authority(runtime: Any, connection: Any, row: dict, *, historical: bool = False) -> TaskPolicy: +def _task_effect_authority(runtime: Any, connection: Any, row: dict[str, Any], *, + historical: bool = False) -> TaskPolicy: _task_effect_identity(runtime, connection, row, historical) return _task_effect_policy(runtime, connection, row) -def _task_effect_policy(runtime: Any, connection: Any, row: dict) -> TaskPolicy: +def _task_effect_policy(runtime: Any, connection: Any, row: dict[str, Any]) -> TaskPolicy: # pylint: disable-next=protected-access # reason: retain current host profiles and caller origin ceilings policy = TaskPolicy(runtime._validated_spec(row['spec'])) policy.validate_snapshot() @@ -221,7 +224,7 @@ def _task_effect_policy(runtime: Any, connection: Any, row: dict) -> TaskPolicy: return policy -def check_historical_admission(connection: Any, row: dict) -> None: +def check_historical_admission(connection: Any, row: dict[str, Any]) -> None: """Refresh actual original DAG principals without reopening their stopped input attempt.""" found = connection.execute('SELECT a.actor,b.owner FROM agent_dag_local_tasks a ' 'JOIN agent_dag_batches b ON b.id=a.batch_id WHERE a.task_id=?', (row['id'],)).fetchone() @@ -235,7 +238,7 @@ def check_historical_admission(connection: Any, row: dict) -> None: _check_pair({'actor': actor, 'owner': owner}) -def _handoff_scope(parent: dict, child: dict) -> None: +def _handoff_scope(parent: dict[str, Any], child: dict[str, Any]) -> None: fixed = set(parent) - {'goal', 'actions', 'roots', 'options'} if (set(parent) != set(child) or json.dumps({key: parent[key] for key in fixed}, sort_keys=True) != @@ -252,7 +255,8 @@ def _handoff_scope(parent: dict, child: dict) -> None: raise AgentTaskError('handoff recovery changed fixed options') -def _handoff_retired(runtime: Any, source: dict, child: dict, link: dict, evidence: dict, +def _handoff_retired(runtime: Any, source: dict[str, Any], child: dict[str, Any], link: dict[str, Any], + evidence: dict[str, Any], scope: HandoffScope | None = None) -> None: # pylint: disable-next=protected-access # reason: only inspect short owned runtime retirement witnesses with runtime._mutex: @@ -267,7 +271,8 @@ def _handoff_retired(runtime: Any, source: dict, child: dict, link: dict, eviden raise AgentTaskError('handoff source recovery snapshot changed') -def check_historical_recovery_identity(runtime: Any, connection: Any, source: dict, child: dict, link: dict) -> None: +def check_historical_recovery_identity(runtime: Any, connection: Any, source: dict[str, Any], child: dict[str, Any], + link: dict[str, Any]) -> None: """Refresh actual historical ownership/admission without reviving unavailable input policies.""" ownership = recorded_recovery_owner(connection, child['id']) _check_pair(ownership or {'owner': source['owner'], 'actor': child['owner']}) @@ -278,7 +283,7 @@ def check_historical_recovery_identity(runtime: Any, connection: Any, source: di _task_effect_identity(runtime, connection, row, True) -def _handoff_owners(runtime: Any, connection: Any, source: dict, child: dict, link: dict, +def _handoff_owners(runtime: Any, connection: Any, source: dict[str, Any], child: dict[str, Any], link: dict[str, Any], scope: HandoffScope | None = None) -> TaskPolicy: check_historical_recovery_identity(runtime, connection, source, child, link) if scope is not None: @@ -289,8 +294,9 @@ def _handoff_owners(runtime: Any, connection: Any, source: dict, child: dict, li return source_policy -def check_handoff_history(runtime: Any, connection: Any, source: dict, child: dict, - link: dict, evidence: dict, reader: Callable) -> None: +def check_handoff_history(runtime: Any, connection: Any, source: dict[str, Any], child: dict[str, Any], + link: dict[str, Any], evidence: dict[str, Any], + reader: Callable[[Any, dict[str, Any], dict[str, Any]], HandoffScope | bool]) -> None: """Validate historical authority and effects without reopening a stopped DAG input attempt.""" reviewed = reader(connection, source, child) scope = reviewed if isinstance(reviewed, HandoffScope) else None @@ -306,7 +312,7 @@ def check_handoff_history(runtime: Any, connection: Any, source: dict, child: di source_policy.check(action['command'], action['arguments']) -def _check_pair(value: dict) -> None: +def _check_pair(value: dict[str, Any]) -> None: owner, actor = value["owner"], value["actor"] with DeferredAuthorization(AuthorizationContext(**actor) if actor else None).scope(): if not owns_task(owner, current_authorization()): diff --git a/je_auto_control/utils/agent_runtime/task_recovery.py b/je_auto_control/utils/agent_runtime/task_recovery.py index 7ec36bfbf..27f6cf0cb 100644 --- a/je_auto_control/utils/agent_runtime/task_recovery.py +++ b/je_auto_control/utils/agent_runtime/task_recovery.py @@ -39,9 +39,10 @@ _STOPPED = frozenset({"paused", "waiting_user", "recovering", "cancelled", "timed_out", "failed"}) _POINTER_TOOLS = ("AC_click_mouse", "AC_set_mouse_position", "AC_mouse_scroll", "AC_press_mouse", "AC_release_mouse", "AC_android_tap", "AC_android_swipe") +_Link = tuple[dict[str, Any], dict[str, Any], dict[str, Any]] -def recovery_link(store: Any, task_id: str) -> dict: +def recovery_link(store: Any, task_id: str) -> dict[str, Any]: """Return durable successor provenance, without treating the source as completed.""" with store.connection() as connection: row = connection.execute("SELECT r.source_task,r.snapshot,r.note,r.created,a.details,o.details AS ownership " @@ -82,7 +83,7 @@ def _handoffs(self, *, standalone: bool = False) -> EvidenceHandoffs: return EvidenceHandoffs(self.runtime, context, self.handoff_witness, self.handoff_scope, HandoffRecords(standalone)) - def _handoffs_for(self, operation: str, request: dict) -> EvidenceHandoffs: + def _handoffs_for(self, operation: str, request: dict[str, Any]) -> EvidenceHandoffs: # pylint: disable-next=protected-access # reason: resolve no private storage family after service shutdown if self.runtime._closed: raise AgentTaskError('runtime is closed') @@ -97,8 +98,9 @@ def task_handoff_evidence(self, source_task: str, task_id: str, handoff_id: str, """Adopt only a validated explicit non-DAG projection without ordinary task access.""" return self._handoffs(standalone=True).consume_task(source_task, task_id, handoff_id, connection=connection) - def handoff_scope(self, connection: Any, context: dict, links: list, issuer_policies: list[str] | None, - authorization: dict | None, *, issuing: bool = False) -> dict: + def handoff_scope(self, connection: Any, context: dict[str, Any], links: list[_Link], + issuer_policies: list[str] | None, + authorization: dict[str, Any] | None, *, issuing: bool = False) -> dict[str, Any]: """Derive historical input policy or explicitly reviewed read-only evidence policy on the host.""" # pylint: disable-next=import-outside-toplevel # reason: only explicit handoff proof needs completion renewal validation from je_auto_control.utils.agent_runtime.completion_recovery import handoff_completion_scope @@ -112,7 +114,8 @@ def handoff_scope(self, connection: Any, context: dict, links: list, issuer_poli return {'policy': self._task_handoff_policy(context, links, issuer_policies), 'evidence_scope': True} return {'policy': self.runtime.batches.handoff_policy(context['source'], issuer_policies)} - def _task_handoff_policy(self, context: dict, links: list, issuer_policies: list[str] | None) -> TaskPolicy: + def _task_handoff_policy(self, context: dict[str, Any], links: list[_Link], + issuer_policies: list[str] | None) -> TaskPolicy: template = detached(context['source']['spec']) origins = set(issuer_policies or []) for row in (links[0][0], *(child for _source, child, _link in links)): @@ -127,15 +130,16 @@ def _task_handoff_policy(self, context: dict, links: list, issuer_policies: list return TaskPolicy(self.runtime._validated_spec(template)) def handoff_evidence(self, batch_id: str, node_id: str, source_task: str, - task_id: str, handoff_id: str, *, connection: Any = None) -> tuple[dict, list]: + task_id: str, handoff_id: str, *, + connection: Any = None) -> tuple[dict[str, Any], list[dict[str, Any]]]: """Read one explicitly granted completion projection without changing ordinary runtime access.""" return self._handoffs().consume(batch_id, node_id, source_task, task_id, handoff_id, connection=connection) - def handoff_snapshot(self, connection: Any, row: dict) -> dict: + def handoff_snapshot(self, connection: Any, row: dict[str, Any]) -> dict[str, Any]: """Supply the existing private task/completion snapshot to host-owned evidence collaborators.""" return self._handoff_snapshot(connection, row) - def _handoff_snapshot(self, connection: Any, row: dict) -> dict: + def _handoff_snapshot(self, connection: Any, row: dict[str, Any]) -> dict[str, Any]: actions = self.runtime.store.read_actions(connection, row['id']) reviews = [dict(item) for item in connection.execute( 'SELECT * FROM agent_reviews WHERE task_id=? ORDER BY action_id', (row['id'],))] @@ -145,18 +149,20 @@ def _handoff_snapshot(self, connection: Any, row: dict) -> dict: return {'actions': actions, 'snapshot': snapshot, 'completion_snapshot': request_spec_digest({ 'snapshot': snapshot, 'retirement': dict(retired) if retired is not None else None})} - def handoff_witness(self, connection: Any, source: dict, child: dict, link: dict, *, scope: Any = None) -> dict: + def handoff_witness(self, connection: Any, source: dict[str, Any], child: dict[str, Any], link: dict[str, Any], *, + scope: Any = None) -> dict[str, Any]: """Bind real historical recovery snapshots and current authority without target probes.""" before, after = self._handoff_snapshot(connection, source), self._handoff_snapshot(connection, child) evidence = {'source_snapshot': before['snapshot'], 'source_actions': before['actions'], 'snapshot': after['snapshot'], 'actions': after['actions'], 'completion_snapshot': after['completion_snapshot']} - def reader(active: Any, parent: dict, task: dict) -> Any: + def reader(active: Any, parent: dict[str, Any], task: dict[str, Any]) -> Any: return self._handoff_reader(active, parent, task, scope=scope) check_handoff_history(self.runtime, connection, source, child, link, evidence, reader) return evidence - def _handoff_reader(self, connection: Any, source: dict, child: dict, *, scope: Any = None) -> bool | HandoffScope: + def _handoff_reader(self, connection: Any, source: dict[str, Any], child: dict[str, Any], *, + scope: Any = None) -> bool | HandoffScope: # pylint: disable-next=import-outside-toplevel # reason: reuse privately admitted read-only scope without a reverse import from je_auto_control.utils.agent_runtime.completion_recovery import check_completion_authority, completion_spec if scope is not None: @@ -179,7 +185,8 @@ def _handoff_reader(self, connection: Any, source: dict, child: dict, *, scope: raise AgentTaskError('handoff read-only verification scope changed') return True - def review_evidence(self, connection: Any, source: dict, child: dict, link: dict) -> dict: + def review_evidence(self, connection: Any, source: dict[str, Any], child: dict[str, Any], + link: dict[str, Any]) -> dict[str, Any]: """Read exact source/child snapshots for skill publication without input or clock renewal.""" # pylint: disable-next=protected-access # reason: do not adopt live or unwinding source/child input with self.runtime._mutex: @@ -205,7 +212,7 @@ def review_evidence(self, connection: Any, source: dict, child: dict, link: dict 'retirement': dict(retired) if retired is not None else None}), 'source_actions': actions, 'actions': child_actions} - def control(self, operation: str, request: Any = None) -> dict: + def control(self, operation: str, request: Any = None) -> dict[str, Any]: """Preview without target access, or create an owner-scoped, deduplicated successor.""" request = durable_payload(detached(request)) if not isinstance(operation, str) or operation not in OPERATIONS or not isinstance(request, dict): @@ -233,7 +240,7 @@ def control(self, operation: str, request: Any = None) -> dict: return self._preview(row, receipts, reviews, reauthorize=operation == "review_authorization", ownership=ownership) - def _read(self, row: dict) -> tuple[list[dict], list[dict]]: + def _read(self, row: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: # pylint: disable-next=protected-access # reason: a successor cannot bypass an unretired input owner if row["state"] not in _STOPPED or row["id"] in self.runtime._leases: raise AgentTaskError("recovery requires a stopped task with no active input owner") @@ -244,7 +251,7 @@ def _read(self, row: dict) -> tuple[list[dict], list[dict]]: "SELECT * FROM agent_reviews WHERE task_id=? ORDER BY action_id", (row["id"],))] return self.runtime.store.actions(row["id"]), reviews - def _template(self, row: dict, authorization: dict | None = None) -> dict: + def _template(self, row: dict[str, Any], authorization: dict[str, Any] | None = None) -> dict[str, Any]: spec = detached(row["spec"]) spec["goal"] = "Reviewed remainder: " + spec["goal"][:15940] spec["options"].pop("skill_pin", None) @@ -255,8 +262,8 @@ def _template(self, row: dict, authorization: dict | None = None) -> dict: # pylint: disable-next=protected-access # reason: the shared host policy must normalize every review template return self.runtime._validated_spec(spec).to_dict() - def _preview(self, row: dict, receipts: list[dict], reviews: list[dict], *, reauthorize: bool = False, - ownership: dict | None = None) -> dict: + def _preview(self, row: dict[str, Any], receipts: list[dict[str, Any]], reviews: list[dict[str, Any]], *, + reauthorize: bool = False, ownership: dict[str, Any] | None = None) -> dict[str, Any]: active = effective_actions(receipts) source = AgentTaskSpec.from_dict(row["spec"]) snapshot = _snapshot(row, receipts, reviews) @@ -284,7 +291,7 @@ def _preview(self, row: dict, receipts: list[dict], reviews: list[dict], *, reau self._review_authorized_actions(result, template) return result - def _review_authorized_actions(self, result: dict, template: dict) -> None: + def _review_authorized_actions(self, result: dict[str, Any], template: dict[str, Any]) -> None: if result["source_mode"] != "skill": return candidate = result["draft"] @@ -298,7 +305,8 @@ def _review_authorized_actions(self, result: dict, template: dict) -> None: result.update(draft=None, review_template=candidate) result["issues"].append("action_scope_requires_review") - def _creation_scope(self, row: dict, request: dict) -> tuple[dict, dict | None]: + def _creation_scope(self, row: dict[str, Any], + request: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any] | None]: if "authorization_review" not in request: return self._template(row), None authorization = prepare_authorization(AgentTaskSpec.from_dict(row["spec"]), request["snapshot"]) @@ -306,7 +314,8 @@ def _creation_scope(self, row: dict, request: dict) -> tuple[dict, dict | None]: raise AgentTaskError("source authorization context changed; review authorization again") return self._template(row, authorization), authorization - def _create(self, row: dict, request: dict, ownership: dict | None = None) -> dict: + def _create(self, row: dict[str, Any], request: dict[str, Any], + ownership: dict[str, Any] | None = None) -> dict[str, Any]: # pylint: disable-next=import-outside-toplevel # reason: ordinary recovery cannot upgrade a read-only admission from je_auto_control.utils.agent_runtime.completion_recovery import require_executable_task require_executable_task(self.runtime.store, row["id"]) @@ -337,8 +346,8 @@ def _create(self, row: dict, request: dict, ownership: dict | None = None) -> di return {"task_id": task.task_id, "state": task.state, "recovery": recovery_link(self.runtime.store, task.task_id)} - def _existing(self, source: str, snapshot: Any, spec: dict, review: str | None = None, - ownership: dict | None = None) -> dict | None: + def _existing(self, source: str, snapshot: Any, spec: dict[str, Any], review: str | None = None, + ownership: dict[str, Any] | None = None) -> dict[str, Any] | None: with self.runtime.store.connection() as connection: record = connection.execute("SELECT task_id,snapshot FROM agent_task_recoveries WHERE source_task=?", (source,)).fetchone() @@ -356,7 +365,7 @@ def _existing(self, source: str, snapshot: Any, spec: dict, review: str | None = "recovery": link} -def _snapshot(row: dict, receipts: list[dict], reviews: list[dict]) -> str: +def _snapshot(row: dict[str, Any], receipts: list[dict[str, Any]], reviews: list[dict[str, Any]]) -> str: return request_spec_digest({"task": row, "actions": receipts, "reviews": reviews}) @@ -366,7 +375,7 @@ def _review_note(note: Any) -> str: return note -def _successor(store: Any, source: str) -> dict | None: +def _successor(store: Any, source: str) -> dict[str, Any] | None: with store.connection() as connection: row = connection.execute("SELECT task_id FROM agent_task_recoveries WHERE source_task=?", (source,)).fetchone() return {"task_id": row["task_id"], "recovery": recovery_link(store, row["task_id"])} if row is not None else None @@ -378,7 +387,7 @@ def _require_operator() -> None: raise AuthorizationError("reviewing task recovery requires drive_input") -def _source_issues(spec: AgentTaskSpec, receipts: list[dict]) -> list[str]: +def _source_issues(spec: AgentTaskSpec, receipts: list[dict[str, Any]]) -> list[str]: if any(item["status"] != "confirmed" for item in receipts): return ["unknown_source_effects"] if spec.mode != "skill": @@ -389,7 +398,8 @@ def _source_issues(spec: AgentTaskSpec, receipts: list[dict]) -> list[str]: return ["source_readback_mismatch"] -def _review_plan(source: AgentTaskSpec, receipts: list[dict], active: list[dict], template: dict) -> dict: +def _review_plan(source: AgentTaskSpec, receipts: list[dict[str, Any]], active: list[dict[str, Any]], + template: dict[str, Any]) -> dict[str, Any]: issues = _source_issues(source, active) if source.mode != "skill": template.update(goal="", actions=[]) @@ -422,7 +432,7 @@ def _capture_names(value: Any) -> set[str]: return set() -def _capture_reference(value: dict) -> set[str]: +def _capture_reference(value: dict[str, Any]) -> set[str]: if _CAPTURE_KEY not in value: return set() if set(value) - {_CAPTURE_KEY, "transform"} or not isinstance(value[_CAPTURE_KEY], str) or not value[_CAPTURE_KEY]: @@ -431,7 +441,7 @@ def _capture_reference(value: dict) -> set[str]: return {value[_CAPTURE_KEY]} -def _action_issues(actions: list[dict]) -> list[str]: +def _action_issues(actions: list[dict[str, Any]]) -> list[str]: available: set[str] = set() issues = [] for action in actions: @@ -449,7 +459,7 @@ def _action_issues(actions: list[dict]) -> list[str]: return issues -def _capture_declaration(action: dict) -> set[str]: +def _capture_declaration(action: dict[str, Any]) -> set[str]: if "capture" not in action: return set() if not isinstance(action["capture"], str) or not action["capture"]: @@ -463,7 +473,7 @@ def _check_transform(operation: Any) -> None: transformed("", operation) -def _check_scope(template: dict, reviewed: dict) -> None: +def _check_scope(template: dict[str, Any], reviewed: dict[str, Any]) -> None: # The reviewer may add fresh-state resume conditions; everything else must match the source. fixed = set(template) - {"goal", "actions", "resume_conditions"} if any(request_spec_digest({"value": template[key]}) != request_spec_digest({"value": reviewed[key]}) diff --git a/je_auto_control/utils/agent_runtime/task_skills.py b/je_auto_control/utils/agent_runtime/task_skills.py index ea20825c7..64a0089b5 100644 --- a/je_auto_control/utils/agent_runtime/task_skills.py +++ b/je_auto_control/utils/agent_runtime/task_skills.py @@ -29,14 +29,15 @@ class AgentSkills: """Keep reviewed skills in the task database, separate from mutable legacy action macros.""" - def __init__(self, runtime: Any, *, completion_authority: Callable | None = None, - completion_template: Callable | None = None, recovery_review: Callable | None = None) -> None: + def __init__(self, runtime: Any, *, completion_authority: Callable[..., Any] | None = None, + completion_template: Callable[..., Any] | None = None, + recovery_review: Callable[..., Any] | None = None) -> None: self.runtime = runtime self._completion_authority = completion_authority self._completion_template = completion_template self._recovery_review = recovery_review - def control(self, operation: str, request: Any = None) -> dict: + def control(self, operation: str, request: Any = None) -> dict[str, Any]: """Perform a fixed owner-scoped skill operation; accepted snapshots never mutate.""" request = durable_payload(detached({} if request is None else request)) if not isinstance(request, dict) or not isinstance(operation, str) or operation not in OPERATIONS: @@ -52,11 +53,11 @@ def control(self, operation: str, request: Any = None) -> dict: return handlers[operation](request) @staticmethod - def _fields(request: dict, required: set[str], optional: set[str] | None = None) -> None: + def _fields(request: dict[str, Any], required: set[str], optional: set[str] | None = None) -> None: if not required <= set(request) or set(request) - required - (optional or set()): raise AgentTaskError("invalid skill operation fields") - def _get(self, candidate_id: str) -> dict: + def _get(self, candidate_id: str) -> dict[str, Any]: if not isinstance(candidate_id, str): raise AgentTaskError("candidate_id must be a string") with self.runtime.store.connection() as connection: @@ -76,7 +77,7 @@ def _get(self, candidate_id: str) -> dict: result["publication"] = publication_details(connection, publication) return result - def task_pin(self, row: dict) -> dict: + def task_pin(self, row: dict[str, Any]) -> dict[str, Any]: """Return only a service-bound immutable task pin, never a caller's unsupported version claim.""" with self.runtime.store.connection() as connection: trial = connection.execute("SELECT spec_hash FROM agent_skill_trials WHERE task_id=?", @@ -85,18 +86,18 @@ def task_pin(self, row: dict) -> dict: return {} return detached(row["spec"]["options"].get("skill_pin", {})) - def _get_request(self, request: dict) -> dict: + def _get_request(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {"candidate_id"}) return self._get(request["candidate_id"]) - def _list(self, request: dict) -> dict: + def _list(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, set()) with self.runtime.store.connection() as connection: rows = connection.execute("SELECT id,owner FROM agent_skill_candidates ORDER BY created DESC").fetchall() identifiers = [row["id"] for row in rows if owns_task(json.loads(row["owner"]), current_authorization())] return {"candidates": [self._get(identifier) for identifier in identifiers[:200]], "total": len(identifiers)} - def _record(self, request: dict) -> dict: + def _record(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {"task_id", "name"}, {"parameters", "validation_criteria", "completion_task_id", "handoff_id"}) if 'handoff_id' in request and 'completion_task_id' not in request: @@ -113,7 +114,7 @@ def _record(self, request: dict) -> dict: return self._save(request["name"], uuid.uuid4().hex, row["owner"], spec, parameters, {"source_task": row["id"], "kind": "semantic_recording", "parent_version": 0}) - def _record_completed(self, request: dict) -> dict: + def _record_completed(self, request: dict[str, Any]) -> dict[str, Any]: with self.runtime.store.connection(write=True) as connection: # pylint: disable-next=protected-access # reason: retain the runtime's live source ownership boundary row = self.runtime._row(request['task_id']) @@ -133,8 +134,8 @@ def _record_completed(self, request: dict) -> dict: raise AgentTaskError('skill recording ownership changed') return self._get(candidate_id) - def _recording_scope(self, connection: Any, task_id: str, proof: dict, - selection: Any = None) -> dict | None: + def _recording_scope(self, connection: Any, task_id: str, proof: dict[str, Any], + selection: Any = None) -> dict[str, Any] | None: if isinstance(selection, HandoffAccess): template = detached(selection.read(proof['effect_task'])['spec']) template['roots'] = list(selection.policy.spec.roots) @@ -149,14 +150,16 @@ def _recording_scope(self, connection: Any, task_id: str, proof: dict, raise AgentTaskError('renewed skill completion has no approved effect scope') return scope['effect_spec'] - def _save(self, name: str, skill_id: str, owner: dict, spec: dict, parameters: dict, provenance: dict) -> dict: + def _save(self, name: str, skill_id: str, owner: dict[str, Any], spec: dict[str, Any], parameters: dict[str, Any], + provenance: dict[str, Any]) -> dict[str, Any]: candidate = self._candidate(name, skill_id, owner, spec, parameters, provenance) with self.runtime.store.connection(write=True) as connection: candidate_id = self._insert_candidate(connection, candidate) return self._get(candidate_id) @staticmethod - def _candidate(name: str, skill_id: str, owner: dict, spec: dict, parameters: dict, provenance: dict) -> dict: + def _candidate(name: str, skill_id: str, owner: dict[str, Any], spec: dict[str, Any], parameters: dict[str, Any], + provenance: dict[str, Any]) -> dict[str, Any]: if not isinstance(name, str) or not name.strip() or len(name) > 200: raise AgentTaskError("skill name must have between one and two hundred characters") return {'id': uuid.uuid4().hex, 'skill_id': skill_id, 'name': name, 'owner': owner, 'spec': spec, @@ -165,7 +168,7 @@ def _candidate(name: str, skill_id: str, owner: dict, spec: dict, parameters: di 'state': 'draft', 'version': 0, 'created': time.time()} @staticmethod - def _insert_candidate(connection: Any, candidate: dict) -> str: + def _insert_candidate(connection: Any, candidate: dict[str, Any]) -> str: provenance = candidate['provenance'] existing = existing_authorization(connection, provenance, candidate['digest']) if existing is not None: @@ -181,7 +184,7 @@ def _insert_candidate(connection: Any, candidate: dict) -> str: candidate['digest'], candidate['id'])) return candidate['id'] - def _repair(self, request: dict) -> dict: + def _repair(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {"candidate_id", "changes", "note"}) parent = self._get(request["candidate_id"]) if parent["state"] != "accepted": @@ -196,23 +199,23 @@ def _repair(self, request: dict) -> dict: {"kind": "semantic_repair", "parent": parent["id"], "parent_version": parent["version"], "changes": request["changes"], "note": note}) - def _materialize(self, candidate: dict, parameters: Any) -> dict: + def _materialize(self, candidate: dict[str, Any], parameters: Any) -> dict[str, Any]: spec = instantiate(candidate["spec"], candidate["parameters"], parameters) spec["options"]["skill_pin"] = _pin(candidate) return self.runtime._validated_spec(spec).to_dict() - def _preview(self, request: dict) -> dict: + def _preview(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {"candidate_id"}, {"parameters"}) candidate = self._get(request["candidate_id"]) return {"spec": self._materialize(candidate, request.get("parameters", {})), "candidate_id": candidate["id"], "digest": candidate["digest"]} - def _validate(self, request: dict) -> dict: + def _validate(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {"candidate_id"}, {"parameters"}) candidate = self._get(request["candidate_id"]) return self._submit(candidate, request.get("parameters", {}), "validation") - def _submit(self, candidate: dict, parameters: dict, purpose: str) -> dict: + def _submit(self, candidate: dict[str, Any], parameters: dict[str, Any], purpose: str) -> dict[str, Any]: spec = self._materialize(candidate, parameters) task = self.runtime.submit(spec, idempotency_key='skill-trial-' + uuid.uuid4().hex) with self.runtime.store.connection(write=True) as connection: @@ -223,7 +226,7 @@ def _submit(self, candidate: dict, parameters: dict, purpose: str) -> dict: return {"task_id": task.task_id, "state": task.state, "candidate_id": candidate["id"], "purpose": purpose, "digest": candidate["digest"]} - def _accept(self, request: dict) -> dict: + def _accept(self, request: dict[str, Any]) -> dict[str, Any]: required = {"candidate_id", "task_id", "expected_version", "note"} if 'execution_task_id' in request: required |= {'execution_task_id', 'execution_review'} @@ -234,7 +237,7 @@ def _accept(self, request: dict) -> dict: except AuthorizationError as error: raise AgentTaskError('skill publication authority changed; review again') from error - def _review_execution(self, request: dict) -> dict: + def _review_execution(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {'candidate_id', 'task_id', 'execution_task_id'}, {'completion_task_id', 'handoff_id'}) try: with DeferredAuthorization.capture().scope(), self.runtime.store.connection(write=True) as connection: @@ -253,7 +256,7 @@ def _review_execution(self, request: dict) -> dict: except AuthorizationError as error: raise AgentTaskError('skill execution authority changed; review again') from error - def _publish(self, request: dict) -> dict: + def _publish(self, request: dict[str, Any]) -> dict[str, Any]: note = _note(request["note"]) expected = request["expected_version"] if isinstance(expected, bool) or not isinstance(expected, int) or expected < 0: @@ -270,12 +273,13 @@ def _publish(self, request: dict) -> dict: return self._get(candidate["id"]) @staticmethod - def _check_candidate_owner(candidate: dict) -> None: + def _check_candidate_owner(candidate: dict[str, Any]) -> None: with DeferredAuthorization.capture().scope(): if not owns_task(candidate['owner'], current_authorization()): raise AgentTaskError('skill candidate ownership changed') - def _publication_evidence(self, connection: Any, row: dict, request: dict) -> tuple[dict | None, dict | None]: + def _publication_evidence(self, connection: Any, row: dict[str, Any], + request: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: if 'execution_task_id' in request: execution = self._execution_proof(connection, row, request) if request['execution_review'] != execution['review']: @@ -288,19 +292,19 @@ def _publication_evidence(self, connection: Any, row: dict, request: dict) -> tu assert_verified(row) return None, None - def _execution_proof(self, connection: Any, row: dict, request: dict) -> dict: + def _execution_proof(self, connection: Any, row: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: if self._recovery_review is None: raise AgentTaskError('runtime has no reviewed skill recovery provider') selection = self._completion_selection(connection, row, request) review = selection if isinstance(selection, HandoffAccess) else self._recovery_review - def completed(active: Any, effect: dict, identifier: Any) -> dict: + def completed(active: Any, effect: dict[str, Any], identifier: Any) -> dict[str, Any]: selected = selection if isinstance(selection, HandoffAccess) else identifier return self._completion_proof(active, effect, selected) proof = check_skill_execution(self.runtime, connection, row, request, review, verified_skill_actions, completed) return {**proof, 'review': digest(proof)} - def _completion_selection(self, connection: Any, row: dict, request: dict) -> Any: + def _completion_selection(self, connection: Any, row: dict[str, Any], request: dict[str, Any]) -> Any: if 'handoff_id' not in request: return request.get('completion_task_id') selected = request.get('completion_task_id', request.get('execution_task_id')) @@ -312,15 +316,15 @@ def _completion_selection(self, connection: Any, row: dict, request: dict) -> An return self.runtime.recovery.task_handoff_evidence(row['id'], selected, request['handoff_id'], connection=connection) - def _completion_proof(self, connection: Any, row: dict, task_id: Any) -> dict: + def _completion_proof(self, connection: Any, row: dict[str, Any], task_id: Any) -> dict[str, Any]: if self._completion_authority is None or self._completion_template is None: raise AgentTaskError('runtime has no reviewed skill completion provider') return check_skill_completion(self.runtime, connection, row, task_id, self._completion_authority, self._completion_template, digest) @staticmethod - def _record_publication(connection: Any, candidate: dict, row: dict, note: str, expected: int, - proof: dict | None, execution: dict | None = None) -> None: + def _record_publication(connection: Any, candidate: dict[str, Any], row: dict[str, Any], note: str, expected: int, + proof: dict[str, Any] | None, execution: dict[str, Any] | None = None) -> None: latest = connection.execute('SELECT COALESCE(MAX(version),0) FROM agent_skill_candidates WHERE skill_id=?', (candidate['skill_id'],)).fetchone()[0] if latest != expected or candidate['provenance']['parent_version'] != expected: @@ -340,7 +344,7 @@ def _record_publication(connection: Any, candidate: dict, row: dict, note: str, (candidate['id'], json.dumps(execution))) @staticmethod - def _check_trial(connection: Any, candidate: dict, row: dict) -> None: + def _check_trial(connection: Any, candidate: dict[str, Any], row: dict[str, Any]) -> None: trial = connection.execute("SELECT * FROM agent_skill_trials WHERE task_id=? AND candidate_id=?", (row["id"], candidate["id"])).fetchone() if trial is None or trial["purpose"] != "validation" or digest(row["spec"]) != trial["spec_hash"]: @@ -349,7 +353,7 @@ def _check_trial(connection: Any, candidate: dict, row: dict) -> None: if pin != _pin(candidate): raise AgentTaskError("validation task skill snapshot does not match") - def _run(self, request: dict) -> dict: + def _run(self, request: dict[str, Any]) -> dict[str, Any]: self._fields(request, {"skill_id", "version"}, {"parameters"}) version = request["version"] if isinstance(version, bool) or not isinstance(version, int) or version < 1: @@ -368,6 +372,6 @@ def _note(value: Any) -> str: return value -def _pin(candidate: dict) -> dict: +def _pin(candidate: dict[str, Any]) -> dict[str, Any]: return {"candidate_id": candidate["id"], "skill_id": candidate["skill_id"], "version": candidate["version"], "digest": candidate["digest"]} diff --git a/je_auto_control/utils/agent_runtime/transfer_host.py b/je_auto_control/utils/agent_runtime/transfer_host.py index 5414e8763..205cc50bd 100644 --- a/je_auto_control/utils/agent_runtime/transfer_host.py +++ b/je_auto_control/utils/agent_runtime/transfer_host.py @@ -19,31 +19,33 @@ from je_auto_control.utils.rbac.authorization import AuthorizationContext, current_authorization from je_auto_control.utils.rbac.deferred import DeferredAuthorization +_Link = tuple[dict[str, Any], dict[str, Any], dict[str, Any]] -def principal() -> dict: + +def principal() -> dict[str, Any]: """Capture only the actual local authenticated identity, never a request-authored principal.""" with DeferredAuthorization.capture().scope(): current = current_authorization() return asdict(current) if current is not None else {} -def actor_key(actor: dict) -> str: +def actor_key(actor: dict[str, Any]) -> str: """Bind stable principal provenance while checking current roles separately on each operation.""" return sha256(_canonical({'user_id': actor.get('user_id'), 'store_path': actor.get('store_path')})).hexdigest() -def _refresh(actor: dict) -> DeferredAuthorization: +def _refresh(actor: dict[str, Any]) -> DeferredAuthorization: return DeferredAuthorization(AuthorizationContext(**actor) if actor else None) -def _manager(actor: dict, owner: dict) -> None: +def _manager(actor: dict[str, Any], owner: dict[str, Any]) -> None: with _refresh(actor).scope(): current = current_authorization() if current is not None and current.role != 'admin' and actor_key(asdict(current)) != actor_key(owner): raise AgentTaskError('source task does not exist or belongs to another caller') -def _with_origin_scope(spec: dict, scope: list[str] | None) -> dict: +def _with_origin_scope(spec: dict[str, Any], scope: list[str] | None) -> dict[str, Any]: if scope is None: return spec options = spec['options'] @@ -56,8 +58,8 @@ def _with_origin_scope(spec: dict, scope: list[str] | None) -> dict: class TransferHost: """Actual runtime callbacks supply policy, private completion checks and lifecycle observations.""" - def __init__(self, runtime: Any, policy: tuple[Callable, ...], - completion: Callable, available: Callable[[], bool], retired: Callable[[str], bool]) -> None: + def __init__(self, runtime: Any, policy: tuple[Callable[..., Any], ...], + completion: Callable[..., Any], available: Callable[[], bool], retired: Callable[[str], bool]) -> None: self.runtime, self.completion = runtime, completion self._callbacks = policy _policy, submitted, digest, ownership, _paths = policy[:5] @@ -65,23 +67,23 @@ def __init__(self, runtime: Any, policy: tuple[Callable, ...], self.available, self.retired = available, retired @property - def policy(self) -> Callable: + def policy(self) -> Callable[..., Any]: """Use the injected source policy factory without a reverse dependency on task models.""" return self._callbacks[0] @property - def private_paths(self) -> Callable: + def private_paths(self) -> Callable[..., Any]: """Inspect actual host-private paths through the source host's existing collaborator.""" return self._callbacks[4] - def destination_context(self, target: str, directory: str, *, reviewed: dict | None = None, - connection: Any = None) -> dict: + def destination_context(self, target: str, directory: str, *, reviewed: dict[str, Any] | None = None, + connection: Any = None) -> dict[str, Any]: """Validate a destination against actual local profile and retained live origin constraints.""" self.check_open() return destination_scope(self._callbacks[5], self._callbacks[6], target, directory, reviewed=reviewed, connection=connection) - def managed(self, source_task: str, actor: dict, *, connection: Any = None) -> dict: + def managed(self, source_task: str, actor: dict[str, Any], *, connection: Any = None) -> dict[str, Any]: """Authorize source management without requiring still-active export or input authority.""" self.check_open() _hex(source_task, 32) @@ -91,8 +93,8 @@ def managed(self, source_task: str, actor: dict, *, connection: Any = None) -> d _manager(actor, row['owner']) return row - def context(self, source_task: str, issuer: dict, *, connection: Any = None, - origin_scope: list[str] | None = None) -> dict: + def context(self, source_task: str, issuer: dict[str, Any], *, connection: Any = None, + origin_scope: list[str] | None = None) -> dict[str, Any]: """Recheck actual completion and current source/issuer rights without exporting private evidence.""" self.check_open() transaction = self.runtime.store.connection() if connection is None else nullcontext(connection) @@ -134,8 +136,8 @@ def check_open(self) -> None: if private not in self.runtime.source_private_files: self.runtime.source_private_files += (private,) - def evidence_proof(self, source_task: str, task_id: str, issuer: dict, *, connection: Any = None, - reviewed: dict | None = None, issuing: bool = False) -> dict: + def evidence_proof(self, source_task: str, task_id: str, issuer: dict[str, Any], *, connection: Any = None, + reviewed: dict[str, Any] | None = None, issuing: bool = False) -> dict[str, Any]: """Reuse actual recovery/completion authority while keeping all private proof on its source host.""" self.check_open() _hex(source_task, 32) @@ -150,7 +152,8 @@ def evidence_proof(self, source_task: str, task_id: str, issuer: dict, *, connec issuer_policies=previous.get('issuer_policies'), authorization=previous.get('completion_authorization')) return self._evidence_projection(reading, row, task_id, *described[:2]) - def _evidence_engine(self, connection: Any, row: dict, issuer: dict, origins: list | None) -> tuple: + def _evidence_engine(self, connection: Any, row: dict[str, Any], issuer: dict[str, Any], + origins: list[str] | None) -> tuple[EvidenceHandoffs, dict[str, Any]]: context = self.lineage.evidence_context(connection, row, issuer, origins) local = 'admission' in context['binding'] engine = EvidenceHandoffs(self.runtime, lambda *_args, **_kwargs: context, @@ -160,13 +163,15 @@ def _evidence_engine(self, connection: Any, row: dict, issuer: dict, origins: li request.update({name: context['binding'][name] for name in ('batch_id', 'node_id')}) return engine, request - def _handoff_scope(self, connection: Any, context: dict, links: list, issuer_policies: list | None, - authorization: dict | None, *, issuing: bool = False) -> dict: + def _handoff_scope(self, connection: Any, context: dict[str, Any], links: list[_Link], + issuer_policies: list[str] | None, + authorization: dict[str, Any] | None, *, issuing: bool = False) -> dict[str, Any]: """Revalidate this host's retained private consent while the engine still checks issuance state.""" return self.runtime.recovery.handoff_scope(connection, context, links, issuer_policies, authorization, issuing=issuing and authorization is None) - def _evidence_projection(self, connection: Any, row: dict, task_id: str, proof: dict, tasks: list) -> dict: + def _evidence_projection(self, connection: Any, row: dict[str, Any], task_id: str, proof: dict[str, Any], + tasks: list[dict[str, Any]]) -> dict[str, Any]: requests = self.lineage.accepted_requests(connection, row) if not requests: raise AgentTaskError('portable evidence requires an actual original accepted request witness') @@ -180,7 +185,7 @@ def _evidence_projection(self, connection: Any, row: dict, task_id: str, proof: 'submitted_spec_digest': submitted[0] if submitted else self.lineage.submitted(row['spec']), 'node': row['spec']['options'].get('dag_batch')} - def skill_evidence(self, connection: Any, record: dict) -> HandoffAccess: + def skill_evidence(self, connection: Any, record: dict[str, Any]) -> HandoffAccess: """Build a source-private skill view from current portable consent without creating a local grant.""" scope = record['scope'] previous = scope['context']['proof'] diff --git a/je_auto_control/utils/executor/action_executor.py b/je_auto_control/utils/executor/action_executor.py index 98995b129..a214614bb 100644 --- a/je_auto_control/utils/executor/action_executor.py +++ b/je_auto_control/utils/executor/action_executor.py @@ -1,6 +1,6 @@ import threading import types -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple +from typing import TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Optional, Sequence, Set, Tuple from je_auto_control.utils.diagnostics.capability_commands import probe_current_capabilities as _probe_capabilities from je_auto_control.utils.exception.exception_tags import ( @@ -134,10 +134,18 @@ windows_for_process_id, ) +if TYPE_CHECKING: + from je_auto_control.utils.agent_memory import AgentMemory + from je_auto_control.utils.element_repository import ElementRepository + from je_auto_control.utils.layered_config import LayeredConfig + from je_auto_control.utils.locator_chain.locator_chain import Candidates + from je_auto_control.utils.skill_library import SkillLibrary + from je_auto_control.utils.work_queue import WorkQueue + def _a11y_list_as_dicts(app_name: Optional[str] = None, max_results: int = 200, - window_title: Optional[str] = None) -> List[dict]: + window_title: Optional[str] = None) -> List[Dict[str, Any]]: """Executor adapter: list accessibility elements as plain dicts.""" from je_auto_control.utils.accessibility.accessibility_api import ( list_accessibility_elements, @@ -155,7 +163,7 @@ def _a11y_find_as_dict(name: Optional[str] = None, role: Optional[str] = None, app_name: Optional[str] = None, window_title: Optional[str] = None, - contains: Any = False) -> Optional[dict]: + contains: Any = False) -> Optional[Dict[str, Any]]: """Executor adapter: find an accessibility element, return its dict.""" element = find_accessibility_element( name=name, role=role, app_name=app_name, window_title=window_title, @@ -164,7 +172,7 @@ def _a11y_find_as_dict(name: Optional[str] = None, return None if element is None else element.to_dict() -def _a11y_focused_as_dict(app_name: Optional[str] = None) -> Optional[dict]: +def _a11y_focused_as_dict(app_name: Optional[str] = None) -> Optional[Dict[str, Any]]: """Executor adapter: the element holding keyboard focus, as a dict.""" from je_auto_control.utils.accessibility.accessibility_api import ( focused_accessibility_element, @@ -179,7 +187,7 @@ def _a11y_find_all_as_dicts(name: Optional[str] = None, window_title: Optional[str] = None, contains: Any = False, max_results: int = 50, - scan_limit: int = 1500) -> List[dict]: + scan_limit: int = 1500) -> List[Dict[str, Any]]: """Executor adapter: every matching accessibility element, best match first.""" from je_auto_control.utils.accessibility.accessibility_api import ( find_accessibility_elements, @@ -1678,7 +1686,7 @@ def _ac_web_run(action: Optional[Dict[str, Any]] = None, return run_webrunner_action(payload) -def _ac_web_run_actions(actions: List[Dict[str, Any]]) -> list: +def _ac_web_run_actions(actions: List[Dict[str, Any]]) -> List[Any]: """Bridge a list of WR_* actions through the WebRunner executor.""" from je_auto_control.utils.webrunner_bridge import run_webrunner_actions return run_webrunner_actions(actions) @@ -1690,7 +1698,7 @@ def _ac_web_available() -> bool: return is_webrunner_available() -def _ac_web_list_commands() -> list: +def _ac_web_list_commands() -> List[str]: """Return every WR_* command the local WebRunner install exposes.""" from je_auto_control.utils.webrunner_bridge import list_webrunner_commands return list_webrunner_commands() @@ -1798,7 +1806,7 @@ def _ac_android_screenshot(file_path: str, return str(path) -def _ac_android_list_devices(adb_path: Optional[str] = None) -> list: +def _ac_android_list_devices(adb_path: Optional[str] = None) -> List[Dict[str, Any]]: """Return ``{serial, state, model, …}`` for every adb-attached device.""" devices = _android_client(None, adb_path).list_devices() return [ @@ -1938,9 +1946,9 @@ def _ac_ios_dump_source(url: Optional[str] = None) -> str: def _llm_plan_for_executor(description: str, - examples: Optional[list] = None, + examples: Optional[List[Dict[str, Any]]] = None, model: Optional[str] = None, - max_tokens: int = 2048) -> list: + max_tokens: int = 2048) -> List[List[Any]]: """Executor adapter: plan without executing, using current command set.""" return llm_plan_actions( description, @@ -1952,7 +1960,7 @@ def _llm_plan_for_executor(description: str, def _llm_run_for_executor(description: str, - examples: Optional[list] = None, + examples: Optional[List[Dict[str, Any]]] = None, model: Optional[str] = None, max_tokens: int = 2048) -> Dict[str, Any]: """Executor adapter: plan and execute, as the caller this thread already serves (so no ``owner``).""" @@ -1967,7 +1975,7 @@ def _llm_run_for_executor(description: str, def _ocr_read_region_as_dicts(region: Optional[List[int]] = None, lang: str = "eng", - min_confidence: float = 60.0) -> List[dict]: + min_confidence: float = 60.0) -> List[Dict[str, Any]]: """Executor adapter: dump OCR hits in a region as JSON-friendly dicts.""" return [ { @@ -1985,7 +1993,7 @@ def _ocr_find_regex_as_dicts(pattern: str, lang: str = "eng", region: Optional[List[int]] = None, min_confidence: float = 60.0, - flags: int = 0) -> List[dict]: + flags: int = 0) -> List[Dict[str, Any]]: """Executor adapter: regex OCR search returning JSON-friendly dicts.""" return [ { @@ -2198,7 +2206,7 @@ def _secret_status() -> Dict[str, Any]: } -def _profiler_stats_as_dicts(limit: Optional[int] = None) -> List[dict]: +def _profiler_stats_as_dicts(limit: Optional[int] = None) -> List[Dict[str, object]]: """Executor adapter: dump profiler stats as JSON-friendly dicts.""" rows = default_profiler.stats() if limit is not None: @@ -2206,7 +2214,7 @@ def _profiler_stats_as_dicts(limit: Optional[int] = None) -> List[dict]: return [row.to_dict() for row in rows] -def _profiler_hot_spots_as_dicts(limit: int = 10) -> List[dict]: +def _profiler_hot_spots_as_dicts(limit: int = 10) -> List[Dict[str, object]]: """Executor adapter: top N actions by total time, as dicts.""" return [row.to_dict() for row in default_profiler.hot_spots(int(limit))] @@ -2227,7 +2235,7 @@ def _profiler_reset() -> Dict[str, Any]: def _history_list_as_dicts(limit: int = 100, - source_type: Optional[str] = None) -> List[dict]: + source_type: Optional[str] = None) -> List[Dict[str, Any]]: """Executor adapter: list run history as plain dicts (JSON-friendly).""" rows = default_history_store.list_runs( limit=int(limit), source_type=source_type, @@ -2247,7 +2255,7 @@ def _history_list_as_dicts(limit: int = 100, _EXECUTOR_METRIC_CACHE: Dict[str, Any] = {} -def _executor_metrics(): +def _executor_metrics() -> Dict[str, Any]: """Lazily register the action-executor Counter + Histogram (Phase 10.1).""" if "calls" in _EXECUTOR_METRIC_CACHE: return _EXECUTOR_METRIC_CACHE @@ -2582,7 +2590,7 @@ def _control_get_value(name: Optional[str] = None, role: Optional[str] = None, def _control_get_state(name: Optional[str] = None, role: Optional[str] = None, app_name: Optional[str] = None, - automation_id: Optional[str] = None) -> Optional[dict]: + automation_id: Optional[str] = None) -> Optional[Dict[str, Any]]: """Adapter: read everything a native control currently holds, in one call.""" from je_auto_control.utils.accessibility import control_get_state return control_get_state(name=name, role=role, app_name=app_name, @@ -3064,7 +3072,7 @@ def _idle_point(busy_samples: Any, quiet_samples: Any = 3) -> Dict[str, Any]: return {"index": idle_point(samples, quiet_samples=int(quiet_samples))} -def _coerce_rgb(value: Any) -> tuple: +def _coerce_rgb(value: Any) -> Tuple[int, int, int]: """Normalise an RGB argument (JSON '[r,g,b]' string / list) to (r, g, b).""" seq = _coerce_list(value) if isinstance(value, str) else list(value) return (int(seq[0]), int(seq[1]), int(seq[2])) @@ -3345,7 +3353,7 @@ def _assert_session_active() -> Dict[str, Any]: return {"interactive": ensure_interactive_session()} -def _queue(db: str, name: str): +def _queue(db: str, name: str) -> "WorkQueue": from je_auto_control.utils.work_queue import WorkQueue return WorkQueue(db, name) @@ -3432,7 +3440,7 @@ def _select_tests(flows: List[str], k: Optional[int] = None, window=int(window))} -def _element_repo(path: str): +def _element_repo(path: str) -> "ElementRepository": from je_auto_control.utils.element_repository import ElementRepository return ElementRepository(path) @@ -3471,7 +3479,7 @@ def _debug_trace(actions: List[Any], dry_run: bool = False) -> Dict[str, Any]: return {"trace": trace_actions(actions, dry_run=_as_bool(dry_run))} -def _skill_lib(path: str): +def _skill_lib(path: str) -> "SkillLibrary": from je_auto_control.utils.skill_library import SkillLibrary return SkillLibrary(path) @@ -3556,7 +3564,7 @@ def _write_presentation(path: str, slides: List[Any]) -> Dict[str, Any]: return {"path": write_presentation(path, slides)} -def _memory(db: str): +def _memory(db: str) -> "AgentMemory": from je_auto_control.utils.agent_memory import AgentMemory return AgentMemory(db) @@ -3623,7 +3631,7 @@ def handler(_event: str, _value: Any) -> None: return handler -def _observe_predicate(kind: str, params: Dict[str, Any]): +def _observe_predicate(kind: str, params: Dict[str, Any]) -> Callable[[], Any]: from je_auto_control.utils.observer import ( image_predicate, pixel_predicate, text_predicate) builders = { @@ -4157,7 +4165,7 @@ def _move_mouse_relative(dx: Any, dy: Any) -> Dict[str, Any]: return move_mouse_relative(int(dx), int(dy)) -def _stop_record_timeline() -> List[dict]: +def _stop_record_timeline() -> List[Dict[str, Any]]: """Adapter: stop recording and return the full replayable timeline.""" from je_auto_control.wrapper.auto_control_record import ( stop_record_timeline, @@ -4707,7 +4715,7 @@ def _find_rectangles(region: Any = None, min_area: Any = 400, max_area: Any = No return {"count": len(rects), "rectangles": rects} -def _resolve_screen(screen: Any) -> list: +def _resolve_screen(screen: Any) -> List[int]: """Parse a JSON screen rect, or default to the live primary screen work area.""" import json if isinstance(screen, str): @@ -4791,7 +4799,7 @@ def _monitor_at_point(x: Any, y: Any) -> Dict[str, Any]: "monitor": monitor.to_dict() if monitor else None} -def _region_pixel_token(bbox): +def _region_pixel_token(bbox: Sequence[int]) -> int: """Stability token: a hash of the bbox region's pixels (changes on movement). Sampled where the match was found, through ``grab_logical``: the bbox is in @@ -4812,7 +4820,7 @@ def _wait_actionable(template: str, timeout_s: Any = 5.0, stable_for_s: Any = 0. if isinstance(region, str): region = json.loads(region) if region.strip() else None - def locate(): + def locate() -> Optional[Tuple[int, int, int, int]]: match = match_template(template, region=region, min_score=float(min_score)) return (match.x, match.y, match.width, match.height) if match else None @@ -4829,7 +4837,7 @@ def _fuse_elements(ocr: Any = None, icon: Any = None, a11y: Any = None, import json from je_auto_control.utils.element_parse import fuse_elements - def parse(value: Any) -> list: + def parse(value: Any) -> List[Dict[str, Any]]: if isinstance(value, str): return json.loads(value) if value.strip() else [] return list(value) if value else [] @@ -4956,7 +4964,7 @@ def _expect_poll(action: Any, key: Any = None, op: str = "truthy", "truthy": to_be_truthy} matcher = builders.get(str(op), to_be_truthy)() - def getter(): + def getter() -> Any: try: record = _running_executor().execute_action([list(action)], raise_on_error=True) except (AutoControlException, OSError, RuntimeError, ValueError, @@ -4977,7 +4985,7 @@ def getter(): "waited_s": result.waited_s} -def _apply_locate_op(candidates, op: Dict[str, Any]): +def _apply_locate_op(candidates: "Candidates", op: Dict[str, Any]) -> "Candidates": """Apply one locate-chain op spec to a Candidates set.""" name = op.get("op") if name == "within": @@ -5100,7 +5108,7 @@ def _diff_formats(before: Any, after: Any) -> Dict[str, Any]: return diff_formats(before, after) -def _coerce_paths(paths: Any) -> list: +def _coerce_paths(paths: Any) -> List[str]: """Normalise a paths argument (JSON list string / single path / list). A string is a JSON list only if it parses as one: "[draft] notes.txt" @@ -5118,7 +5126,7 @@ def _coerce_paths(paths: Any) -> list: return [str(p) for p in paths] -def _coerce_point(point: Any) -> tuple: +def _coerce_point(point: Any) -> Tuple[int, int]: """Normalise a point argument (JSON '[x,y]' / list / default origin).""" import json if isinstance(point, str): @@ -5142,7 +5150,7 @@ def _drop_files(hwnd: Any, paths: Any, point: Any = None) -> Dict[str, Any]: return {"dropped": bool(dropped), "count": len(coerced)} -def _coerce_region(region: Any): +def _coerce_region(region: Any) -> Any: """Normalise a region argument (JSON '[x,y,w,h]' string / list / None).""" import json if isinstance(region, str): @@ -5166,7 +5174,7 @@ def _quality_gate(source: Any = None, region: Any = None, min_contrast=float(min_contrast)) -def _coerce_scales(scales: Any): +def _coerce_scales(scales: Any) -> Any: """Normalise a scales argument (JSON '[1.0,1.5]' string / list / None).""" import json if isinstance(scales, str): @@ -5338,7 +5346,7 @@ def _has_motion(before: str, after: Any = None, threshold: Any = 25, "activity": activity_score(before, resolved, threshold=int(threshold))} -def _resolve_after(after: Any): +def _resolve_after(after: Any) -> Any: """Return the 'after' frame, grabbing the screen when it is not given.""" if after is not None: return after @@ -5635,7 +5643,7 @@ def _replay_trace(trace: Any) -> Dict[str, Any]: trace = (json.loads(trace) if trace.strip().startswith("[") else from_jsonl(trace)) - def runner(action): + def runner(action: Any) -> Any: record = _running_executor().execute_action([list(action)]) return next(iter(record.values()), None) @@ -6124,7 +6132,7 @@ def _parse_sse(text: str) -> Dict[str, Any]: return {"events": [event.to_dict() for event in parse_event_stream(text)]} -def _build_layered_config(layers: Any): +def _build_layered_config(layers: Any) -> "LayeredConfig": """Build a LayeredConfig from a list of {name, mapping, priority?} dicts.""" import json from je_auto_control.utils.layered_config import LayeredConfig @@ -6222,7 +6230,7 @@ def _check_row_count(rows: Any, minimum: Any = None, return check_row_count(_json_rows(rows), low, high) -def _coerce_diff_inputs(old_rows: Any, new_rows: Any, key: Any): +def _coerce_diff_inputs(old_rows: Any, new_rows: Any, key: Any) -> Tuple[Any, Any, Any]: import json if isinstance(old_rows, str): old_rows = json.loads(old_rows) @@ -7277,7 +7285,7 @@ class Executor: # ``catch``/``finally`` belong here too: AC_try only binds ``error_var`` # once the body has failed, so eagerly interpolating them at dispatch # would resolve ${err} before it exists. - _DEFERRED_ARG_KEYS: frozenset = frozenset( + _DEFERRED_ARG_KEYS: FrozenSet[str] = frozenset( {"body", "then", "else", "branches", "catch", "finally"}) # Commands that run an action list held under another key. Expanding it @@ -7285,7 +7293,7 @@ class Executor: # *value*: text read from OCR, HTTP or a file that contained # ``${secrets.NAME}`` was resolved from the vault. Per command, because # the same key is plain data elsewhere (``AC_tween_drag``'s ``steps``). - _DEFERRED_COMMAND_KEYS: Dict[str, frozenset] = { + _DEFERRED_COMMAND_KEYS: Dict[str, FrozenSet[str]] = { "AC_execute_action": frozenset({"action_list"}), "AC_expect_poll": frozenset({"action"}), "AC_run_saga": frozenset({"steps"}), @@ -7325,13 +7333,13 @@ def variables(self) -> VariableScope: def variables(self, scope: VariableScope) -> None: self._own_variables = scope - def __init__(self): + def __init__(self) -> None: self._block_commands = BLOCK_COMMANDS self.variables = VariableScope() # Named, parameterised macros registered via AC_define_macro. self.macros: Dict[str, Any] = {} # 事件字典,對應字串名稱到函式 - self.event_dict: dict = { + self.event_dict: Dict[str, Callable[..., Any]] = { **AGENT_TASK_COMMANDS, # Mouse 滑鼠相關 **MOUSE_BUTTON_COMMANDS, @@ -8281,11 +8289,11 @@ def allow_packages(*packages: str) -> None: """Add packages, and their submodules, to the allowlist of ``AC_add_package_to_executor``.""" package_manager.allow_packages(*packages) - def known_commands(self) -> set: + def known_commands(self) -> Set[str]: """Return the set of all command names the executor recognises.""" return set(self.event_dict.keys()) | set(self._block_commands.keys()) - def unknown_commands_in(self, action_list: list | dict) -> List[str]: + def unknown_commands_in(self, action_list: List[Any] | Dict[str, Any]) -> List[str]: """Return the unrecognised command names in ``action_list``, in order. Nothing is executed. Structural problems raise exactly as @@ -8332,7 +8340,7 @@ def _resolve_runtime_args(self, args: Any, command: str = "") -> Any: return [interpolate_value(item, self.variables) for item in args] return args - def _execute_event(self, action: list) -> Any: + def _execute_event(self, action: List[Any]) -> Any: """ 執行單一事件 Execute a single event @@ -8372,11 +8380,11 @@ def execute_one(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> from je_auto_control.utils.executor.dispatch import execute_one return execute_one(self, name, arguments) - def execute_action(self, action_list: list | dict, + def execute_action(self, action_list: List[Any] | Dict[str, Any], raise_on_error: bool = False, _validated: bool = False, dry_run: bool = False, - step_callback: Optional[Callable[[list], None]] = None, + step_callback: Optional[Callable[[List[Any]], None]] = None, result_callback: Optional[ResultHook] = None, ) -> Dict[str, str]: """ @@ -8418,9 +8426,9 @@ def execute_action(self, action_list: list | dict, _STRICT_BODIES.value = inherited _RUNNING.value = running - def _execute_list(self, action_list: list | dict, raise_on_error: bool, + def _execute_list(self, action_list: List[Any] | Dict[str, Any], raise_on_error: bool, _validated: bool, dry_run: bool, - step_callback: Optional[Callable[[list], None]], + step_callback: Optional[Callable[[List[Any]], None]], ) -> Dict[str, str]: """The body of :meth:`execute_action`, with strictness already settled.""" action_list = self._unwrap_action_list(action_list) @@ -8444,8 +8452,8 @@ def _execute_list(self, action_list: list | dict, raise_on_error: bool, autocontrol_logger.info("%s -> %s", key, redact_result(record_command(key), value)) return execute_record_dict - def _execute_list_step(self, action: list, record: Dict[str, Any], raise_on_error: bool, - validated: bool, dry_run: bool, callback: Optional[Callable[[list], None]]) -> None: + def _execute_list_step(self, action: List[Any], record: Dict[str, Any], raise_on_error: bool, + validated: bool, dry_run: bool, callback: Optional[Callable[[List[Any]], None]]) -> None: """Dispatch one step inside its optional journal capture boundary.""" if callback is not None: callback(action) @@ -8492,7 +8500,7 @@ def _record_unwound_signal(signal: Exception, record: Dict[str, Any], _count_recorded_failure() @staticmethod - def _unwrap_action_list(action_list: list | dict) -> list: + def _unwrap_action_list(action_list: List[Any] | Dict[str, Any]) -> List[Any]: """Normalise the ``action_list`` argument or raise on invalid input.""" actions: Any = action_list if isinstance(actions, dict): @@ -8503,7 +8511,7 @@ def _unwrap_action_list(action_list: list | dict) -> list: raise AutoControlActionNullException(action_is_null_error_message) return actions - def _run_one_action(self, action: list, record: Dict[str, Any], + def _run_one_action(self, action: List[Any], record: Dict[str, Any], raise_on_error: bool, key: str) -> None: """Execute a single action, recording the result under ``key`` or raising.""" import time as _time @@ -8545,7 +8553,7 @@ def _run_one_action(self, action: list, record: Dict[str, Any], record[key] = repr(error) _count_recorded_failure() - def execute_files(self, execute_files_list: list) -> List[Dict[str, str]]: + def execute_files(self, execute_files_list: List[str]) -> List[Dict[str, str]]: """ 執行 action files Execute actions from files @@ -8608,7 +8616,7 @@ def _count_recorded_failure() -> None: package_manager.executor = executor -def add_command_to_executor(command_dict: dict) -> None: +def add_command_to_executor(command_dict: Dict[str, Any]) -> None: """ 新增自訂指令到 Executor Add custom commands to Executor @@ -8622,9 +8630,9 @@ def add_command_to_executor(command_dict: dict) -> None: raise AutoControlAddCommandException(add_command_exception_error_message) -def execute_action(action_list: list | dict, *, +def execute_action(action_list: List[Any] | Dict[str, Any], *, raise_on_error: bool = False, dry_run: bool = False, - step_callback: Optional[Callable[[list], None]] = None, + step_callback: Optional[Callable[[List[Any]], None]] = None, result_callback: Optional[ResultHook] = None, ) -> Dict[str, str]: """Run ``action_list`` on the shared executor; return its execution record. @@ -8642,11 +8650,11 @@ def execute_action(action_list: list | dict, *, step_callback=step_callback, result_callback=result_callback) -def execute_files(execute_files_list: list) -> List[Dict[str, str]]: +def execute_files(execute_files_list: List[str]) -> List[Dict[str, str]]: return executor.execute_files(execute_files_list) -def execute_action_with_vars(action_list: list, variables: dict, +def execute_action_with_vars(action_list: List[Any], variables: Dict[str, Any], run_id: Optional[str] = None) -> Dict[str, str]: """Run ``action_list`` in a fresh variable scope seeded with ``variables``. diff --git a/je_auto_control/utils/json_schema/json_schema.py b/je_auto_control/utils/json_schema/json_schema.py index b4fa9d8ef..8471c8983 100644 --- a/je_auto_control/utils/json_schema/json_schema.py +++ b/je_auto_control/utils/json_schema/json_schema.py @@ -28,14 +28,14 @@ import re from dataclasses import dataclass, field from fractions import Fraction -from typing import Any, Callable, Dict, List, Set, Tuple +from typing import Any, Callable, Dict, List, Set, Tuple, Union from urllib.parse import unquote from je_auto_control.utils.exception.exceptions import ( AutoControlAssertionException, AutoControlJsonException) from je_auto_control.utils.json_schema.ecma_regex import compile_ecma_pattern -Schema = Any # a dict, or a bool (a boolean schema) +Schema = Union[Dict[str, Any], bool] # a dict, or a bool (a boolean schema) @dataclass(frozen=True) @@ -148,7 +148,7 @@ def _has_duplicates(items: List[Any]) -> bool: # --- keyword checkers (each returns a list of error dicts) ---------------- -def _check_type(instance: Any, schema: Dict, path: str, _root: _Root) -> List[Dict]: +def _check_type(instance: Any, schema: Dict[str, Any], path: str, _root: _Root) -> List[Dict[str, str]]: if "type" not in schema: return [] types = schema["type"] @@ -158,8 +158,8 @@ def _check_type(instance: Any, schema: Dict, path: str, _root: _Root) -> List[Di return [_err(path, "type", f"expected type {schema['type']}")] -def _check_enum_const(instance: Any, schema: Dict, path: str, _root: _Root) -> List[Dict]: - errors: List[Dict] = [] +def _check_enum_const(instance: Any, schema: Dict[str, Any], path: str, _root: _Root) -> List[Dict[str, str]]: + errors: List[Dict[str, str]] = [] if "const" in schema and not _json_equal(instance, schema["const"]): errors.append(_err(path, "const", f"must equal {schema['const']!r}")) if "enum" in schema and not any( @@ -176,10 +176,10 @@ def _check_enum_const(instance: Any, schema: Dict, path: str, _root: _Root) -> L ) -def _check_number(instance: Any, schema: Dict, path: str, _root: _Root) -> List[Dict]: +def _check_number(instance: Any, schema: Dict[str, Any], path: str, _root: _Root) -> List[Dict[str, str]]: if not _is_number(instance): return [] - errors: List[Dict] = [] + errors: List[Dict[str, str]] = [] for key, ok, message in _NUMBER_BOUNDS: if key in schema and not ok(instance, schema[key]): errors.append(_err(path, key, f"{message} {schema[key]}")) @@ -189,10 +189,10 @@ def _check_number(instance: Any, schema: Dict, path: str, _root: _Root) -> List[ return errors -def _check_string(instance: Any, schema: Dict, path: str, _root: _Root) -> List[Dict]: +def _check_string(instance: Any, schema: Dict[str, Any], path: str, _root: _Root) -> List[Dict[str, str]]: if not isinstance(instance, str): return [] - errors: List[Dict] = [] + errors: List[Dict[str, str]] = [] if "minLength" in schema and len(instance) < schema["minLength"]: errors.append(_err(path, "minLength", f"shorter than {schema['minLength']}")) if "maxLength" in schema and len(instance) > schema["maxLength"]: @@ -213,8 +213,8 @@ def _search(pattern: str, text: str) -> bool: return compile_ecma_pattern(pattern).search(text) is not None -def _array_size_errors(instance: List, schema: Dict, path: str) -> List[Dict]: - errors: List[Dict] = [] +def _array_size_errors(instance: List[Any], schema: Dict[str, Any], path: str) -> List[Dict[str, str]]: + errors: List[Dict[str, str]] = [] if "minItems" in schema and len(instance) < schema["minItems"]: errors.append(_err(path, "minItems", f"fewer than {schema['minItems']} items")) if "maxItems" in schema and len(instance) > schema["maxItems"]: @@ -224,8 +224,8 @@ def _array_size_errors(instance: List, schema: Dict, path: str) -> List[Dict]: return errors -def _array_item_errors(instance: List, schema: Dict, path: str, root: _Root) -> List[Dict]: - errors: List[Dict] = [] +def _array_item_errors(instance: List[Any], schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: + errors: List[Dict[str, str]] = [] prefix = schema.get("prefixItems") start = 0 if isinstance(prefix, list): @@ -239,7 +239,7 @@ def _array_item_errors(instance: List, schema: Dict, path: str, root: _Root) -> return errors -def _array_contains_errors(instance: List, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _array_contains_errors(instance: List[Any], schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: if "contains" not in schema: return [] subschema = schema["contains"] @@ -248,7 +248,7 @@ def _array_contains_errors(instance: List, schema: Dict, path: str, root: _Root) return [_err(path, "contains", "no items match the 'contains' schema")] -def _check_array(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _check_array(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: if not isinstance(instance, list): return [] errors = _array_size_errors(instance, schema, path) @@ -257,8 +257,8 @@ def _check_array(instance: Any, schema: Dict, path: str, root: _Root) -> List[Di return errors -def _object_size_required_errors(instance: Dict, schema: Dict, path: str) -> List[Dict]: - errors: List[Dict] = [] +def _object_size_required_errors(instance: Dict[str, Any], schema: Dict[str, Any], path: str) -> List[Dict[str, str]]: + errors: List[Dict[str, str]] = [] for key in schema.get("required", []): if key not in instance: errors.append(_err(path, "required", f"missing required property '{key}'")) @@ -271,7 +271,7 @@ def _object_size_required_errors(instance: Dict, schema: Dict, path: str) -> Lis return errors -def _additional_property_errors(value: Any, additional: Any, path: str, root: _Root) -> List[Dict]: +def _additional_property_errors(value: Any, additional: Any, path: str, root: _Root) -> List[Dict[str, str]]: if additional is None or additional is True: return [] if additional is False: @@ -279,7 +279,7 @@ def _additional_property_errors(value: Any, additional: Any, path: str, root: _R return _validate(value, additional, path, root) -def _one_property_errors(key: str, value: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _one_property_errors(key: str, value: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: child = f"{path}.{key}" matched: List[Schema] = [] if key in schema.get("properties", {}): @@ -288,7 +288,7 @@ def _one_property_errors(key: str, value: Any, schema: Dict, path: str, root: _R sub for pattern, sub in schema.get("patternProperties", {}).items() if _search(pattern, key)) if matched: - errors: List[Dict] = [] + errors: List[Dict[str, str]] = [] for subschema in matched: errors.extend(_validate(value, subschema, child, root)) return errors @@ -296,7 +296,7 @@ def _one_property_errors(key: str, value: Any, schema: Dict, path: str, root: _R value, schema.get("additionalProperties"), child, root) -def _check_object(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _check_object(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: if not isinstance(instance, dict): return [] errors = _object_size_required_errors(instance, schema, path) @@ -305,14 +305,14 @@ def _check_object(instance: Any, schema: Dict, path: str, root: _Root) -> List[D return errors -def _check_all_of(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: - errors: List[Dict] = [] +def _check_all_of(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: + errors: List[Dict[str, str]] = [] for subschema in schema.get("allOf", []): errors.extend(_validate(instance, subschema, path, root)) return errors -def _check_any_of(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _check_any_of(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: options = schema.get("anyOf") if not options: return [] @@ -321,7 +321,7 @@ def _check_any_of(instance: Any, schema: Dict, path: str, root: _Root) -> List[D return [_err(path, "anyOf", "does not match any schema in anyOf")] -def _check_one_of(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _check_one_of(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: options = schema.get("oneOf") if not options: return [] @@ -331,7 +331,7 @@ def _check_one_of(instance: Any, schema: Dict, path: str, root: _Root) -> List[D return [_err(path, "oneOf", f"matched {matches} schemas in oneOf, expected 1")] -def _check_not(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _check_not(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: if "not" not in schema: return [] if _validate(instance, schema["not"], path, root): @@ -339,7 +339,7 @@ def _check_not(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict return [_err(path, "not", "must not match the 'not' schema")] -def _check_combinators(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: +def _check_combinators(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: errors = _check_all_of(instance, schema, path, root) errors.extend(_check_any_of(instance, schema, path, root)) errors.extend(_check_one_of(instance, schema, path, root)) @@ -380,7 +380,7 @@ def _resolve_ref(ref: str, root: Schema) -> Schema: return node -def _validate(instance: Any, schema: Schema, path: str, root: _Root) -> List[Dict]: +def _validate(instance: Any, schema: Schema, path: str, root: _Root) -> List[Dict[str, str]]: if schema is True: return [] if schema is False: @@ -397,8 +397,8 @@ def _validate(instance: Any, schema: Schema, path: str, root: _Root) -> List[Dic root.active.discard(key) -def _validate_keywords(instance: Any, schema: Dict, path: str, root: _Root) -> List[Dict]: - errors: List[Dict] = [] +def _validate_keywords(instance: Any, schema: Dict[str, Any], path: str, root: _Root) -> List[Dict[str, str]]: + errors: List[Dict[str, str]] = [] if "$ref" in schema: # Draft 2020-12 applies the keywords next to a $ref as well. errors.extend(_validate(instance, _resolve_ref(schema["$ref"], root.schema), diff --git a/je_auto_control/utils/mcp_server/tools/_handlers.py b/je_auto_control/utils/mcp_server/tools/_handlers.py index fbd992ae1..183a347dd 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers.py @@ -6,7 +6,7 @@ top-level MCP server boot cheap. """ import os -from typing import Any, Dict, List +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union from je_auto_control.utils.mcp_server.tools._handlers_vision_executor import ( anchor_locate, @@ -18,36 +18,44 @@ _element_repo, ) +if TYPE_CHECKING: + from datetime import date + + from je_auto_control.utils.agent_memory import Episode + # === Semantic locators (a11y / VLM) ========================================= -def handle_file_dialog(path, action="open", window_title=None, - timeout_s=10.0, confirm_key="enter"): +def handle_file_dialog(path: str, action: str = "open", window_title: Optional[str] = None, + timeout_s: float = 10.0, confirm_key: str = "enter") -> Dict[str, object]: from je_auto_control.utils.file_dialog import handle_file_dialog as _h return _h(path, action=action, window_title=window_title, timeout_s=float(timeout_s), confirm_key=confirm_key) -def queue_add(db, data, reference=None, name="default"): +def queue_add(db: str, data: Dict[str, Any], reference: Optional[str] = None, + name: str = "default") -> Dict[str, Optional[int]]: return {"id": _work_queue(db, name).add(data, reference=reference)} -def queue_next(db, name="default", stale_after_s=None): +def queue_next(db: str, name: str = "default", + stale_after_s: Optional[float] = None) -> Optional[Dict[str, Any]]: item = _work_queue(db, name).get_next(stale_after_s=stale_after_s) return None if item is None else { "id": item.id, "reference": item.reference, "data": item.data, "status": item.status, "retries": item.retries, "claim": item.claim} -def queue_complete(db, item_id, output=None, name="default", claim=None): +def queue_complete(db: str, item_id: int, output: Any = None, name: str = "default", + claim: Optional[int] = None) -> Dict[str, Any]: _work_queue(db, name).complete(int(item_id), output=output, claim=None if claim is None else int(claim)) return {"id": int(item_id), "status": "success"} -def queue_fail(db, item_id, error, kind="application", max_retries=3, - name="default", claim=None): +def queue_fail(db: str, item_id: int, error: str, kind: str = "application", max_retries: int = 3, + name: str = "default", claim: Optional[int] = None) -> Dict[str, Any]: status = _work_queue(db, name).fail(int(item_id), str(error), kind=str(kind), max_retries=int(max_retries), @@ -55,7 +63,7 @@ def queue_fail(db, item_id, error, kind="application", max_retries=3, return {"id": int(item_id), "status": status} -def queue_stats(db, name="default"): +def queue_stats(db: str, name: str = "default") -> Dict[str, int]: if _no_database(db): from je_auto_control.utils.work_queue.work_queue import ( STATUS_FAILED, STATUS_IN_PROGRESS, STATUS_NEW, STATUS_SUCCESS, @@ -64,7 +72,7 @@ def queue_stats(db, name="default"): return _work_queue(db, name).stats() -def _no_database(db) -> bool: +def _no_database(db: str) -> bool: """Whether a read-only tool's ``db`` does not exist yet. Opening it would create an empty SQLite file at a caller-chosen path, @@ -73,115 +81,119 @@ def _no_database(db) -> bool: return not os.path.exists(db) -def element_save(path, key, name=None, role=None, app_name=None): +def element_save(path: str, key: str, name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None) -> Dict[str, Dict[str, str]]: return {"locator": _element_repo(path).save( key, name=name, role=role, app_name=app_name)} -def element_find(path, key): +def element_find(path: str, key: str) -> Dict[str, Any]: return _element_repo(path).find_info(key) -def element_click(path, key): +def element_click(path: str, key: str) -> Dict[str, bool]: return {"clicked": _element_repo(path).click(key)} -def element_remove(path, key): +def element_remove(path: str, key: str) -> Dict[str, bool]: return {"removed": _element_repo(path).remove(key)} -def element_list(path): +def element_list(path: str) -> Dict[str, List[str]]: return {"keys": _element_repo(path).keys()} -def skill_save(path, name, actions, description="", tags=None): +def skill_save(path: str, name: str, actions: List[Any], description: str = "", + tags: Optional[List[str]] = None) -> Dict[str, Any]: skill = _skill_lib(path).save(name, actions, description=description, tags=tags) return {"name": skill.name, "tags": skill.tags} -def skill_run(path, name): +def skill_run(path: str, name: str) -> Dict[str, Dict[str, Any]]: return {"record": _skill_lib(path).run(name)} -def skill_list(path): +def skill_list(path: str) -> Dict[str, List[str]]: return {"names": _skill_lib(path).names()} -def skill_remove(path, name): +def skill_remove(path: str, name: str) -> Dict[str, bool]: return {"removed": _skill_lib(path).remove(name)} -def skill_search(path, query): +def skill_search(path: str, query: str) -> Dict[str, List[str]]: return {"names": [s.name for s in _skill_lib(path).search(query)]} -def read_workbook(path, sheet=""): +def read_workbook(path: str, sheet: str = "") -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.office import read_workbook as _read return {"rows": _read(path, sheet=sheet)} -def write_workbook(path, rows, sheet="Sheet1"): +def write_workbook(path: str, rows: List[Dict[str, Any]], sheet: str = "Sheet1") -> Dict[str, str]: from je_auto_control.utils.office import write_workbook as _write return {"path": _write(path, rows, sheet=sheet)} -def read_document(path): +def read_document(path: str) -> Dict[str, List[str]]: from je_auto_control.utils.office import read_document as _read return _read(path) -def write_document(path, paragraphs): +def write_document(path: str, paragraphs: List[str]) -> Dict[str, str]: from je_auto_control.utils.office import write_document as _write return {"path": _write(path, paragraphs)} -def read_presentation(path): +def read_presentation(path: str) -> Dict[str, List[List[str]]]: from je_auto_control.utils.office import read_presentation as _read return _read(path) -def write_presentation(path, slides): +def write_presentation(path: str, slides: List[Any]) -> Dict[str, str]: from je_auto_control.utils.office import write_presentation as _write return {"path": _write(path, slides)} -def _episode_dict(episode): +def _episode_dict(episode: "Episode") -> Dict[str, Any]: return {"id": episode.id, "goal": episode.goal, "steps": episode.steps, "outcome": episode.outcome, "tags": episode.tags, "score": episode.score} -def memory_remember(db, goal, steps=None, outcome="", tags=None): +def memory_remember(db: str, goal: str, steps: Optional[List[Any]] = None, outcome: str = "", + tags: Optional[List[str]] = None) -> Dict[str, int]: return {"id": _agent_memory(db).remember( goal, steps=steps, outcome=outcome, tags=tags)} -def memory_recall(db, query, limit=5): +def memory_recall(db: str, query: str, limit: int = 5) -> Dict[str, List[Dict[str, Any]]]: if _no_database(db): return {"episodes": []} eps = _agent_memory(db).recall(query, limit=int(limit)) return {"episodes": [_episode_dict(ep) for ep in eps]} -def memory_recent(db, limit=10): +def memory_recent(db: str, limit: int = 10) -> Dict[str, List[Dict[str, Any]]]: if _no_database(db): return {"episodes": []} eps = _agent_memory(db).recent(limit=int(limit)) return {"episodes": [_episode_dict(ep) for ep in eps]} -def memory_forget(db, episode_id): +def memory_forget(db: str, episode_id: int) -> Dict[str, bool]: return {"removed": _agent_memory(db).forget(int(episode_id))} -def memory_stats(db): +def memory_stats(db: str) -> Dict[str, int]: if _no_database(db): return {"episodes": 0} return _agent_memory(db).stats() -def pseudo_localize(text=None, mapping=None, expansion=0.4): +def pseudo_localize(text: Optional[str] = None, mapping: Optional[Dict[str, Any]] = None, + expansion: float = 0.4) -> Dict[str, Any]: from je_auto_control.utils.i18n_test import ( pseudo_localize as _pl, pseudo_localize_catalog as _plc) if mapping is not None: @@ -189,7 +201,8 @@ def pseudo_localize(text=None, mapping=None, expansion=0.4): return {"text": _pl(text or "", expansion=float(expansion))} -def check_overflow(elements=None, avg_char_px=7.0, app_name=None): +def check_overflow(elements: Optional[List[Any]] = None, avg_char_px: float = 7.0, + app_name: Optional[str] = None) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.i18n_test import check_overflow as _co items = elements if items is None: @@ -199,49 +212,50 @@ def check_overflow(elements=None, avg_char_px=7.0, app_name=None): return {"issues": _co(items, avg_char_px=float(avg_char_px))} -def check_catalog(base, target): +def check_catalog(base: Dict[str, Any], target: Dict[str, Any]) -> Dict[str, Any]: from je_auto_control.utils.i18n_test import check_catalog as _cc return _cc(base, target) -def replay_timeline(events, speed=1.0): +def replay_timeline(events: List[Dict[str, Any]], speed: float = 1.0) -> Dict[str, int]: from je_auto_control.utils.input_macro import replay_timeline as _rt return {"played": _rt(events, speed=float(speed))} -def input_sequence(steps): +def input_sequence(steps: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.input_macro import run_sequence as _rs return {"log": _rs(steps)} -def clip_history_capture(): +def clip_history_capture() -> Dict[str, bool]: from je_auto_control.utils.clipboard_history import default_clipboard_history return {"added": default_clipboard_history.capture_once()} -def clip_history_list(): +def clip_history_list() -> Dict[str, List[str]]: from je_auto_control.utils.clipboard_history import default_clipboard_history return {"history": default_clipboard_history.snapshot()} -def clip_history_search(query): +def clip_history_search(query: str) -> Dict[str, List[str]]: from je_auto_control.utils.clipboard_history import default_clipboard_history return {"matches": default_clipboard_history.search(query)} -def clip_history_start(): +def clip_history_start() -> Dict[str, bool]: from je_auto_control.utils.clipboard_history import default_clipboard_history default_clipboard_history.start() return {"running": default_clipboard_history.running} -def clip_history_stop(): +def clip_history_stop() -> Dict[str, bool]: from je_auto_control.utils.clipboard_history import default_clipboard_history default_clipboard_history.stop() return {"running": default_clipboard_history.running} -def generate_sop(actions, title="Automation Procedure", path=None): +def generate_sop(actions: List[Any], title: str = "Automation Procedure", + path: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.process_doc import generate_sop as _gen from je_auto_control.utils.process_doc import write_sop as _write if path: @@ -258,12 +272,13 @@ def tween_drag(start, end, steps=30, easing="ease_in_out_quad", settle_s=float(settle_s))["points"]} -def fuzzy_ratio(left, right, ignore_case=True): +def fuzzy_ratio(left: Any, right: Any, ignore_case: bool = True) -> Dict[str, float]: from je_auto_control.utils.fuzzy import fuzzy_ratio as _ratio return {"score": _ratio(left, right, ignore_case=ignore_case)} -def fuzzy_best_match(query, choices, score_cutoff=0.0, ignore_case=True): +def fuzzy_best_match(query: Any, choices: Sequence[Any], score_cutoff: float = 0.0, + ignore_case: bool = True) -> Dict[str, Any]: from je_auto_control.utils.fuzzy import fuzzy_best_match as _best best = _best(query, choices, score_cutoff=score_cutoff, ignore_case=ignore_case) @@ -272,18 +287,19 @@ def fuzzy_best_match(query, choices, score_cutoff=0.0, ignore_case=True): return {"match": best[0], "score": best[1], "index": best[2]} -def fuzzy_dedupe(items, threshold=0.9, ignore_case=True): +def fuzzy_dedupe(items: Sequence[Any], threshold: float = 0.9, + ignore_case: bool = True) -> Dict[str, List[Any]]: from je_auto_control.utils.fuzzy import fuzzy_dedupe as _dedupe return {"unique": _dedupe(items, threshold=threshold, ignore_case=ignore_case)} -def canonicalize_url(url): +def canonicalize_url(url: str) -> Dict[str, str]: from je_auto_control.utils.url_canon import canonicalize_url as _canon return {"url": _canon(url)} -def normalize_url(url, sort_query=False, drop_fragment=False): +def normalize_url(url: str, sort_query: bool = False, drop_fragment: bool = False) -> Dict[str, str]: from je_auto_control.utils.url_canon import normalize_url as _norm # `drop_fragment` is this surface's name for it; url_canon calls the # same flag `strip_fragment`. @@ -291,101 +307,102 @@ def normalize_url(url, sort_query=False, drop_fragment=False): strip_fragment=bool(drop_fragment))} -def urls_equal(first, second): +def urls_equal(first: str, second: str) -> Dict[str, bool]: from je_auto_control.utils.url_canon import urls_equal as _equal return {"equal": _equal(first, second)} -def parse_decimal(text, locale="en_US"): +def parse_decimal(text: str, locale: str = "en_US") -> Dict[str, float]: from je_auto_control.utils.locale_parse import parse_decimal as _parse return {"value": _parse(text, locale)} -def parse_number(text, locale="en_US"): +def parse_number(text: str, locale: str = "en_US") -> Dict[str, int]: from je_auto_control.utils.locale_parse import parse_number as _parse return {"value": _parse(text, locale)} -def format_decimal(value, locale="en_US"): +def format_decimal(value: Union[int, float], locale: str = "en_US") -> Dict[str, str]: from je_auto_control.utils.locale_parse import format_decimal as _fmt return {"text": _fmt(value, locale)} -def format_currency(value, currency, locale="en_US"): +def format_currency(value: Union[int, float], currency: str, locale: str = "en_US") -> Dict[str, str]: from je_auto_control.utils.locale_parse import format_currency as _fmt return {"text": _fmt(value, currency, locale)} -def format_date(value, locale="en_US", fmt="medium"): +def format_date(value: Union[str, "date"], locale: str = "en_US", fmt: str = "medium") -> Dict[str, str]: from je_auto_control.utils.locale_parse import format_date as _fmt return {"text": _fmt(value, locale, fmt)} -def voice_register(phrase, actions): +def voice_register(phrase: str, actions: List[Any]) -> Dict[str, List[str]]: from je_auto_control.utils.voice import default_voice_router default_voice_router.register(phrase, actions) return {"phrases": default_voice_router.phrases()} -def voice_dispatch(text): +def voice_dispatch(text: str) -> Dict[str, Any]: from je_auto_control.utils.voice import default_voice_router outcome = default_voice_router.dispatch(text) return {"matched": outcome["matched"], "phrase": outcome["phrase"]} -def voice_list(): +def voice_list() -> Dict[str, List[str]]: from je_auto_control.utils.voice import default_voice_router return {"phrases": default_voice_router.phrases()} -def voice_clear(): +def voice_clear() -> Dict[str, bool]: from je_auto_control.utils.voice import default_voice_router default_voice_router.clear() return {"cleared": True} -def json_query(data, path): +def json_query(data: Any, path: str) -> Dict[str, List[Any]]: from je_auto_control.utils.jsonpath import json_query as _q return {"matches": _q(data, path)} -def json_extract(data, mapping): +def json_extract(data: Any, mapping: Mapping[str, str]) -> Dict[str, Dict[str, Any]]: from je_auto_control.utils.jsonpath import json_extract as _x return {"result": _x(data, mapping)} -def validate_json(data, schema): +def validate_json(data: Any, schema: Union[Dict[str, Any], bool]) -> Dict[str, Any]: from je_auto_control.utils.json_schema import validate_json as _v return _v(data, schema).to_dict() -def resolve_pointer(doc, pointer): +def resolve_pointer(doc: Any, pointer: str) -> Dict[str, Any]: from je_auto_control.utils.json_patch import resolve_pointer as _resolve return {"value": _resolve(doc, pointer)} -def apply_json_patch(doc, patch): +def apply_json_patch(doc: Any, patch: List[Dict[str, Any]]) -> Dict[str, Any]: from je_auto_control.utils.json_patch import apply_patch return {"result": apply_patch(doc, patch)} -def make_json_patch(old, new): +def make_json_patch(old: Any, new: Any) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.json_patch import make_patch return {"patch": make_patch(old, new)} -def merge_patch(doc, patch): +def merge_patch(doc: Any, patch: Any) -> Dict[str, Any]: from je_auto_control.utils.json_patch import merge_patch as _merge return {"result": _merge(doc, patch)} -def search_documents(docs, query, top_k=10, mode="bm25"): +def search_documents(docs: Union[Dict[str, str], Iterable[Tuple[str, str]]], query: str, + top_k: int = 10, mode: str = "bm25") -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.search_index import search_documents as _search hits = _search(docs, query, top_k=int(top_k), mode=mode) return {"hits": [{"doc_id": h.doc_id, "score": h.score} for h in hits]} -def rrule_occurrences(rule, dtstart, count=10): +def rrule_occurrences(rule: str, dtstart: str, count: int = 10) -> Dict[str, List[str]]: import datetime as _dt from je_auto_control.utils.recurrence import occurrences, parse_rrule start = _dt.datetime.fromisoformat(dtstart) @@ -393,7 +410,7 @@ def rrule_occurrences(rule, dtstart, count=10): return {"occurrences": [moment.isoformat() for moment in moments]} -def rrule_next(rule, dtstart, now=None): +def rrule_next(rule: str, dtstart: str, now: Optional[str] = None) -> Dict[str, Optional[str]]: import datetime as _dt from je_auto_control.utils.recurrence import next_occurrence, parse_rrule start = _dt.datetime.fromisoformat(dtstart) @@ -402,42 +419,44 @@ def rrule_next(rule, dtstart, now=None): return {"next": moment.isoformat() if moment else None} -def match_json(actual, expected, partial=False, match_type=False): +def match_json(actual: Any, expected: Any, partial: bool = False, + match_type: bool = False) -> Dict[str, Any]: from je_auto_control.utils.json_contract import match_json as _match return _match(actual, expected, partial=bool(partial), match_type=bool(match_type)).to_dict() -def diff_json(actual, expected): +def diff_json(actual: Any, expected: Any) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.json_contract import diff_json as _diff return {"diffs": _diff(actual, expected)} -def unified_diff(a, b): +def unified_diff(a: str, b: str) -> Dict[str, str]: from je_auto_control.utils.text_diff import unified_diff as _diff return {"diff": _diff(a, b)} -def apply_unified(text, diff): +def apply_unified(text: str, diff: str) -> Dict[str, str]: from je_auto_control.utils.text_diff import apply_unified as _apply return {"result": _apply(text, diff)} -def three_way_merge(base, ours, theirs): +def three_way_merge(base: str, ours: str, theirs: str) -> Dict[str, Any]: from je_auto_control.utils.text_diff import three_way_merge as _merge outcome = _merge(base, ours, theirs) return {"text": outcome.text, "clean": outcome.clean, "conflicts": outcome.conflicts} -def detect_pii(text, kinds=None): +def detect_pii(text: str, kinds: Optional[Sequence[str]] = None) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.pii_text import detect_pii as _detect findings = _detect(text, kinds=kinds) return {"findings": [{"kind": f.kind, "value": f.value, "start": f.start, "end": f.end} for f in findings]} -def redact_pii(text, kinds=None, mode="label", mask_char="*"): +def redact_pii(text: str, kinds: Optional[Sequence[str]] = None, mode: str = "label", + mask_char: str = "*") -> Dict[str, str]: from je_auto_control.utils.pii_text import redact_pii_text return {"text": redact_pii_text(text, kinds=kinds, mode=mode, mask_char=mask_char)} diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_locators.py b/je_auto_control/utils/mcp_server/tools/_handlers_locators.py index c5709a464..219eeaacd 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_locators.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_locators.py @@ -5,12 +5,15 @@ by theme because ``_handlers.py`` is over the 750-line limit. """ import math -from typing import Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence from je_auto_control.utils.mcp_server.tools._handlers_automation_executor import ( _observe_handler, ) +if TYPE_CHECKING: + from je_auto_control.utils.element_repository import ElementRepository + def a11y_list(app_name: Optional[str] = None, max_results: int = 100, @@ -67,51 +70,57 @@ def a11y_click(name: Optional[str] = None, app_name=app_name)) -def control_get_value(name=None, role=None, app_name=None, - automation_id=None): +def control_get_value(name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None) -> Optional[str]: from je_auto_control.utils.accessibility import control_get_value as _g return _g(name=name, role=role, app_name=app_name, automation_id=automation_id) -def control_get_state(name=None, role=None, app_name=None, - automation_id=None): +def control_get_state(name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None) -> Optional[Dict[str, Any]]: from je_auto_control.utils.accessibility import control_get_state as _g return _g(name=name, role=role, app_name=app_name, automation_id=automation_id) -def control_set_value(value, name=None, role=None, app_name=None, - automation_id=None): +def control_set_value(value: str, name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, + automation_id: Optional[str] = None) -> bool: from je_auto_control.utils.accessibility import control_set_value as _s return _s(value, name=name, role=role, app_name=app_name, automation_id=automation_id) -def control_invoke(name=None, role=None, app_name=None, automation_id=None): +def control_invoke(name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, automation_id: Optional[str] = None) -> bool: from je_auto_control.utils.accessibility import control_invoke as _i return _i(name=name, role=role, app_name=app_name, automation_id=automation_id) -def control_toggle(name=None, role=None, app_name=None, automation_id=None): +def control_toggle(name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, automation_id: Optional[str] = None) -> bool: from je_auto_control.utils.accessibility import control_toggle as _t return _t(name=name, role=role, app_name=app_name, automation_id=automation_id) -def read_table(name=None, role=None, app_name=None, automation_id=None): +def read_table(name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, automation_id: Optional[str] = None) -> List[List[str]]: from je_auto_control.utils.accessibility import read_control_table as _r return _r(name=name, role=role, app_name=app_name, automation_id=automation_id) -def _element_repo(path): +def _element_repo(path: str) -> "ElementRepository": from je_auto_control.utils.element_repository import ElementRepository return ElementRepository(path) -def _observe_predicate(kind, params): +def _observe_predicate(kind: str, params: Dict[str, Any]) -> Callable[[], Any]: from je_auto_control.utils.observer import ( image_predicate, pixel_predicate, text_predicate) builders = { @@ -126,82 +135,83 @@ def _observe_predicate(kind, params): return builders[kind]() -def observe_add(name, kind="image", event="appear", actions=None, **params): +def observe_add(name: str, kind: str = "image", event: str = "appear", + actions: Optional[List[Any]] = None, **params: Any) -> Dict[str, str]: from je_auto_control.utils.observer import default_observer default_observer.add(name, _observe_predicate(kind, params), _observe_handler(actions or []), events=(event,)) return {"name": name, "kind": kind, "event": event} -def observe_remove(name): +def observe_remove(name: str) -> Dict[str, bool]: from je_auto_control.utils.observer import default_observer return {"removed": default_observer.remove(name)} -def observe_list(): +def observe_list() -> Dict[str, List[str]]: from je_auto_control.utils.observer import default_observer return {"names": default_observer.names()} -def observe_poll(): +def observe_poll() -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.observer import default_observer return {"fired": default_observer.poll_once()} -def observe_start(): +def observe_start() -> Dict[str, bool]: from je_auto_control.utils.observer import default_observer default_observer.start() return {"running": default_observer.running} -def observe_stop(): +def observe_stop() -> Dict[str, bool]: from je_auto_control.utils.observer import default_observer default_observer.stop() return {"running": default_observer.running} -def mark_screen(app_name=None, render_path=None): +def mark_screen(app_name: Optional[str] = None, render_path: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.set_of_marks import mark_screen as _ms return _ms(app_name=app_name, render_path=render_path) -def mark_click(mark_id): +def mark_click(mark_id: int) -> Dict[str, bool]: from je_auto_control.utils.set_of_marks import mark_click as _mc return {"clicked": _mc(int(mark_id))} -def screen_snapshot(app_name=None): +def screen_snapshot(app_name: Optional[str] = None) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.screen_state import snapshot_screen return {"snapshot": snapshot_screen(app_name=app_name)} -def screen_diff(before, after): +def screen_diff(before: List[Dict[str, Any]], after: List[Dict[str, Any]]) -> Dict[str, Any]: from je_auto_control.utils.screen_state import diff_snapshots return diff_snapshots(before, after) -def screen_changed(app_name=None): +def screen_changed(app_name: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.screen_state import screen_changed as _sc return _sc(app_name=app_name) -def describe_screen(app_name=None): +def describe_screen(app_name: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.screen_state import describe_screen as _ds return _ds(app_name=app_name) -def heal_stats(limit=200): +def heal_stats(limit: int = 200) -> Dict[str, Any]: from je_auto_control.utils.heal_analytics import analyze_heal_log return analyze_heal_log(limit=int(limit)) -def image_hash(path, algo="average"): +def image_hash(path: str, algo: str = "average") -> Dict[str, str]: from je_auto_control.utils.image_dedup import average_hash, dhash hasher = dhash if algo == "dhash" else average_hash return {"hash": hasher(path)} -def dedupe_images(paths, max_distance=5): +def dedupe_images(paths: Sequence[str], max_distance: int = 5) -> Dict[str, List[str]]: from je_auto_control.utils.image_dedup import dedupe_images as _dedupe return {"unique": _dedupe(paths, max_distance=max_distance)} @@ -214,7 +224,8 @@ def _finite(**values: Any) -> None: raise ValueError(f"{name} must be a finite number, got {value!r}") -def to_physical(x, y, physical_w, physical_h, model_w, model_h): +def to_physical(x: float, y: float, physical_w: int, physical_h: int, model_w: int, + model_h: int) -> Dict[str, int]: from je_auto_control.utils.coordinate_space import CoordinateSpace _finite(x=x, y=y, physical_w=physical_w, physical_h=physical_h, model_w=model_w, model_h=model_h) @@ -223,7 +234,8 @@ def to_physical(x, y, physical_w, physical_h, model_w, model_h): return {"x": px, "y": py} -def to_model(x, y, physical_w, physical_h, model_w, model_h): +def to_model(x: int, y: int, physical_w: int, physical_h: int, model_w: int, + model_h: int) -> Dict[str, int]: from je_auto_control.utils.coordinate_space import CoordinateSpace _finite(x=x, y=y, physical_w=physical_w, physical_h=physical_h, model_w=model_w, model_h=model_h) @@ -232,8 +244,9 @@ def to_model(x, y, physical_w, physical_h, model_w, model_h): return {"x": mx, "y": my} -def repair_record(key, method, coordinates=None, description=None, - confidence=1.0, auto_threshold=0.9, db=None): +def repair_record(key: str, method: str, coordinates: Optional[List[int]] = None, + description: Optional[str] = None, confidence: float = 1.0, + auto_threshold: float = 0.9, db: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.locator_repair import repair_store sug = repair_store(db).record( key, method=method, coordinates=coordinates, description=description, @@ -241,17 +254,17 @@ def repair_record(key, method, coordinates=None, description=None, return {"id": sug.id, "status": sug.status} -def repair_resolved(key, db=None): +def repair_resolved(key: str, db: Optional[str] = None) -> Dict[str, Optional[Dict[str, Any]]]: from je_auto_control.utils.locator_repair import repair_store return {"locator": repair_store(db).resolved(key)} -def repair_pending(db=None): +def repair_pending(db: Optional[str] = None) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.locator_repair import repair_store return {"pending": repair_store(db).pending()} -def repair_approve(suggestion_id, db=None): +def repair_approve(suggestion_id: str, db: Optional[str] = None) -> Dict[str, bool]: from je_auto_control.utils.locator_repair import repair_store return {"approved": repair_store(db).approve(suggestion_id)} diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_operations.py b/je_auto_control/utils/mcp_server/tools/_handlers_operations.py index a36d89285..33a260745 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_operations.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_operations.py @@ -5,8 +5,13 @@ by theme because ``_handlers.py`` is over the 750-line limit. """ import os -from typing import Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Union +if TYPE_CHECKING: + from je_auto_control.utils.agent_memory import AgentMemory + from je_auto_control.utils.feature_flags import FlagStore + from je_auto_control.utils.skill_library import SkillLibrary + from je_auto_control.utils.work_queue import WorkQueue #: Where approval artefacts are written when the caller names no directory. @@ -15,47 +20,49 @@ #: Named token buckets shared by every ``rate_limit`` call. -def watchdog_add(title, action="close", case_sensitive=False, name=None): +def watchdog_add(title: str, action: str = "close", case_sensitive: bool = False, + name: Optional[str] = None) -> Dict[str, List[str]]: from je_auto_control.utils.watchdog import default_popup_watchdog default_popup_watchdog.add_window_rule( title, action=action, case_sensitive=bool(case_sensitive), name=name) return {"rules": default_popup_watchdog.rule_names()} -def watchdog_start(): +def watchdog_start() -> Dict[str, bool]: from je_auto_control.utils.watchdog import default_popup_watchdog default_popup_watchdog.start() return {"running": True} -def watchdog_stop(): +def watchdog_stop() -> Dict[str, bool]: from je_auto_control.utils.watchdog import default_popup_watchdog default_popup_watchdog.stop() return {"running": False} -def watchdog_list(): +def watchdog_list() -> Dict[str, Any]: from je_auto_control.utils.watchdog import default_popup_watchdog w = default_popup_watchdog return {"running": w.running, "rules": w.rule_names(), "hits": w.hits} -def generate_otp(secret, step=30, digits=6): +def generate_otp(secret: str, step: int = 30, digits: int = 6) -> str: from je_auto_control.utils.otp import generate_totp return generate_totp(secret, step=int(step), digits=int(digits)) -def assert_session_active(): +def assert_session_active() -> Dict[str, bool]: from je_auto_control.utils.session_guard import ensure_interactive_session return {"interactive": ensure_interactive_session()} -def _work_queue(db, name): +def _work_queue(db: str, name: str) -> "WorkQueue": from je_auto_control.utils.work_queue import WorkQueue return WorkQueue(db, name) -def generate_data(schema, count=10, path=None, fmt=None, seed=None): +def generate_data(schema: Dict[str, Any], count: int = 10, path: Optional[str] = None, + fmt: Optional[str] = None, seed: Optional[int] = None) -> Dict[str, Any]: from je_auto_control.utils.test_data import generate_rows, write_dataset rows = generate_rows(schema, int(count), seed=seed) if path: @@ -63,7 +70,7 @@ def generate_data(schema, count=10, path=None, fmt=None, seed=None): return {"rows": rows, "count": len(rows)} -def mcp_manifest(path=None, include_tools=False): +def mcp_manifest(path: Optional[str] = None, include_tools: bool = False) -> Dict[str, Any]: from je_auto_control.utils.mcp_registry import ( build_server_manifest, write_server_manifest) if path: @@ -73,52 +80,54 @@ def mcp_manifest(path=None, include_tools=False): include_tools=bool(include_tools))} -def rank_tests(flows, history_path=None, window=10): +def rank_tests(flows: List[str], history_path: Optional[str] = None, + window: int = 10) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.test_select import rank_flows return {"ranked": rank_flows(flows, history_path=history_path, window=int(window))} -def select_tests(flows, k=None, threshold=None, history_path=None, window=10): +def select_tests(flows: List[str], k: Optional[int] = None, threshold: Optional[float] = None, + history_path: Optional[str] = None, window: int = 10) -> Dict[str, List[str]]: from je_auto_control.utils.test_select import select_flows return {"selected": select_flows( flows, k=k, threshold=threshold, history_path=history_path, window=int(window))} -def debug_trace(actions, dry_run=False): +def debug_trace(actions: List[Any], dry_run: bool = False) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.flow_debugger import trace_actions return {"trace": trace_actions(actions, dry_run=bool(dry_run))} -def _skill_lib(path): +def _skill_lib(path: str) -> "SkillLibrary": from je_auto_control.utils.skill_library import SkillLibrary return SkillLibrary(path) -def guard_text(text, threshold=2): +def guard_text(text: str, threshold: int = 2) -> Dict[str, Any]: from je_auto_control.utils.guardrail import assess_text return assess_text(text, threshold=int(threshold)) -def agent_card(path=None): +def agent_card(path: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.a2a import build_agent_card, write_agent_card if path: return {"path": write_agent_card(path)} return {"card": build_agent_card()} -def _agent_memory(db): +def _agent_memory(db: str) -> "AgentMemory": from je_auto_control.utils.agent_memory import AgentMemory return AgentMemory(db) -def seed_everything(seed=0): +def seed_everything(seed: int = 0) -> Dict[str, int]: from je_auto_control.utils.deterministic import seed_everything as _seed return {"seed": _seed(int(seed))} -def generate_sbom(path=None, root="je_auto_control"): +def generate_sbom(path: Optional[str] = None, root: Optional[str] = "je_auto_control") -> Dict[str, Any]: from je_auto_control.utils.sbom import build_sbom, write_sbom root_arg = root or None if path: @@ -126,41 +135,44 @@ def generate_sbom(path=None, root="je_auto_control"): return {"sbom": build_sbom(root_arg)} -def shard_suite(flows, shards=2, history_path=None, window=20): +def shard_suite(flows: List[str], shards: int = 2, history_path: Optional[str] = None, + window: int = 20) -> Dict[str, List[List[str]]]: from je_auto_control.utils.test_shard import shard_flows return {"shards": shard_flows(flows, int(shards), history_path=history_path, window=int(window))} -def merge_results(reports): +def merge_results(reports: List[Dict[str, Any]]) -> Dict[str, Any]: from je_auto_control.utils.test_shard import merge_results as _merge return _merge(reports) -def validate_rows(rows, schema): +def validate_rows(rows: List[Dict[str, Any]], schema: Dict[str, Any]) -> Dict[str, Any]: from je_auto_control.utils.data_quality import validate_rows as _validate return _validate(rows, schema) -def extract_fields(text, fields=None, patterns=None): +def extract_fields(text: str, fields: Optional[List[str]] = None, + patterns: Optional[Dict[str, str]] = None) -> Dict[str, Dict[str, List[str]]]: from je_auto_control.utils.data_quality import extract_fields as _extract return {"fields": _extract(text, fields=fields, patterns=patterns)} -def mask_rows(rows, rules): +def mask_rows(rows: List[Dict[str, Any]], rules: Dict[str, str]) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.data_quality import mask_rows as _mask return {"rows": _mask(rows, rules)} -def run_resumable(actions, run_id, db, variables=None): +def run_resumable(actions: List[Any], run_id: str, db: str, + variables: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: from je_auto_control.utils.checkpoint import ( CheckpointStore, run_resumable as _run) return _run(actions, run_id=run_id, store=CheckpointStore(db), variables=variables) -def checkpoint_status(run_id, db): +def checkpoint_status(run_id: str, db: str) -> Dict[str, Any]: if not os.path.exists(db): # read-only: never create the store return {"checkpoint": None} from je_auto_control.utils.checkpoint import CheckpointStore @@ -171,7 +183,7 @@ def checkpoint_status(run_id, db): "variables": cp.variables}} -def checkpoint_clear(run_id, db): +def checkpoint_clear(run_id: str, db: str) -> Dict[str, bool]: from je_auto_control.utils.checkpoint import CheckpointStore return {"cleared": CheckpointStore(db).clear(run_id)} @@ -182,107 +194,109 @@ def ci_annotations(annotations: List[Dict[str, Any]]) -> Dict[str, List[str]]: return {"lines": [format_annotation(item) for item in annotations]} -def scan_secrets(data): +def scan_secrets(data: Any) -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.secrets_scan import scan_secrets as _scan return {"findings": _scan(data)} -def list_plugins(group="je_auto_control.commands"): +def list_plugins(group: str = "je_auto_control.commands") -> Dict[str, List[str]]: from je_auto_control.utils.plugin_sdk import discover_plugins return {"commands": sorted(discover_plugins(group))} -def load_plugins(group="je_auto_control.commands"): +def load_plugins(group: str = "je_auto_control.commands") -> Dict[str, List[str]]: from je_auto_control.utils.plugin_sdk import load_plugins as _load return {"loaded": _load(group)} def approval_request(action: str, requester: str = "", - db: Optional[str] = None): + db: Optional[str] = None) -> Dict[str, str]: from je_auto_control.utils.governance import approval_gate return {"token": approval_gate(db).request(action, requester)} -def approval_approve(token: str, approver: str, db: Optional[str] = None): +def approval_approve(token: str, approver: str, db: Optional[str] = None) -> Dict[str, bool]: from je_auto_control.utils.governance import approval_gate return {"approved": approval_gate(db).approve(token, approver)} -def approval_reject(token: str, approver: str, db: Optional[str] = None): +def approval_reject(token: str, approver: str, db: Optional[str] = None) -> Dict[str, bool]: from je_auto_control.utils.governance import approval_gate return {"rejected": approval_gate(db).reject(token, approver)} -def approval_status(token: str, db: Optional[str] = None): +def approval_status(token: str, db: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.governance import approval_gate gate = approval_gate(db) return {"status": gate.status(token), "approved": gate.is_approved(token)} -def lease_secret(name: str, ttl: float = 300.0): +def lease_secret(name: str, ttl: float = 300.0) -> Dict[str, Any]: from je_auto_control.utils.governance import default_broker return {"token": default_broker.lease(name, ttl), "ttl": float(ttl)} -def lease_valid(token: str): +def lease_valid(token: str) -> Dict[str, bool]: from je_auto_control.utils.governance import default_broker return {"valid": default_broker.is_valid(token)} -def revoke_lease(token: str): +def revoke_lease(token: str) -> Dict[str, bool]: from je_auto_control.utils.governance import default_broker return {"revoked": default_broker.revoke(token)} -def lease_active(): +def lease_active() -> Dict[str, List[Dict[str, object]]]: from je_auto_control.utils.governance import default_broker return {"leases": default_broker.active()} -def user_add(user_id: str, role: str = "viewer", display_name: str = "", tags=None): +def user_add(user_id: str, role: str = "viewer", display_name: str = "", + tags: Optional[Sequence[str]] = None) -> Dict[str, Any]: from je_auto_control.utils.rbac.admin import add_user return dict(add_user(user_id, role=role, display_name=display_name, tags=tags)) -def user_remove(user_id: str): +def user_remove(user_id: str) -> Dict[str, Any]: from je_auto_control.utils.rbac.admin import remove_user return remove_user(user_id) -def user_set_role(user_id: str, role: str): +def user_set_role(user_id: str, role: str) -> Dict[str, Any]: from je_auto_control.utils.rbac.admin import set_user_role return set_user_role(user_id, role) -def user_rotate_token(user_id: str): +def user_rotate_token(user_id: str) -> Dict[str, Any]: from je_auto_control.utils.rbac.admin import rotate_user_token return dict(rotate_user_token(user_id)) -def user_list(): +def user_list() -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.rbac.admin import list_users return {"users": list_users()} -def egress_allow(allow=None, deny=None): +def egress_allow(allow: Union[str, Sequence[str], None] = None, + deny: Union[str, Sequence[str], None] = None) -> Dict[str, Any]: from je_auto_control.utils.egress import set_egress_policy policy = set_egress_policy(allow, deny) return {"allow": policy.allow, "deny": policy.deny} -def egress_check(url: str): +def egress_check(url: str) -> Dict[str, bool]: from je_auto_control.utils.egress import get_egress_policy return {"allowed": get_egress_policy().is_allowed(url)} -def egress_reset(): +def egress_reset() -> Dict[str, Any]: from je_auto_control.utils.egress import set_egress_policy set_egress_policy(None, None) return {"allow": None, "deny": []} -def verify_artifact(name: str, content, approvals_dir: str = _DEFAULT_APPROVALS_DIR, - extension: str = "txt"): +def verify_artifact(name: str, content: Any, approvals_dir: str = _DEFAULT_APPROVALS_DIR, + extension: str = "txt") -> Dict[str, Any]: from je_auto_control.utils.approval import verify_artifact as _verify result = _verify(name, content, approvals_dir, extension) return {"status": result.status, "match": result.match, @@ -291,23 +305,25 @@ def verify_artifact(name: str, content, approvals_dir: str = _DEFAULT_APPROVALS_ def approve_artifact(name: str, approvals_dir: str = _DEFAULT_APPROVALS_DIR, - extension: str = "txt"): + extension: str = "txt") -> Dict[str, str]: from je_auto_control.utils.approval import approve_artifact as _approve return {"approved": _approve(name, approvals_dir, extension)} -def pending_artifacts(approvals_dir: str = _DEFAULT_APPROVALS_DIR): +def pending_artifacts(approvals_dir: str = _DEFAULT_APPROVALS_DIR) -> Dict[str, List[str]]: from je_auto_control.utils.approval import pending_artifacts as _pending return {"pending": _pending(approvals_dir)} -def evaluate_trajectory(trajectory, rubric): +def evaluate_trajectory(trajectory: Sequence[Mapping[str, Any]], + rubric: Mapping[str, Any]) -> Dict[str, Any]: from je_auto_control.utils.trajectory_eval import ( evaluate_trajectory as _evaluate) return _evaluate(trajectory, rubric) -def compliance_report(evidence, frameworks=None, path=None, fmt="json"): +def compliance_report(evidence: Mapping[str, Any], frameworks: Optional[Sequence[str]] = None, + path: Optional[str] = None, fmt: str = "json") -> Dict[str, Any]: from je_auto_control.utils.compliance import ( build_compliance_report, write_compliance_report) report = build_compliance_report(evidence, frameworks) @@ -316,9 +332,10 @@ def compliance_report(evidence, frameworks=None, path=None, fmt="json"): return report -def trace_record(operation, model=None, system=None, input_tokens=None, - output_tokens=None, tool_name=None, duration_s=0.0, - status="ok"): +def trace_record(operation: str, model: Optional[str] = None, system: Optional[str] = None, + input_tokens: Optional[int] = None, output_tokens: Optional[int] = None, + tool_name: Optional[str] = None, duration_s: float = 0.0, + status: str = "ok") -> Dict[str, Any]: from je_auto_control.utils.agent_trace import default_trace return default_trace.record( operation, model=model, system=system, input_tokens=input_tokens, @@ -326,62 +343,64 @@ def trace_record(operation, model=None, system=None, input_tokens=None, duration_s=duration_s, status=status) -def trace_summary(): +def trace_summary() -> Dict[str, Any]: from je_auto_control.utils.agent_trace import default_trace return default_trace.summary() -def trace_export(): +def trace_export() -> Dict[str, List[Dict[str, Any]]]: from je_auto_control.utils.agent_trace import default_trace return {"spans": default_trace.to_otel()} -def trace_reset(): +def trace_reset() -> Dict[str, bool]: from je_auto_control.utils.agent_trace import reset_trace reset_trace() return {"reset": True} -def write_step_video(steps, output, fps=10, seconds_per_step=2.0): +def write_step_video(steps: Sequence[Any], output: str, fps: int = 10, + seconds_per_step: float = 2.0) -> Dict[str, Any]: from je_auto_control.utils.video_report import ( write_step_video as _write) return _write(steps, output, fps=fps, seconds_per_step=seconds_per_step) -def s3_upload(local_path, key=None): +def s3_upload(local_path: str, key: Optional[str] = None) -> Dict[str, str]: from je_auto_control.utils.artifact_store import get_default_store return {"key": get_default_store().upload(local_path, key)} -def s3_download(key, local_path): +def s3_download(key: str, local_path: str) -> Dict[str, str]: from je_auto_control.utils.artifact_store import get_default_store return {"path": get_default_store().download(key, local_path)} -def s3_list(prefix=None): +def s3_list(prefix: Optional[str] = None) -> Dict[str, List[str]]: from je_auto_control.utils.artifact_store import get_default_store return {"keys": get_default_store().list(prefix)} -def s3_delete(key): +def s3_delete(key: str) -> Dict[str, bool]: from je_auto_control.utils.artifact_store import get_default_store return {"deleted": get_default_store().delete(key)} -def loop_guard_observe(tool, args=None, result_digest=""): +def loop_guard_observe(tool: str, args: Any = None, result_digest: str = "") -> Dict[str, Any]: from je_auto_control.utils.loop_guard import default_loop_guard verdict = default_loop_guard.observe(tool, args, result_digest) return {"pattern": verdict.pattern, "level": verdict.level, "count": verdict.count} -def loop_guard_reset(): +def loop_guard_reset() -> Dict[str, bool]: from je_auto_control.utils.loop_guard import default_loop_guard default_loop_guard.reset() return {"reset": True} -def mine_actions(actions, min_len=2, max_len=5, min_count=3): +def mine_actions(actions: Sequence[Any], min_len: int = 2, max_len: int = 5, + min_count: int = 3) -> Dict[str, Any]: from je_auto_control.utils.process_mining import mine_action_log report = mine_action_log(actions, min_len=min_len, max_len=max_len, min_count=min_count) @@ -395,24 +414,25 @@ def mine_actions(actions, min_len=2, max_len=5, min_count=3): } -def set_asset(name, value, asset_type="text", environment="default", db=None): +def set_asset(name: str, value: Any, asset_type: str = "text", environment: str = "default", + db: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.assets.assets import store_set return store_set(name, value, asset_type=asset_type, environment=environment, db=db) -def get_asset(name, environment="default", db=None): +def get_asset(name: str, environment: str = "default", db: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.assets.assets import store_get return store_get(name, environment=environment, db=db) -def list_assets(environment=None, db=None): +def list_assets(environment: Optional[str] = None, db: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.assets.assets import store_list return store_list(environment=environment, db=db) -def emit_event(event_type, data=None, source="je_auto_control", - subject=None, url=None): +def emit_event(event_type: str, data: Any = None, source: str = "je_auto_control", + subject: Optional[str] = None, url: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.events import post_cloudevent, to_cloudevent event = to_cloudevent(event_type, source, data, subject=subject) result: Dict[str, Any] = {"event": event} @@ -421,7 +441,8 @@ def emit_event(event_type, data=None, source="je_auto_control", return result -def notify_webhook(url, text, transport="raw", title=None): +def notify_webhook(url: str, text: str, transport: str = "raw", + title: Optional[str] = None) -> Dict[str, Any]: from je_auto_control.utils.notify_channels import ( notify_webhook as _notify) outcome = _notify(url, text, transport=transport, title=title) @@ -429,7 +450,8 @@ def notify_webhook(url, text, transport="raw", title=None): "transport": outcome.transport} -def scan_vulns(components, advisories=None): +def scan_vulns(components: Any, + advisories: Optional[Sequence[Mapping[str, Any]]] = None) -> Dict[str, Any]: from je_auto_control.utils.vuln_scan import scan_components if isinstance(components, dict): components = components.get("components", []) @@ -437,13 +459,15 @@ def scan_vulns(components, advisories=None): return {"findings": findings, "count": len(findings)} -def apply_vex(findings, vex): +def apply_vex(findings: Sequence[Mapping[str, Any]], vex: Mapping[str, Any]) -> Dict[str, Any]: from je_auto_control.utils.vex import apply_vex as _apply kept = _apply(findings, vex) return {"findings": kept, "count": len(kept)} -def check_licenses(components, allow=None, deny=None): +def check_licenses(components: Any, + allow: Optional[Sequence[str]] = None, + deny: Optional[Sequence[str]] = None) -> Dict[str, Any]: from je_auto_control.utils.license_policy import evaluate_sbom if isinstance(components, dict): components = components.get("components", []) @@ -451,12 +475,13 @@ def check_licenses(components, allow=None, deny=None): return {"violations": violations, "count": len(violations)} -def jwt_encode(claims, key, alg="HS256"): +def jwt_encode(claims: Mapping[str, Any], key: Union[str, bytes], alg: str = "HS256") -> Dict[str, str]: from je_auto_control.utils.jwt import encode_jwt return {"token": encode_jwt(claims, key, alg=alg)} -def jwt_decode(token, key, algorithms=None, audience=None, leeway=0.0): +def jwt_decode(token: str, key: Union[str, bytes], algorithms: Optional[Sequence[str]] = None, + audience: Any = None, leeway: float = 0.0) -> Dict[str, Any]: from je_auto_control.utils.jwt import ClaimsPolicy, JwtError, decode_jwt policy = ClaimsPolicy(algorithms=tuple(algorithms) if algorithms else ("HS256",), audience=audience, leeway=leeway) @@ -467,44 +492,47 @@ def jwt_decode(token, key, algorithms=None, audience=None, leeway=0.0): return {"ok": True, "claims": claims} -def rate_limit(name, rate=1.0, capacity=1.0, n=1.0): +def rate_limit(name: str, rate: float = 1.0, capacity: float = 1.0, n: float = 1.0) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _rate_limit return _rate_limit(name, rate, capacity, n) -def describe_stats(values): +def describe_stats(values: Sequence[float]) -> Dict[str, float]: from je_auto_control.utils.stats import describe return describe(values) -def ab_significance(a_conv, a_n, b_conv, b_n): +def ab_significance(a_conv: int, a_n: int, b_conv: int, b_n: int) -> Dict[str, Any]: from je_auto_control.utils.stats import two_proportion_z_test return two_proportion_z_test(int(a_conv), int(a_n), int(b_conv), int(b_n)) -def evaluate_slo(records, target, window_s=None): +def evaluate_slo(records: Sequence[Mapping[str, Any]], target: float, + window_s: Optional[float] = None) -> Dict[str, Any]: from je_auto_control.utils.slo import evaluate_slo as _slo return _slo(records, float(target), window_s=window_s) -def burn_alerts(records, target): +def burn_alerts(records: Sequence[Mapping[str, Any]], target: float) -> Dict[str, Any]: from je_auto_control.utils.slo import burn_alerts as _alerts alerts = _alerts(records, float(target)) return {"alerts": alerts, "firing": bool(alerts)} -def percentiles(samples, qs=None): +def percentiles(samples: Sequence[float], + qs: Optional[Sequence[float]] = None) -> Dict[str, Dict[str, float]]: from je_auto_control.utils.percentiles import exact_percentiles result = exact_percentiles(samples, qs=tuple(qs) if qs else (50, 90, 95, 99)) return {"percentiles": {str(q): value for q, value in result.items()}} -def retry_after(response): +def retry_after(response: Mapping[str, Any]) -> Dict[str, float]: from je_auto_control.utils.bulkhead import next_delay return {"delay": next_delay(response)} -def http_replay(cassette, url, method="GET"): +def http_replay(cassette: Union[Dict[str, Any], Sequence[Mapping[str, Any]]], url: str, + method: str = "GET") -> Dict[str, Dict[str, Any]]: from je_auto_control.utils.http_cassette import Cassette interactions = (cassette.get("interactions", []) if isinstance(cassette, dict) else cassette) @@ -513,44 +541,49 @@ def http_replay(cassette, url, method="GET"): return {"response": response} -def build_provenance(paths, builder_id="je_auto_control"): +def build_provenance(paths: Sequence[str], + builder_id: str = "je_auto_control") -> Dict[str, Dict[str, Any]]: from je_auto_control.utils.provenance import build_provenance, subject_for subjects = [subject_for(path) for path in paths] return {"statement": build_provenance(subjects, builder_id=builder_id)} -def verify_provenance(statement, files): +def verify_provenance(statement: Mapping[str, Any], files: Mapping[str, str]) -> Dict[str, Any]: from je_auto_control.utils.provenance import verify_provenance as _verify mismatches = _verify(statement, files) return {"ok": not mismatches, "mismatches": mismatches} -def evaluate_flag(flags, key, context=None): +def evaluate_flag(flags: Union[Dict[str, Any], "FlagStore"], key: str, + context: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]: from je_auto_control.utils.feature_flags import ( FlagStore, evaluate_flag as _ev) store = FlagStore.from_dict(flags) if isinstance(flags, dict) else flags return _ev(store, key, context or {}) -def flag_enabled(flags, key, context=None, default=False): +def flag_enabled(flags: Union[Dict[str, Any], "FlagStore"], key: str, + context: Optional[Mapping[str, Any]] = None, + default: bool = False) -> Dict[str, bool]: from je_auto_control.utils.feature_flags import FlagStore, is_enabled store = FlagStore.from_dict(flags) if isinstance(flags, dict) else flags return {"enabled": is_enabled(store, key, context or {}, bool(default))} -def run_saga(steps): +def run_saga(steps: Any) -> Dict[str, Any]: # The executor's adapter: this copy dropped compensation_errors, so a # failed rollback read as "no compensation defined". from je_auto_control.utils.executor.action_executor import _run_saga return _run_saga(steps) -def decision_table(spec, context): +def decision_table(spec: Mapping[str, Any], context: Mapping[str, Any]) -> Dict[str, Any]: from je_auto_control.utils.decision_table import evaluate_table return {"result": evaluate_table(spec, context)} -def export_sarif(findings, path=None, tool_name="AutoControl"): +def export_sarif(findings: Sequence[Mapping[str, Any]], path: Optional[str] = None, + tool_name: str = "AutoControl") -> Dict[str, Any]: from je_auto_control.utils.sarif import to_sarif, write_sarif result: Dict[str, Any] = {"sarif": to_sarif(findings, tool_name=tool_name)} if path: diff --git a/je_auto_control/utils/mcp_server/tools/_handlers_system.py b/je_auto_control/utils/mcp_server/tools/_handlers_system.py index 47bb9308f..099241ebe 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers_system.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers_system.py @@ -10,7 +10,7 @@ """ import base64 import os -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Sequence from je_auto_control.utils.exception.exceptions import AutoControlActionException from je_auto_control.utils.mcp_server.tools._base import MCPContent @@ -290,137 +290,138 @@ def shell_command(command: str, timeout: float = 30.0 } -def open_path(target, verb="open"): +def open_path(target: str, verb: str = "open") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _open_path return _open_path(target, verb) -def plan_open(target, verb="open"): +def plan_open(target: str, verb: str = "open") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _plan_open return _plan_open(target, verb) -def idle_seconds(): +def idle_seconds() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _idle_seconds return _idle_seconds() -def is_idle(threshold): +def is_idle(threshold: float) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _is_idle return _is_idle(threshold) -def plan_keep_awake(display=True, system=True): +def plan_keep_awake(display: bool = True, system: bool = True) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _plan_keep_awake return _plan_keep_awake(display, system) -def keep_awake_on(display=True, system=True): +def keep_awake_on(display: bool = True, system: bool = True) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _keep_awake_on return _keep_awake_on(display, system) -def allow_sleep(): +def allow_sleep() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _allow_sleep return _allow_sleep() -def get_volume(): +def get_volume() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _get_volume return _get_volume() -def set_volume(level): +def set_volume(level: float) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _set_volume return _set_volume(level) -def change_volume(delta): +def change_volume(delta: float) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _change_volume return _change_volume(delta) -def set_mute(muted=True): +def set_mute(muted: bool = True) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _set_mute return _set_mute(muted) -def toggle_mute(): +def toggle_mute() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _toggle_mute return _toggle_mute() -def lock_session(): +def lock_session() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _lock_session return _lock_session() -def plan_lock_session(): +def plan_lock_session() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _plan_lock_session, ) return _plan_lock_session() -def wait_for_unlock(timeout=30.0, interval=0.5): +def wait_for_unlock(timeout: float = 30.0, interval: float = 0.5) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _wait_for_unlock return _wait_for_unlock(timeout, interval) -def classify_lock_transitions(states): +def classify_lock_transitions(states: List[bool]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _classify_lock_transitions, ) return _classify_lock_transitions(states) -def ime_state(): +def ime_state() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _ime_state return _ime_state() -def is_composing(): +def is_composing() -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _is_composing return _is_composing() -def wait_for_composition_commit(timeout=5.0, interval=0.1): +def wait_for_composition_commit(timeout: float = 5.0, interval: float = 0.1) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _wait_for_composition_commit, ) return _wait_for_composition_commit(timeout, interval) -def decode_conversion_mode(flags): +def decode_conversion_mode(flags: int) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _decode_conversion_mode, ) return _decode_conversion_mode(flags) -def retry_delay(attempt, base=0.1, max_delay=5.0, multiplier=2.0, - jitter="none"): +def retry_delay(attempt: int, base: float = 0.1, max_delay: float = 5.0, multiplier: float = 2.0, + jitter: str = "none") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _retry_delay return _retry_delay(attempt, base, max_delay, multiplier, jitter) -def plan_retry_delays(attempts, base=0.1, max_delay=5.0, multiplier=2.0, - jitter="none"): +def plan_retry_delays(attempts: int, base: float = 0.1, max_delay: float = 5.0, multiplier: float = 2.0, + jitter: str = "none") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _plan_retry_delays, ) return _plan_retry_delays(attempts, base, max_delay, multiplier, jitter) -def compare_field_value(expected, actual, mode="exact"): +def compare_field_value(expected: Any, actual: Any, mode: str = "exact") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _compare_field_value, ) return _compare_field_value(expected, actual, mode) -def verify_field_value(expected, name=None, role=None, app_name=None, - automation_id=None, mode="exact"): +def verify_field_value(expected: Any, name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, automation_id: Optional[str] = None, + mode: str = "exact") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _verify_field_value, ) @@ -428,22 +429,23 @@ def verify_field_value(expected, name=None, role=None, app_name=None, mode) -def adaptive_timeout(durations, percentile_q=95.0, factor=1.5, min_s=1.0, - max_s=60.0): +def adaptive_timeout(durations: List[float], percentile_q: float = 95.0, factor: float = 1.5, + min_s: float = 1.0, max_s: float = 60.0) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _adaptive_timeout, ) return _adaptive_timeout(durations, percentile_q, factor, min_s, max_s) -def timeout_stats(durations, percentile_q=95.0, factor=1.5, min_s=1.0, - max_s=60.0): +def timeout_stats(durations: List[float], percentile_q: float = 95.0, factor: float = 1.5, + min_s: float = 1.0, max_s: float = 60.0) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _timeout_stats return _timeout_stats(durations, percentile_q, factor, min_s, max_s) -def ensure_field_value(desired, name=None, role=None, app_name=None, - automation_id=None, attempts=2): +def ensure_field_value(desired: str, name: Optional[str] = None, role: Optional[str] = None, + app_name: Optional[str] = None, automation_id: Optional[str] = None, + attempts: int = 2) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _ensure_field_value, ) @@ -451,112 +453,117 @@ def ensure_field_value(desired, name=None, role=None, app_name=None, attempts) -def wait_until_app_idle(quiet_samples=3, timeout=10.0, interval=0.1): +def wait_until_app_idle(quiet_samples: int = 3, timeout: float = 10.0, + interval: float = 0.1) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _wait_until_app_idle, ) return _wait_until_app_idle(quiet_samples, timeout, interval) -def idle_point(busy_samples, quiet_samples=3): +def idle_point(busy_samples: List[bool], quiet_samples: int = 3) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _idle_point return _idle_point(busy_samples, quiet_samples) -def simulate_cvd(rgb, kind="deuteranopia", severity=1.0): +def simulate_cvd(rgb: Sequence[int], kind: str = "deuteranopia", severity: float = 1.0) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _simulate_cvd return _simulate_cvd(rgb, kind, severity) -def colors_collide(left, right, kind="deuteranopia", severity=1.0, - threshold=40.0): +def colors_collide(left: Sequence[int], right: Sequence[int], kind: str = "deuteranopia", + severity: float = 1.0, threshold: float = 40.0) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _colors_collide return _colors_collide(left, right, kind, severity, threshold) -def place_labels(marks, label_width=22, label_height=16, bounds=None): +def place_labels(marks: List[Dict[str, Any]], label_width: int = 22, label_height: int = 16, + bounds: Optional[Sequence[int]] = None) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _place_labels return _place_labels(marks, label_width, label_height, bounds) -def label_color(background): +def label_color(background: Sequence[int]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _label_color return _label_color(background) -def grade_contrast(foreground, background): +def grade_contrast(foreground: Sequence[int], background: Sequence[int]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _grade_contrast return _grade_contrast(foreground, background) -def dominant_pair(pixels): +def dominant_pair(pixels: List[Sequence[int]]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _dominant_pair return _dominant_pair(pixels) -def region_contrast(region=None): +def region_contrast(region: Optional[Sequence[int]] = None) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _region_contrast return _region_contrast(region) -def match_theme(template, region=None, method="sobel", min_score=0.5): +def match_theme(template: str, region: Optional[Sequence[int]] = None, method: str = "sobel", + min_score: float = 0.5) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _match_theme return _match_theme(template, region, method, min_score) -def rank_changes(scored_boxes, threshold=0.1): +def rank_changes(scored_boxes: List[Dict[str, Any]], threshold: float = 0.1) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _rank_changes return _rank_changes(scored_boxes, threshold) -def localize_changes(reference, boxes, current=None, threshold=0.1, - region=None): +def localize_changes(reference: str, boxes: List[Sequence[int]], current: Optional[str] = None, + threshold: float = 0.1, + region: Optional[Sequence[int]] = None) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _localize_changes, ) return _localize_changes(reference, boxes, current, threshold, region) -def classify_widget(features): +def classify_widget(features: Dict[str, Any]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _classify_widget return _classify_widget(features) -def classify_icon(source, box): +def classify_icon(source: str, box: Sequence[int]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _classify_icon return _classify_icon(source, box) -def propose_elements(region=None, min_area=80, iou_threshold=0.5): +def propose_elements(region: Optional[Sequence[int]] = None, min_area: int = 80, + iou_threshold: float = 0.5) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import ( _propose_elements, ) return _propose_elements(region, min_area, iou_threshold) -def tag_kinds(elements): +def tag_kinds(elements: List[Dict[str, Any]]) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _tag_kinds return _tag_kinds(elements) -def act_in_view(target, kind="image", direction="down", max_scrolls=10, - scroll_amount=3, button="left"): +def act_in_view(target: str, kind: str = "image", direction: str = "down", max_scrolls: int = 10, + scroll_amount: int = 3, button: str = "left") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _act_in_view return _act_in_view(target, kind, direction, max_scrolls, scroll_amount, button) -def act_with_mode(x, y, mode="auto", button="left"): +def act_with_mode(x: int, y: int, mode: str = "auto", button: str = "left") -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _act_with_mode return _act_with_mode(x, y, mode, button) -def normalize_ext(target): +def normalize_ext(target: str) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _normalize_ext return _normalize_ext(target) -def file_association(target): +def file_association(target: str) -> Dict[str, Any]: from je_auto_control.utils.executor.action_executor import _file_association return _file_association(target) diff --git a/je_auto_control/utils/remote_desktop/webrtc_host.py b/je_auto_control/utils/remote_desktop/webrtc_host.py index 2867879ec..1721214f1 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_host.py +++ b/je_auto_control/utils/remote_desktop/webrtc_host.py @@ -16,6 +16,7 @@ import asyncio import json +import os import threading from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional, Tuple @@ -55,6 +56,7 @@ ) if TYPE_CHECKING: # imported lazily at runtime to keep startup cheap + from pathlib import Path from je_auto_control.utils.remote_desktop.webrtc_audio import ( OpusMicAudioTrack, OpusMicReceiver, ) @@ -64,7 +66,7 @@ from je_auto_control.utils.remote_desktop.webrtc_mic import ( MicUplinkReceiver, ) - from je_auto_control.utils.usb.passthrough import UsbChannelHost + from je_auto_control.utils.usb.passthrough import UsbChannelHost, UsbPassthroughSession _AUTH_GRACE_S = 5.0 @@ -97,11 +99,11 @@ def __init__(self, *, token: str, # NOSONAR python:S107 trust_list: Optional[TrustList] = None, read_only: bool = False, permissions: Optional[SessionPermissions] = None, - external_video_track=None, - inbox_dir=None, - ip_whitelist: Optional[list] = None, + external_video_track: Any = None, + inbox_dir: Optional[Path] = None, + ip_whitelist: Optional[list[str]] = None, rate_limit: Optional[RateLimitConfig] = None, - on_annotation: Optional[Callable[[dict], None]] = None) -> None: + on_annotation: Optional[Callable[[dict[str, Any]], None]] = None) -> None: if not token: raise ValueError("WebRTC host requires a non-empty token") self._token = token @@ -136,8 +138,8 @@ def __init__(self, *, token: str, # NOSONAR python:S107 self._file_callbacks = FileReceiveCallbacks( audit=lambda path: default_audit_log().log( 'file_received', viewer_id=self._pending_viewer_id, detail=str(path))) - self._on_viewer_video_frame: Optional[Callable] = None - self._viewer_video_task: Optional[asyncio.Task] = None + self._on_viewer_video_frame: Optional[Callable[[Any], None]] = None + self._viewer_video_task: Optional[asyncio.Task[Any]] = None self._opus_audio_receiver: Optional[OpusMicReceiver] = None # Outbound host voice, when the host shares its own microphone. self._host_voice_track: Optional[OpusMicAudioTrack] = None @@ -147,7 +149,7 @@ def __init__(self, *, token: str, # NOSONAR python:S107 # Hold strong refs to fire-and-forget tasks so the asyncio event # loop doesn't garbage-collect them mid-flight (S7502). Tasks # remove themselves from this set in their done callback. - self._background_tasks: set = set() + self._background_tasks: set[asyncio.Task[Any]] = set() self._retirement = PeerRetirement() self._media_owners = PeerMediaOwners() self._closed = threading.Event() @@ -263,7 +265,7 @@ async def _stop_generation(self, peer: object) -> None: async def _stop_peer(self) -> None: await stop_host(self) - def _spawn_bg(self, coro) -> "asyncio.Task": + def _spawn_bg(self, coro: Coroutine[Any, Any, Any]) -> "asyncio.Task[Any]": """Schedule ``coro`` and pin a strong ref while it runs (S7502).""" task = asyncio.ensure_future(coro) self._background_tasks.add(task) @@ -274,7 +276,7 @@ def _spawn_bg(self, coro) -> "asyncio.Task": def _wire_viewer_video_handler(self, pc: RTCPeerConnection) -> None: @pc.on("track") - def _on_track(track) -> None: + def _on_track(track: Any) -> None: if self._pc is not pc or self._closed.is_set(): return if track.kind == "video": @@ -287,7 +289,7 @@ def _on_track(track) -> None: return self._start_opus_audio_receive(track) - def _start_opus_audio_receive(self, track) -> None: + def _start_opus_audio_receive(self, track: Any) -> None: from je_auto_control.utils.remote_desktop.webrtc_audio import ( OpusMicReceiver, ) @@ -301,7 +303,7 @@ def _start_opus_audio_receive(self, track) -> None: self._media_owners.activate("opus receiver", lambda: receiver.consume(track), receiver) autocontrol_logger.info("webrtc host: receiving Opus audio from viewer") - async def _consume_viewer_video(self, track) -> None: + async def _consume_viewer_video(self, track: Any) -> None: from aiortc.mediastreams import MediaStreamError try: while True: @@ -321,7 +323,7 @@ async def _consume_viewer_video(self, track) -> None: finally: self._viewer_video_task = None - def set_viewer_video_callback(self, callback) -> None: + def set_viewer_video_callback(self, callback: Optional[Callable[[Any], None]]) -> None: """Register ``cb(av.VideoFrame)`` for incoming viewer-screen frames.""" self._on_viewer_video_frame = callback @@ -361,7 +363,7 @@ async def _snapshot_remote_ip(self) -> None: autocontrol_logger.info("webrtc host: remote ip = %s", ip) @staticmethod - def _extract_remote_ip(report) -> Optional[str]: + def _extract_remote_ip(report: Mapping[str, Any]) -> Optional[str]: for entry in report.values(): if (getattr(entry, "type", None) != "candidate-pair" or not getattr(entry, "selected", False)): @@ -374,16 +376,16 @@ def _extract_remote_ip(report) -> Optional[str]: return str(ip) if ip else None return None - def _wire_mic_channel(self, channel) -> None: + def _wire_mic_channel(self, channel: Any) -> None: @channel.on("message") - def _on_message(message) -> None: + def _on_message(message: Any) -> None: if not self._authenticated or self._mic_receiver is None: return if not self._permissions.allow_audio: return self._mic_receiver.on_chunk(message) - def _wire_files_channel(self, channel) -> None: + def _wire_files_channel(self, channel: Any) -> None: from je_auto_control.utils.remote_desktop.webrtc_files import FileTransferReceiver close_file_receiver(self._files_receiver, self._files_channel) receiver = self._files_receiver = FileTransferReceiver(self._inbox_dir) @@ -403,7 +405,7 @@ def accept_begin() -> bool: bind_file_receiver(channel, receiver, active, self._on_file_done, accept_begin, received=self._file_callbacks.received) - def _wire_usb_channel(self, channel) -> None: + def _wire_usb_channel(self, channel: Any) -> None: """Carry USB passthrough over the ``usb`` DataChannel. Gated on viewer authentication *and* the global passthrough flag @@ -414,7 +416,7 @@ def _wire_usb_channel(self, channel) -> None: """ from je_auto_control.utils.usb.passthrough import UsbChannelHost - def _factory(): + def _factory() -> UsbPassthroughSession: from je_auto_control.utils.usb.passthrough import ( UsbAcl, UsbPassthroughSession, default_passthrough_backend, ) @@ -441,7 +443,7 @@ def _release_usb_claims(self) -> None: if self._usb_host is usb_host: self._usb_host = None - def set_file_received_callback(self, callback) -> None: + def set_file_received_callback(self, callback: Optional[Callable[[Path], None]]) -> None: """Register a sync callback ``cb(path: Path)`` for completed transfers.""" self._file_callbacks.on_file = callback @@ -449,7 +451,7 @@ def set_file_receipt_callback(self, callback: Optional[ReceiptCallback]) -> None """Register an inert local publication-receipt listener; None clears it.""" self._file_callbacks.on_receipt = callback - def push_file(self, local_path, remote_name=None, *, + def push_file(self, local_path: str | os.PathLike[str], remote_name: Optional[str] = None, *, cancelled: Optional[Callable[[], bool]] = None, require_commit: bool = False) -> None: """Send to the viewer, optionally requiring its matching atomic-publication receipt.""" if self._files_channel is None or not self._authenticated: @@ -461,7 +463,7 @@ def push_file(self, local_path, remote_name=None, *, local_path, remote_name=remote_name, cancelled=cancelled, require_commit=require_commit, ) - def _on_file_done(self, path) -> None: + def _on_file_done(self, path: Path) -> None: self._file_callbacks.published(path) def enable_mic_receive(self) -> None: @@ -485,13 +487,13 @@ def disable_mic_receive(self) -> None: self._media_owners.stop_field("mic receiver", self._mic_receiver) self._mic_receiver = None - def _wire_control_channel(self, channel) -> None: + def _wire_control_channel(self, channel: Any) -> None: @channel.on("open") def _on_open() -> None: autocontrol_logger.info("webrtc host: control channel open") @channel.on("message") - def _on_message(message) -> None: + def _on_message(message: Any) -> None: if self._control_channel is channel: self._handle_ctrl_message(message) @@ -508,6 +510,8 @@ def _handle_ctrl_message(self, message: Any) -> None: if data is None: return msg_type = data.get("type") + if not isinstance(msg_type, str): # {"type": []} raised TypeError in the lookup below + return if not self._authenticated: if msg_type == "auth": self._handle_auth(data) @@ -517,7 +521,7 @@ def _handle_ctrl_message(self, message: Any) -> None: handler(data) @staticmethod - def _parse_ctrl_envelope(message: Any) -> Optional[dict]: + def _parse_ctrl_envelope(message: Any) -> Optional[dict[str, Any]]: if not isinstance(message, str): return None try: @@ -527,7 +531,7 @@ def _parse_ctrl_envelope(message: Any) -> Optional[dict]: return None return data if isinstance(data, dict) else None - def _authenticated_handlers(self) -> dict: + def _authenticated_handlers(self) -> dict[str, Callable[[dict[str, Any]], object]]: return { "input": self._handle_input_message, "send_sas": self._handle_send_sas_message, @@ -540,7 +544,7 @@ def _authenticated_handlers(self) -> dict: "renegotiate_answer": self._handle_renegotiate_answer, } - def _handle_input_message(self, data: dict) -> None: + def _handle_input_message(self, data: dict[str, Any]) -> None: if not self._permissions.allow_input: return if not self._rate_limiter.allow_input(): @@ -549,12 +553,12 @@ def _handle_input_message(self, data: dict) -> None: return self._dispatch_input_safely(data.get("payload")) - def _handle_send_sas_message(self, _data: dict) -> None: + def _handle_send_sas_message(self, _data: dict[str, Any]) -> None: if not self._permissions.allow_input: return self._handle_send_sas() - def _handle_annotate(self, data: dict) -> None: + def _handle_annotate(self, data: dict[str, Any]) -> None: if self._on_annotation is None: return try: @@ -564,7 +568,7 @@ def _handle_annotate(self, data: dict) -> None: except (RuntimeError, OSError) as error: autocontrol_logger.debug("annotation cb: %r", error) - def _handle_renegotiate_answer(self, data: dict) -> None: + def _handle_renegotiate_answer(self, data: dict[str, Any]) -> None: sdp = data.get("sdp") if isinstance(sdp, str) and self._pc is not None: self._spawn_bg(self._async_apply_renegotiate_answer(sdp)) @@ -582,7 +586,7 @@ def _safe_audit_log(self, event_type: str) -> None: def _async_apply_renegotiate_answer(self, sdp: str) -> Coroutine[Any, Any, None]: return self._apply_renegotiate_answer(self._pc, sdp) - async def _apply_renegotiate_answer(self, peer, sdp: str) -> None: + async def _apply_renegotiate_answer(self, peer: Any, sdp: str) -> None: if self._pc is not peer: return async with self._retirement.starting(): diff --git a/je_auto_control/utils/remote_desktop/webrtc_viewer.py b/je_auto_control/utils/remote_desktop/webrtc_viewer.py index 704075cd9..7fbbf1858 100644 --- a/je_auto_control/utils/remote_desktop/webrtc_viewer.py +++ b/je_auto_control/utils/remote_desktop/webrtc_viewer.py @@ -8,6 +8,7 @@ import asyncio import json +import os import threading from typing import TYPE_CHECKING, Any, Callable, Coroutine, Mapping, Optional @@ -15,7 +16,7 @@ from je_auto_control.utils.remote_desktop.media_retirement import raise_cleanup_failures from je_auto_control.utils.remote_desktop.webrtc_peer_cleanup import stop_viewer from je_auto_control.utils.remote_desktop.webrtc_retirement import ( - PeerRetirement, PeerStopFailed, stop_resource, + PeerRetirement, PeerStopFailed, Stoppable, stop_resource, ) from je_auto_control.utils.exception.control_signals import raise_caused_run_interruption from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -31,6 +32,7 @@ ) if TYPE_CHECKING: # imported lazily at runtime to keep startup cheap + from pathlib import Path from je_auto_control.utils.remote_desktop.webrtc_audio import ( OpusMicAudioTrack, OpusMicReceiver, ) @@ -51,7 +53,7 @@ StateCallback = Callable[[str], None] AuthCallback = Callable[[bool], None] FingerprintCallback = Callable[[str], None] -InboxListingCallback = Callable[[list], None] +InboxListingCallback = Callable[[list[Any]], None] InboxOpResultCallback = Callable[[str, bool, Optional[str]], None] FileReceivedCallback = Callable[[Any], None] @@ -94,7 +96,7 @@ def __init__(self, *, token: str, self._viewer_screen_track: Optional[ScreenVideoTrack] = None self._opus_audio_track: Optional[OpusMicAudioTrack] = None self._host_voice_receiver: Optional[OpusMicReceiver] = None - self._receive_task: Optional[asyncio.Task] = None + self._receive_task: Optional[asyncio.Task[None]] = None self._authenticated = False self._read_only = False self._host_fingerprint: Optional[str] = None @@ -103,7 +105,7 @@ def __init__(self, *, token: str, self._closed = threading.Event() # Pin fire-and-forget asyncio tasks so they aren't reaped before # they finish (S7502). Tasks self-discard via a done callback. - self._background_tasks: set = set() + self._background_tasks: set[asyncio.Task[None]] = set() def _require_pc(self) -> RTCPeerConnection: """Return the live peer connection, or raise if there isn't one yet.""" @@ -112,7 +114,7 @@ def _require_pc(self) -> RTCPeerConnection: raise RuntimeError("viewer has no peer connection; connect first") return pc - def _spawn_bg(self, coro) -> "asyncio.Task": + def _spawn_bg(self, coro: Coroutine[Any, Any, None]) -> "asyncio.Task[None]": task = asyncio.ensure_future(coro) self._background_tasks.add(task) task.add_done_callback(self._background_tasks.discard) @@ -175,7 +177,7 @@ def disable_mic_send(self) -> None: def mic_active(self) -> bool: return self._mic_sender is not None and self._mic_sender.is_running() - def send_file(self, local_path, remote_name: Optional[str] = None, + def send_file(self, local_path: str | os.PathLike[str], remote_name: Optional[str] = None, on_progress: Optional[Callable[[int, int], None]] = None, *, cancelled: Optional[Callable[[], bool]] = None, require_commit: bool = False) -> None: """Stream to the host inbox, optionally requiring its matching atomic-publication receipt.""" @@ -189,7 +191,7 @@ def send_file(self, local_path, remote_name: Optional[str] = None, require_commit=require_commit, ) - def set_file_received_callback(self, callback) -> None: + def set_file_received_callback(self, callback: Optional[Callable[[Path], None]]) -> None: """Register ``cb(path)`` for files the host pushes to the viewer.""" self._file_callbacks.on_file = callback @@ -197,11 +199,11 @@ def set_file_receipt_callback(self, callback: Optional[ReceiptCallback]) -> None """Register an inert local publication-receipt listener; None clears it.""" self._file_callbacks.on_receipt = callback - def set_inbox_listing_callback(self, callback) -> None: + def set_inbox_listing_callback(self, callback: Optional[InboxListingCallback]) -> None: """Register ``cb(files: list[dict])`` for list_inbox responses.""" self._on_inbox_listing = callback - def set_inbox_op_result_callback(self, callback) -> None: + def set_inbox_op_result_callback(self, callback: Optional[InboxOpResultCallback]) -> None: """Register ``cb(name: str, ok: bool, error: Optional[str])``.""" self._on_inbox_op_result = callback @@ -272,7 +274,7 @@ def _inplace_detach_track(self, *, kind: str) -> None: if peer is not None and track is not None: get_bridge().call_soon(lambda: self._detach_media_track(peer, attr, track)) - def _detach_media_track(self, peer: RTCPeerConnection, attr: str, track) -> None: + def _detach_media_track(self, peer: RTCPeerConnection, attr: str, track: Stoppable) -> None: label = "screen track" if attr == "_viewer_screen_track" else "opus mic track" with self._media_owners.operation_lock(label): if not self._current_media_peer(peer) or getattr(self, attr) is not track: @@ -291,7 +293,7 @@ def _detach_media_track(self, peer: RTCPeerConnection, attr: str, track) -> None setattr(self, attr, None) @staticmethod - def _detach_sender(peer, kind: str, track) -> list[BaseException]: + def _detach_sender(peer: RTCPeerConnection, kind: str, track: object) -> list[BaseException]: for transceiver in peer.getTransceivers(): if transceiver.kind == kind and transceiver.sender.track is track: try: @@ -304,7 +306,7 @@ def _detach_sender(peer, kind: str, track) -> list[BaseException]: def _async_handle_renegotiate(self, offer_sdp: str) -> Coroutine[Any, Any, None]: return self._handle_renegotiate(self._pc, offer_sdp) - async def _handle_renegotiate(self, peer, offer_sdp: str) -> None: + async def _handle_renegotiate(self, peer: Optional[RTCPeerConnection], offer_sdp: str) -> None: """Apply the offer only to its original peer generation.""" if self._pc is not peer: return @@ -333,7 +335,7 @@ async def _handle_renegotiate(self, peer, offer_sdp: str) -> None: }) autocontrol_logger.info("webrtc viewer: sent renegotiate answer") - def _wire_files_channel(self, channel) -> None: + def _wire_files_channel(self, channel: Any) -> None: from je_auto_control.utils.remote_desktop.webrtc_files import FileTransferReceiver close_file_receiver(self._files_receiver, self._files_channel) receiver = self._files_receiver = FileTransferReceiver() @@ -346,7 +348,7 @@ def active() -> bool: bind_file_receiver(channel, receiver, active, self._on_viewer_file_done, received=self._file_callbacks.received) - def _wire_usb_channel(self, channel) -> None: + def _wire_usb_channel(self, channel: Any) -> None: """Attach a USB passthrough client to the ``usb`` DataChannel. Exposed via :meth:`usb_client` so the GUI can drive @@ -355,11 +357,11 @@ def _wire_usb_channel(self, channel) -> None: from je_auto_control.utils.usb.passthrough import UsbChannelClient self._usb_client = UsbChannelClient(channel) - def usb_client(self): + def usb_client(self) -> Optional[UsbChannelClient]: """Return the live USB passthrough client, or None if not wired.""" return self._usb_client - def _on_viewer_file_done(self, path) -> None: + def _on_viewer_file_done(self, path: Path) -> None: self._file_callbacks.published(path) def stop(self) -> None: @@ -527,7 +529,7 @@ async def _on_state() -> None: autocontrol_logger.warning("state cb: %r", error) @pc.on("track") - def _on_track(track) -> None: + def _on_track(track: Any) -> None: if self._pc is not pc or self._closed.is_set(): return autocontrol_logger.info("webrtc viewer: got %s track", track.kind) @@ -539,12 +541,12 @@ def _on_track(track) -> None: self._start_host_voice_play(track) @pc.on("datachannel") - def _on_datachannel(channel) -> None: + def _on_datachannel(channel: Any) -> None: if self._pc is not pc or self._closed.is_set(): return self._attach_datachannel(channel) - def _attach_datachannel(self, channel) -> None: + def _attach_datachannel(self, channel: Any) -> None: """Route an inbound data channel to its handler by label.""" autocontrol_logger.info( "webrtc viewer: data channel %r open", channel.label, @@ -563,13 +565,13 @@ def _attach_datachannel(self, channel) -> None: self._control_channel = channel self._wire_control_channel(channel) - def _wire_control_channel(self, channel) -> None: + def _wire_control_channel(self, channel: Any) -> None: @channel.on("open") def _on_open() -> None: self._send_auth() @channel.on("message") - def _on_message(message) -> None: + def _on_message(message: Any) -> None: if self._control_channel is channel: self._handle_ctrl_message(message) @@ -584,7 +586,7 @@ def _on_close() -> None: if getattr(channel, "readyState", "") == "open": self._send_auth() - def _start_host_voice_play(self, track) -> None: + def _start_host_voice_play(self, track: Any) -> None: from je_auto_control.utils.remote_desktop.webrtc_audio import ( OpusMicReceiver, ) @@ -598,7 +600,7 @@ def _start_host_voice_play(self, track) -> None: self._media_owners.activate("host voice", lambda: receiver.consume(track), receiver) autocontrol_logger.info("webrtc viewer: playing host voice") - async def _consume_video(self, track) -> None: + async def _consume_video(self, track: Any) -> None: # CancelledError is intentionally not caught — it must propagate # so the awaiter knows the consumer ended via cancellation # rather than a stream error (S7497). @@ -641,6 +643,8 @@ def _handle_ctrl_message(self, message: Any) -> None: if not isinstance(data, dict): return msg_type = data.get("type") + if not isinstance(msg_type, str): # {"type": []} raised TypeError in the lookup below + return handler = self._ctrl_dispatch.get(msg_type) if handler is not None: handler(data) @@ -648,7 +652,7 @@ def _handle_ctrl_message(self, message: Any) -> None: self._handle_inbox_op_result(data) @property - def _ctrl_dispatch(self) -> dict: + def _ctrl_dispatch(self) -> dict[str, Callable[[dict[str, Any]], None]]: return { "auth_ok": self._handle_auth_ok, "auth_fail": self._handle_auth_fail, @@ -658,7 +662,7 @@ def _ctrl_dispatch(self) -> dict: "renegotiate_offer": self._handle_renegotiate_offer, } - def _handle_auth_ok(self, data: dict) -> None: + def _handle_auth_ok(self, data: dict[str, Any]) -> None: self._authenticated = True self._read_only = bool(data.get("read_only", False)) fingerprint = data.get("fingerprint") @@ -671,19 +675,19 @@ def _handle_auth_ok(self, data: dict) -> None: autocontrol_logger.debug("fingerprint cb: %r", error) self._fire_auth_result(True) - def _handle_auth_fail(self, _data: dict) -> None: + def _handle_auth_fail(self, _data: dict[str, Any]) -> None: self._authenticated = False self._fire_auth_result(False) - def _handle_read_only_msg(self, data: dict) -> None: + def _handle_read_only_msg(self, data: dict[str, Any]) -> None: self._read_only = bool(data.get("value", False)) - def _handle_permissions_msg(self, data: dict) -> None: + def _handle_permissions_msg(self, data: dict[str, Any]) -> None: value = data.get("value") if isinstance(value, dict): self._read_only = not bool(value.get("allow_input", True)) - def _handle_list_inbox_response(self, data: dict) -> None: + def _handle_list_inbox_response(self, data: dict[str, Any]) -> None: if self._on_inbox_listing is None: return files = data.get("files") or [] @@ -692,12 +696,12 @@ def _handle_list_inbox_response(self, data: dict) -> None: except (RuntimeError, OSError) as error: autocontrol_logger.debug("inbox listing cb: %r", error) - def _handle_renegotiate_offer(self, data: dict) -> None: + def _handle_renegotiate_offer(self, data: dict[str, Any]) -> None: sdp = data.get("sdp") if isinstance(sdp, str) and self._pc is not None: self._spawn_bg(self._async_handle_renegotiate(sdp)) - def _handle_inbox_op_result(self, data: dict) -> None: + def _handle_inbox_op_result(self, data: dict[str, Any]) -> None: if self._on_inbox_op_result is None: return try: diff --git a/pyproject.toml b/pyproject.toml index 228406413..dbedd602c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -442,45 +442,7 @@ module = [ "je_auto_control.gui.rbac_users_panel", "je_auto_control.gui.recording_editor_tab", "je_auto_control.gui.remote_desktop", - "je_auto_control.gui.remote_desktop._connect_task", - "je_auto_control.gui.remote_desktop._helpers", - "je_auto_control.gui.remote_desktop._host_ops", - "je_auto_control.gui.remote_desktop._webrtc_types", - "je_auto_control.gui.remote_desktop.advanced_group", - "je_auto_control.gui.remote_desktop.annotation_overlay", - "je_auto_control.gui.remote_desktop.blanking_overlay", - "je_auto_control.gui.remote_desktop.connection_recent", - "je_auto_control.gui.remote_desktop.connection_screen", - "je_auto_control.gui.remote_desktop.folder_sync_controls", - "je_auto_control.gui.remote_desktop.folder_sync_io", - "je_auto_control.gui.remote_desktop.frame_display", - "je_auto_control.gui.remote_desktop.host_panel", - "je_auto_control.gui.remote_desktop.remote_screen_window", - "je_auto_control.gui.remote_desktop.sparkline", - "je_auto_control.gui.remote_desktop.tab", - "je_auto_control.gui.remote_desktop.tray_icon", - "je_auto_control.gui.remote_desktop.trusted_group", - "je_auto_control.gui.remote_desktop.view_approvals", - "je_auto_control.gui.remote_desktop.view_frames", - "je_auto_control.gui.remote_desktop.view_lifetime", - "je_auto_control.gui.remote_desktop.view_upload", - "je_auto_control.gui.remote_desktop.viewer_panel", - "je_auto_control.gui.remote_desktop.viewer_screen_window", - "je_auto_control.gui.remote_desktop.webrtc_host_connection", - "je_auto_control.gui.remote_desktop.webrtc_host_media", - "je_auto_control.gui.remote_desktop.webrtc_host_sessions", - "je_auto_control.gui.remote_desktop.webrtc_host_trust", - "je_auto_control.gui.remote_desktop.webrtc_host_ui", - "je_auto_control.gui.remote_desktop.webrtc_known_hosts", - "je_auto_control.gui.remote_desktop.webrtc_panel", - "je_auto_control.gui.remote_desktop.webrtc_panel_common", - "je_auto_control.gui.remote_desktop.webrtc_panel_state", - "je_auto_control.gui.remote_desktop.webrtc_viewer_address_book", - "je_auto_control.gui.remote_desktop.webrtc_viewer_connection", - "je_auto_control.gui.remote_desktop.webrtc_viewer_files", - "je_auto_control.gui.remote_desktop.webrtc_viewer_media", - "je_auto_control.gui.remote_desktop.webrtc_viewer_ui", - "je_auto_control.gui.remote_desktop.webrtc_workers", + "je_auto_control.gui.remote_desktop.*", "je_auto_control.gui.remote_desktop_tab", "je_auto_control.gui.rest_api_tab", "je_auto_control.gui.run_history_tab", @@ -554,15 +516,7 @@ module = [ "je_auto_control.utils.ab_locator.*", "je_auto_control.utils.accessibility", "je_auto_control.utils.accessibility.backends", - "je_auto_control.utils.accessibility.backends.base", - "je_auto_control.utils.accessibility.backends.linux_backend", - "je_auto_control.utils.accessibility.backends.macos_backend", - "je_auto_control.utils.accessibility.backends.null_backend", - "je_auto_control.utils.accessibility.backends.windows_automation", - "je_auto_control.utils.accessibility.backends.windows_events", - "je_auto_control.utils.accessibility.backends.windows_query", - "je_auto_control.utils.accessibility.backends.windows_reads", - "je_auto_control.utils.accessibility.backends.windows_state", + "je_auto_control.utils.accessibility.backends.*", "je_auto_control.utils.accessibility.element", "je_auto_control.utils.accessibility.recorder", "je_auto_control.utils.accessibility.tree", @@ -594,179 +548,7 @@ module = [ "je_auto_control.utils.agent_replay", "je_auto_control.utils.agent_replay.*", "je_auto_control.utils.agent_runtime", - "je_auto_control.utils.agent_runtime.__main__", - "je_auto_control.utils.agent_runtime.activity", - "je_auto_control.utils.agent_runtime.activity_windows", - "je_auto_control.utils.agent_runtime.android_action_result", - "je_auto_control.utils.agent_runtime.android_adapter", - "je_auto_control.utils.agent_runtime.android_commands", - "je_auto_control.utils.agent_runtime.android_control", - "je_auto_control.utils.agent_runtime.android_geometry", - "je_auto_control.utils.agent_runtime.android_hierarchy", - "je_auto_control.utils.agent_runtime.android_input_evidence", - "je_auto_control.utils.agent_runtime.android_input_windows", - "je_auto_control.utils.agent_runtime.android_scope", - "je_auto_control.utils.agent_runtime.android_session", - "je_auto_control.utils.agent_runtime.android_transport", - "je_auto_control.utils.agent_runtime.api", - "je_auto_control.utils.agent_runtime.browser_commands", - "je_auto_control.utils.agent_runtime.browser_environment", - "je_auto_control.utils.agent_runtime.browser_readonly_scope", - "je_auto_control.utils.agent_runtime.browser_retirement", - "je_auto_control.utils.agent_runtime.browser_target", - "je_auto_control.utils.agent_runtime.browser_transfers", - "je_auto_control.utils.agent_runtime.browser_validation", - "je_auto_control.utils.agent_runtime.browser_verification", - "je_auto_control.utils.agent_runtime.browser_workflows", - "je_auto_control.utils.agent_runtime.budget_clock", - "je_auto_control.utils.agent_runtime.cli", - "je_auto_control.utils.agent_runtime.client", - "je_auto_control.utils.agent_runtime.commands", - "je_auto_control.utils.agent_runtime.completion_contract", - "je_auto_control.utils.agent_runtime.context", - "je_auto_control.utils.agent_runtime.control_admission", - "je_auto_control.utils.agent_runtime.dag_admission", - "je_auto_control.utils.agent_runtime.dag_batch_recording", - "je_auto_control.utils.agent_runtime.dag_continuation_evidence", - "je_auto_control.utils.agent_runtime.dag_continuation_plan", - "je_auto_control.utils.agent_runtime.dag_jobs", - "je_auto_control.utils.agent_runtime.dag_local", - "je_auto_control.utils.agent_runtime.dag_retention", - "je_auto_control.utils.agent_runtime.dag_service_client", - "je_auto_control.utils.agent_runtime.dag_transfer_checks", - "je_auto_control.utils.agent_runtime.dag_transfer_stop", - "je_auto_control.utils.agent_runtime.delegation", - "je_auto_control.utils.agent_runtime.dialog_scope", - "je_auto_control.utils.agent_runtime.document_launch", - "je_auto_control.utils.agent_runtime.errors", - "je_auto_control.utils.agent_runtime.evidence", - "je_auto_control.utils.agent_runtime.evidence_cache", - "je_auto_control.utils.agent_runtime.file_dialog_scope", - "je_auto_control.utils.agent_runtime.file_target", - "je_auto_control.utils.agent_runtime.handoff_records", - "je_auto_control.utils.agent_runtime.helper_environment", - "je_auto_control.utils.agent_runtime.helper_owner_linux", - "je_auto_control.utils.agent_runtime.images", - "je_auto_control.utils.agent_runtime.input_journal", - "je_auto_control.utils.agent_runtime.input_ledger", - "je_auto_control.utils.agent_runtime.jobs", - "je_auto_control.utils.agent_runtime.local_evidence", - "je_auto_control.utils.agent_runtime.manifest_evidence", - "je_auto_control.utils.agent_runtime.model_tools", - "je_auto_control.utils.agent_runtime.models", - "je_auto_control.utils.agent_runtime.native_channel", - "je_auto_control.utils.agent_runtime.native_control", - "je_auto_control.utils.agent_runtime.native_job", - "je_auto_control.utils.agent_runtime.native_recovery", - "je_auto_control.utils.agent_runtime.native_scope", - "je_auto_control.utils.agent_runtime.native_target", - "je_auto_control.utils.agent_runtime.native_worker", - "je_auto_control.utils.agent_runtime.observation_refs", - "je_auto_control.utils.agent_runtime.ollama", - "je_auto_control.utils.agent_runtime.origin_policy", - "je_auto_control.utils.agent_runtime.owned_channel_factory", - "je_auto_control.utils.agent_runtime.owner_service_nested", - "je_auto_control.utils.agent_runtime.owner_service_wire", - "je_auto_control.utils.agent_runtime.ownership", - "je_auto_control.utils.agent_runtime.parent_watch", - "je_auto_control.utils.agent_runtime.path_identity", - "je_auto_control.utils.agent_runtime.policy", - "je_auto_control.utils.agent_runtime.presence_broker", - "je_auto_control.utils.agent_runtime.presence_channel_linux", - "je_auto_control.utils.agent_runtime.presence_endpoint_linux", - "je_auto_control.utils.agent_runtime.presence_frames", - "je_auto_control.utils.agent_runtime.presence_handshake", - "je_auto_control.utils.agent_runtime.presence_host", - "je_auto_control.utils.agent_runtime.presence_messages_linux", - "je_auto_control.utils.agent_runtime.presence_native_types", - "je_auto_control.utils.agent_runtime.presence_owner", - "je_auto_control.utils.agent_runtime.presence_peer_linux", - "je_auto_control.utils.agent_runtime.presence_pipe_linux", - "je_auto_control.utils.agent_runtime.presence_pipe_windows", - "je_auto_control.utils.agent_runtime.presence_platform", - "je_auto_control.utils.agent_runtime.presence_pool", - "je_auto_control.utils.agent_runtime.presence_protocol", - "je_auto_control.utils.agent_runtime.presence_quartz", - "je_auto_control.utils.agent_runtime.presence_reader", - "je_auto_control.utils.agent_runtime.presence_security_windows", - "je_auto_control.utils.agent_runtime.presence_server", - "je_auto_control.utils.agent_runtime.presence_session_windows", - "je_auto_control.utils.agent_runtime.presence_state", - "je_auto_control.utils.agent_runtime.presence_win32", - "je_auto_control.utils.agent_runtime.presence_windows", - "je_auto_control.utils.agent_runtime.presence_worker", - "je_auto_control.utils.agent_runtime.presence_x11", - "je_auto_control.utils.agent_runtime.readiness", - "je_auto_control.utils.agent_runtime.readonly_target", - "je_auto_control.utils.agent_runtime.readonly_worker", - "je_auto_control.utils.agent_runtime.receipts", - "je_auto_control.utils.agent_runtime.recovery_authorization", - "je_auto_control.utils.agent_runtime.remote_effect", - "je_auto_control.utils.agent_runtime.remote_journal", - "je_auto_control.utils.agent_runtime.remote_target", - "je_auto_control.utils.agent_runtime.remote_worker", - "je_auto_control.utils.agent_runtime.resume_gate", - "je_auto_control.utils.agent_runtime.retained_browser", - "je_auto_control.utils.agent_runtime.retained_browser_runtime", - "je_auto_control.utils.agent_runtime.retained_browser_target", - "je_auto_control.utils.agent_runtime.retention", - "je_auto_control.utils.agent_runtime.routes", - "je_auto_control.utils.agent_runtime.runner", - "je_auto_control.utils.agent_runtime.runtime", - "je_auto_control.utils.agent_runtime.runtime_lock", - "je_auto_control.utils.agent_runtime.service", - "je_auto_control.utils.agent_runtime.skill_completion", - "je_auto_control.utils.agent_runtime.skill_execution", - "je_auto_control.utils.agent_runtime.skill_parameters", - "je_auto_control.utils.agent_runtime.skill_reauthorization", - "je_auto_control.utils.agent_runtime.skill_recording", - "je_auto_control.utils.agent_runtime.store", - "je_auto_control.utils.agent_runtime.submission", - "je_auto_control.utils.agent_runtime.target_config", - "je_auto_control.utils.agent_runtime.target_continuity", - "je_auto_control.utils.agent_runtime.target_factory", - "je_auto_control.utils.agent_runtime.target_profiles", - "je_auto_control.utils.agent_runtime.targets", - "je_auto_control.utils.agent_runtime.task_handoff", - "je_auto_control.utils.agent_runtime.task_triggers", - "je_auto_control.utils.agent_runtime.transfer_adoption", - "je_auto_control.utils.agent_runtime.transfer_cache", - "je_auto_control.utils.agent_runtime.transfer_destination_scope", - "je_auto_control.utils.agent_runtime.transfer_evidence", - "je_auto_control.utils.agent_runtime.transfer_evidence_contract", - "je_auto_control.utils.agent_runtime.transfer_evidence_management", - "je_auto_control.utils.agent_runtime.transfer_files", - "je_auto_control.utils.agent_runtime.transfer_import", - "je_auto_control.utils.agent_runtime.transfer_import_contract", - "je_auto_control.utils.agent_runtime.transfer_import_files", - "je_auto_control.utils.agent_runtime.transfer_import_jobs", - "je_auto_control.utils.agent_runtime.transfer_import_ledger", - "je_auto_control.utils.agent_runtime.transfer_lineage", - "je_auto_control.utils.agent_runtime.transfer_management", - "je_auto_control.utils.agent_runtime.transfer_models", - "je_auto_control.utils.agent_runtime.transfer_operations", - "je_auto_control.utils.agent_runtime.transfer_privacy", - "je_auto_control.utils.agent_runtime.transfer_protocol", - "je_auto_control.utils.agent_runtime.transfer_records", - "je_auto_control.utils.agent_runtime.transfer_routing", - "je_auto_control.utils.agent_runtime.transfer_selection", - "je_auto_control.utils.agent_runtime.transfer_source", - "je_auto_control.utils.agent_runtime.transfer_staging", - "je_auto_control.utils.agent_runtime.transfer_transport", - "je_auto_control.utils.agent_runtime.transport", - "je_auto_control.utils.agent_runtime.trigger_config", - "je_auto_control.utils.agent_runtime.trigger_history", - "je_auto_control.utils.agent_runtime.trigger_reauthorization", - "je_auto_control.utils.agent_runtime.trigger_registration", - "je_auto_control.utils.agent_runtime.verification", - "je_auto_control.utils.agent_runtime.window_pixels", - "je_auto_control.utils.agent_runtime.wire_data", - "je_auto_control.utils.agent_runtime.workflow_desktop", - "je_auto_control.utils.agent_runtime.workflow_files", - "je_auto_control.utils.agent_runtime.workflow_specs", - "je_auto_control.utils.agent_runtime.workflow_values", - "je_auto_control.utils.agent_runtime.workflow_wait", - "je_auto_control.utils.agent_runtime.workspace_scope", + "je_auto_control.utils.agent_runtime.*", "je_auto_control.utils.agent_trace", "je_auto_control.utils.agent_trace.*", "je_auto_control.utils.anchor_locator", @@ -923,15 +705,7 @@ module = [ "je_auto_control.utils.exception", "je_auto_control.utils.exception.*", "je_auto_control.utils.executor", - "je_auto_control.utils.executor.action_redaction", - "je_auto_control.utils.executor.action_schema", - "je_auto_control.utils.executor.dispatch", - "je_auto_control.utils.executor.flags", - "je_auto_control.utils.executor.flow_control", - "je_auto_control.utils.executor.flow_data_commands", - "je_auto_control.utils.executor.mouse_aliases", - "je_auto_control.utils.executor.result_hook", - "je_auto_control.utils.executor.run_control", + "je_auto_control.utils.executor.*", "je_auto_control.utils.expect_poll", "je_auto_control.utils.expect_poll.*", "je_auto_control.utils.failure_bundle", @@ -1028,7 +802,7 @@ module = [ "je_auto_control.utils.json_patch", "je_auto_control.utils.json_patch.*", "je_auto_control.utils.json_schema", - "je_auto_control.utils.json_schema.ecma_regex", + "je_auto_control.utils.json_schema.*", "je_auto_control.utils.json_store", "je_auto_control.utils.json_store.*", "je_auto_control.utils.jsonpath", @@ -1122,12 +896,15 @@ module = [ "je_auto_control.utils.mcp_server.tools._handlers_desktop_executor", "je_auto_control.utils.mcp_server.tools._handlers_input", "je_auto_control.utils.mcp_server.tools._handlers_journal", + "je_auto_control.utils.mcp_server.tools._handlers_locators", "je_auto_control.utils.mcp_server.tools._handlers_mobile_executor", + "je_auto_control.utils.mcp_server.tools._handlers_operations", "je_auto_control.utils.mcp_server.tools._handlers_qa", "je_auto_control.utils.mcp_server.tools._handlers_remote", "je_auto_control.utils.mcp_server.tools._handlers_runs", "je_auto_control.utils.mcp_server.tools._handlers_scheduling", "je_auto_control.utils.mcp_server.tools._handlers_screen", + "je_auto_control.utils.mcp_server.tools._handlers_system", "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", "je_auto_control.utils.mcp_server.tools._healing_evaluation", "je_auto_control.utils.mcp_server.tools._healing_run", @@ -1291,6 +1068,7 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_file_tasks", "je_auto_control.utils.remote_desktop.webrtc_file_write", "je_auto_control.utils.remote_desktop.webrtc_files", + "je_auto_control.utils.remote_desktop.webrtc_host", "je_auto_control.utils.remote_desktop.webrtc_host_auth", "je_auto_control.utils.remote_desktop.webrtc_host_media", "je_auto_control.utils.remote_desktop.webrtc_inspector", @@ -1300,6 +1078,7 @@ module = [ "je_auto_control.utils.remote_desktop.webrtc_retirement", "je_auto_control.utils.remote_desktop.webrtc_stats", "je_auto_control.utils.remote_desktop.webrtc_transport", + "je_auto_control.utils.remote_desktop.webrtc_viewer", "je_auto_control.utils.remote_desktop.ws_host", "je_auto_control.utils.remote_desktop.ws_protocol", "je_auto_control.utils.remote_desktop.ws_viewer", diff --git a/test/unit_test/headless/test_webrtc_ctrl_message_type.py b/test/unit_test/headless/test_webrtc_ctrl_message_type.py new file mode 100644 index 000000000..06f8ab17e --- /dev/null +++ b/test/unit_test/headless/test_webrtc_ctrl_message_type.py @@ -0,0 +1,51 @@ +"""A control message whose ``type`` is not a string is ignored, on the host and the viewer. + +``{"type": []}`` reached a dict lookup and raised ``TypeError: unhashable type`` +from inside the data channel's message callback. +""" +import json +import threading + +import pytest + +pytest.importorskip("aiortc") + +from je_auto_control.utils.remote_desktop.webrtc_host import WebRTCDesktopHost # noqa: E402 +from je_auto_control.utils.remote_desktop.webrtc_viewer import WebRTCDesktopViewer # noqa: E402 + +_ODD_TYPES = ([], {}, 7, None) + + +def _bare(cls: type, **attributes: object) -> object: + """The class without its constructor: only what ``_handle_ctrl_message`` reads.""" + instance = object.__new__(cls) + instance._closed = threading.Event() + for name, value in attributes.items(): + setattr(instance, name, value) + return instance + + +@pytest.mark.parametrize("odd", _ODD_TYPES) +def test_the_host_ignores_a_non_string_type(odd): + host = _bare(WebRTCDesktopHost, _authenticated=True) + host._handle_ctrl_message(json.dumps({"type": odd})) + + +@pytest.mark.parametrize("odd", _ODD_TYPES) +def test_the_host_ignores_a_non_string_type_before_auth(odd): + host = _bare(WebRTCDesktopHost, _authenticated=False) + host._handle_ctrl_message(json.dumps({"type": odd})) + + +@pytest.mark.parametrize("odd", _ODD_TYPES) +def test_the_viewer_ignores_a_non_string_type(odd): + viewer = _bare(WebRTCDesktopViewer) + viewer._handle_ctrl_message(json.dumps({"type": odd})) + + +def test_a_string_type_still_reaches_its_handler(): + seen = [] + viewer = _bare(WebRTCDesktopViewer) + viewer._handle_read_only_msg = seen.append + viewer._handle_ctrl_message(json.dumps({"type": "read_only", "value": True})) + assert seen == [{"type": "read_only", "value": True}] diff --git a/test/verify/typing_not_yet_strict.txt b/test/verify/typing_not_yet_strict.txt index f69a6fc7f..bff8b19a1 100644 --- a/test/verify/typing_not_yet_strict.txt +++ b/test/verify/typing_not_yet_strict.txt @@ -5,11 +5,3 @@ # (which may not grow). Each is debt, not an exemption: this list may only # shrink. Move a module into the strict block once mypy passes it there, and # delete its line. -je_auto_control.utils.agent_runtime.completion_recovery -je_auto_control.utils.agent_runtime.dag_batches -je_auto_control.utils.agent_runtime.dag_continuation -je_auto_control.utils.agent_runtime.evidence_handoff -je_auto_control.utils.agent_runtime.task_authority -je_auto_control.utils.agent_runtime.task_recovery -je_auto_control.utils.agent_runtime.task_skills -je_auto_control.utils.agent_runtime.transfer_host diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 8e86d671e..15d462df7 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -14,23 +14,14 @@ # written later under the same name is new and therefore strict. # je_auto_control.android.client -je_auto_control.gui.remote_desktop.webrtc_dialogs je_auto_control.gui.vlm_tab je_auto_control.ios.client je_auto_control.linux_wayland.libei je_auto_control.utils.accessibility.accessibility_api -je_auto_control.utils.accessibility.backends.windows_backend je_auto_control.utils.actionability.actionability -je_auto_control.utils.executor.action_executor -je_auto_control.utils.json_schema.json_schema je_auto_control.utils.logging.logging_instance je_auto_control.utils.mcp_server.tools._handlers -je_auto_control.utils.mcp_server.tools._handlers_locators -je_auto_control.utils.mcp_server.tools._handlers_operations -je_auto_control.utils.mcp_server.tools._handlers_system je_auto_control.utils.remote_desktop.hw_codec -je_auto_control.utils.remote_desktop.webrtc_host -je_auto_control.utils.remote_desktop.webrtc_viewer je_auto_control.utils.table_grid_fill.table_grid_fill je_auto_control.utils.tool_use_schema.schema je_auto_control.utils.vision.backends.anthropic_backend From 8ecac7cc780cbb180ef06fa33039a7444e3eb1ab Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 16:32:51 +0800 Subject: [PATCH 132/161] Serve dashboard assets from a table so the request path never picks a file SonarCloud flagged the dashboard route as reflected XSS through file content: the request path still chose which file to open, even though the checks kept it inside dashboard/. The shipped assets are now read once into a name lookup, and responses carry nosniff. --- CHANGELOG.md | 5 ++ architecture_explore.md | 14 +++--- docs/updates/2026-11-b.md | 7 +++ docs/updates/README.md | 1 + je_auto_control/utils/rest_api/rest_server.py | 48 +++++++++++-------- test/unit_test/headless/test_dashboard.py | 16 +++++++ 6 files changed, 63 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a0e97199..2cda9445e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- REST dashboard: `/dashboard/*` and `/docs` now serve only the `.html`, `.css`, `.js`, `.svg` and + `.png` files shipped in `utils/rest_api/dashboard/`, read once on first request, and send + `X-Content-Type-Options: nosniff`. A file of another type in that directory is no longer served + as `application/octet-stream` (none ships), and editing an asset needs a restart to show. + - Remote desktop: a WebRTC control message whose `type` is not a string (`{"type": []}`) is ignored by the host and the viewer; it raised `TypeError: unhashable type` from the data channel's message callback. diff --git a/architecture_explore.md b/architecture_explore.md index a72909fbd..46818b8fd 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 238,044 | +| 程式碼總行數 | 238,050 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,585 行。 +> 24 個套件、約 7,591 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -584,7 +584,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/otp/` | 37 | TOTP 一次性密碼產生(自動化 2FA 登入) | | `utils/outbox/` | 107 | 交易式 outbox,保證至少一次的事件投遞 | | `utils/pytest_plugin/` | 283 | pytest 外掛 + BDD step library(`pytest11` entry point) | -| `utils/rest_api/` | 2,228 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | +| `utils/rest_api/` | 2,234 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | | `utils/socket_server/` | 164 | 執行 action JSON 的執行緒式 TCP 指令伺服器(預設綁 127.0.0.1) | | `utils/sse_client/` | 142 | Server-Sent Events 用戶端解析 | | `utils/tls_acme/` | 475 | TLS 自動化:HTTP-01 挑戰伺服器、金鑰/CSR、自動續期 | @@ -906,11 +906,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `usbip/libusb_backend.py` | 224 | 以 PyUSB/libusb 執行 URB 的正式後端。 | | `usbip/backend.py` | 87 | 可插拔 URB 執行後端。 | -#### `utils/rest_api/`(2,228 行) +#### `utils/rest_api/`(2,234 行) | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `rest_server.py` | 713 | HTTP 前端主體;相容 check-only gate,RBAC 必須帶使用者身分。 | +| `rest_server.py` | 719 | HTTP 前端主體;相容 check-only gate,RBAC 必須帶使用者身分。 | | `rest_handlers.py` | 539 | 端點實作。 | | `rest_openapi.py` | 503 | 走訪路由表產生 OpenAPI 3.1 規格。 | | `rest_auth.py` | 227 | Bearer token 驗證 + 逐 client 限流閘門。 | @@ -1558,7 +1558,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/accessibility/` | 16 | 3,378 | | `wrapper/` | 25 | 6,053 | | `windows/` | 24 | 2,363 | -| `utils/rest_api/` | 8 | 2,228 | +| `utils/rest_api/` | 8 | 2,234 | | `utils/agent/` | 13 | 2,254 | | `linux_with_x11/` | 19 | 1,382 | | `linux_wayland/` | 24 | 4,448 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,714 | -| **總計** | **1,533** | **237,299** | +| **總計** | **1,533** | **237,305** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 53bc2b429..809f43d7d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -753,3 +753,10 @@ - **Tests:** mypy with both flags: 57 errors in 14 files on each of win32 / linux / darwin, from 781 in 31 -- the 14 are exactly the modules `Progress.md` › H lists, and no file gained an error. `typing_contract_verify.py` and `--extras`: 0 failing; `test_typing_modernization_contract.py` 14 passed; ruff clean; the facade stays Qt-free; the agent's 36 related test files 1,044 passed, 2 skipped; new `test_webrtc_ctrl_message_type.py` (4 of 13 fail on the old code, 13 pass) with the WebRTC file-transfer, annotation-screen and retirement tests 147 passed; `test_adapter_registry_sweep.py` 1,911 passed, 6 skipped; doc, file-length and complexity gates passed. - **Files:** 18 modules under `je_auto_control/`, the new test, `pyproject.toml`, the two `test/verify` lists, `architecture_explore.md` (line counts), `CHANGELOG.md`, `Progress.md`. - **Open items:** `Progress.md` › H (14 modules that need a code change, not an annotation). + +## U-20261115-15 · 2026-11-15 · Dashboard assets served from a table, not a request-chosen path · #done #security #rest-api + +- **What:** SonarCloud's quality gate on PR #552 failed with E security rating on new code: one BLOCKER, `pythonsecurity:S5131` (reflected XSS via file content) at `rest_server.py` `_serve_dashboard()`. The taint flow ran from the request path through `_load_dashboard_asset()` to `target.read_bytes()` and back into `wfile.write()`. It was not exploitable (a name regex, `resolve()` + `relative_to()` and a suffix allowlist kept the read inside `dashboard/`), but the request path still chose which file to open. +- **Change:** `_dashboard_assets()` reads every file in `dashboard/` with a known type once (`lru_cache`) into name → (body, MIME type); `_load_dashboard_asset()` only looks the requested name up, so traversal, hidden files, sub-directories and `.py` files are names missing from the table. Dashboard responses add `X-Content-Type-Options: nosniff`. The name regex and the `re` import are gone. +- **Tests:** `test_dashboard.py` gains two (the table is exactly the shipped assets; `nosniff` is sent); with the REST OpenAPI and route-sweep tests, the typing contract, complexity and broad-except gates: 217 passed. +- **Files:** `utils/rest_api/rest_server.py`, `test_dashboard.py`, `architecture_explore.md` (re-measured), `CHANGELOG.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 8f72e58cc..5565b057f 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-15 | 2026-11-15 | Dashboard assets served from a table, not a request-chosen path | #done #security #rest-api | [2026-11-b](2026-11-b.md) | | U-20261115-14 | 2026-11-15 | The 18 largest modules typed; a non-string WebRTC control type is ignored | #done #typing #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261115-13 | 2026-11-15 | Dev CI red on ac_wait_for_pixel after get_pixel was annotated | #incident #mcp #typing | [2026-11-b](2026-11-b.md) | | U-20261115-12 | 2026-11-15 | 25 more modules join the strict typing tier (11 to 20 fixes each) | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/rest_api/rest_server.py b/je_auto_control/utils/rest_api/rest_server.py index a6b0cd3cd..78c0c9207 100644 --- a/je_auto_control/utils/rest_api/rest_server.py +++ b/je_auto_control/utils/rest_api/rest_server.py @@ -9,8 +9,8 @@ """ from __future__ import annotations +import functools import json -import re import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -156,6 +156,7 @@ def _serve_dashboard(self, path: str) -> None: body, content_type, status = _load_dashboard_asset(asset) self.send_response(status) self.send_header("Content-Type", content_type) + self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Content-Length", str(len(body))) # Static assets — safe to cache briefly inside the same session. self.send_header("Cache-Control", "private, max-age=60") @@ -513,30 +514,35 @@ def _count_scheduler_jobs() -> int: } _TEXT_PLAIN_UTF8 = "text/plain; charset=utf-8" _NOT_FOUND_BODY = b"not found" -# Conservative whitelist — alphanumerics, dot, dash, underscore. No path -# separators, no parent traversal, no leading dots. ``\w`` would also -# match (it's [A-Za-z0-9_]), but the explicit class makes the intent -# more legible at the cost of a tiny S6353 noise we accept. -_DASHBOARD_ASSET_RE = re.compile(r"^\w[\w.-]*$") + + +@functools.lru_cache(maxsize=1) +def _dashboard_assets() -> Dict[str, Tuple[bytes, str]]: + """Every file shipped in ``dashboard/`` with a known type, read once: name -> (body, MIME type). + + A request only ever looks a name up here, so the path it carries never + chooses a file to open: traversal, hidden files, sub-directories and + Python source are simply names that are not in the table. + """ + assets: Dict[str, Tuple[bytes, str]] = {} + if not _DASHBOARD_DIR.is_dir(): + return assets + for entry in sorted(_DASHBOARD_DIR.iterdir()): + mime = _DASHBOARD_MIME.get(entry.suffix.lower()) + if mime is None or entry.name.startswith(".") or not entry.is_file(): + continue + try: + assets[entry.name] = (entry.read_bytes(), mime) + except OSError as error: + autocontrol_logger.warning("dashboard asset read %s: %r", entry.name, error) + return assets def _load_dashboard_asset(asset: str) -> Tuple[bytes, str, int]: - if not _DASHBOARD_ASSET_RE.match(asset): + found = _dashboard_assets().get(asset) + if found is None: return _NOT_FOUND_BODY, _TEXT_PLAIN_UTF8, 404 - target = (_DASHBOARD_DIR / asset).resolve() - try: - target.relative_to(_DASHBOARD_DIR) - except ValueError: - return _NOT_FOUND_BODY, _TEXT_PLAIN_UTF8, 404 - if not target.is_file(): - return _NOT_FOUND_BODY, _TEXT_PLAIN_UTF8, 404 - suffix = target.suffix.lower() - mime = _DASHBOARD_MIME.get(suffix, "application/octet-stream") - try: - body = target.read_bytes() - except OSError as error: - autocontrol_logger.warning("dashboard asset read %s: %r", asset, error) - return b"read error", _TEXT_PLAIN_UTF8, 500 + body, mime = found return body, mime, 200 diff --git a/test/unit_test/headless/test_dashboard.py b/test/unit_test/headless/test_dashboard.py index ab41fb850..b3357c4cf 100644 --- a/test/unit_test/headless/test_dashboard.py +++ b/test/unit_test/headless/test_dashboard.py @@ -72,3 +72,19 @@ def test_dashboard_does_not_leak_python_source(server): with pytest.raises(urllib.error.HTTPError) as exc_info: _get(server, "/dashboard/rest_server.py") assert exc_info.value.code == 404 + + +def test_only_the_shipped_assets_are_servable(): + """A request looks a name up in a table built from ``dashboard/``; it never opens a path it names.""" + from je_auto_control.utils.rest_api.rest_server import _DASHBOARD_DIR, _dashboard_assets + shipped = {p.name for p in _DASHBOARD_DIR.iterdir() + if p.is_file() and p.suffix in {".html", ".css", ".js"}} + assert set(_dashboard_assets()) == shipped + assert {"index.html", "swagger.html", "app.css", "app.js"} <= shipped + + +def test_assets_are_served_with_nosniff(server): + host, port = server.address + with urllib.request.urlopen(f"{_TEST_SCHEME}://{host}:{port}/dashboard/app.js", # nosec B310 # reason: localhost test server + timeout=3) as response: + assert response.headers.get("X-Content-Type-Options") == "nosniff" From ab5cc5b780773db5f69d359007dcd6bb38c66097 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 17:03:05 +0800 Subject: [PATCH 133/161] Hold the whole package to the strict typing tier The last 14 modules each needed a code change, not an annotation, and two of those changes fix real faults: the WebRTC hardware encoder divided by PyAV's bit rate, which is None when unset, and the MCP tween_drag handler passed any-length points into the path maths. MouseKeycode is now the platform's own button type, which showed that macOS button codes are strings although the macOS backend declared int. --- CHANGELOG.md | 10 + Progress.md | 2 +- architecture_explore.md | 72 +- docs/updates/2026-11-b.md | 8 + docs/updates/README.md | 1 + je_auto_control/actions.pyi | 1138 ++++++++--------- je_auto_control/android/client.py | 10 +- je_auto_control/gui/vlm_tab.py | 18 +- je_auto_control/ios/client.py | 10 +- je_auto_control/linux_wayland/libei.py | 4 +- je_auto_control/linux_wayland/oeffis.py | 11 +- je_auto_control/osx/mouse/osx_mouse.py | 14 +- .../utils/accessibility/accessibility_api.py | 10 +- .../utils/actionability/actionability.py | 12 +- .../utils/executor/action_executor.py | 4 +- .../utils/executor/mouse_aliases.py | 5 +- .../utils/logging/logging_instance.py | 7 +- .../utils/mcp_server/tools/_factories.py | 4 +- .../utils/mcp_server/tools/_handlers.py | 14 +- .../utils/remote_desktop/hw_codec.py | 13 +- .../utils/table_grid_fill/table_grid_fill.py | 8 +- .../utils/tool_use_schema/schema.py | 9 +- .../vision/backends/anthropic_backend.py | 8 +- .../utils/vision/backends/openai_backend.py | 8 +- je_auto_control/wrapper/auto_control_mouse.py | 20 +- je_auto_control/wrapper/backend_contract.py | 27 +- je_auto_control/wrapper/platform_wrapper.py | 19 +- pyproject.toml | 943 +------------- .../headless/test_parsers_and_codecs_audit.py | 12 + .../headless/test_tween_drag_batch.py | 10 + test/verify/typing_strict_baseline.txt | 14 - 31 files changed, 783 insertions(+), 1662 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cda9445e..c15b7fcb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## [Unreleased] +- Typing: the whole package is held to the strict mypy tier. `MouseKeycode` is now the platform's + own button type (a tuple of three Win32 flags on Windows, a string such as `"Left"` on macOS, an + int on X11 and Wayland) instead of `Any`. The macOS backend's `press_mouse` / `release_mouse` / + `click_mouse` and `DarwinMouseBackend` now declare `mouse_button: str`, what they always compared + against; `Executor.execute_one` accepts any `Mapping` again, as the dispatcher behind it does. +- `ac_tween_drag`: `start` and `end` must be two-value arrays (schema `minItems`/`maxItems` 2); the + handler raises `ValueError` naming the argument instead of failing inside the path maths. +- WebRTC hardware codec: an encoder whose PyAV `bit_rate` is unset (None or 0) is reopened at the + target rate instead of raising `TypeError` / `ZeroDivisionError` on the next frame. + - REST dashboard: `/dashboard/*` and `/docs` now serve only the `.html`, `.css`, `.js`, `.svg` and `.png` files shipped in `utils/rest_api/dashboard/`, read once on first request, and send `X-Content-Type-Options: nosniff`. A file of another type in that directory is no longer served diff --git a/Progress.md b/Progress.md index b4ad60963..9c787aa09 100644 --- a/Progress.md +++ b/Progress.md @@ -526,7 +526,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev D2 仍缺原生半開交握資源回收與合成器釋放證據;D3 的錄製/全域停止/Windows 原生崩潰證據仍缺,詳見計畫與下方生命週期待辦。 計畫 E 已有裝置 context、輸入/畫面、應用生命週期與共用命令入口; 仍缺真實 SDK 契約核對、iOS 擴充 adapter 與裝置驗收,不能以 fake backend 測試結案。 -H 已有三平台型別 gate 與真實相依型別檢查;嚴格型別層收進所有補註記就能通過的模組(U-20261115-05~14,共 1,511 個;`typing_not_yet_strict.txt` 已清空)。仍缺:`test/verify/typing_strict_baseline.txt` 剩 14 個,每個都要改程式碼而不只是補註記——`android/client.py`、`ios/client.py` 與兩個 vision backend(`except (OSError, *_sdk_errors())` 的星號展開,mypy 只接受 `tuple[Any, ...]`,改成 `(OSError, ...) + _sdk_errors()` 才能精確)、`linux_wayland/libei.py`(`oeffis.connect_eis_fd` 的回傳型別)、`utils/logging/logging_instance.py`(`FileHandler._open` 與 `open()` 的 `IO[Any]`)、`utils/accessibility/accessibility_api.py`(`tuple(el.bounds)` 不是 4-tuple)、`utils/actionability/actionability.py`(`visible` 不收窄 `bbox`)、`utils/table_grid_fill/table_grid_fill.py`(`None in (...)` 不收窄)、`utils/tool_use_schema/schema.py`(`Mapping` 傳給宣告 `dict` 的 `execute_one`)、`utils/remote_desktop/hw_codec.py`(PyAV 的 `bit_rate` 可能是 None,真的可能除以 None)、`gui/vlm_tab.py`(`_show_outcome(value: object)` 傳給要 `Optional[Tuple[int, int]]` 的 `_show_located`)、`utils/mcp_server/tools/_handlers.py` 的 `tween_drag`(`tuple(start)` 不是 `Tuple[int, int]`)、`wrapper/backend_contract.py` 的 `MouseKeycode = Any`(依平台寫成 tuple/int 會露出 `platform_wrapper` 各分支匯入的 `mouse_keys_table` 型別不同,其中一個是 `dict[str, str]`,要先重整 wrapper 層);以及完整範例/文件與最終固定來源總驗收。 +H 已有三平台型別 gate 與真實相依型別檢查;整個套件(1,525 個模組)都在嚴格型別層,`typing_strict_baseline.txt` 與 `typing_not_yet_strict.txt` 已清空(U-20261115-05~16)。仍缺:完整範例/文件與最終固定來源總驗收。 F 還缺: - **F2 GUI 重製(`WIP`,維護者 2026-11-14 決定:全面視覺改版;窄視窗時導覽與詳情改為浮層)**: diff --git a/architecture_explore.md b/architecture_explore.md index 46818b8fd..d9592659c 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 238,050 | +| 程式碼總行數 | 238,099 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -184,15 +184,15 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `wrapper/platform_wrapper.py` | 137 | **Strategy 樞紐**。依 `sys.platform` 匯入唯一後端並匯出 `keyboard`、`keyboard_check`、`keyboard_keys_table`、`mouse`、`mouse_keys_table`、`special_mouse_keys_table`、`screen`、`recorder`;八個名稱都帶著 `backend_contract` 的型別出去,其中 `keyboard`/`mouse` 因為四個分支綁的是三種互不相容的形狀,先落在私有的 `_keyboard`/`_mouse`(`Any`)上再標合約;載入失敗直接拋 `AutoControlException`(fail fast);X11 的 `keyboard_keys_table` 透過明確存取才取得真正 dict,其他後端保留原有表。 | -| `wrapper/backend_contract.py` | 249 | 平台縫的型別合約:`ScreenBackend`/`KeyboardCheckBackend`/`RecorderBackend` 三個跨平台 Protocol,加上 `keyboard`/`mouse` 各自的三份——`Win32*`(SendInput 與 Interception)、`Darwin*`(Quartz)、`X11Unix*`(XTest/uinput/Wayland/BSD),因為這兩個名稱的呼叫形狀真的因平台而異;`KeyboardBackend`/`MouseBackend` 依 `sys.platform` 別名到其中一組,所以呼叫端被檢查的是它真的會走到的簽章。四個 `_platform_*` 組裝模組各自標注自己綁的是什麼,少一個成員就在該後端自己的檔案裡紅掉,而不是在三層之上的呼叫點。 | +| `wrapper/platform_wrapper.py` | 138 | **Strategy 樞紐**。依 `sys.platform` 匯入唯一後端並匯出 `keyboard`、`keyboard_check`、`keyboard_keys_table`、`mouse`、`mouse_keys_table`、`special_mouse_keys_table`、`screen`、`recorder`;八個名稱都帶著 `backend_contract` 的型別出去,其中 `keyboard`/`mouse` 因為四個分支綁的是三種互不相容的形狀,先落在私有的 `_keyboard`/`_mouse`(`Any`)上再標合約;載入失敗直接拋 `AutoControlException`(fail fast);X11 的 `keyboard_keys_table` 透過明確存取才取得真正 dict,其他後端保留原有表。 | +| `wrapper/backend_contract.py` | 256 | 平台縫的型別合約:`ScreenBackend`/`KeyboardCheckBackend`/`RecorderBackend` 三個跨平台 Protocol,加上 `keyboard`/`mouse` 各自的三份——`Win32*`(SendInput 與 Interception)、`Darwin*`(Quartz)、`X11Unix*`(XTest/uinput/Wayland/BSD),因為這兩個名稱的呼叫形狀真的因平台而異;`KeyboardBackend`/`MouseBackend` 依 `sys.platform` 別名到其中一組,所以呼叫端被檢查的是它真的會走到的簽章。四個 `_platform_*` 組裝模組各自標注自己綁的是什麼,少一個成員就在該後端自己的檔案裡紅掉,而不是在三層之上的呼叫點。 | | `wrapper/capabilities.py` | 295 | 無副作用的 immutable context/input-capture metadata;不載入原生依賴或要求授權,XWayland 範圍明示。 | | `wrapper/_platform_windows.py` | 376 | Windows 後端組裝:Win32 ctypes 模組 + 虛擬鍵表(含 OEM 鍵與 `keyboard_key_aliases` 別名表)+ 選用 Interception 驅動。 | | `wrapper/_platform_osx.py` | 162 | macOS 後端組裝(Quartz 事件 + osx 虛擬鍵表)。 | | `wrapper/_platform_linux.py` | 155 | X11 後端組裝(python-Xlib + 選用 uinput)。鍵盤/滑鼠共用延後選擇的輸入後端;匯入不探測 uinput,鍵碼表只在明確存取時解析成共用 dict。 | | `wrapper/_platform_wayland.py` | 63 | Wayland 後端組裝(libei/ydotool/grim)。 | | `wrapper/_input_observer.py` | 30 | Optional context-local native input announcements; legacy callers remain unaffected. | -| `wrapper/auto_control_mouse.py` | 600 | 滑鼠 API:位置讀寫、按下/放開/點擊、捲動、座標前處理、送訊息給指定視窗。 | +| `wrapper/auto_control_mouse.py` | 604 | 滑鼠 API:位置讀寫、按下/放開/點擊、捲動、座標前處理、送訊息給指定視窗。 | | `wrapper/auto_control_keyboard.py` | 566 | 鍵盤 API:鍵表查詢、`keyboard_key_name` 反查標準鍵名(不回別名)、按下/放開/敲擊、`write` 字串、`hotkey` 組合鍵、按鍵狀態偵測。**`type_keyboard` 與 `hotkey` 的放開走 `finally`**(見下)。 | | `wrapper/auto_control_screen.py` | 111 | 螢幕 API:`screen_size`、`screenshot`(可指定區域)、`get_pixel`。 | | `wrapper/auto_control_image.py` | 89 | 影像 API:`locate_all_image`、`locate_image_center`、`locate_and_click`。 | @@ -248,7 +248,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `uinput/keyboard.py` | 44 | uinput 鍵盤後端,介面與 X11 版一致。 | | `uinput/mouse.py` | 130 | uinput 滑鼠後端。 | -#### Linux Wayland(`linux_wayland/`,24 檔/4,448 行) +#### Linux Wayland(`linux_wayland/`,24 檔/4,455 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -259,7 +259,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `_input_state.py` | 47 | 不含 Qt/原生載入的失敗中繼資料與有界 cause 分類;先保留取消,再阻止權限拒絕改走 CLI。 | | `_select_input.py` | 106 | 決定使用原生 libei 或 CLI shim;`active_backend()` 是 keyboard/mouse 的唯一入口,`emitted()` 僅容許未分類的選用後端缺席退回 CLI;明確原生選擇、權限/裝置/協定拒絕保持失敗。 | | `_layout.py` | 83 | 版面原點的共用查詢。擷取與輸入不是同一個座標空間,差的就是這個原點:libei 的 region offset 是 `uint32`(描述不了負原點),`ydotool mousemove --absolute` 的原點是合成器夾取的那個角落——兩條路都要減掉它,所以放在這裡而不是各自複製。讀數快取一秒——擷取那一側刻意不快取,但 ydotool 每次絕對移動都會問,不快取等於每次移動多開一個 `wlr-randr` 行程。 | -| `oeffis.py` | 223 | liboeffis 綁定:跑完 RemoteDesktop portal 交握,交出 EIS fd;請求後的拒絕/逾時/失敗保留明確狀態。 | +| `oeffis.py` | 230 | liboeffis 綁定:跑完 RemoteDesktop portal 交握,交出 EIS fd;請求後的拒絕/逾時/失敗保留明確狀態。 | | `libei.py` | 671 | libei 綁定、撤銷閂鎖與只快取中繼資料的失敗狀態;完整握手(seat 綁定能力 → 由事件取得 device → start_emulating → 每次發送後 frame)。公開預設存取轉交 ei_default;直接建構仍在程序內。另負責絕對指標的座標空間:讀回裝置的 region,把版面座標映射進去,沒有任何 region 涵蓋就以 failed 拒絕,停止隱含 CLI 備援與後續點擊(不撤銷 sender)。 快取觀測不讀事件,完整就緒涵蓋全部請求的事件種類。 | | `ei_protocol.py` | 116 | 有界事件批次與版本封包,嚴格驗證事件與數值。 | | `ei_worker.py` | 161 | 子程序原生 EI 擁有者;逐請求回覆與輸入清理。 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,570 行。 +> 25 個套件、約 19,571 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -304,7 +304,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,764 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,765 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | | `utils/input_macro/` | 481 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,866 行。 +> 15 個套件、約 4,867 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -336,7 +336,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/exception/` | 377 | **例外階層根**。框架錯誤繼承 `AutoControlException`;`control_signals.py` 共用無 executor 相依的取消載體/分類,保留 MCP 與 history 舊匯入別名;`cancellation.py` 提供 Qt-free 協作式 token 與 immutable progress;另有集中式錯誤訊息(`exception_tags`)。 | | `utils/failure_bundle/` | 229 | 可攜、已遮蔽的失敗診斷 ZIP(截圖 + 診斷 + log 尾段) | | `utils/file_process/` | 40 | 目錄檔案列舉(`execute_dir` 的後端) | -| `utils/logging/` | 358 | `autocontrol_logger`、共用 handler、executor/CLI/REST/MCP/背景 run 的 vault 值遮罩與持久化診斷快照 | +| `utils/logging/` | 359 | `autocontrol_logger`、共用 handler、executor/CLI/REST/MCP/背景 run 的 vault 值遮罩與持久化診斷快照 | | `utils/package_manager/` | 198 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | @@ -364,7 +364,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.4 輸入模擬與動作品質 -> 22 個套件、約 2,983 行。 +> 22 個套件、約 2,989 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -372,7 +372,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/act_modes/` | 69 | actionability 閘門之上的 trial/force 動作模式 | | `utils/action_effect/` | 109 | 判定一個動作是否真的產生效果,並歸因到目標區域 | | `utils/action_grounding/` | 83 | 動作前的接地守衛(邊界檢查 + 吸附到元素) | -| `utils/actionability/` | 194 | 動作前就緒閘門(可見 + 穩定 + 啟用 + 未被遮擋) | +| `utils/actionability/` | 198 | 動作前就緒閘門(可見 + 穩定 + 啟用 + 未被遮擋) | | `utils/ensure_state/` | 74 | 冪等地把控制項/設定帶到期望狀態 | | `utils/field_entry/` | 79 | 清空再輸入的欄位填寫慣用法(Playwright `fill`) | | `utils/gamepad/` | 335 | 虛擬遊戲手把後端(Windows ViGEmBus 驅動) | @@ -384,7 +384,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/mouse_relative/` | 59 | 相對位移滑鼠移動 | | `utils/postcondition/` | 157 | 宣告式的動作預期結果規格,對照畫面驗證 | | `utils/step_repair/` | 136 | 失敗/無效動作的修復策略(自我修正迴圈) | -| `utils/table_grid_fill/` | 187 | 以 OCR 文字填滿格線表格,取得可定址的表格 | +| `utils/table_grid_fill/` | 189 | 以 OCR 文字填滿格線表格,取得可定址的表格 | | `utils/input_reach/` | 111 | 送出去的輸入到不到得了:桌面鎖定查詢(免費)+ 實際送一個 F13 確認沒有被過濾(有副作用,只給診斷用) | | `utils/keyboard_layout/` | 182 | 向系統問「這個鍵盤配置下每個鍵印出什麼字」(`ToUnicodeEx`),問不到退回 US 對照表 | | `utils/text_unicode/` | 173 | 輸入任意 Unicode(emoji/CJK/重音字):優先送字元按鍵事件,不支援時退回剪貼簿貼上 | @@ -463,12 +463,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.7 無障礙樹與原生控制項 -> 16 個套件、約 4,929 行。 +> 16 個套件、約 4,935 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a11y_audit/` | 362 | 以無障礙樹 + OCR 進行無障礙與 i18n 稽核 | -| `utils/accessibility/` | 3,378 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | +| `utils/accessibility/` | 3,384 | 跨平台無障礙樹定位與錄製;Windows UIA/macOS AX/null 三後端。支援限定視窗(換搜尋起點,不是過濾)、逐節點可中斷走訪、`IUIAutomation2` 連線逾時、名稱子字串比對與排序、`control_get_state` 一次讀完值/勾選/選取/數值(密碼欄位不回內容) | | `utils/ax_events/` | 35 | 反應式 UIA 事件等待(focus-changed) | | `utils/ax_props/` | 44 | 讀取豐富 UIA 屬性(enabled/offscreen/help/status/快捷鍵) | | `utils/ax_text/` | 105 | 透過 UIA TextPattern 取得原生文字(讀取/尋找/選取/屬性) | @@ -516,7 +516,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 53,158 行。 +> 14 個套件、約 53,169 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -530,21 +530,21 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cua_action/` | 204 | 標準化 computer-use 動作結構(Anthropic/OpenAI → `AC_*`) | | `utils/llm/` | 369 | 自然語言 → action list 規劃器 + Anthropic/null 後端;規劃執行隔離頂層變數並沿用巢狀範圍 | | `utils/mcp_registry/` | 97 | MCP registry `server.json` 資訊清單產生(可被發現) | -| `utils/mcp_server/` | 22,314 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | -| `utils/tool_use_schema/` | 191 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | +| `utils/mcp_server/` | 22,322 | **無頭 MCP 伺服器**(預設註冊 820 個工具=801 個 `ac_*` + 19 個別名):stdio + HTTP 傳輸、工具工廠與處理器、資源、prompt、稽核、限流、外掛熱重載 | +| `utils/tool_use_schema/` | 194 | 把 `AC_*` 指令匯出成 Claude/OpenAI 的 tool-use schema | | `utils/trajectory_eval/` | 132 | agent 軌跡評估:依評分規準為一次執行打分 | | `utils/vision/` | 666 | VLM 元素定位器(依描述找元素)+ Anthropic/OpenAI/null 後端 | ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,263 行。 +> 6 個套件、約 32,266 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,935 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,938 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -744,7 +744,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | | `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,764 行)— 執行核心 +#### `utils/executor/`(10,765 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -753,15 +753,15 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `flow_data_commands.py` | 275 | `AC_*_to_var` 資料來源與轉換指令:shell、時鐘、亂數、PDF、TOTP、SQL、檔案、HTTP、OCR,加上 `AC_assert_var`/`AC_assert_db`/`AC_assert_duration`/`AC_transform_var`。都不執行巢狀 action list,所以沒有迴圈/分支語意。 | | `action_schema.py` | 225 | action list 的結構驗證:形狀、參數型別、未知指令拒絕。單一走訪同時支援兩種消費方式:`validate_actions()` 遇到第一個問題就拋、`unknown_command_names()` 收齊全部不認得的名字(REST `/execute` 用它回 400)。 | | `action_redaction.py` | 196 | 記錄與紀錄鍵用的遮蔽:`AC_secret_*` 的參數(金庫通行碼、機密值)在寫進 log、當成結果紀錄的鍵之前換成 `***`,巢狀在區塊指令裡的也一樣。 | -| `mouse_aliases.py` | 39 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | +| `mouse_aliases.py` | 40 | 單鍵點擊別名(`AC_click_left` 等),executor 與 callback executor 共用。 | | `flags.py` | 19 | 旗標讀取 `as_bool`:依拼法(`"true"`/`"yes"`/`"on"`/`"1"`)而非 Python 真值判斷,所以 JSON、CLI、MCP 傳來的 `"false"` 是關;所有 adapter 與流程指令共用。 | -#### `utils/mcp_server/`(22,314 行,820 個工具)— 最大子系統 +#### `utils/mcp_server/`(22,322 行,820 個工具)— 最大子系統 | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `tools/_factories.py` | 9,390 | 工具工廠:每個函式回傳一個領域的 `MCPTool` 清單(把 `AC_*` 能力包成 MCP 工具)。 | -| `tools/_handlers.py` | 566 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | +| `tools/_handlers.py` | 574 | 把 MCP 工具呼叫橋接到 AutoControl 無頭 API 的 adapter;主題模組拆完之後這裡留的是資料/文字/HTTP 那一類與 WebRunner 橋接。 | | `tools/_handlers_qa.py` | 619 | 同一種 adapter,QA 主題:斷言 DSL、資料驅動、SQL/PDF/郵件/HTTP 步驟、codegen、視覺回歸、狀態機、flaky 偵測與隔離、suite runner、無障礙稽核、裝置矩陣、媒體斷言。從 `_handlers.py` 依主題拆出的第一塊(750 行上限);兩者互不引用。 | | `tools/_handlers_input.py` | 221 | 同一種 adapter,輸入主題:滑鼠、鍵盤、虛擬手把(ViGEm)。 | | `tools/_handlers_screen.py` | 352 | 同一種 adapter,螢幕主題:擷取、像素、影像與文字搜尋、螢幕錄影。 | @@ -817,7 +817,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,935 行/77 檔) +#### `utils/remote_desktop/`(16,938 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -862,7 +862,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `lan_discovery.py` | 387 | mDNS/Zeroconf 區網探索。 | | `video_codec.py` | 197 | TCP/WS 路徑的可插拔視訊編解碼。 | | `webrtc_host_media.py` | 258 | 重新協商與 recvonly 軌管理。aiortc 沒有 `removeTransceiver`,所以開/關不對稱——開是加軌重新 offer,關只能設 inactive 並停掉 receiver。 | -| `hw_codec.py` | 204 | 硬體 H.264 編碼偵測與啟用。 | +| `hw_codec.py` | 207 | 硬體 H.264 編碼偵測與啟用。 | | `webrtc_stats.py` | 226 | 以單一 future 擁有 aiortc 統計輪詢;啟停不等待網路,停止後拒絕晚到樣本並釋放回呼。 | | `connect_coordinator.py` | 158 | 由使用者輸入的目標決定該用哪條傳輸。 | | `adaptive_bitrate.py` | 151 | 依統計調整主機擷取 FPS。 | @@ -1362,7 +1362,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | recording_editor | `recording_editor_tab.py` | 255 | 裁切、過濾、重新縮放錄製內容;Actions 提供背景日誌候選審閱。 | | variables | `variables_tab.py` | 170 | 檢視、灌入、清除 executor 執行期作用域。 | | secrets | `secrets_tab.py` | 190 | 解鎖保險庫並管理 `${secrets.NAME}`。 | -| vlm | `vlm_tab.py` | 150 | 用文字描述 UI 元素,交由模型定位。 | +| vlm | `vlm_tab.py` | 152 | 用文字描述 UI 元素,交由模型定位。 | | self_healing | `self_healing_tab.py`、`healing_evaluation_panel.py`、`healing_evaluation_worker.py`、`template_candidate_panel.py`、`template_candidate_worker.py` | 952 | 執行時定位/記錄、固定影像版本比較、原始步驟與候選樣板生命週期;背景工作可取消並丟棄過期結果。 | | ocr_reader | `ocr_tab.py` | 193 | 傾印區域文字或以 regex 搜尋。 | | accessibility | `accessibility_tab.py` | 193 | 瀏覽 OS UI 樹並依 role/name 點擊。 | @@ -1549,19 +1549,19 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,932 | -| `utils/mcp_server/` | 63 | 22,314 | -| `utils/remote_desktop/` | 77 | 16,935 | -| `utils/executor/` | 11 | 10,764 | +| `gui/` | 166 | 43,934 | +| `utils/mcp_server/` | 63 | 22,322 | +| `utils/remote_desktop/` | 77 | 16,938 | +| `utils/executor/` | 11 | 10,765 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | -| `utils/accessibility/` | 16 | 3,378 | -| `wrapper/` | 25 | 6,053 | +| `utils/accessibility/` | 16 | 3,384 | +| `wrapper/` | 25 | 6,065 | | `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,234 | | `utils/agent/` | 13 | 2,254 | | `linux_with_x11/` | 19 | 1,382 | -| `linux_wayland/` | 24 | 4,448 | +| `linux_wayland/` | 24 | 4,455 | | `utils/triggers/` | 4 | 1,409 | | `utils/ocr/` | 10 | 1,393 | | `utils/usbip/` | 5 | 1,008 | @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,714 | -| **總計** | **1,533** | **237,305** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,724 | +| **總計** | **1,533** | **237,354** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 809f43d7d..39f0250dd 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -760,3 +760,11 @@ - **Change:** `_dashboard_assets()` reads every file in `dashboard/` with a known type once (`lru_cache`) into name → (body, MIME type); `_load_dashboard_asset()` only looks the requested name up, so traversal, hidden files, sub-directories and `.py` files are names missing from the table. Dashboard responses add `X-Content-Type-Options: nosniff`. The name regex and the `re` import are gone. - **Tests:** `test_dashboard.py` gains two (the table is exactly the shipped assets; `nosniff` is sent); with the REST OpenAPI and route-sweep tests, the typing contract, complexity and broad-except gates: 217 passed. - **Files:** `utils/rest_api/rest_server.py`, `test_dashboard.py`, `architecture_explore.md` (re-measured), `CHANGELOG.md`. + +## U-20261115-16 · 2026-11-15 · The last 14 modules join the strict tier: the whole package is strict · #done #typing + +- **What:** `Progress.md` › H listed 14 modules left in `typing_strict_baseline.txt`, each needing a code change rather than an annotation. All 14 are now strict, so the strict override names the package itself (`je_auto_control`, `je_auto_control.*`, `je_auto_control_pytest`: 3 patterns instead of 944), 1,525 modules, and both shrink-only lists are empty. +- **Code changes:** the Android and iOS clients and both vision backends build their `except` tuple by concatenation (`(OSError, RuntimeError, ValueError) + _sdk_errors()`), which mypy reads, where a starred call inside a literal was rejected; `_sdk_errors()` returns `Tuple[Type[BaseException], ...]`. `oeffis` gains a `PortalSession` protocol (`close()`), the return type of `connect_eis_fd` and the type of `LibeiBackend._session`. `accessibility_api` keeps a node's bounds a 4-tuple; `actionability` checks `bbox is not None` where `visible` already implied it; `table_grid_fill` checks each index `is None` instead of `None in (...)`. The log handler's `/dev/null` fallback opens with a literal `"a"`, so `_open` returns the `TextIOWrapper` the base class declares. `vlm_tab` turns the task result into a bool or a point before showing it. `Executor.execute_one` takes a `Mapping` again (an earlier stage had narrowed it to `Dict`; the dispatcher behind it takes `Mapping`). +- **Found:** `hw_codec._shape_changed` divided by PyAV's `bit_rate`, which is `None` (or 0) when unset: the next frame raised `TypeError` / `ZeroDivisionError`; an unset rate now counts as changed, so the encoder is reopened at the target rate, and the comparison multiplies instead of dividing. The MCP `tween_drag` handler passed `tuple(start)` on, so a three-value point failed inside the path maths; `_xy()` raises `ValueError` naming the argument, and the `ac_tween_drag` schema says `minItems`/`maxItems` 2. `MouseKeycode` was `Any` and its comment said macOS used ints: macOS button codes are strings (`"Left"`), and the macOS backend and `DarwinMouseBackend` declared `mouse_button: int` while comparing against them. `MouseKeycode` is now spelt per platform with literal `sys.platform` checks (the only form mypy narrows; `platform_id` stays the run-time decision); `platform_wrapper` takes each backend's table as `Any` and gives it the contract on the way out, as it already did for `keyboard` and `mouse`; `mouse_preprocess` and the `AC_mouse_*` aliases carry the type. The generated `actions.pyi` was stale (bare `dict`/`list` from before the sources were typed) and fell under the strict tier with the package; it is regenerated (876 signatures). +- **Tests:** two new: an unset encoder bit rate reopens (`test_parsers_and_codecs_audit.py`; fails on the old division), and the MCP handler's two-coordinate check (`test_tween_drag_batch.py`). The tests for every changed module, the MCP adapter sweep, the stub generator, the typing contract and the complexity and broad-except gates: 2,333 passed, 25 skipped. `typing_contract_verify.py` with and without `--extras`: 0 modules failing on win32, linux and darwin. +- **Files:** the 14 modules, `linux_wayland/oeffis.py`, `osx/mouse/osx_mouse.py`, `wrapper/{platform_wrapper,auto_control_mouse}.py`, `utils/executor/{action_executor,mouse_aliases}.py`, `utils/mcp_server/tools/_factories.py`, `actions.pyi`, `pyproject.toml`, both typing lists, the two tests, `architecture_explore.md` (re-measured), `CHANGELOG.md`, `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 5565b057f..e9e1d8ad4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-16 | 2026-11-15 | The last 14 modules join the strict tier: the whole package is strict | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-15 | 2026-11-15 | Dashboard assets served from a table, not a request-chosen path | #done #security #rest-api | [2026-11-b](2026-11-b.md) | | U-20261115-14 | 2026-11-15 | The 18 largest modules typed; a non-string WebRTC control type is ignored | #done #typing #remote-desktop | [2026-11-b](2026-11-b.md) | | U-20261115-13 | 2026-11-15 | Dev CI red on ac_wait_for_pixel after get_pixel was annotated | #incident #mcp #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/actions.pyi b/je_auto_control/actions.pyi index bacab8c78..ef9c8207a 100644 --- a/je_auto_control/actions.pyi +++ b/je_auto_control/actions.pyi @@ -8,52 +8,52 @@ from typing import ( ) def AC_a11y_click( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - window_title: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + window_title: str | None = ..., contains: bool = ..., ) -> bool: """Click the center of the first element matching the filters.""" -def AC_a11y_dump(app_name: Optional[str] = ..., max_results: int = ...) -> Dict[str, Any]: +def AC_a11y_dump(app_name: str | None = ..., max_results: int = ...) -> Dict[str, Any]: """Executor adapter: dump the accessibility tree as nested dict.""" def AC_a11y_find( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - window_title: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + window_title: str | None = ..., contains: Any = ..., -) -> Optional[dict]: +) -> Dict[str, Any] | None: """Executor adapter: find an accessibility element, return its dict.""" def AC_a11y_find_all( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - window_title: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + window_title: str | None = ..., contains: Any = ..., max_results: int = ..., scan_limit: int = ..., -) -> List[dict]: +) -> List[Dict[str, Any]]: """Executor adapter: every matching accessibility element, best match first.""" -def AC_a11y_focused(app_name: Optional[str] = ...) -> Optional[dict]: +def AC_a11y_focused(app_name: str | None = ...) -> Dict[str, Any] | None: """Executor adapter: the element holding keyboard focus, as a dict.""" def AC_a11y_list( - app_name: Optional[str] = ..., + app_name: str | None = ..., max_results: int = ..., - window_title: Optional[str] = ..., -) -> List[dict]: + window_title: str | None = ..., +) -> List[Dict[str, Any]]: """Executor adapter: list accessibility elements as plain dicts.""" def AC_a11y_record_events() -> List[Dict[str, Any]]: """Executor adapter: peek at events without stopping the recorder.""" def AC_a11y_record_start( - app_name: Optional[str] = ..., + app_name: str | None = ..., poll_interval_s: float = ..., min_movement_px: int = ..., ) -> Dict[str, Any]: @@ -110,22 +110,22 @@ def AC_add_package_to_callback_executor(package: str) -> None: def AC_add_package_to_executor(package: str) -> None: """將套件成員加入 Executor""" -def AC_admin_add_host(label: str, base_url: str, token: str, tags: Optional[List[str]] = ...) -> Dict[str, Any]: +def AC_admin_add_host(label: str, base_url: str, token: str, tags: List[str] | None = ...) -> Dict[str, Any]: """Executor adapter: register a remote AutoControl REST endpoint.""" -def AC_admin_broadcast_execute(actions: List[Any], labels: Optional[List[str]] = ...) -> List[Dict[str, Any]]: +def AC_admin_broadcast_execute(actions: List[Any], labels: List[str] | None = ...) -> List[Dict[str, Any]]: ... def AC_admin_list_hosts() -> List[Dict[str, Any]]: ... -def AC_admin_poll(labels: Optional[List[str]] = ...) -> List[Dict[str, Any]]: +def AC_admin_poll(labels: List[str] | None = ...) -> List[Dict[str, Any]]: ... def AC_admin_remove_host(label: str) -> Dict[str, Any]: ... -def AC_agent_card(path: Optional[str] = ...) -> Dict[str, Any]: +def AC_agent_card(path: str | None = ...) -> Dict[str, Any]: """Adapter: build (or write) the A2A agent card.""" def AC_agent_dag(operation: str, request: Mapping[str, Any] | None = ...) -> dict[str, Any]: @@ -248,41 +248,41 @@ def AC_anchor_locate_all( """Executor adapter: every anchor-relative match, nearest-first.""" def AC_android_alert_accept( - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Accept the alert or system dialog showing.""" def AC_android_alert_dismiss( - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Dismiss the alert or system dialog showing.""" def AC_android_app_state( app_id: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """not_installed, not_running, background or foreground.""" def AC_android_click_element( - text: Optional[str] = ..., - resource_id: Optional[str] = ..., - description: Optional[str] = ..., - class_name: Optional[str] = ..., + text: str | None = ..., + resource_id: str | None = ..., + description: str | None = ..., + class_name: str | None = ..., timeout_s: float = ..., - serial: Optional[str] = ..., + serial: str | None = ..., ) -> Dict[str, int]: """Tap the first widget matching the selectors; return click centre.""" def AC_android_device_info( - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Backend, versions and capabilities of the device. Sends no input.""" @@ -293,32 +293,32 @@ def AC_android_drag( y2: int, hold_s: float = ..., duration_s: float = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Press, hold so the item lifts, and move it.""" -def AC_android_dump_hierarchy(serial: Optional[str] = ...) -> str: +def AC_android_dump_hierarchy(serial: str | None = ...) -> str: """Return the device's widget tree as an XML string.""" def AC_android_find_by_description( description: str, - model: Optional[str] = ..., + model: str | None = ..., tap: bool = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Ask a vision-language model where something is on the device screen.""" def AC_android_find_element( - text: Optional[str] = ..., - resource_id: Optional[str] = ..., - description: Optional[str] = ..., - class_name: Optional[str] = ..., + text: str | None = ..., + resource_id: str | None = ..., + description: str | None = ..., + class_name: str | None = ..., timeout_s: float = ..., - serial: Optional[str] = ..., + serial: str | None = ..., ) -> Dict[str, int]: """Find an Android widget via uiautomator2; return its bounding rect.""" @@ -326,9 +326,9 @@ def AC_android_find_image( template_path: str, detect_threshold: float = ..., tap: bool = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Template-match in the device screen; answers in device points.""" @@ -337,48 +337,49 @@ def AC_android_find_text( lang: str = ..., min_confidence: float = ..., tap: bool = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """OCR the device screen for text; answers in device points.""" def AC_android_get_clipboard( - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + allow_app_switch: bool = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Read the device clipboard's text.""" def AC_android_install_app( path: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Install an app package from the host.""" -def AC_android_key(key: str, serial: Optional[str] = ..., adb_path: Optional[str] = ...) -> None: +def AC_android_key(key: str, serial: str | None = ..., adb_path: str | None = ...) -> None: """Send a keycode (``KEYCODE_HOME`` etc.) via ``input keyevent``.""" def AC_android_launch_app( app_id: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Launch an app; returns its state.""" -def AC_android_list_devices(adb_path: Optional[str] = ...) -> list: +def AC_android_list_devices(adb_path: str | None = ...) -> List[Dict[str, Any]]: """Return ``{serial, state, model, …}`` for every adb-attached device.""" def AC_android_long_press( x: int, y: int, duration_s: float = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Press and hold at a point.""" @@ -388,86 +389,86 @@ def AC_android_pinch( scale: float, duration_s: float = ..., span: int = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Two-finger pinch: scale above 1 zooms in, below 1 out.""" def AC_android_pull_file( remote_path: str, local_path: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Copy a device file to the host.""" def AC_android_push_file( local_path: str, remote_path: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Copy a host file to the device.""" def AC_android_screen_info( - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Pixel size, point size, scale and orientation of the current screen.""" -def AC_android_screenshot(file_path: str, serial: Optional[str] = ..., adb_path: Optional[str] = ...) -> str: +def AC_android_screenshot(file_path: str, serial: str | None = ..., adb_path: str | None = ...) -> str: """Capture the live Android screen and save it as PNG at ``file_path``.""" def AC_android_self_heal( - template_path: Optional[str] = ..., - description: Optional[str] = ..., + template_path: str | None = ..., + description: str | None = ..., detect_threshold: float = ..., - model: Optional[str] = ..., + model: str | None = ..., tap: bool = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Template first, VLM on a miss, against the device screen.""" def AC_android_set_clipboard( text: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Put text on the device clipboard.""" -def AC_android_shell(command: str, serial: Optional[str] = ..., adb_path: Optional[str] = ...) -> str: +def AC_android_shell(command: str, serial: str | None = ..., adb_path: str | None = ...) -> str: """Run an ``adb shell`` command and return its stdout.""" def AC_android_start_recording( - remote_path: Optional[str] = ..., - time_limit_s: Optional[int] = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + remote_path: str | None = ..., + time_limit_s: int | None = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Start recording the device screen.""" def AC_android_stop_app( app_id: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Stop an app; returns its state.""" def AC_android_stop_recording( local_path: str, - remote_path: Optional[str] = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + remote_path: str | None = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Stop recording and save the video on the host.""" @@ -477,22 +478,22 @@ def AC_android_swipe( x2: int, y2: int, duration_ms: int = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., + serial: str | None = ..., + adb_path: str | None = ..., ) -> None: """Send a touch swipe via ``input swipe``.""" -def AC_android_tap(x: int, y: int, serial: Optional[str] = ..., adb_path: Optional[str] = ...) -> None: +def AC_android_tap(x: int, y: int, serial: str | None = ..., adb_path: str | None = ...) -> None: """Send a single ``input tap`` to an Android device.""" -def AC_android_text(text: str, serial: Optional[str] = ..., adb_path: Optional[str] = ...) -> None: +def AC_android_text(text: str, serial: str | None = ..., adb_path: str | None = ...) -> None: """Type a string: ``input text`` for ASCII, a Unicode-capable path otherwise.""" def AC_android_type_text( text: str, - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Type text through a path that can carry it; raises when none can.""" @@ -500,17 +501,13 @@ def AC_android_wait_for_app( app_id: str, timeout_s: float = ..., state: str = ..., - serial: Optional[str] = ..., - adb_path: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + serial: str | None = ..., + adb_path: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Wait until an app reaches a state; raises on timeout.""" -def AC_annotate_screenshot( - source: str, - annotations: Union[List[Dict[str, Any]], str], - output_path: str, -) -> Dict[str, Any]: +def AC_annotate_screenshot(source: str, annotations: List[Dict[str, Any]] | str, output_path: str) -> Dict[str, Any]: """Executor adapter: draw annotations onto a screenshot and save it.""" def AC_apply_json_patch(doc: Any, patch: Any) -> Dict[str, Any]: @@ -522,16 +519,16 @@ def AC_apply_unified(text: str, diff: str) -> Dict[str, Any]: def AC_apply_vex(findings: Any, vex: Any) -> Dict[str, Any]: """Adapter: suppress VEX'd vulnerability findings (each JSON string/obj).""" -def AC_approval_approve(token: str, approver: str, db: Optional[str] = ...) -> Dict[str, Any]: +def AC_approval_approve(token: str, approver: str, db: str | None = ...) -> Dict[str, Any]: """Adapter: approve a request as ``approver`` (must differ from maker).""" -def AC_approval_reject(token: str, approver: str, db: Optional[str] = ...) -> Dict[str, Any]: +def AC_approval_reject(token: str, approver: str, db: str | None = ...) -> Dict[str, Any]: """Adapter: reject a request as ``approver`` (must differ from maker).""" -def AC_approval_request(action: str, requester: str = ..., db: Optional[str] = ...) -> Dict[str, Any]: +def AC_approval_request(action: str, requester: str = ..., db: str | None = ...) -> Dict[str, Any]: """Adapter: file a maker-checker approval request; return its token.""" -def AC_approval_status(token: str, db: Optional[str] = ...) -> Dict[str, Any]: +def AC_approval_status(token: str, db: str | None = ...) -> Dict[str, Any]: """Adapter: report the status and approved flag of a request token.""" def AC_approve_artifact(name: str, approvals_dir: str = ..., extension: str = ...) -> Dict[str, Any]: @@ -580,9 +577,9 @@ def AC_assert_eventually( def AC_assert_file( path: str, exists: bool = ..., - contains: Optional[str] = ..., - sha256: Optional[str] = ..., - min_size: Optional[int] = ..., + contains: str | None = ..., + sha256: str | None = ..., + min_size: int | None = ..., raise_on_fail: bool = ..., ) -> Dict[str, Any]: """Executor adapter: assert a file's existence / content / hash / size.""" @@ -590,7 +587,7 @@ def AC_assert_file( def AC_assert_http( url: str, status: int = ..., - contains: Optional[str] = ..., + contains: str | None = ..., timeout: float = ..., method: str = ..., raise_on_fail: bool = ..., @@ -640,7 +637,7 @@ def AC_assert_session_active() -> Dict[str, Any]: def AC_assert_text( text: str, - region: Optional[List[int]] = ..., + region: List[int] | None = ..., lang: str = ..., regex: bool = ..., present: bool = ..., @@ -654,20 +651,20 @@ def AC_assert_text( def AC_assert_video_changes( video_path: str, start_s: float = ..., - end_s: Optional[float] = ..., + end_s: float | None = ..., threshold: float = ..., expect_motion: bool = ..., - region: Optional[List[int]] = ..., + region: List[int] | None = ..., raise_on_fail: bool = ..., ) -> Dict[str, Any]: """Executor adapter: assert a video segment has motion / is static.""" def AC_assert_visual( golden_path: str, - region: Optional[List[int]] = ..., + region: List[int] | None = ..., tolerance: float = ..., per_pixel_threshold: int = ..., - diff_path: Optional[str] = ..., + diff_path: str | None = ..., create_if_missing: bool = ..., raise_on_fail: bool = ..., ) -> Dict[str, Any]: @@ -676,8 +673,8 @@ def AC_assert_visual( def AC_assert_vlm( description: str, present: bool = ..., - screen_region: Optional[List[int]] = ..., - model: Optional[str] = ..., + screen_region: List[int] | None = ..., + model: str | None = ..., raise_on_fail: bool = ..., capture_on_fail: bool = ..., ) -> Dict[str, Any]: @@ -699,9 +696,9 @@ def AC_associate_fields(text_boxes: Any, directions: Any = ..., max_gap: Any = . """Adapter: pair form labels with their nearest aligned value boxes.""" def AC_audit_accessibility( - app_name: Optional[str] = ..., - contrast_pairs: Optional[List[Dict[str, Any]]] = ..., - texts: Optional[List[str]] = ..., + app_name: str | None = ..., + contrast_pairs: List[Dict[str, Any]] | None = ..., + texts: List[str] | None = ..., min_ratio: float = ..., max_results: int = ..., ) -> Dict[str, Any]: @@ -710,15 +707,15 @@ def AC_audit_accessibility( def AC_audit_contrast(foreground: List[int], background: List[int], min_ratio: float = ...) -> Dict[str, Any]: """Executor adapter: WCAG contrast ratio for one colour pair.""" -def AC_audit_focus_order(app_name: Optional[str] = ..., max_results: int = ...) -> Dict[str, Any]: +def AC_audit_focus_order(app_name: str | None = ..., max_results: int = ...) -> Dict[str, Any]: """Executor adapter: WCAG focus-order audit over the app's elements.""" def AC_audit_log_clear() -> Dict[str, Any]: ... def AC_audit_log_list( - event_type: Optional[str] = ..., - host_id: Optional[str] = ..., + event_type: str | None = ..., + host_id: str | None = ..., limit: int = ..., ) -> List[Dict[str, Any]]: """Executor adapter: query the audit log.""" @@ -753,7 +750,7 @@ def AC_browser_check(selector: str, frame: str = ...) -> bool: def AC_browser_click(selector: str, frame: str = ...) -> bool: """Click one unique visible enabled element once, without retrying submissions.""" -def AC_browser_download(url: str, directory: str, name: str, sha256: str = ...) -> dict: +def AC_browser_download(url: str, directory: str, name: str, sha256: str = ...) -> dict[str, Any]: """Download through WebRunner and publish a complete file within explicit task roots.""" def AC_browser_fill(selector: str, value: str, frame: str = ...) -> bool: @@ -771,7 +768,7 @@ def AC_browser_read(operation: str, selector: str, frame: str = ...) -> Any: def AC_browser_select(selector: str, value: str, frame: str = ...) -> bool: """Select one option through the owned WebRunner session.""" -def AC_browser_upload(selector: str, path: str, sha256: str = ..., frame: str = ...) -> dict: +def AC_browser_upload(selector: str, path: str, sha256: str = ..., frame: str = ...) -> dict[str, Any]: """Send one rooted bounded file as immutable bytes; never submit the form automatically.""" def AC_browser_wait( @@ -831,10 +828,10 @@ def AC_categorical_drift(reference: Any, current: Any) -> Dict[str, Any]: def AC_cell_by_header( row: Any, column_header: str, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read the cell at (row, named column) — assert by header.""" @@ -858,8 +855,8 @@ def AC_changed_regions( def AC_chatops_dispatch( message: str, - context: Optional[Dict[str, Any]] = ..., - script_root: Optional[str] = ..., + context: Dict[str, Any] | None = ..., + script_root: str | None = ..., ) -> Dict[str, Any]: """Executor adapter: route one chat message through the default router.""" @@ -875,16 +872,16 @@ def AC_check_compatibility(old: Any, new: Any, mode: str = ...) -> Dict[str, Any def AC_check_foreign_key(child_rows: Any, child_col: str, parent_rows: Any, parent_col: str) -> Dict[str, Any]: """Adapter: foreign-key referential check across two row-sets.""" -def AC_check_key_is_press(keycode: int | str) -> Optional[bool]: +def AC_check_key_is_press(keycode: int | str) -> bool | None: """檢查某個鍵是否正在被按下""" def AC_check_licenses(components: Any, allow: Any = ..., deny: Any = ...) -> Dict[str, Any]: """Adapter: evaluate SBOM component licenses against allow/deny lists.""" def AC_check_overflow( - elements: Optional[List[Any]] = ..., + elements: List[Any] | None = ..., avg_char_px: float = ..., - app_name: Optional[str] = ..., + app_name: str | None = ..., ) -> Dict[str, Any]: """Adapter: flag text wider than its widget (live a11y unless given).""" @@ -939,14 +936,14 @@ def AC_click_mouse( y: int | None = ..., clicks: int = ..., interval: float = ..., -) -> Tuple[Any, int, int]: +) -> Tuple[Tuple[int, int, int], int, int]: """在指定座標按下並放開滑鼠按鍵;``clicks=2`` 就是雙擊""" def AC_click_text( target: str, mouse_keycode: int | str = ..., lang: str = ..., - region: Optional[Sequence[int]] = ..., + region: Sequence[int] | None = ..., min_confidence: float = ..., case_sensitive: bool = ..., backend: Any = ..., @@ -993,10 +990,10 @@ def AC_cofailure_pairs(runs: Any, threshold: Any = ...) -> Dict[str, Any]: """Adapter: test pairs that fail together above a Jaccard threshold.""" def AC_collapse_control( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: collapse a tree node / combobox (ExpandCollapsePattern).""" @@ -1024,16 +1021,16 @@ def AC_compare_field_value(expected: Any, actual: Any, mode: Any = ...) -> Dict[ def AC_compliance_report( evidence: Any, frameworks: Any = ..., - path: Optional[str] = ..., + path: str | None = ..., fmt: str = ..., ) -> Dict[str, Any]: """Adapter: map governance evidence to SOC2/ISO controls; optionally write.""" def AC_computer_use( goal: str, - display_width_px: Optional[int] = ..., - display_height_px: Optional[int] = ..., - display_number: Optional[int] = ..., + display_width_px: int | None = ..., + display_height_px: int | None = ..., + display_number: int | None = ..., max_steps: int = ..., wall_seconds: float = ..., model: str = ..., @@ -1047,18 +1044,18 @@ def AC_config_causal_commit( bucket: dict[str, object], actor: dict[str, object], operation_id: str, - options: Optional[dict[str, object]] = ..., + options: dict[str, object] | None = ..., *, - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: ... def AC_config_causal_fetch( endpoint: str, user_id: str, - options: Optional[dict[str, object]] = ..., + options: dict[str, object] | None = ..., *, - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: ... @@ -1095,67 +1092,67 @@ def AC_consensus_point(candidates: Any, cluster_radius: Any = ...) -> Dict[str, """Adapter: agreed target point from clustered grounding proposals.""" def AC_control_expand_state( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: the expand/collapse state of a control.""" def AC_control_get_state( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., -) -> Optional[dict]: + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., +) -> Dict[str, Any] | None: """Adapter: read everything a native control currently holds, in one call.""" def AC_control_get_value( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., -) -> Optional[str]: + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., +) -> str | None: """Adapter: read a native control's value via the accessibility backend.""" def AC_control_invoke( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: invoke a native control (e.g. press a button).""" def AC_control_range( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read a slider / progress range (RangeValuePattern).""" def AC_control_set_value( value: str, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: set a native control's value via the accessibility backend.""" def AC_control_text_attributes( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read a control selection's font/colour formatting (TextPattern).""" def AC_control_toggle( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: toggle a native control (e.g. a checkbox).""" @@ -1173,19 +1170,19 @@ def AC_costs_record( model: str, input_tokens: int, output_tokens: int, - label: Optional[str] = ..., - run_id: Optional[str] = ..., - user: Optional[str] = ..., + label: str | None = ..., + run_id: str | None = ..., + user: str | None = ..., ) -> Dict[str, Any]: """Executor adapter: append one LLM call to the cost-telemetry log.""" def AC_costs_summary(limit: int = ...) -> Dict[str, Any]: """Executor adapter: aggregate cost events by model / provider / day.""" -def AC_create_project(project_path: Optional[str] = ..., parent_name: str = ...) -> None: +def AC_create_project(project_path: str | None = ..., parent_name: str = ...) -> None: """Create project directory structure and templates.""" -def AC_create_signing_keypair(private_path: str, public_path: str, passphrase: Optional[str] = ...) -> Dict[str, Any]: +def AC_create_signing_keypair(private_path: str, public_path: str, passphrase: str | None = ...) -> Dict[str, Any]: """Executor adapter: create an Ed25519 action-signing key pair.""" def AC_critical_steps(steps: Any, top: Any = ...) -> Dict[str, Any]: @@ -1206,7 +1203,7 @@ def AC_decode_body(headers: Any, body_base64: str) -> Dict[str, Any]: def AC_decode_conversion_mode(flags: Any) -> Dict[str, Any]: """Adapter: decode an IMM32 conversion bitmask into named flags (pure).""" -def AC_decrypt_action_file(enc_path: str, key: Optional[str] = ..., output_path: Optional[str] = ...) -> Dict[str, Any]: +def AC_decrypt_action_file(enc_path: str, key: str | None = ..., output_path: str | None = ...) -> Dict[str, Any]: """Executor adapter: decrypt a Fernet-encrypted action file.""" def AC_dedup_check(name: str, message_id: str, ttl_s: Any = ...) -> Dict[str, Any]: @@ -1225,7 +1222,7 @@ def AC_delta_observation( ) -> Dict[str, Any]: """Adapter: token-budgeted \"what changed\" delta between two element frames.""" -def AC_describe_screen(app_name: Optional[str] = ...) -> Dict[str, Any]: +def AC_describe_screen(app_name: str | None = ...) -> Dict[str, Any]: """Adapter: structured 'where am I' description of the live screen.""" def AC_describe_stats(values: Any) -> Dict[str, Any]: @@ -1317,7 +1314,7 @@ def AC_edge_match_all( def AC_effect_near_point(before: Any, after: Any, point: Any, radius: Any = ...) -> Dict[str, Any]: """Adapter: did any before/after change land within radius of a point.""" -def AC_egress_allow(allow: Optional[List[str]] = ..., deny: Optional[List[str]] = ...) -> Dict[str, Any]: +def AC_egress_allow(allow: List[str] | None = ..., deny: List[str] | None = ...) -> Dict[str, Any]: """Adapter: lock the HTTP client to an egress allow/deny policy.""" def AC_egress_check(url: str) -> Dict[str, Any]: @@ -1341,9 +1338,9 @@ def AC_element_remove(path: str, key: str) -> Dict[str, Any]: def AC_element_save( path: str, key: str, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., ) -> Dict[str, Any]: """Adapter: save a named native-UI locator (object repository).""" @@ -1352,7 +1349,7 @@ def AC_email_trigger_add( username: str, password: str, script_path: str, - port: Optional[int] = ..., + port: int | None = ..., use_ssl: bool = ..., mailbox: str = ..., search_criteria: str = ..., @@ -1380,20 +1377,20 @@ def AC_emit_event( event_type: str, data: Any = ..., source: str = ..., - subject: Optional[str] = ..., - url: Optional[str] = ..., + subject: str | None = ..., + url: str | None = ..., ) -> Dict[str, Any]: """Adapter: build a CloudEvent; optionally POST it (egress-guarded).""" -def AC_encrypt_action_file(path: str, key: Optional[str] = ...) -> Dict[str, Any]: +def AC_encrypt_action_file(path: str, key: str | None = ...) -> Dict[str, Any]: """Executor adapter: Fernet-encrypt an action file to .enc.""" def AC_ensure_field_value( desired: Any, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., attempts: Any = ..., ) -> Dict[str, Any]: """Adapter: idempotently set a native control's value and verify (read-act).""" @@ -1404,7 +1401,7 @@ def AC_enumerate_monitors() -> Dict[str, Any]: def AC_evaluate_flag(flags: Any, key: str, context: Any = ...) -> Dict[str, Any]: """Adapter: evaluate a feature flag (flags/context dict or JSON string).""" -def AC_evaluate_slo(records: Any, target: float, window_s: Optional[float] = ...) -> Dict[str, Any]: +def AC_evaluate_slo(records: Any, target: float, window_s: float | None = ...) -> Dict[str, Any]: """Adapter: SLI + error budget for outcome records (list or JSON string).""" def AC_evaluate_trajectory(trajectory: Any, rubric: Any) -> Dict[str, Any]: @@ -1414,26 +1411,26 @@ def AC_ewma(values: Any, alpha: Any = ...) -> Dict[str, Any]: """Adapter: exponentially-weighted moving average.""" def AC_execute_action( - action_list: Union[list, dict], + action_list: List[Any] | Dict[str, Any], raise_on_error: bool = ..., _validated: bool = ..., dry_run: bool = ..., - step_callback: Optional[Callable[[list], None]] = ..., + step_callback: Callable[[List[Any]], None] | None = ..., result_callback: Any = ..., ) -> Dict[str, str]: """執行 action list""" -def AC_execute_files(execute_files_list: list) -> List[Dict[str, str]]: +def AC_execute_files(execute_files_list: List[str]) -> List[Dict[str, str]]: """執行 action files""" def AC_execute_process(exe_path: str) -> None: """Start an external executable file.""" def AC_expand_control( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: expand a tree node / combobox (ExpandCollapsePattern).""" @@ -1450,13 +1447,13 @@ def AC_expect_poll( def AC_explain_config(layers: Any, key: str) -> Dict[str, Any]: """Adapter: report the value and winning layer for a dotted config key.""" -def AC_export_sarif(findings: Any, path: Optional[str] = ..., tool_name: str = ...) -> Dict[str, Any]: +def AC_export_sarif(findings: Any, path: str | None = ..., tool_name: str = ...) -> Dict[str, Any]: """Adapter: build (and optionally write) a SARIF 2.1.0 document.""" def AC_extract_fields( text: str, - fields: Optional[List[str]] = ..., - patterns: Optional[Dict[str, str]] = ..., + fields: List[str] | None = ..., + patterns: Dict[str, str] | None = ..., ) -> Dict[str, Any]: """Adapter: extract structured fields from free text.""" @@ -1470,10 +1467,10 @@ def AC_failure_hook_fire( source: str, source_id: str, error_text: str = ..., - script_path: Optional[str] = ..., - screenshot_path: Optional[str] = ..., + script_path: str | None = ..., + screenshot_path: str | None = ..., log_tail: str = ..., - metadata: Optional[Dict[str, Any]] = ..., + metadata: Dict[str, Any] | None = ..., ) -> List[Dict[str, Any]]: """Executor adapter: file a ticket through every registered backend.""" @@ -1501,10 +1498,10 @@ def AC_find_color_region(rgb: Any, tolerance: Any = ..., min_area: Any = ..., re def AC_find_control_text( text: str, ignore_case: Any = ..., - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: whether text occurs in a control (TextPattern.FindText).""" @@ -1540,10 +1537,10 @@ def AC_find_text_lines(y_tolerance: Any = ..., region: Any = ...) -> Dict[str, A def AC_find_text_regex( pattern: str, lang: str = ..., - region: Optional[List[int]] = ..., + region: List[int] | None = ..., min_confidence: float = ..., flags: int = ..., -) -> List[dict]: +) -> List[Dict[str, Any]]: """Executor adapter: regex OCR search returning JSON-friendly dicts.""" def AC_find_text_regions( @@ -1565,10 +1562,10 @@ def AC_flow_order(boxes: Any, min_gap: Any = ...) -> Dict[str, Any]: """Adapter: column-aware reading order of OCR boxes (XY-cut).""" def AC_focus_control( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Executor adapter: set keyboard focus on a control (UIA SetFocus).""" @@ -1646,7 +1643,7 @@ def AC_generate_candidate_from_log( def AC_generate_code( source: Any, - output: Optional[str] = ..., + output: str | None = ..., target: str = ..., name: str = ..., style: str = ..., @@ -1656,9 +1653,9 @@ def AC_generate_code( def AC_generate_data( schema: Dict[str, Any], count: int = ..., - path: Optional[str] = ..., - fmt: Optional[str] = ..., - seed: Optional[int] = ..., + path: str | None = ..., + fmt: str | None = ..., + seed: int | None = ..., ) -> Dict[str, Any]: """Adapter: generate synthetic rows; write to ``path`` when given.""" @@ -1674,10 +1671,10 @@ def AC_generate_json() -> Tuple[Dict[str, Dict[str, str]], Dict[str, Dict[str, s def AC_generate_json_report(json_file_name: str = ...) -> None: """Output JSON report files (success and failure).""" -def AC_generate_sbom(path: Optional[str] = ..., root: str = ...) -> Dict[str, Any]: +def AC_generate_sbom(path: str | None = ..., root: str = ...) -> Dict[str, Any]: """Adapter: build (or write) a CycloneDX SBOM for the project.""" -def AC_generate_sop(actions: List[Any], title: str = ..., path: Optional[str] = ...) -> Dict[str, Any]: +def AC_generate_sop(actions: List[Any], title: str = ..., path: str | None = ...) -> Dict[str, Any]: """Adapter: build (or write) a step-by-step SOP from an action list.""" def AC_generate_xml() -> Tuple[str | bytes, str | bytes]: @@ -1686,7 +1683,7 @@ def AC_generate_xml() -> Tuple[str | bytes, str | bytes]: def AC_generate_xml_report(xml_file_name: str = ...) -> None: """Output XML report files (success and failure).""" -def AC_get_asset(name: str, environment: str = ..., db: Optional[str] = ...) -> Dict[str, Any]: +def AC_get_asset(name: str, environment: str = ..., db: str | None = ...) -> Dict[str, Any]: """Adapter: read a typed asset (credential stays a reference).""" def AC_get_client_rect(title: str) -> Dict[str, Any]: @@ -1705,51 +1702,51 @@ def AC_get_clipboard_rtf() -> Dict[str, Any]: """Adapter: read the clipboard's RTF document string (Windows).""" def AC_get_control_text( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read a control's full text via TextPattern (multiline-safe).""" def AC_get_element_properties( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read rich UIA properties (enabled/offscreen/help/status/keys).""" -def AC_get_keyboard_keys_table() -> dict: +def AC_get_keyboard_keys_table() -> dict[str, int]: """取得鍵盤對應表""" def AC_get_mouse_position() -> tuple[int, int] | None: """取得滑鼠目前位置""" -def AC_get_mouse_table() -> dict: +def AC_get_mouse_table() -> Dict[str, Tuple[int, int, int]]: """取得滑鼠按鍵對應表""" def AC_get_selected_text( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read a control's currently selected text (TextPattern).""" def AC_get_selection( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: a container's selection state (SelectionPattern).""" def AC_get_visible_text( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: read only the on-screen text of a control (TextPattern).""" @@ -1786,7 +1783,7 @@ def AC_guard_text(text: str, threshold: int = ...) -> Dict[str, Any]: def AC_handle_file_dialog( path: str, action: str = ..., - window_title: Optional[str] = ..., + window_title: str | None = ..., timeout_s: float = ..., confirm_key: str = ..., ) -> Dict[str, Any]: @@ -1814,13 +1811,13 @@ def AC_history_capture(*, body: list[object], source_id: str = ..., script_path: def AC_history_clear() -> int: """Delete every row (and its artifact file); return rows removed.""" -def AC_history_list(limit: int = ..., source_type: Optional[str] = ...) -> List[dict]: +def AC_history_list(limit: int = ..., source_type: str | None = ...) -> List[Dict[str, Any]]: """Executor adapter: list run history as plain dicts (JSON-friendly).""" def AC_hold_key(key: str, duration_s: Any = ..., rate_hz: Any = ...) -> Dict[str, Any]: """Adapter: hold a key for a duration (or auto-repeat at rate_hz).""" -def AC_hotkey(key_code_list: list, is_shift: bool = ...) -> Tuple[str, str]: +def AC_hotkey(key_code_list: Sequence[int | str], is_shift: bool = ...) -> Tuple[str, str]: """模擬組合鍵 (依序按下,再反向放開)""" def AC_http_replay(cassette: Any, url: str, method: str = ...) -> Dict[str, Any]: @@ -1829,10 +1826,10 @@ def AC_http_replay(cassette: Any, url: str, method: str = ...) -> Dict[str, Any] def AC_http_request( url: str, method: str = ..., - headers: Optional[Mapping[str, Any]] = ..., + headers: Mapping[str, Any] | None = ..., json_body: Any = ..., data: Any = ..., - auth: Optional[Mapping[str, Any]] = ..., + auth: Mapping[str, Any] | None = ..., timeout: float = ..., ) -> Dict[str, Any]: """Perform an HTTP(S) request and return a response dict.""" @@ -1844,7 +1841,7 @@ def AC_human_move( curve: float = ..., overshoot: float = ..., jitter: float = ..., - seed: Optional[int] = ..., + seed: int | None = ..., ) -> Dict[str, Any]: """Executor adapter: move the mouse to (x, y) along a human-like path.""" @@ -1853,7 +1850,7 @@ def AC_human_type( base_delay: float = ..., jitter: float = ..., pause_chance: float = ..., - seed: Optional[int] = ..., + seed: int | None = ..., ) -> Dict[str, Any]: """Executor adapter: type text with humanized inter-key delays.""" @@ -1905,25 +1902,25 @@ def AC_inspector_reset() -> Dict[str, Any]: def AC_inspector_summary() -> Dict[str, Any]: ... -def AC_ios_alert_accept(url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_alert_accept(url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Accept the alert or system dialog showing.""" -def AC_ios_alert_dismiss(url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_alert_dismiss(url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Dismiss the alert or system dialog showing.""" -def AC_ios_app_state(app_id: str, url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_app_state(app_id: str, url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """not_installed, not_running, background or foreground.""" def AC_ios_click_element( - name: Optional[str] = ..., - class_name: Optional[str] = ..., - predicate: Optional[str] = ..., + name: str | None = ..., + class_name: str | None = ..., + predicate: str | None = ..., timeout_s: float = ..., - url: Optional[str] = ..., + url: str | None = ..., ) -> Dict[str, int]: ... -def AC_ios_device_info(url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_device_info(url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Backend, versions and capabilities of the device. Sends no input.""" def AC_ios_drag( @@ -1933,29 +1930,29 @@ def AC_ios_drag( y2: int, hold_s: float = ..., duration_s: float = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Press, hold so the item lifts, and move it.""" -def AC_ios_dump_source(url: Optional[str] = ...) -> str: +def AC_ios_dump_source(url: str | None = ...) -> str: ... def AC_ios_find_by_description( description: str, - model: Optional[str] = ..., + model: str | None = ..., tap: bool = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Ask a vision-language model where something is on the device screen.""" def AC_ios_find_element( - name: Optional[str] = ..., - class_name: Optional[str] = ..., - predicate: Optional[str] = ..., + name: str | None = ..., + class_name: str | None = ..., + predicate: str | None = ..., timeout_s: float = ..., - url: Optional[str] = ..., + url: str | None = ..., ) -> Dict[str, int]: ... @@ -1963,8 +1960,8 @@ def AC_ios_find_image( template_path: str, detect_threshold: float = ..., tap: bool = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Template-match in the device screen; answers in device points.""" @@ -1973,26 +1970,30 @@ def AC_ios_find_text( lang: str = ..., min_confidence: float = ..., tap: bool = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """OCR the device screen for text; answers in device points.""" -def AC_ios_get_clipboard(url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_get_clipboard( + allow_app_switch: bool = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., +) -> Any: """Read the device clipboard's text.""" -def AC_ios_install_app(path: str, url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_install_app(path: str, url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Install an app package from the host.""" -def AC_ios_launch_app(app_id: str, url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_launch_app(app_id: str, url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Launch an app; returns its state.""" def AC_ios_long_press( x: int, y: int, duration_s: float = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Press and hold at a point.""" @@ -2002,91 +2003,84 @@ def AC_ios_pinch( scale: float, duration_s: float = ..., span: int = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Two-finger pinch: scale above 1 zooms in, below 1 out.""" -def AC_ios_press_key(key: str, url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_press_key(key: str, url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Press a hardware key (home, volumeUp, volumeDown).""" def AC_ios_pull_file( remote_path: str, local_path: str, - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Copy a device file to the host.""" def AC_ios_push_file( local_path: str, remote_path: str, - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Copy a host file to the device.""" -def AC_ios_screen_info(url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_screen_info(url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Pixel size, point size, scale and orientation of the current screen.""" -def AC_ios_screenshot(file_path: str, url: Optional[str] = ...) -> str: +def AC_ios_screenshot(file_path: str, url: str | None = ...) -> str: ... def AC_ios_self_heal( - template_path: Optional[str] = ..., - description: Optional[str] = ..., + template_path: str | None = ..., + description: str | None = ..., detect_threshold: float = ..., - model: Optional[str] = ..., + model: str | None = ..., tap: bool = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Template first, VLM on a miss, against the device screen.""" -def AC_ios_set_clipboard(text: str, url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_set_clipboard(text: str, url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Put text on the device clipboard.""" def AC_ios_start_recording( - remote_path: Optional[str] = ..., - time_limit_s: Optional[int] = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + remote_path: str | None = ..., + time_limit_s: int | None = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Start recording the device screen.""" -def AC_ios_stop_app(app_id: str, url: Optional[str] = ..., device_timeout_s: Optional[float] = ...) -> Any: +def AC_ios_stop_app(app_id: str, url: str | None = ..., device_timeout_s: float | None = ...) -> Any: """Stop an app; returns its state.""" def AC_ios_stop_recording( local_path: str, - remote_path: Optional[str] = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + remote_path: str | None = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Stop recording and save the video on the host.""" -def AC_ios_swipe( - x1: int, - y1: int, - x2: int, - y2: int, - duration_s: float = ..., - url: Optional[str] = ..., -) -> Dict[str, Any]: +def AC_ios_swipe(x1: int, y1: int, x2: int, y2: int, duration_s: float = ..., url: str | None = ...) -> Dict[str, Any]: ... -def AC_ios_tap(x: int, y: int, url: Optional[str] = ...) -> Dict[str, int]: +def AC_ios_tap(x: int, y: int, url: str | None = ...) -> Dict[str, int]: ... -def AC_ios_type(text: str, url: Optional[str] = ...) -> str: +def AC_ios_type(text: str, url: str | None = ...) -> str: ... def AC_ios_wait_for_app( app_id: str, timeout_s: float = ..., state: str = ..., - url: Optional[str] = ..., - device_timeout_s: Optional[float] = ..., + url: str | None = ..., + device_timeout_s: float | None = ..., ) -> Any: """Wait until an app reaches a state; raises on timeout.""" @@ -2100,13 +2094,13 @@ def AC_journal_capture( *, body: list[object], path: str, - run_id: Optional[str] = ..., - device_id: Optional[str] = ..., - session_id: Optional[str] = ..., + run_id: str | None = ..., + device_id: str | None = ..., + session_id: str | None = ..., ) -> Any: """Capture named body arguments on their executor without eager interpolation.""" -def AC_journal_read(path: str | Path, *, run_id: Optional[str] = ..., limit: int = ...) -> list[dict[str, object]]: +def AC_journal_read(path: str | Path, *, run_id: str | None = ..., limit: int = ...) -> list[dict[str, object]]: """Return bounded sanitized snapshots under the enclosing journal roots.""" def AC_json_extract(data: Any, mapping: Any) -> Dict[str, Any]: @@ -2119,7 +2113,7 @@ def AC_jwt_decode( token: str, key: str, algorithms: Any = ..., - audience: Optional[str] = ..., + audience: str | None = ..., leeway: float = ..., ) -> Dict[str, Any]: """Adapter: verify a JWT and return {ok, claims} or {ok: False, error}.""" @@ -2143,22 +2137,22 @@ def AC_lease_valid(token: str) -> Dict[str, Any]: """Adapter: report whether a lease token is still valid.""" def AC_legacy_default_action( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: fire an old control's MSAA default action (Value/Invoke fallback).""" def AC_legacy_info( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: MSAA IAccessible info of an old control (LegacyIAccessible).""" -def AC_list_assets(environment: Optional[str] = ..., db: Optional[str] = ...) -> Dict[str, Any]: +def AC_list_assets(environment: str | None = ..., db: str | None = ...) -> Dict[str, Any]: """Adapter: list assets, optionally restricted to one environment.""" def AC_list_executions() -> List[Dict[str, Any]]: @@ -2171,10 +2165,10 @@ def AC_list_usb_devices() -> Dict[str, Any]: """Executor adapter: enumerate USB devices on this host.""" def AC_list_views( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: a control's selectable views (MultipleViewPattern).""" @@ -2183,16 +2177,16 @@ def AC_list_windows(titled_only: bool = ...) -> List[Tuple[int, str]]: def AC_llm_plan( description: str, - examples: Optional[list] = ..., - model: Optional[str] = ..., + examples: List[Dict[str, Any]] | None = ..., + model: str | None = ..., max_tokens: int = ..., -) -> list: +) -> List[List[Any]]: """Executor adapter: plan without executing, using current command set.""" def AC_llm_run( description: str, - examples: Optional[list] = ..., - model: Optional[str] = ..., + examples: List[Dict[str, Any]] | None = ..., + model: str | None = ..., max_tokens: int = ..., ) -> Dict[str, Any]: """Executor adapter: plan and execute, as the caller this thread already serves (so no ``owner``).""" @@ -2235,7 +2229,7 @@ def AC_locate_image_center(image: Any, detect_threshold: float = ..., draw_image def AC_locate_text( target: str, lang: str = ..., - region: Optional[Sequence[int]] = ..., + region: Sequence[int] | None = ..., min_confidence: float = ..., case_sensitive: bool = ..., backend: Any = ..., @@ -2257,7 +2251,7 @@ def AC_make_json_patch(old: Any, new: Any) -> Dict[str, Any]: def AC_mark_click(mark_id: int) -> Dict[str, Any]: """Adapter: click the element behind a numbered mark.""" -def AC_mark_screen(app_name: Optional[str] = ..., render_path: Optional[str] = ...) -> Dict[str, Any]: +def AC_mark_screen(app_name: str | None = ..., render_path: str | None = ...) -> Dict[str, Any]: """Adapter: number live UI elements (Set-of-Marks) for VLM grounding.""" def AC_mask_rows(rows: List[Dict[str, Any]], rules: Dict[str, str]) -> Dict[str, Any]: @@ -2380,7 +2374,7 @@ def AC_match_with_trust( ) -> Dict[str, Any]: """Adapter: best template match with trust metrics (ambiguity / PSR).""" -def AC_mcp_manifest(path: Optional[str] = ..., include_tools: bool = ...) -> Dict[str, Any]: +def AC_mcp_manifest(path: str | None = ..., include_tools: bool = ...) -> Dict[str, Any]: """Adapter: build (or write) the MCP registry server.json manifest.""" def AC_mcp_tool_schema(name: str, *, read_only: bool | None = ...) -> dict[str, Any]: @@ -2401,9 +2395,9 @@ def AC_memory_recent(db: str, limit: int = ...) -> Dict[str, Any]: def AC_memory_remember( db: str, goal: str, - steps: Optional[List[Any]] = ..., + steps: List[Any] | None = ..., outcome: str = ..., - tags: Optional[List[str]] = ..., + tags: List[str] | None = ..., ) -> Dict[str, Any]: """Adapter: store an agent episode (goal/trajectory/outcome).""" @@ -2437,19 +2431,19 @@ def AC_most_salient( ) -> Dict[str, Any]: """Adapter: the single most visually-salient region (where to look).""" -def AC_mouse_left(x: Optional[int] = ..., y: Optional[int] = ...) -> Tuple[int, int, int]: +def AC_mouse_left(x: int | None = ..., y: int | None = ...) -> Tuple[Tuple[int, int, int], int, int]: """Click the mouse left mouse button at (x, y).""" -def AC_mouse_middle(x: Optional[int] = ..., y: Optional[int] = ...) -> Tuple[int, int, int]: +def AC_mouse_middle(x: int | None = ..., y: int | None = ...) -> Tuple[Tuple[int, int, int], int, int]: """Click the mouse middle mouse button at (x, y).""" -def AC_mouse_right(x: Optional[int] = ..., y: Optional[int] = ...) -> Tuple[int, int, int]: +def AC_mouse_right(x: int | None = ..., y: int | None = ...) -> Tuple[Tuple[int, int, int], int, int]: """Click the mouse right mouse button at (x, y).""" def AC_mouse_scroll( scroll_value: int, - x: Optional[int] = ..., - y: Optional[int] = ..., + x: int | None = ..., + y: int | None = ..., scroll_direction: str = ..., ) -> Tuple[int, int | str]: """模擬滑鼠滾輪操作""" @@ -2460,10 +2454,10 @@ def AC_move_along_path(waypoints: Any, easing: str = ..., per_segment_steps: Any def AC_move_element( x: Any, y: Any, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: move a UIA element to (x, y) (TransformPattern).""" @@ -2477,8 +2471,8 @@ def AC_move_window( title_substring: str, x: int, y: int, - width: Optional[int] = ..., - height: Optional[int] = ..., + width: int | None = ..., + height: int | None = ..., case_sensitive: bool = ..., ) -> bool: """Move (and optionally resize) the first matching window.""" @@ -2501,7 +2495,7 @@ def AC_normalize_url(url: str, sort_query: bool = ..., drop_fragment: bool = ... def AC_notify(title: str, message: str = ...) -> Dict[str, Any]: """Executor adapter: show a cross-platform desktop notification.""" -def AC_notify_webhook(url: str, text: str, transport: str = ..., title: Optional[str] = ...) -> Dict[str, Any]: +def AC_notify_webhook(url: str, text: str, transport: str = ..., title: str | None = ...) -> Dict[str, Any]: """Adapter: send a chat/webhook notification (slack/discord/teams/raw).""" def AC_observation_index(elements: Any, viewport: Any = ..., max_elements: Any = ...) -> Dict[str, Any]: @@ -2511,7 +2505,7 @@ def AC_observe_add( name: str, kind: str = ..., event: str = ..., - actions: Optional[List[Any]] = ..., + actions: List[Any] | None = ..., **params: Any, ) -> Dict[str, Any]: """Adapter: watch image/text/pixel; run ``actions`` on the event.""" @@ -2535,7 +2529,7 @@ def AC_ocr_languages() -> Dict[str, Any]: """Executor adapter: installed Tesseract languages; ``None`` when unknown.""" def AC_ocr_read_structure( - region: Optional[List[int]] = ..., + region: List[int] | None = ..., lang: str = ..., min_confidence: float = ..., ) -> Dict[str, Any]: @@ -2675,14 +2669,14 @@ def AC_presence_unregister(viewer_id: str) -> Dict[str, Any]: def AC_presence_update_cursor(viewer_id: str, x: int, y: int) -> Dict[str, Any]: ... -def AC_press_keyboard_key(keycode: int | str, is_shift: bool = ..., skip_record: bool = ...) -> Optional[str]: +def AC_press_keyboard_key(keycode: int | str, is_shift: bool = ..., skip_record: bool = ...) -> str | None: """按下指定鍵""" def AC_press_mouse( mouse_keycode: int | str, - x: Optional[int] = ..., - y: Optional[int] = ..., -) -> tuple[Any, int, int] | None: + x: int | None = ..., + y: int | None = ..., +) -> tuple[Tuple[int, int, int], int, int] | None: """按下滑鼠按鍵""" def AC_probe_capabilities() -> dict[str, object]: @@ -2697,21 +2691,21 @@ def AC_profiler_disable() -> Dict[str, Any]: def AC_profiler_enable() -> Dict[str, Any]: ... -def AC_profiler_hot_spots(limit: int = ...) -> List[dict]: +def AC_profiler_hot_spots(limit: int = ...) -> List[Dict[str, object]]: """Executor adapter: top N actions by total time, as dicts.""" def AC_profiler_reset() -> Dict[str, Any]: ... -def AC_profiler_stats(limit: Optional[int] = ...) -> List[dict]: +def AC_profiler_stats(limit: int | None = ...) -> List[Dict[str, object]]: """Executor adapter: dump profiler stats as JSON-friendly dicts.""" def AC_propose_elements(region: Any = ..., min_area: Any = ..., iou_threshold: Any = ...) -> Dict[str, Any]: """Adapter: propose text/widget element boxes from pixels (device).""" def AC_pseudo_localize( - text: Optional[str] = ..., - mapping: Optional[Dict[str, Any]] = ..., + text: str | None = ..., + mapping: Dict[str, Any] | None = ..., expansion: float = ..., ) -> Dict[str, Any]: """Adapter: pseudo-localize a string or a whole catalog mapping.""" @@ -2744,7 +2738,7 @@ def AC_quarantine_list() -> List[Dict[str, Any]]: def AC_quarantine_remove(name: str) -> Dict[str, Any]: ... -def AC_queue_add(db: str, data: Any, reference: Optional[str] = ..., name: str = ...) -> Dict[str, Any]: +def AC_queue_add(db: str, data: Any, reference: str | None = ..., name: str = ...) -> Dict[str, Any]: """Adapter: enqueue a work item (skips live duplicate references).""" def AC_queue_complete( @@ -2752,7 +2746,7 @@ def AC_queue_complete( item_id: int, output: Any = ..., name: str = ..., - claim: Optional[int] = ..., + claim: int | None = ..., ) -> Dict[str, Any]: """Adapter: mark a work item successful (``claim`` from AC_queue_next).""" @@ -2763,11 +2757,11 @@ def AC_queue_fail( kind: str = ..., max_retries: int = ..., name: str = ..., - claim: Optional[int] = ..., + claim: int | None = ..., ) -> Dict[str, Any]: """Adapter: fail a work item (application errors retry, business don't).""" -def AC_queue_next(db: str, name: str = ..., stale_after_s: Optional[float] = ...) -> Optional[Dict[str, Any]]: +def AC_queue_next(db: str, name: str = ..., stale_after_s: float | None = ...) -> Dict[str, Any] | None: """Adapter: atomically claim the next work item (or None).""" def AC_queue_stats(db: str, name: str = ...) -> Dict[str, int]: @@ -2776,7 +2770,7 @@ def AC_queue_stats(db: str, name: str = ...) -> Dict[str, int]: def AC_rank_changes(scored_boxes: Any, threshold: Any = ...) -> Dict[str, Any]: """Adapter: rank scored element boxes by how much they changed (pure).""" -def AC_rank_tests(flows: List[str], history_path: Optional[str] = ..., window: int = ...) -> Dict[str, Any]: +def AC_rank_tests(flows: List[str], history_path: str | None = ..., window: int = ...) -> Dict[str, Any]: """Adapter: score flows by risk (riskiest first).""" def AC_rate_limit(name: str, rate: float = ..., capacity: float = ..., n: float = ...) -> Dict[str, Any]: @@ -2791,22 +2785,22 @@ def AC_read_document(path: str) -> Dict[str, Any]: def AC_read_presentation(path: str) -> Dict[str, Any]: """Adapter: read a .pptx file's per-slide text.""" -def AC_read_qr(region: Union[List[int], str, None] = ...) -> Dict[str, Any]: +def AC_read_qr(region: List[int] | str | None = ...) -> Dict[str, Any]: """Executor adapter: decode QR codes in a screen region.""" def AC_read_table( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> List[List[str]]: """Adapter: read a grid/table/list control as rows of cell strings.""" def AC_read_text_in_region( - region: Optional[List[int]] = ..., + region: List[int] | None = ..., lang: str = ..., min_confidence: float = ..., -) -> List[dict]: +) -> List[Dict[str, Any]]: """Executor adapter: dump OCR hits in a region as JSON-friendly dicts.""" def AC_read_workbook(path: str, sheet: str = ...) -> Dict[str, Any]: @@ -2821,10 +2815,10 @@ def AC_reading_order(elements: Any, row_tol: Any = ...) -> Dict[str, Any]: def AC_realize_item( item_name: str, by: str = ..., - container_name: Optional[str] = ..., - container_role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + container_name: str | None = ..., + container_role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: find + realize a virtualized list/grid item (VirtualizedItem).""" @@ -2839,18 +2833,18 @@ def AC_redact_pii(text: str, kinds: Any = ..., mode: str = ..., mask_char: str = def AC_redact_screenshot( file_path: str, - output_path: Optional[str] = ..., + output_path: str | None = ..., policy: str = ..., - regions: Optional[List[List[int]]] = ..., - accessibility: Optional[List[Dict[str, Any]]] = ..., - ocr: Optional[List[Dict[str, Any]]] = ..., + regions: List[List[int]] | None = ..., + accessibility: List[Dict[str, Any]] | None = ..., + ocr: List[Dict[str, Any]] | None = ..., ) -> Dict[str, Any]: """Executor adapter: blur PII regions in a saved screenshot.""" def AC_redact_secret_text(text: str, mask: str = ...) -> Dict[str, Any]: """Adapter: mask secret-looking tokens within a free-text string.""" -def AC_region_color_stats(region: Union[List[int], str, None] = ..., buckets: int = ...) -> Dict[str, Any]: +def AC_region_color_stats(region: List[int] | str | None = ..., buckets: int = ...) -> Dict[str, Any]: """Executor adapter: average + dominant colour of a screen region.""" def AC_region_contrast(region: Any = ...) -> Dict[str, Any]: @@ -2859,14 +2853,14 @@ def AC_region_contrast(region: Any = ...) -> Dict[str, Any]: def AC_region_stability(frames: Any, settle_threshold: Any = ...) -> Dict[str, Any]: """Adapter: how settled an injected frame sequence is (consecutive SSIM).""" -def AC_release_keyboard_key(keycode: int | str, is_shift: bool = ..., skip_record: bool = ...) -> Optional[str]: +def AC_release_keyboard_key(keycode: int | str, is_shift: bool = ..., skip_record: bool = ...) -> str | None: """放開指定鍵""" def AC_release_mouse( mouse_keycode: int | str, - x: Optional[int] = ..., - y: Optional[int] = ..., -) -> tuple[Any, int, int] | None: + x: int | None = ..., + y: int | None = ..., +) -> tuple[Tuple[int, int, int], int, int] | None: """放開滑鼠按鍵""" def AC_remote_connect(host: str, port: int, token: str, timeout: float = ...) -> Dict[str, Any]: @@ -2884,24 +2878,24 @@ def AC_remote_send_input(action: Dict[str, Any]) -> Dict[str, Any]: def AC_remote_viewer_status() -> Dict[str, Any]: ... -def AC_repair_approve(suggestion_id: str, db: Optional[str] = ...) -> Dict[str, Any]: +def AC_repair_approve(suggestion_id: str, db: str | None = ...) -> Dict[str, Any]: """Adapter: approve a pending locator-repair suggestion.""" -def AC_repair_pending(db: Optional[str] = ...) -> Dict[str, Any]: +def AC_repair_pending(db: str | None = ...) -> Dict[str, Any]: """Adapter: list locator-repair suggestions awaiting review.""" def AC_repair_record( key: str, method: str, coordinates: Any = ..., - description: Optional[str] = ..., + description: str | None = ..., confidence: float = ..., auto_threshold: float = ..., - db: Optional[str] = ..., + db: str | None = ..., ) -> Dict[str, Any]: """Adapter: record a corrected locator from a heal (auto-apply or queue).""" -def AC_repair_resolved(key: str, db: Optional[str] = ...) -> Dict[str, Any]: +def AC_repair_resolved(key: str, db: str | None = ...) -> Dict[str, Any]: """Adapter: return the learned corrected locator for a key (or null).""" def AC_replay_timeline(events: List[Dict[str, Any]], speed: float = ...) -> Dict[str, Any]: @@ -2913,10 +2907,10 @@ def AC_replay_trace(trace: Any) -> Dict[str, Any]: def AC_resize_element( width: Any, height: Any, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: resize a UIA element (TransformPattern).""" @@ -2935,7 +2929,7 @@ def AC_resolve_refs(obj: Any) -> Dict[str, Any]: def AC_rest_api_start( host: str = ..., port: int = ..., - token: Optional[str] = ..., + token: str | None = ..., enable_audit: bool = ..., ) -> Dict[str, Any]: """Executor adapter: start the singleton REST API server.""" @@ -2946,7 +2940,7 @@ def AC_rest_api_status() -> Dict[str, Any]: def AC_rest_api_stop() -> Dict[str, Any]: ... -def AC_restore_window_layout(layout: Union[List[Dict[str, Any]], str], maximize: bool = ...) -> Dict[str, Any]: +def AC_restore_window_layout(layout: List[Dict[str, Any]] | str, maximize: bool = ...) -> Dict[str, Any]: """Executor adapter: move windows back to a saved layout (list or path).""" def AC_retry_after(response: Any) -> Dict[str, Any]: @@ -2964,7 +2958,7 @@ def AC_retry_delay( def AC_revoke_lease(token: str) -> Dict[str, Any]: """Adapter: revoke a lease token immediately.""" -def AC_rrule_next(rule: str, dtstart: str, now: Optional[str] = ...) -> Dict[str, Any]: +def AC_rrule_next(rule: str, dtstart: str, now: str | None = ...) -> Dict[str, Any]: """Adapter: next RRULE occurrence at/after now (ISO in, ISO out).""" def AC_rrule_occurrences(rule: str, dtstart: str, count: int = ...) -> Dict[str, Any]: @@ -2975,7 +2969,7 @@ def AC_run_agent( backend: str = ..., max_steps: int = ..., wall_seconds: float = ..., - model: Optional[str] = ..., + model: str | None = ..., max_tokens: int = ..., ) -> Dict[str, Any]: """Executor adapter: drive the closed-loop ``AgentLoop`` against ``goal``.""" @@ -2986,8 +2980,8 @@ def AC_run_chaos(spec: Any) -> Dict[str, Any]: def AC_run_dag( definition: Dict[str, Any], max_parallel: int = ..., - batch_id: Optional[str] = ..., - recovery: Optional[Dict[str, Any]] = ..., + batch_id: str | None = ..., + recovery: Dict[str, Any] | None = ..., ) -> Dict[str, Any]: """Executor adapter: run a cross-host DAG definition.""" @@ -3003,7 +2997,7 @@ def AC_run_resumable( actions: List[Any], run_id: str, db: str, - variables: Optional[Dict[str, Any]] = ..., + variables: Dict[str, Any] | None = ..., ) -> Dict[str, Any]: """Adapter: run actions with checkpoint/resume keyed by run_id.""" @@ -3015,10 +3009,10 @@ def AC_run_state_machine(spec: Any) -> Dict[str, Any]: def AC_run_suite( spec: Dict[str, Any], - tags: Optional[List[str]] = ..., + tags: List[str] | None = ..., respect_quarantine: bool = ..., - junit_path: Optional[str] = ..., - allure_dir: Optional[str] = ..., + junit_path: str | None = ..., + allure_dir: str | None = ..., ) -> Dict[str, Any]: """Executor adapter: run a QA suite and optionally write CI reports.""" @@ -3028,10 +3022,10 @@ def AC_s3_delete(key: str) -> Dict[str, Any]: def AC_s3_download(key: str, local_path: str) -> Dict[str, Any]: """Adapter: download an artifact from the default S3 store.""" -def AC_s3_list(prefix: Optional[str] = ...) -> Dict[str, Any]: +def AC_s3_list(prefix: str | None = ...) -> Dict[str, Any]: """Adapter: list artifact keys in the default S3 store.""" -def AC_s3_upload(local_path: str, key: Optional[str] = ...) -> Dict[str, Any]: +def AC_s3_upload(local_path: str, key: str | None = ...) -> Dict[str, Any]: """Adapter: upload an artifact to the default S3 store; return the key.""" def AC_salient_regions( @@ -3043,7 +3037,7 @@ def AC_salient_regions( ) -> Dict[str, Any]: """Adapter: ranked visually-salient regions of an image / the screen.""" -def AC_save_window_layout(path: Optional[str] = ...) -> Dict[str, Any]: +def AC_save_window_layout(path: str | None = ...) -> Dict[str, Any]: """Executor adapter: snapshot every window's geometry (optionally to file).""" def AC_scale_sweep( @@ -3058,7 +3052,7 @@ def AC_scale_sweep( def AC_scan_secrets(data: Any) -> Dict[str, Any]: """Adapter: scan JSON/data for hardcoded secrets.""" -def AC_scan_vulns(components: Any, advisories: Any = ..., sarif_path: Optional[str] = ...) -> Dict[str, Any]: +def AC_scan_vulns(components: Any, advisories: Any = ..., sarif_path: str | None = ...) -> Dict[str, Any]: """Adapter: match SBOM components against an OSV advisory database.""" def AC_score_candidates( @@ -3072,7 +3066,7 @@ def AC_score_candidates( def AC_score_step(record: Any) -> Dict[str, Any]: """Adapter: rule-based score of a critic record.""" -def AC_screen_changed(app_name: Optional[str] = ...) -> Dict[str, Any]: +def AC_screen_changed(app_name: str | None = ...) -> Dict[str, Any]: """Adapter: diff the live screen against the last snapshot baseline.""" def AC_screen_diff(before: List[Dict[str, Any]], after: List[Dict[str, Any]]) -> Dict[str, Any]: @@ -3081,17 +3075,17 @@ def AC_screen_diff(before: List[Dict[str, Any]], after: List[Dict[str, Any]]) -> def AC_screen_size() -> Tuple[int, int]: """get screen size""" -def AC_screen_snapshot(app_name: Optional[str] = ...) -> Dict[str, Any]: +def AC_screen_snapshot(app_name: str | None = ...) -> Dict[str, Any]: """Adapter: snapshot the live a11y tree as a diff baseline.""" -def AC_screenshot(file_path: Optional[str] = ..., screen_region: Optional[list] = ...) -> Any: +def AC_screenshot(file_path: str | None = ..., screen_region: List[int] | None = ...) -> Any: """use to capture current screen""" def AC_scroll_control_into_view( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: scroll a control into view (ScrollItemPattern).""" @@ -3135,39 +3129,39 @@ def AC_segment_hsv(lower_hsv: Any, upper_hsv: Any, min_area: Any = ..., region: """Adapter: locate blobs inside an explicit HSV band on the screen.""" def AC_select_control_item( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: select a list / tree / tab item (SelectionItemPattern).""" def AC_select_control_text( text: str, ignore_case: Any = ..., - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: find + select text in a control (TextPattern.FindText + Select).""" def AC_select_tests( flows: List[str], - k: Optional[int] = ..., - threshold: Optional[float] = ..., - history_path: Optional[str] = ..., + k: int | None = ..., + threshold: float | None = ..., + history_path: str | None = ..., window: int = ..., ) -> Dict[str, Any]: """Adapter: pick the riskiest flows to run (top-k / threshold).""" def AC_self_heal_click( - template_path: Optional[str] = ..., - description: Optional[str] = ..., + template_path: str | None = ..., + description: str | None = ..., mouse_keycode: str = ..., detect_threshold: float = ..., - screen_region: Optional[List[int]] = ..., - model: Optional[str] = ..., + screen_region: List[int] | None = ..., + model: str | None = ..., raise_on_miss: bool = ..., ) -> Dict[str, Any]: """Executor adapter: locate with self-heal, then click.""" @@ -3176,11 +3170,11 @@ def AC_self_heal_evaluate(path: str) -> dict[str, object]: """Executor adapter shared by scripts, CLI and server action execution.""" def AC_self_heal_locate( - template_path: Optional[str] = ..., - description: Optional[str] = ..., + template_path: str | None = ..., + description: str | None = ..., detect_threshold: float = ..., - screen_region: Optional[List[int]] = ..., - model: Optional[str] = ..., + screen_region: List[int] | None = ..., + model: str | None = ..., raise_on_miss: bool = ..., ) -> Dict[str, Any]: """Executor adapter: template-first locate with VLM fallback.""" @@ -3214,7 +3208,7 @@ def AC_set_asset( value: Any, asset_type: str = ..., environment: str = ..., - db: Optional[str] = ..., + db: str | None = ..., ) -> Dict[str, Any]: """Adapter: store a typed, environment-scoped asset.""" @@ -3232,10 +3226,10 @@ def AC_set_clipboard_rtf(text: str) -> Dict[str, Any]: def AC_set_control_range( value: Any, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: set a slider / progress / spinner value (RangeValuePattern).""" @@ -3256,10 +3250,10 @@ def AC_set_topmost(title: str, on: Any = ...) -> Dict[str, Any]: def AC_set_view( view: str, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: switch a control to a named view (MultipleViewPattern).""" @@ -3268,10 +3262,10 @@ def AC_set_volume(level: Any) -> Dict[str, Any]: def AC_set_window_state( state: str, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> bool: """Adapter: set a window's visual state normal/maximized/minimized.""" @@ -3281,23 +3275,19 @@ def AC_settle_point(churns: Any, quiet_samples: Any = ..., max_churn: Any = ...) def AC_shard_suite( flows: List[str], shards: int = ..., - history_path: Optional[str] = ..., + history_path: str | None = ..., window: int = ..., ) -> Dict[str, Any]: """Adapter: balance flows into duration-aware shards.""" -def AC_shell_command( - shell_command: Union[str, List[str], None] = ..., - *, - command: Union[str, List[str], None] = ..., -) -> None: +def AC_shell_command(shell_command: str | List[str] | None = ..., *, command: str | List[str] | None = ...) -> None: """Execute shell command with shell=False.""" def AC_sign_action_file( path: str, - key: Optional[str] = ..., - private_key_path: Optional[str] = ..., - passphrase: Optional[str] = ..., + key: str | None = ..., + private_key_path: str | None = ..., + passphrase: str | None = ..., ) -> Dict[str, Any]: """Executor adapter: write an Ed25519 or HMAC signature sidecar for a file.""" @@ -3321,7 +3311,7 @@ def AC_skill_save( name: str, actions: List[Any], description: str = ..., - tags: Optional[List[str]] = ..., + tags: List[str] | None = ..., ) -> Dict[str, Any]: """Adapter: save a reusable action sequence (skill).""" @@ -3360,7 +3350,7 @@ def AC_start_mcp_http_server( host: str = ..., port: int = ..., mcp: Any = ..., - auth_token: Optional[str] = ..., + auth_token: str | None = ..., ssl_context: Any = ..., user_store: Any = ..., ) -> Any: @@ -3381,7 +3371,7 @@ def AC_start_remote_host( port: int = ..., fps: float = ..., quality: int = ..., - region: Optional[List[int]] = ..., + region: List[int] | None = ..., max_clients: int = ..., ) -> Dict[str, Any]: """Executor adapter: start the singleton remote-desktop host.""" @@ -3389,7 +3379,7 @@ def AC_start_remote_host( def AC_start_webrtc_host(token: str, read_only: bool = ...) -> Dict[str, Any]: """Executor adapter: allocate the singleton WebRTC host.""" -def AC_start_webrtc_viewer(token: str, viewer_id: Optional[str] = ...) -> Dict[str, Any]: +def AC_start_webrtc_viewer(token: str, viewer_id: str | None = ...) -> Dict[str, Any]: """Executor adapter: allocate the singleton WebRTC viewer.""" def AC_start_ws_host( @@ -3398,18 +3388,18 @@ def AC_start_ws_host( port: int = ..., fps: float = ..., quality: int = ..., - region: Optional[List[int]] = ..., + region: List[int] | None = ..., max_clients: int = ..., ) -> Dict[str, Any]: """Executor adapter: start the singleton WebSocket-transport host.""" -def AC_stop_execution(run_id: Optional[str] = ..., reason: str = ...) -> Dict[str, Any]: +def AC_stop_execution(run_id: str | None = ..., reason: str = ...) -> Dict[str, Any]: """Adapter: ask one stoppable run (or every other one) to stop.""" -def AC_stop_record() -> list: +def AC_stop_record() -> List[List[Any]]: """stop current record""" -def AC_stop_record_timeline() -> List[dict]: +def AC_stop_record_timeline() -> List[Dict[str, Any]]: """Adapter: stop recording and return the full replayable timeline.""" def AC_stop_remote_host() -> Dict[str, Any]: @@ -3432,7 +3422,7 @@ def AC_sync_adapter_apply( entries: dict[str, dict[str, object]], *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Persist incoming portable versions as an inert profile, preserving all parallel alternatives.""" @@ -3444,7 +3434,7 @@ def AC_sync_adapter_resolve( is_deleted: bool = ..., *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Resolve exactly the reviewed alternatives into a value or tombstone; runtime sources stay untouched.""" @@ -3452,7 +3442,7 @@ def AC_sync_adapter_snapshot( profile: dict[str, object], *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Capture source changes and return portable heads without activating anything.""" @@ -3461,7 +3451,7 @@ def AC_sync_asset_manifest( paths: list[str], *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Read an explicit confined local selection into a portable content-addressed manifest.""" @@ -3471,7 +3461,7 @@ def AC_sync_assets( target_root: str, *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Copy an explicit local selection into one verified immutable generation without executing its data.""" @@ -3485,10 +3475,10 @@ def AC_sync_outbox_flush( path: str, endpoint: str, user_id: str, - options: Optional[dict[str, object]] = ..., + options: dict[str, object] | None = ..., *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: ... @@ -3508,19 +3498,19 @@ def AC_sync_peer_control( endpoint: str, user_id: str, operation: str = ..., - options: Optional[dict[str, object]] = ..., + options: dict[str, object] | None = ..., *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: ... def AC_sync_peer_state( state: dict[str, object], operation: str, - peer_id: Optional[str] = ..., - revision: Optional[int] = ..., - epoch: Optional[int] = ..., + peer_id: str | None = ..., + revision: int | None = ..., + epoch: int | None = ..., full_resync: bool = ..., ) -> dict[str, object]: ... @@ -3531,7 +3521,7 @@ def AC_sync_profile_load( expected_digest: str, *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Load one completely verified native working snapshot without registering or enabling received work.""" @@ -3540,45 +3530,45 @@ def AC_sync_profile_materialize( target_root: str, *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Publish one complete ready local profile generation without replacing active workspace files.""" def AC_sync_workspace( configuration: dict[str, object], operation: str = ..., - options: Optional[dict[str, object]] = ..., + options: dict[str, object] | None = ..., *, path_policy: Any = ..., - cancelled: Optional[Callable[[], bool]] = ..., + cancelled: Callable[[], bool] | None = ..., ) -> dict[str, object]: """Coordinate explicit local profiles; even local status requires private DRIVE authority at server boundaries.""" -def AC_tab_order(app_name: Optional[str] = ..., max_results: int = ...) -> Dict[str, Any]: +def AC_tab_order(app_name: str | None = ..., max_results: int = ...) -> Dict[str, Any]: """Executor adapter: focusable elements in keyboard Tab order.""" def AC_table_cell( row: Any, column: Any, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: the cell at (row, column) with its span (GridItemPattern).""" def AC_table_headers( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: a table's row/column header labels (TablePattern).""" def AC_tag_kinds(elements: Any) -> Dict[str, Any]: """Adapter: label fused boxes text/widget by source (pure).""" -def AC_take_golden(path: str, region: Optional[List[int]] = ...) -> str: +def AC_take_golden(path: str, region: List[int] | None = ...) -> str: """Adapter: capture and save a golden/baseline image.""" def AC_template_candidate_accept(bundle_path: str, dataset_path: str, expected_revision: str) -> dict[str, object]: @@ -3639,11 +3629,11 @@ def AC_trace_inject(headers: Any = ..., traceparent: Any = ...) -> Dict[str, Any def AC_trace_record( operation: str, - model: Optional[str] = ..., - system: Optional[str] = ..., - input_tokens: Optional[int] = ..., - output_tokens: Optional[int] = ..., - tool_name: Optional[str] = ..., + model: str | None = ..., + system: str | None = ..., + input_tokens: int | None = ..., + output_tokens: int | None = ..., + tool_name: str | None = ..., duration_s: float = ..., status: str = ..., ) -> Dict[str, Any]: @@ -3672,7 +3662,7 @@ def AC_tween_drag( ) -> Dict[str, Any]: """Adapter: drag along an eased path from start to end.""" -def AC_type_keyboard(keycode: int | str, is_shift: bool = ..., skip_record: bool = ...) -> Optional[str]: +def AC_type_keyboard(keycode: int | str, is_shift: bool = ..., skip_record: bool = ...) -> str | None: """模擬輸入 (按下再放開)""" def AC_type_unicode(text: str, modifier: str = ...) -> Dict[str, Any]: @@ -3693,7 +3683,7 @@ def AC_urls_equal(first: str, second: str) -> Dict[str, Any]: def AC_usb_acl_add( vendor_id: str, product_id: str, - serial: Optional[str] = ..., + serial: str | None = ..., allow: bool = ..., prompt_on_open: bool = ..., label: str = ..., @@ -3709,7 +3699,7 @@ def AC_usb_acl_import(path: str, replace: bool = ...) -> Dict[str, Any]: def AC_usb_acl_list() -> Dict[str, Any]: ... -def AC_usb_acl_remove(vendor_id: str, product_id: str, serial: Optional[str] = ...) -> Dict[str, Any]: +def AC_usb_acl_remove(vendor_id: str, product_id: str, serial: str | None = ...) -> Dict[str, Any]: ... def AC_usb_acl_set_default(policy: str) -> Dict[str, Any]: @@ -3718,7 +3708,7 @@ def AC_usb_acl_set_default(policy: str) -> Dict[str, Any]: def AC_usb_loopback_list() -> Dict[str, Any]: ... -def AC_usb_loopback_open(vendor_id: str, product_id: str, serial: Optional[str] = ...) -> Dict[str, Any]: +def AC_usb_loopback_open(vendor_id: str, product_id: str, serial: str | None = ...) -> Dict[str, Any]: ... def AC_usb_passthrough_enable(enabled: bool = ...) -> Dict[str, Any]: @@ -3727,13 +3717,13 @@ def AC_usb_passthrough_enable(enabled: bool = ...) -> Dict[str, Any]: def AC_usb_passthrough_status() -> Dict[str, Any]: ... -def AC_usb_recent_events(since: int = ..., limit: Optional[int] = ...) -> List[Dict[str, Any]]: +def AC_usb_recent_events(since: int = ..., limit: int | None = ...) -> List[Dict[str, Any]]: ... def AC_usb_remote_list() -> Dict[str, Any]: ... -def AC_usb_remote_open(vendor_id: str, product_id: str, serial: Optional[str] = ...) -> Dict[str, Any]: +def AC_usb_remote_open(vendor_id: str, product_id: str, serial: str | None = ...) -> Dict[str, Any]: ... def AC_usb_watch_start(poll_interval_s: float = ...) -> Dict[str, Any]: @@ -3746,21 +3736,21 @@ def AC_user_add( user_id: str, role: str = ..., display_name: str = ..., - tags: Optional[List[str]] = ..., - users_path: Optional[str] = ..., + tags: List[str] | None = ..., + users_path: str | None = ..., ) -> Dict[str, Any]: """Executor adapter: add an RBAC user; the reply carries its token, once.""" -def AC_user_list(users_path: Optional[str] = ...) -> List[Dict[str, Any]]: +def AC_user_list(users_path: str | None = ...) -> List[Dict[str, Any]]: """Executor adapter: list RBAC users (no tokens, no hashes).""" -def AC_user_remove(user_id: str, users_path: Optional[str] = ...) -> Dict[str, Any]: +def AC_user_remove(user_id: str, users_path: str | None = ...) -> Dict[str, Any]: """Executor adapter: remove an RBAC user.""" -def AC_user_rotate_token(user_id: str, users_path: Optional[str] = ...) -> Dict[str, Any]: +def AC_user_rotate_token(user_id: str, users_path: str | None = ...) -> Dict[str, Any]: """Executor adapter: replace an RBAC user's token; the reply carries it, once.""" -def AC_user_set_role(user_id: str, role: str, users_path: Optional[str] = ...) -> Dict[str, Any]: +def AC_user_set_role(user_id: str, role: str, users_path: str | None = ...) -> Dict[str, Any]: """Executor adapter: change an RBAC user's role.""" def AC_validate_action(action: Any, screen: Any = ..., targets: Any = ...) -> Dict[str, Any]: @@ -3777,9 +3767,9 @@ def AC_validate_rows(rows: List[Dict[str, Any]], schema: Dict[str, Any]) -> Dict def AC_verify_action_file( path: str, - key: Optional[str] = ..., + key: str | None = ..., raise_on_fail: bool = ..., - public_key_path: Optional[str] = ..., + public_key_path: str | None = ..., ) -> Dict[str, Any]: """Executor adapter: verify an action file against its signature sidecar.""" @@ -3788,10 +3778,10 @@ def AC_verify_artifact(name: str, content: Any, approvals_dir: str = ..., extens def AC_verify_field_value( expected: Any, - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., mode: Any = ..., ) -> Dict[str, Any]: """Adapter: read a native control's value back and compare to expected.""" @@ -3801,17 +3791,13 @@ def AC_verify_provenance(statement: Any, files: Any) -> Dict[str, Any]: def AC_vlm_click( description: str, - screen_region: Optional[List[int]] = ..., - model: Optional[str] = ..., + screen_region: List[int] | None = ..., + model: str | None = ..., backend: Any = ..., ) -> bool: """Locate by description, then click the center of the match.""" -def AC_vlm_locate( - description: str, - screen_region: Optional[List[int]] = ..., - model: Optional[str] = ..., -) -> Optional[List[int]]: +def AC_vlm_locate(description: str, screen_region: List[int] | None = ..., model: str | None = ...) -> List[int] | None: """Executor adapter: return VLM-located coords as a JSON-safe list.""" def AC_voice_clear() -> Dict[str, Any]: @@ -3839,8 +3825,8 @@ def AC_wait_actionable( """Adapter: wait until a template is visible + stable before acting.""" def AC_wait_clipboard_change( - baseline: Optional[str] = ..., - target: Optional[str] = ..., + baseline: str | None = ..., + target: str | None = ..., contains: bool = ..., timeout_s: float = ..., poll_interval_s: float = ..., @@ -3921,7 +3907,7 @@ def AC_wait_region_idle( """Executor adapter: smart wait for a sub-region to stop moving.""" def AC_wait_screen_stable( - region: Optional[List[int]] = ..., + region: List[int] | None = ..., timeout_s: float = ..., poll_interval_s: float = ..., stable_for_s: float = ..., @@ -3932,7 +3918,7 @@ def AC_wait_screen_stable( def AC_wait_text( target: str, lang: str = ..., - region: Optional[Sequence[int]] = ..., + region: Sequence[int] | None = ..., timeout: float = ..., poll: float = ..., min_confidence: float = ..., @@ -3972,14 +3958,14 @@ def AC_wait_window_title( ) -> Dict[str, Any]: """Executor adapter: wait for a window title (regex) to appear / vanish.""" -def AC_walk_tree(app_name: Optional[str] = ..., max_results: int = ...) -> Dict[str, Any]: +def AC_walk_tree(app_name: str | None = ..., max_results: int = ...) -> Dict[str, Any]: """Executor adapter: dump the a11y tree with friendly roles + node paths.""" def AC_watchdog_add( title: str, action: str = ..., case_sensitive: bool = ..., - name: Optional[str] = ..., + name: str | None = ..., ) -> Dict[str, Any]: """Adapter: register a popup-dismissal rule on the default watchdog.""" @@ -3993,9 +3979,9 @@ def AC_watchdog_stop() -> Dict[str, Any]: """Adapter: stop the background popup watchdog.""" def AC_wcag_audit( - app_name: Optional[str] = ..., - contrast_pairs: Optional[List[Dict[str, Any]]] = ..., - texts: Optional[List[str]] = ..., + app_name: str | None = ..., + contrast_pairs: List[Dict[str, Any]] | None = ..., + texts: List[str] | None = ..., level: str = ..., min_target_px: int = ..., max_results: int = ..., @@ -4008,7 +3994,7 @@ def AC_web_available() -> bool: def AC_web_current_url() -> Any: """Convenience executor: return the active browser tab's URL.""" -def AC_web_list_commands() -> list: +def AC_web_list_commands() -> List[str]: """Return every WR_* command the local WebRunner install exposes.""" def AC_web_open(url: str, browser: str = ..., **driver_kwargs: Any) -> Any: @@ -4017,10 +4003,10 @@ def AC_web_open(url: str, browser: str = ..., **driver_kwargs: Any) -> Any: def AC_web_quit() -> Any: """Convenience executor: tear down WebRunner driver sessions.""" -def AC_web_run(action: Optional[Dict[str, Any]] = ..., **action_kwargs: Any) -> Any: +def AC_web_run(action: Dict[str, Any] | None = ..., **action_kwargs: Any) -> Any: """Bridge one WR_* action into the WebRunner executor (Phase 7.7).""" -def AC_web_run_actions(actions: List[Dict[str, Any]]) -> list: +def AC_web_run_actions(actions: List[Dict[str, Any]]) -> List[Any]: """Bridge a list of WR_* actions through the WebRunner executor.""" def AC_web_screenshot(file_path: str) -> Any: @@ -4029,8 +4015,8 @@ def AC_web_screenshot(file_path: str) -> Any: def AC_webhook_add( path: str, script_path: str, - methods: Optional[List[str]] = ..., - token: Optional[str] = ..., + methods: List[str] | None = ..., + token: str | None = ..., ) -> Dict[str, Any]: ... @@ -4058,7 +4044,7 @@ def AC_webrtc_create_offer(peer_label: str = ...) -> Dict[str, Any]: def AC_webrtc_host_status() -> Dict[str, Any]: ... -def AC_webrtc_process_offer(offer_sdp: str, expected_dtls_fingerprint: Optional[str] = ...) -> Dict[str, Any]: +def AC_webrtc_process_offer(offer_sdp: str, expected_dtls_fingerprint: str | None = ...) -> Dict[str, Any]: ... def AC_webrtc_send_input(action: Dict[str, Any]) -> Dict[str, Any]: @@ -4068,10 +4054,10 @@ def AC_webrtc_viewer_status() -> Dict[str, Any]: ... def AC_window_interaction_state( - name: Optional[str] = ..., - role: Optional[str] = ..., - app_name: Optional[str] = ..., - automation_id: Optional[str] = ..., + name: str | None = ..., + role: str | None = ..., + app_name: str | None = ..., + automation_id: str | None = ..., ) -> Dict[str, Any]: """Adapter: a window's interaction state (ready/blocked/not_responding).""" @@ -4099,10 +4085,10 @@ def AC_workflow_manifest(directory: str, path: str, names: list[str]) -> dict[st def AC_workflow_open(path: str) -> bool: """Open one explicitly approved existing document with its registered application.""" -def AC_workflow_wait(selector: dict, expected: Any, state: bool = ..., timeout_seconds: float = ...) -> Any: +def AC_workflow_wait(selector: dict[str, Any], expected: Any, state: bool = ..., timeout_seconds: float = ...) -> Any: """Wait for one scoped control's exact value/state without replaying set, invoke or submit.""" -def AC_write(write_string: str, is_shift: bool = ...) -> Optional[str]: +def AC_write(write_string: str, is_shift: bool = ...) -> str | None: """模擬輸入整個字串""" def AC_write_document(path: str, paragraphs: List[str]) -> Dict[str, Any]: diff --git a/je_auto_control/android/client.py b/je_auto_control/android/client.py index e02652695..ffb72a896 100644 --- a/je_auto_control/android/client.py +++ b/je_auto_control/android/client.py @@ -11,7 +11,7 @@ class so the cheap adb-only path stays available when the daemon import functools import threading -from typing import Any, Callable, Optional, TypeVar +from typing import Any, Callable, List, Optional, Tuple, Type, TypeVar from je_auto_control.wrapper.device_context import DeviceUnavailableError @@ -63,7 +63,7 @@ def _resolve_handle(self) -> Any: ) from error try: self._handle = u2.connect(self._serial) - except (OSError, RuntimeError, ValueError, *_sdk_errors()) as error: + except (OSError, RuntimeError, ValueError) + _sdk_errors() as error: raise UIAutomatorUnavailableError( f"could not connect to Android device " f"{self._serial or '(default)'}: {error}", @@ -97,10 +97,10 @@ def reset_default_ui_device() -> None: _Result = TypeVar("_Result") -def _sdk_errors() -> tuple: +def _sdk_errors() -> Tuple[Type[BaseException], ...]: """``adbutils.AdbError`` (no device, or several without a serial) and uiautomator2's base error, whichever are installed.""" - errors = [] + errors: List[Type[BaseException]] = [] try: import adbutils errors.append(adbutils.AdbError) @@ -124,6 +124,6 @@ def translate_device_errors(function: Callable[..., _Result]) -> Callable[..., _ def wrapper(*args: Any, **kwargs: Any) -> _Result: try: return function(*args, **kwargs) - except (*_sdk_errors(),) as error: + except _sdk_errors() as error: raise UIAutomatorUnavailableError(f"{function.__name__}: {error}") from error return wrapper diff --git a/je_auto_control/gui/vlm_tab.py b/je_auto_control/gui/vlm_tab.py index 4d7f387ae..695292c14 100644 --- a/je_auto_control/gui/vlm_tab.py +++ b/je_auto_control/gui/vlm_tab.py @@ -6,7 +6,7 @@ cancellation once the model has answered, before it moves the mouse. """ import functools -from typing import Optional +from typing import Callable, List, Optional, Sequence, Tuple from PySide6.QtWidgets import ( QFormLayout, QLabel, QLineEdit, QVBoxLayout, QWidget, @@ -82,7 +82,7 @@ def dispose(self) -> None: """ release_resources(self) - def menu_actions(self) -> list: + def menu_actions(self) -> List[Tuple[str, Callable[[], None]]]: """Expose tab commands to the window-level Actions menu.""" return [ ("vlm_locate", self._on_locate), @@ -90,7 +90,7 @@ def menu_actions(self) -> list: ("task_stop", self._on_stop), ] - def _collect_inputs(self): + def _collect_inputs(self) -> Optional[Tuple[str, Optional[str]]]: description = self._description.text().strip() if not description: self._status.setText(_t("vlm_desc_required")) @@ -98,7 +98,7 @@ def _collect_inputs(self): model = self._model.text().strip() or None return description, model - def _run_off_gui_thread(self, call, tag: str) -> None: + def _run_off_gui_thread(self, call: Callable[[], object], tag: str) -> None: """The VLM round trip (network, seconds) froze the window on the GUI thread.""" if not self._task.start(call, tag=tag, timeout_s=REQUEST_DEADLINE_S): self._status.setText(_t("task_busy")) @@ -110,10 +110,12 @@ def _on_stop(self) -> None: self._status.setText(_t("task_stopped")) def _show_outcome(self, value: object) -> None: + # The task hands back whatever the call returned: a bool from + # click_by_description, a point or None from locate_by_description. if self._task.tag == "click": - self._show_clicked(value) + self._show_clicked(bool(value)) else: - self._show_located(value) + self._show_located(value if isinstance(value, (tuple, list)) else None) def _show_task_error(self, error: object) -> None: if isinstance(error, TaskTimeout): @@ -128,7 +130,7 @@ def _on_locate(self) -> None: description, model = inputs self._run_off_gui_thread(functools.partial(locate_by_description, description, model=model), "locate") - def _show_located(self, coords) -> None: + def _show_located(self, coords: Optional[Sequence[int]]) -> None: if coords is None: self._status.setText(_t("vlm_not_found")) self._last_result.setText("") @@ -146,5 +148,5 @@ def _on_click(self) -> None: description, model = inputs self._run_off_gui_thread(functools.partial(click_by_description, description, model=model), "click") - def _show_clicked(self, ok) -> None: + def _show_clicked(self, ok: bool) -> None: self._status.setText(_t("vlm_ok") if ok else _t("vlm_not_found")) diff --git a/je_auto_control/ios/client.py b/je_auto_control/ios/client.py index f374cbec2..d9cb7223c 100644 --- a/je_auto_control/ios/client.py +++ b/je_auto_control/ios/client.py @@ -18,7 +18,7 @@ import functools import threading -from typing import Any, Callable, Optional, TypeVar +from typing import Any, Callable, Optional, Tuple, Type, TypeVar from je_auto_control.wrapper.device_context import DeviceUnavailableError @@ -67,7 +67,7 @@ def _resolve_handle(self) -> Any: ) from error try: self._handle = wda.Client(self._url) - except (OSError, RuntimeError, ValueError, *_sdk_errors()) as error: + except (OSError, RuntimeError, ValueError) + _sdk_errors() as error: raise IOSUnavailableError( f"could not reach WebDriverAgent at {self._url}: {error}", ) from error @@ -100,9 +100,9 @@ def reset_default_ios_device() -> None: _Result = TypeVar("_Result") -def _sdk_errors() -> tuple: +def _sdk_errors() -> Tuple[Type[BaseException], ...]: """facebook-wda's base error (an invalid session, a crashed app...), if installed.""" - errors: tuple = () + errors: Tuple[Type[BaseException], ...] = () try: from wda import exceptions as wda_exceptions except ImportError: @@ -121,6 +121,6 @@ def translate_device_errors(function: Callable[..., _Result]) -> Callable[..., _ def wrapper(*args: Any, **kwargs: Any) -> _Result: try: return function(*args, **kwargs) - except (*_sdk_errors(),) as error: + except _sdk_errors() as error: raise IOSUnavailableError(f"{function.__name__}: {error}") from error return wrapper diff --git a/je_auto_control/linux_wayland/libei.py b/je_auto_control/linux_wayland/libei.py index e2ffa2223..f00a63197 100644 --- a/je_auto_control/linux_wayland/libei.py +++ b/je_auto_control/linux_wayland/libei.py @@ -194,13 +194,13 @@ class LibeiBackend: """ def __init__(self, *, symbols: Optional[BoundSymbols] = None, - portal_connect: Optional[Callable[..., tuple]] = None) -> None: + portal_connect: Optional[Callable[[], Tuple[int, oeffis.PortalSession]]] = None) -> None: self._symbols = symbols if symbols is not None else _load_symbols() self._portal_connect = portal_connect or oeffis.connect_eis_fd self._ei: Optional[int] = None self._backend_open = False self._handshake_complete = False - self._session = None + self._session: Optional[oeffis.PortalSession] = None self._devices: Dict[int, int] = {} # Every device this sender holds a reference to, whichever # capability currently points at it. diff --git a/je_auto_control/linux_wayland/oeffis.py b/je_auto_control/linux_wayland/oeffis.py index 1e900ba8b..765b44b28 100644 --- a/je_auto_control/linux_wayland/oeffis.py +++ b/je_auto_control/linux_wayland/oeffis.py @@ -22,7 +22,7 @@ import ctypes import select import time -from typing import Optional, Tuple +from typing import Optional, Protocol, Tuple from je_auto_control.linux_wayland._ctypes_bind import BoundSymbols, bind from je_auto_control.linux_wayland._input_state import InputFailure @@ -127,9 +127,16 @@ def _pump(symbols: BoundSymbols, handle: int, deadline: float) -> int: return event +class PortalSession(Protocol): + """What :func:`connect_eis_fd` hands back with the fd: a handle the caller closes to end the grant.""" + + def close(self) -> None: + """End the portal session.""" + + def connect_eis_fd(devices: int = OEFFIS_DEVICE_DEFAULT, timeout: float = DEFAULT_TIMEOUT, - symbols: Optional[BoundSymbols] = None) -> Tuple[int, object]: + symbols: Optional[BoundSymbols] = None) -> Tuple[int, PortalSession]: """Run the portal session and return ``(eis_fd, session_handle)``. The session handle must be kept alive for as long as the EIS fd is used: diff --git a/je_auto_control/osx/mouse/osx_mouse.py b/je_auto_control/osx/mouse/osx_mouse.py index 5dd3a9e7d..460dc6c16 100644 --- a/je_auto_control/osx/mouse/osx_mouse.py +++ b/je_auto_control/osx/mouse/osx_mouse.py @@ -57,7 +57,7 @@ def mouse_event(event: int, x: int, y: int, mouse_button: int, :param event: Quartz event type 事件類型 (例如 kCGEventMouseMoved) :param x: X coordinate X 座標 :param y: Y coordinate Y 座標 - :param mouse_button: Mouse button code 滑鼠按鍵代碼 + :param mouse_button: Mouse button name (``"Left"``, ``"Middle"``, ``"Right"``) 滑鼠按鍵名稱 :param click_count: 這是連續第幾次點擊 Which click of a run this is (>= 1) """ Quartz.CGEventPost( @@ -118,14 +118,14 @@ def set_position(x: int, y: int) -> None: mouse_event(Quartz.kCGEventMouseMoved, x, y, 0) -def press_mouse(x: int, y: int, mouse_button: int, click_count: int = 1) -> None: +def press_mouse(x: int, y: int, mouse_button: str, click_count: int = 1) -> None: """ Press mouse button 模擬按下滑鼠按鍵 :param x: X coordinate X 座標 :param y: Y coordinate Y 座標 - :param mouse_button: Mouse button code 滑鼠按鍵代碼 + :param mouse_button: Mouse button name (``"Left"``, ``"Middle"``, ``"Right"``) 滑鼠按鍵名稱 :param click_count: 這是連續第幾次點擊 Which click of a run this is (>= 1) """ if mouse_button == osx_mouse_left: @@ -138,14 +138,14 @@ def press_mouse(x: int, y: int, mouse_button: int, click_count: int = 1) -> None raise AutoControlMouseException(f"unknown mouse button {mouse_button!r}") -def release_mouse(x: int, y: int, mouse_button: int, click_count: int = 1) -> None: +def release_mouse(x: int, y: int, mouse_button: str, click_count: int = 1) -> None: """ Release mouse button 模擬釋放滑鼠按鍵 :param x: X coordinate X 座標 :param y: Y coordinate Y 座標 - :param mouse_button: Mouse button code 滑鼠按鍵代碼 + :param mouse_button: Mouse button name (``"Left"``, ``"Middle"``, ``"Right"``) 滑鼠按鍵名稱 :param click_count: 這是連續第幾次點擊,與對應的按下相同 Which click of a run this is; the same number as the matching press """ @@ -159,14 +159,14 @@ def release_mouse(x: int, y: int, mouse_button: int, click_count: int = 1) -> No raise AutoControlMouseException(f"unknown mouse button {mouse_button!r}") -def click_mouse(x: int, y: int, mouse_button: int, click_count: int = 1) -> None: +def click_mouse(x: int, y: int, mouse_button: str, click_count: int = 1) -> None: """ Perform mouse click (press + release) 模擬滑鼠點擊(按下 + 釋放) :param x: X coordinate X 座標 :param y: Y coordinate Y 座標 - :param mouse_button: Mouse button code 滑鼠按鍵代碼 + :param mouse_button: Mouse button name (``"Left"``, ``"Middle"``, ``"Right"``) 滑鼠按鍵名稱 :param click_count: 這是連續第幾次點擊;雙擊的第二下傳 2 Which click of a run this is; the second click of a double-click is 2 """ diff --git a/je_auto_control/utils/accessibility/accessibility_api.py b/je_auto_control/utils/accessibility/accessibility_api.py index ea1290180..569aa0e22 100644 --- a/je_auto_control/utils/accessibility/accessibility_api.py +++ b/je_auto_control/utils/accessibility/accessibility_api.py @@ -158,7 +158,7 @@ def dump_accessibility_tree(app_name: Optional[str] = None, elements = list_accessibility_elements( app_name=app_name, max_results=int(max_results), ) - by_app: dict = {} + by_app: Dict[str, List[AccessibilityElement]] = {} for element in elements: app = element.app_name or "(unknown)" by_app.setdefault(app, []).append(element) @@ -170,7 +170,7 @@ def dump_accessibility_tree(app_name: Optional[str] = None, app_name=app, children=[AXTreeNode( name=el.name, role=el.role, - bounds=tuple(el.bounds), + bounds=_bounds(el), app_name=el.app_name, process_id=int(el.process_id), ) for el in items], @@ -182,6 +182,12 @@ def dump_accessibility_tree(app_name: Optional[str] = None, ) +def _bounds(element: AccessibilityElement) -> Tuple[int, int, int, int]: + """The element's box as a fresh tuple (a backend may hand back a list).""" + left, top, width, height = element.bounds + return (left, top, width, height) + + def _scope_kwargs(window_title: Optional[str], contains: bool) -> Dict[str, Any]: """The narrowing arguments, omitted entirely when nothing was asked for.""" extra: Dict[str, Any] = {} diff --git a/je_auto_control/utils/actionability/actionability.py b/je_auto_control/utils/actionability/actionability.py index fa2dd1527..d0eecb951 100644 --- a/je_auto_control/utils/actionability/actionability.py +++ b/je_auto_control/utils/actionability/actionability.py @@ -76,7 +76,7 @@ def _reason(visible: bool, stable: bool, enabled: bool, receives: bool) -> str: class _StabilityTracker: """Tracks how long the bbox (and optional pixel sample) has stayed unchanged.""" - def __init__(self, sampler, stable_for_s: float): + def __init__(self, sampler: Optional[Callable[[Bbox], Any]], stable_for_s: float) -> None: self._sampler = sampler self._stable_for_s = stable_for_s self._prev: Any = object() @@ -120,18 +120,22 @@ def _probe_says_enabled(answer: Any) -> bool: return answer is None or bool(answer) -def _evaluate(bbox, tracker, now, enabled_probe, hit_tester): +def _evaluate(bbox: Optional[Bbox], tracker: _StabilityTracker, now: float, + enabled_probe: Optional[Callable[[], Optional[bool]]], + hit_tester: Optional[Callable[[List[int]], bool]], + ) -> Tuple[bool, bool, bool, bool, Optional[List[int]]]: """Return ``(visible, stable, enabled, receives, point)`` for one poll.""" # A zero-size box (a collapsed or hidden element) is not visible. visible = bbox is not None and len(bbox) >= 4 and bbox[2] > 0 and bbox[3] > 0 stable = tracker.update(bbox, now) enabled = enabled_probe is None or _probe_says_enabled(enabled_probe()) - point = _center(bbox) if visible else None + point = _center(bbox) if visible and bbox is not None else None receives = hit_tester is None or point is None or bool(hit_tester(point)) return visible, stable, enabled, receives, point -def _report(visible, stable, enabled, receives, point, waited): +def _report(visible: bool, stable: bool, enabled: bool, receives: bool, + point: Optional[List[int]], waited: float) -> ActionabilityReport: actionable = visible and stable and enabled and receives return ActionabilityReport( actionable, visible, stable, enabled, receives, round(waited, 4), diff --git a/je_auto_control/utils/executor/action_executor.py b/je_auto_control/utils/executor/action_executor.py index a214614bb..d18d7f04c 100644 --- a/je_auto_control/utils/executor/action_executor.py +++ b/je_auto_control/utils/executor/action_executor.py @@ -1,6 +1,6 @@ import threading import types -from typing import TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Optional, Sequence, Set, Tuple +from typing import TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Mapping, Optional, Sequence, Set, Tuple from je_auto_control.utils.diagnostics.capability_commands import probe_current_capabilities as _probe_capabilities from je_auto_control.utils.exception.exception_tags import ( @@ -8375,7 +8375,7 @@ def _execute_event(self, action: List[Any]) -> Any: return event() raise AutoControlActionException(cant_execute_action_error_message + " " + describe_action(action)) - def execute_one(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> Any: + def execute_one(self, name: str, arguments: Optional[Mapping[str, Any]] = None) -> Any: """Execute one public command through validation, policy and journal boundaries.""" from je_auto_control.utils.executor.dispatch import execute_one return execute_one(self, name, arguments) diff --git a/je_auto_control/utils/executor/mouse_aliases.py b/je_auto_control/utils/executor/mouse_aliases.py index e52bb1623..a2194351a 100644 --- a/je_auto_control/utils/executor/mouse_aliases.py +++ b/je_auto_control/utils/executor/mouse_aliases.py @@ -8,13 +8,14 @@ from typing import Callable, Dict, Optional, Tuple from je_auto_control.wrapper.auto_control_mouse import click_mouse +from je_auto_control.wrapper.backend_contract import MouseKeycode -ClickFn = Callable[[Optional[int], Optional[int]], Tuple[int, int, int]] +ClickFn = Callable[[Optional[int], Optional[int]], Tuple[MouseKeycode, int, int]] def _make_button_click(button: str) -> ClickFn: def click(x: Optional[int] = None, - y: Optional[int] = None) -> Tuple[int, int, int]: + y: Optional[int] = None) -> Tuple[MouseKeycode, int, int]: return click_mouse(button, x, y) click.__name__ = f"click_{button}" diff --git a/je_auto_control/utils/logging/logging_instance.py b/je_auto_control/utils/logging/logging_instance.py index 9d9211b8a..c24ec07da 100644 --- a/je_auto_control/utils/logging/logging_instance.py +++ b/je_auto_control/utils/logging/logging_instance.py @@ -24,6 +24,7 @@ import os import tempfile import warnings +from io import TextIOWrapper from logging.handlers import RotatingFileHandler from pathlib import Path from typing import Optional @@ -104,7 +105,7 @@ def __init__( encoding: str = "utf-8", errors: str = "backslashreplace", delay: bool = False, - ): + ) -> None: self._follows_environment = filename is None path = filename if filename is not None else str(default_log_file()) # encoding 必須明確指定。省略時 RotatingFileHandler 會採用系統 @@ -136,7 +137,7 @@ def __init__( self.setFormatter(formatter) # 設定格式器 self.setLevel(logging.DEBUG) # 設定等級 - def _open(self): + def _open(self) -> TextIOWrapper: """Open the file, creating its directory and rotating it first. A file that cannot be opened (read-only home, a path through a regular @@ -155,7 +156,7 @@ def _open(self): warnings.warn( f"AutoControlGUI log file {path} unavailable, file logging " f"off: {error!r}", RuntimeWarning, stacklevel=2) - return open(os.devnull, self.mode, encoding=self.encoding, # noqa: SIM115 # reason: the handler owns and closes its stream + return open(os.devnull, "a", encoding=self.encoding, # noqa: SIM115 # reason: the handler owns and closes its stream errors=self.errors) def emit(self, record: logging.LogRecord) -> None: diff --git a/je_auto_control/utils/mcp_server/tools/_factories.py b/je_auto_control/utils/mcp_server/tools/_factories.py index 8b8ba60c1..a8cf4785a 100644 --- a/je_auto_control/utils/mcp_server/tools/_factories.py +++ b/je_auto_control/utils/mcp_server/tools/_factories.py @@ -3647,8 +3647,8 @@ def tween_drag_tools() -> List[MCPTool]: "press, after it and before the release. Returns " "{points}."), input_schema=schema({ - "start": {"type": "array", "items": {"type": "integer"}}, - "end": {"type": "array", "items": {"type": "integer"}}, + "start": {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer"}}, + "end": {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer"}}, "steps": {"type": "integer"}, "easing": {"type": "string"}, "button": {"type": "string"}, diff --git a/je_auto_control/utils/mcp_server/tools/_handlers.py b/je_auto_control/utils/mcp_server/tools/_handlers.py index 183a347dd..41452dba3 100644 --- a/je_auto_control/utils/mcp_server/tools/_handlers.py +++ b/je_auto_control/utils/mcp_server/tools/_handlers.py @@ -263,10 +263,18 @@ def generate_sop(actions: List[Any], title: str = "Automation Procedure", return _gen(actions, title=title) -def tween_drag(start, end, steps=30, easing="ease_in_out_quad", - button="mouse_left", step_delay_s=0.0, settle_s=0.0): +def _xy(name: str, point: Sequence[int]) -> Tuple[int, int]: + """``point`` as an ``(x, y)`` pair; anything but two numbers is a ``ValueError`` naming the argument.""" + if len(point) != 2: + raise ValueError(f"{name} must be [x, y], got {len(point)} values") + return int(point[0]), int(point[1]) + + +def tween_drag(start: Sequence[int], end: Sequence[int], steps: int = 30, + easing: str = "ease_in_out_quad", button: str = "mouse_left", + step_delay_s: float = 0.0, settle_s: float = 0.0) -> Dict[str, Any]: from je_auto_control.utils.tween_drag import tween_drag as _td - return {"points": _td(tuple(start), tuple(end), steps=int(steps), + return {"points": _td(_xy("start", start), _xy("end", end), steps=int(steps), easing=easing, button=button, step_delay_s=float(step_delay_s), settle_s=float(settle_s))["points"]} diff --git a/je_auto_control/utils/remote_desktop/hw_codec.py b/je_auto_control/utils/remote_desktop/hw_codec.py index 10a873a71..540d8b23f 100644 --- a/je_auto_control/utils/remote_desktop/hw_codec.py +++ b/je_auto_control/utils/remote_desktop/hw_codec.py @@ -99,19 +99,22 @@ def active_hardware_codec() -> Optional[str]: return _active_codec -def _shape_changed(self_codec, frame, target_bitrate) -> bool: +def _shape_changed(self_codec: Optional[av.VideoCodecContext], frame: av.VideoFrame, + target_bitrate: int) -> bool: if self_codec is None: return False + # PyAV reports an unset bit rate as None (or 0): any target then differs + # by more than a tenth, where dividing by it raised. + bit_rate = self_codec.bit_rate or 0 return ( frame.width != self_codec.width or frame.height != self_codec.height - or abs(target_bitrate - self_codec.bit_rate) - / self_codec.bit_rate > 0.1 + or abs(target_bitrate - bit_rate) > 0.1 * bit_rate ) -def _open_codec_context(target: str, frame, target_bitrate: int, - max_frame_rate: int): +def _open_codec_context(target: str, frame: av.VideoFrame, target_bitrate: int, + max_frame_rate: int) -> av.VideoCodecContext: """Open an encoder for ``target``, or libx264 when it cannot open. Opened here, not at the first ``encode``: an encoder that fails to diff --git a/je_auto_control/utils/table_grid_fill/table_grid_fill.py b/je_auto_control/utils/table_grid_fill/table_grid_fill.py index db9da1361..c829fa68e 100644 --- a/je_auto_control/utils/table_grid_fill/table_grid_fill.py +++ b/je_auto_control/utils/table_grid_fill/table_grid_fill.py @@ -36,7 +36,8 @@ def _box_bounds(box: Box) -> Bounds: return int(left), int(top), int(left) + int(box["width"]), int(top) + int(box["height"]) -def _covered(bounds: Bounds, col_spans, row_spans): +def _covered(bounds: Bounds, col_spans: Sequence[Tuple[int, int]], + row_spans: Sequence[Tuple[int, int]]) -> Optional[Tuple[int, int, int, int]]: """``(r0, c0, r1, c1)``: the cells under the middle half of a box, or ``None`` off the grid. The middle half, so a box crossing a rule by a sliver stays in its cell, @@ -46,7 +47,7 @@ def _covered(bounds: Bounds, col_spans, row_spans): quarter_x, quarter_y = (right - left) / 4, (bottom - top) / 4 c0, c1 = _index_of(left + quarter_x, col_spans), _index_of(right - quarter_x, col_spans) r0, r1 = _index_of(top + quarter_y, row_spans), _index_of(bottom - quarter_y, row_spans) - if None in (c0, c1, r0, r1): + if c0 is None or c1 is None or r0 is None or r1 is None: return None return r0, c0, r1, c1 @@ -79,7 +80,8 @@ def _grid_spans(grid: Dict[str, Any]) -> Tuple[List[Tuple[int, int]], List[Tuple return _intervals(grid.get("cols", [])), _intervals(grid.get("rows", [])) -def _placed(box: Box, col_spans, row_spans, overlap: float): +def _placed(box: Box, col_spans: Sequence[Tuple[int, int]], + row_spans: Sequence[Tuple[int, int]], overlap: float) -> Optional[Tuple[int, int]]: """Return ``(row, col)`` for a box, or ``None`` if it misses every cell. A spanning box goes to its anchor (top-left) cell, where its span is diff --git a/je_auto_control/utils/tool_use_schema/schema.py b/je_auto_control/utils/tool_use_schema/schema.py index a07134fa1..42b8f1dcb 100644 --- a/je_auto_control/utils/tool_use_schema/schema.py +++ b/je_auto_control/utils/tool_use_schema/schema.py @@ -2,9 +2,12 @@ from __future__ import annotations import inspect -from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Set, Tuple -def _executor(): +if TYPE_CHECKING: + from je_auto_control.utils.executor.action_executor import Executor + +def _executor() -> Executor: """Lazy import to keep this module dependency-free at import time.""" from je_auto_control.utils.executor.action_executor import executor return executor @@ -85,7 +88,7 @@ def _description_for(name: str, callable_obj: Callable[..., Any]) -> str: return f"AutoControl command {name}" -def _allowed_names(only: Optional[List[str]]) -> Optional[set]: +def _allowed_names(only: Optional[List[str]]) -> Optional[Set[str]]: """``None`` exports every command; any list, even an empty one, is the whole set. An empty list used to export every command, so a filter that matched diff --git a/je_auto_control/utils/vision/backends/anthropic_backend.py b/je_auto_control/utils/vision/backends/anthropic_backend.py index aca54ea36..ec76b87cb 100644 --- a/je_auto_control/utils/vision/backends/anthropic_backend.py +++ b/je_auto_control/utils/vision/backends/anthropic_backend.py @@ -1,7 +1,7 @@ """Anthropic (Claude) VLM backend.""" import base64 import os -from typing import Optional, Tuple +from typing import Optional, Tuple, Type from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.vision.backends._parse import ( @@ -83,7 +83,7 @@ def locate(self, image_bytes: bytes, description: str, # The SDK's errors (rate limit, timeout, 5xx) derive from # anthropic.AnthropicError, a bare Exception, so they escaped here while # the LLM backend already caught them. - except (*_sdk_errors(), OSError, ValueError, RuntimeError) as error: + except _sdk_errors() + (OSError, ValueError, RuntimeError) as error: raise VLMRequestError(f"Anthropic VLM request failed: {error!r}") from error self.last_usage = read_usage(response, "input_tokens", "output_tokens") coords = parse_coords(_first_text_block(response)) @@ -94,14 +94,14 @@ def locate(self, image_bytes: bytes, description: str, return (int(round(coords[0] / scale[0])), int(round(coords[1] / scale[1]))) -def _first_text_block(response) -> str: +def _first_text_block(response: object) -> str: for block in getattr(response, "content", []) or []: if getattr(block, "type", None) == "text": return getattr(block, "text", "") or "" return "" -def _sdk_errors() -> tuple: # NOSONAR python:S8495 # reason: unpacked into an except tuple; empty with no SDK +def _sdk_errors() -> Tuple[Type[BaseException], ...]: # NOSONAR python:S8495 # reason: empty with no SDK """``(anthropic.AnthropicError,)``, the base of every error the SDK raises. Evaluated while an exception is being matched, so it must not raise: diff --git a/je_auto_control/utils/vision/backends/openai_backend.py b/je_auto_control/utils/vision/backends/openai_backend.py index 6cbd2fba7..1bd0b58e6 100644 --- a/je_auto_control/utils/vision/backends/openai_backend.py +++ b/je_auto_control/utils/vision/backends/openai_backend.py @@ -1,7 +1,7 @@ """OpenAI (GPT-4-vision family) VLM backend.""" import base64 import os -from typing import Optional, Tuple +from typing import Optional, Tuple, Type from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.vision.backends._parse import ( @@ -71,7 +71,7 @@ def locate(self, image_bytes: bytes, description: str, # The SDK's errors (rate limit, timeout, 5xx) derive from # openai.OpenAIError, a bare Exception, so they escaped here while # the LLM backend already caught them. - except (*_sdk_errors(), OSError, ValueError, RuntimeError) as error: + except _sdk_errors() + (OSError, ValueError, RuntimeError) as error: raise VLMRequestError(f"OpenAI VLM request failed: {error!r}") from error self.last_usage = read_usage(response, "prompt_tokens", "completion_tokens") try: @@ -81,14 +81,14 @@ def locate(self, image_bytes: bytes, description: str, return parse_coords(text) -def _sdk_errors() -> tuple: +def _sdk_errors() -> Tuple[Type[BaseException], ...]: """``(openai.OpenAIError,)``, the base of every error the SDK raises. Evaluated while an exception is being matched, so it must not raise: with an injected client and no SDK installed there is nothing of the SDK's to catch. """ - errors: tuple = () + errors: Tuple[Type[BaseException], ...] = () try: import openai # nosemgrep: codacy.python.openai.import-without-guardrails # reason: error type only except ImportError: diff --git a/je_auto_control/wrapper/auto_control_mouse.py b/je_auto_control/wrapper/auto_control_mouse.py index b082ff1b2..316dfe111 100644 --- a/je_auto_control/wrapper/auto_control_mouse.py +++ b/je_auto_control/wrapper/auto_control_mouse.py @@ -94,14 +94,18 @@ def mouse_preprocess(mouse_keycode: int | str, x: Optional[int], :param y: Y 座標,None 代表沿用目前游標位置 :return: (keycode, x, y) """ - keycode: MouseKeycode = mouse_keycode - try: - if isinstance(mouse_keycode, str): - keycode = mouse_keys_table.get(_BUTTON_ALIASES.get(mouse_keycode, mouse_keycode)) - if keycode is None: - raise AutoControlCantFindKeyException(table_cant_find_key_error_message) - except AutoControlCantFindKeyException as error: - raise AutoControlCantFindKeyException(table_cant_find_key_error_message) from error + keycode: MouseKeycode + if isinstance(mouse_keycode, str): + found = mouse_keys_table.get(_BUTTON_ALIASES.get(mouse_keycode, mouse_keycode)) + if found is None: + raise AutoControlCantFindKeyException(table_cant_find_key_error_message) + keycode = found + else: + # A number is taken as this platform's own button code and handed to + # the backend unchecked, as it always was: on Windows that is not + # even the right shape, which is what typing it Any says. + raw: Any = mouse_keycode + keycode = raw # 只有在座標缺漏時才查詢游標位置。 # Only query the cursor when a coordinate is actually missing: backends diff --git a/je_auto_control/wrapper/backend_contract.py b/je_auto_control/wrapper/backend_contract.py index 69f3f7721..738223027 100644 --- a/je_auto_control/wrapper/backend_contract.py +++ b/je_auto_control/wrapper/backend_contract.py @@ -48,14 +48,21 @@ "Win32MouseBackend", "X11UnixKeyboardBackend", "X11UnixMouseBackend"] -#: 一顆滑鼠鍵在**當前平台**的代碼。X11/Wayland/macOS 是 int,Windows 是 -#: 三個 Win32 事件旗標組成的 tuple——這是 `mouse_keys_table` 的值型別,也是 -#: `press_mouse` 之類的函式收下與回傳的東西。 +#: 一顆滑鼠鍵在**當前平台**的代碼。X11/Wayland 是 int,macOS 是字串 +#: (``"Left"``),Windows 是三個 Win32 事件旗標組成的 tuple——這是 +#: `mouse_keys_table` 的值型別,也是 `press_mouse` 之類的函式收下與回傳的東西。 +#: 用字面的 ``sys.platform`` 比較,因為 mypy 只認得這種寫法來分平台。 #: -#: One mouse button as *this* platform spells it: an int on X11, Wayland and -#: macOS, a tuple of three Win32 event flags on Windows. Named rather than -#: written as a bare ``Any`` so a signature says which kind of unknown it is. -MouseKeycode = Any +#: One mouse button as *this* platform spells it: an int on X11 and Wayland, a +#: string on macOS (``"Left"``), a tuple of three Win32 event flags on Windows. +#: Spelt with literal ``sys.platform`` checks, the only form mypy reads per +#: platform; ``platform_id.is_windows`` stays the run-time decision. +if sys.platform == "win32" or sys.platform == "cygwin" or sys.platform == "msys": + MouseKeycode = Tuple[int, int, int] +elif sys.platform == "darwin": + MouseKeycode = str +else: + MouseKeycode = int class ScreenBackend(Protocol): @@ -178,15 +185,15 @@ def position(self) -> Tuple[int, int]: def set_position(self, x: int, y: int) -> None: """Move the cursor to a point on the desktop.""" - def press_mouse(self, x: int, y: int, mouse_button: int, + def press_mouse(self, x: int, y: int, mouse_button: str, click_count: int = 1) -> None: """Hold a button down at a point; ``click_count`` as in ``click_mouse``.""" - def release_mouse(self, x: int, y: int, mouse_button: int, + def release_mouse(self, x: int, y: int, mouse_button: str, click_count: int = 1) -> None: """Let a button up at a point; ``click_count`` as in ``click_mouse``.""" - def click_mouse(self, x: int, y: int, mouse_button: int, + def click_mouse(self, x: int, y: int, mouse_button: str, click_count: int = 1) -> None: """Press and release a button at a point. diff --git a/je_auto_control/wrapper/platform_wrapper.py b/je_auto_control/wrapper/platform_wrapper.py index cabf8256a..bb165d12c 100644 --- a/je_auto_control/wrapper/platform_wrapper.py +++ b/je_auto_control/wrapper/platform_wrapper.py @@ -19,9 +19,6 @@ #: Alias -> canonical name for entries of ``keyboard_keys_table`` that are #: aliases (``esc`` for ``escape``); reverse lookups skip them. keyboard_key_aliases: Dict[str, str] -#: Values are platform-specific button codes: a plain int on X11, Wayland and -#: macOS, a tuple of three Win32 event flags on Windows. -mouse_keys_table: Dict[str, MouseKeycode] #: X11 and Wayland name their scroll axes here; Windows and macOS have a single #: wheel axis and publish ``None``. special_mouse_keys_table: Optional[Dict[str, int]] @@ -42,17 +39,18 @@ # one, so a backend missing one is still an ImportError here. _keyboard: Any _mouse: Any +_mouse_keys_table: Any if is_windows(): from je_auto_control.wrapper._platform_windows import ( # noqa: F401 # reason: facade re-export keyboard as _keyboard, keyboard_check, keyboard_key_aliases, keyboard_keys_table, - mouse as _mouse, mouse_keys_table, special_mouse_keys_table, + mouse as _mouse, mouse_keys_table as _mouse_keys_table, special_mouse_keys_table, screen, recorder, ) elif is_macos(): from je_auto_control.wrapper._platform_osx import ( # noqa: F401 # reason: facade re-export keyboard as _keyboard, keyboard_check, keyboard_key_aliases, keyboard_keys_table, - mouse as _mouse, mouse_keys_table, special_mouse_keys_table, + mouse as _mouse, mouse_keys_table as _mouse_keys_table, special_mouse_keys_table, screen, recorder, ) elif sys.platform.startswith("linux"): @@ -65,7 +63,7 @@ try: from je_auto_control.wrapper._platform_wayland import ( # noqa: F401 # reason: facade re-export keyboard as _keyboard, keyboard_check, keyboard_key_aliases, keyboard_keys_table, - mouse as _mouse, mouse_keys_table, special_mouse_keys_table, + mouse as _mouse, mouse_keys_table as _mouse_keys_table, special_mouse_keys_table, screen, recorder, ) except (ImportError, AutoControlException) as _wayland_error: @@ -78,14 +76,14 @@ from je_auto_control.wrapper._platform_linux import ( # noqa: F401 # reason: facade re-export keyboard as _keyboard, keyboard_check, keyboard_key_aliases, get_keyboard_keys_table as _get_x11_key_table, - mouse as _mouse, mouse_keys_table, special_mouse_keys_table, + mouse as _mouse, mouse_keys_table as _mouse_keys_table, special_mouse_keys_table, screen, recorder, ) else: from je_auto_control.wrapper._platform_linux import ( # noqa: F401 # reason: facade re-export keyboard as _keyboard, keyboard_check, keyboard_key_aliases, get_keyboard_keys_table as _get_x11_key_table, - mouse as _mouse, mouse_keys_table, special_mouse_keys_table, + mouse as _mouse, mouse_keys_table as _mouse_keys_table, special_mouse_keys_table, screen, recorder, ) elif is_bsd(): @@ -97,7 +95,7 @@ from je_auto_control.wrapper._platform_linux import ( # noqa: F401 # reason: facade re-export keyboard as _keyboard, keyboard_check, keyboard_key_aliases, get_keyboard_keys_table as _get_x11_key_table, - mouse as _mouse, mouse_keys_table, special_mouse_keys_table, + mouse as _mouse, mouse_keys_table as _mouse_keys_table, special_mouse_keys_table, screen, recorder, ) else: @@ -111,6 +109,9 @@ #: caller is inside it by default rather than when someone remembers. keyboard: KeyboardBackend = _keyboard mouse: MouseBackend = _mouse +#: Values are this platform's button codes (:data:`MouseKeycode`): an int on +#: X11 and Wayland, a string on macOS, a tuple of three Win32 event flags on Windows. +mouse_keys_table: Dict[str, MouseKeycode] = _mouse_keys_table if None in [mouse_keys_table, keyboard, mouse, screen]: raise AutoControlException("Can't init auto control") diff --git a/pyproject.toml b/pyproject.toml index dbedd602c..8d72a59cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -356,948 +356,7 @@ ignore_missing_imports = true # day it is written. Nothing here loosens a setting from `[tool.mypy]`. module = [ "je_auto_control", - "je_auto_control.__main__", - "je_auto_control._export_bindings", - "je_auto_control._lazy_exports", - "je_auto_control.android", - "je_auto_control.android.adb_client", - "je_auto_control.android.apps", - "je_auto_control.android.find", - "je_auto_control.android.input", - "je_auto_control.android.screen", - "je_auto_control.android.session", - "je_auto_control.api", - "je_auto_control.api.*", - "je_auto_control.cli", - "je_auto_control.gui", - "je_auto_control.gui._arrow_icons", - "je_auto_control.gui._auto_click_tab", - "je_auto_control.gui._daemon_thread", - "je_auto_control.gui._dispose", - "je_auto_control.gui._i18n_helpers", - "je_auto_control.gui._image_detect_tab", - "je_auto_control.gui._qt_typed", - "je_auto_control.gui._record_tab", - "je_auto_control.gui._report_tab", - "je_auto_control.gui._screen_geometry", - "je_auto_control.gui._screenshot_tab", - "je_auto_control.gui._script_tab", - "je_auto_control.gui._slow_op", - "je_auto_control.gui._stop_custody", - "je_auto_control.gui._tab_close_icon", - "je_auto_control.gui._tab_task", - "je_auto_control.gui._task_details", - "je_auto_control.gui._validators", - "je_auto_control.gui._weak_call", - "je_auto_control.gui._worker_thread", - "je_auto_control.gui.a11y_audit_tab", - "je_auto_control.gui.accessibility_tab", - "je_auto_control.gui.adaptive", - "je_auto_control.gui.adaptive.*", - "je_auto_control.gui.adaptive_window", - "je_auto_control.gui.admin_console_tab", - "je_auto_control.gui.agent_observation_view", - "je_auto_control.gui.agent_tasks_tab", - "je_auto_control.gui.agent_transfer_view", - "je_auto_control.gui.assertions_tab", - "je_auto_control.gui.audit_log_tab", - "je_auto_control.gui.chatops_tab", - "je_auto_control.gui.computer_use_tab", - "je_auto_control.gui.config_sync_tab", - "je_auto_control.gui.config_sync_worker", - "je_auto_control.gui.dag_tab", - "je_auto_control.gui.data_source_tab", - "je_auto_control.gui.device_matrix_tab", - "je_auto_control.gui.diagnostics_capabilities", - "je_auto_control.gui.diagnostics_tab", - "je_auto_control.gui.email_triggers_tab", - "je_auto_control.gui.failed_stops_view", - "je_auto_control.gui.flakiness_tab", - "je_auto_control.gui.flow_editor", - "je_auto_control.gui.flow_editor.*", - "je_auto_control.gui.healing_evaluation_panel", - "je_auto_control.gui.healing_evaluation_worker", - "je_auto_control.gui.hotkeys_tab", - "je_auto_control.gui.inspector_tab", - "je_auto_control.gui.journal_browser", - "je_auto_control.gui.journal_browser_worker", - "je_auto_control.gui.journal_candidate_dialog", - "je_auto_control.gui.journal_candidate_panel", - "je_auto_control.gui.journal_candidate_worker", - "je_auto_control.gui.language_wrapper", - "je_auto_control.gui.language_wrapper.*", - "je_auto_control.gui.live_hud_tab", - "je_auto_control.gui.llm_planner_tab", - "je_auto_control.gui.main_widget", - "je_auto_control.gui.main_window", - "je_auto_control.gui.manual_run_controls", - "je_auto_control.gui.mcp_discovery_view", - "je_auto_control.gui.media_checks_tab", - "je_auto_control.gui.mobile_tab", - "je_auto_control.gui.navigation", - "je_auto_control.gui.ocr_tab", - "je_auto_control.gui.plugins_tab", - "je_auto_control.gui.presence_tab", - "je_auto_control.gui.profiler_tab", - "je_auto_control.gui.rbac_users_panel", - "je_auto_control.gui.recording_editor_tab", - "je_auto_control.gui.remote_desktop", - "je_auto_control.gui.remote_desktop.*", - "je_auto_control.gui.remote_desktop_tab", - "je_auto_control.gui.rest_api_tab", - "je_auto_control.gui.run_history_tab", - "je_auto_control.gui.run_history_timeline", - "je_auto_control.gui.scheduler_tab", - "je_auto_control.gui.script_builder", - "je_auto_control.gui.script_builder.*", - "je_auto_control.gui.secrets_tab", - "je_auto_control.gui.selector", - "je_auto_control.gui.selector.*", - "je_auto_control.gui.self_healing_tab", - "je_auto_control.gui.tab_registry", - "je_auto_control.gui.tab_task_controller", - "je_auto_control.gui.task_controller", - "je_auto_control.gui.template_candidate_panel", - "je_auto_control.gui.template_candidate_worker", - "je_auto_control.gui.test_suite_tab", - "je_auto_control.gui.theme", - "je_auto_control.gui.trace_replay_tab", - "je_auto_control.gui.triggers_tab", - "je_auto_control.gui.usb_browser_tab", - "je_auto_control.gui.usb_devices_tab", - "je_auto_control.gui.usb_passthrough_panel", - "je_auto_control.gui.usb_passthrough_prompt", - "je_auto_control.gui.variables_tab", - "je_auto_control.gui.webhooks_tab", - "je_auto_control.gui.webrunner_tab", - "je_auto_control.gui.window_tab", - "je_auto_control.gui.workspace", - "je_auto_control.gui.workspace_details", - "je_auto_control.gui.workspace_settings", - "je_auto_control.ios", - "je_auto_control.ios.apps", - "je_auto_control.ios.find", - "je_auto_control.ios.input", - "je_auto_control.ios.screen", - "je_auto_control.ios.session", - "je_auto_control.linux_wayland", - "je_auto_control.linux_wayland._ctypes_bind", - "je_auto_control.linux_wayland._dbus_client", - "je_auto_control.linux_wayland._detect", - "je_auto_control.linux_wayland._input_state", - "je_auto_control.linux_wayland._layout", - "je_auto_control.linux_wayland._select_input", - "je_auto_control.linux_wayland._ydotool_cli", - "je_auto_control.linux_wayland.capture", - "je_auto_control.linux_wayland.ei_default", - "je_auto_control.linux_wayland.ei_protocol", - "je_auto_control.linux_wayland.ei_transport", - "je_auto_control.linux_wayland.ei_worker", - "je_auto_control.linux_wayland.global_shortcuts", - "je_auto_control.linux_wayland.input_events", - "je_auto_control.linux_wayland.keyboard", - "je_auto_control.linux_wayland.keymap", - "je_auto_control.linux_wayland.listener", - "je_auto_control.linux_wayland.mouse", - "je_auto_control.linux_wayland.oeffis", - "je_auto_control.linux_wayland.portal", - "je_auto_control.linux_wayland.record", - "je_auto_control.linux_wayland.screen", - "je_auto_control.linux_with_x11", - "je_auto_control.linux_with_x11.*", - "je_auto_control.osx", - "je_auto_control.osx.*", - "je_auto_control.utils", - "je_auto_control.utils.a11y_audit", - "je_auto_control.utils.a11y_audit.*", - "je_auto_control.utils.a2a", - "je_auto_control.utils.a2a.*", - "je_auto_control.utils.ab_locator", - "je_auto_control.utils.ab_locator.*", - "je_auto_control.utils.accessibility", - "je_auto_control.utils.accessibility.backends", - "je_auto_control.utils.accessibility.backends.*", - "je_auto_control.utils.accessibility.element", - "je_auto_control.utils.accessibility.recorder", - "je_auto_control.utils.accessibility.tree", - "je_auto_control.utils.acme_v2", - "je_auto_control.utils.acme_v2.*", - "je_auto_control.utils.act_in_view", - "je_auto_control.utils.act_in_view.*", - "je_auto_control.utils.act_modes", - "je_auto_control.utils.act_modes.*", - "je_auto_control.utils.action_effect", - "je_auto_control.utils.action_effect.*", - "je_auto_control.utils.action_grounding", - "je_auto_control.utils.action_grounding.*", - "je_auto_control.utils.action_journal", - "je_auto_control.utils.action_journal.*", - "je_auto_control.utils.action_lint", - "je_auto_control.utils.action_lint.*", - "je_auto_control.utils.action_signing", - "je_auto_control.utils.action_signing.*", - "je_auto_control.utils.actionability", - "je_auto_control.utils.adaptive_timeout", - "je_auto_control.utils.adaptive_timeout.*", - "je_auto_control.utils.admin", - "je_auto_control.utils.admin.*", - "je_auto_control.utils.agent", - "je_auto_control.utils.agent.*", - "je_auto_control.utils.agent_memory", - "je_auto_control.utils.agent_memory.*", - "je_auto_control.utils.agent_replay", - "je_auto_control.utils.agent_replay.*", - "je_auto_control.utils.agent_runtime", - "je_auto_control.utils.agent_runtime.*", - "je_auto_control.utils.agent_trace", - "je_auto_control.utils.agent_trace.*", - "je_auto_control.utils.anchor_locator", - "je_auto_control.utils.anchor_locator.*", - "je_auto_control.utils.annotate", - "je_auto_control.utils.annotate.*", - "je_auto_control.utils.anomaly", - "je_auto_control.utils.anomaly.*", - "je_auto_control.utils.app_idle", - "je_auto_control.utils.app_idle.*", - "je_auto_control.utils.approval", - "je_auto_control.utils.approval.*", - "je_auto_control.utils.artifact_store", - "je_auto_control.utils.artifact_store.*", - "je_auto_control.utils.assertion", - "je_auto_control.utils.assertion.*", - "je_auto_control.utils.assets", - "je_auto_control.utils.assets.*", - "je_auto_control.utils.ax_events", - "je_auto_control.utils.ax_events.*", - "je_auto_control.utils.ax_props", - "je_auto_control.utils.ax_props.*", - "je_auto_control.utils.ax_text", - "je_auto_control.utils.ax_text.*", - "je_auto_control.utils.ax_tree_walk", - "je_auto_control.utils.ax_tree_walk.*", - "je_auto_control.utils.baggage", - "je_auto_control.utils.baggage.*", - "je_auto_control.utils.barcode", - "je_auto_control.utils.barcode.*", - "je_auto_control.utils.bidi_check", - "je_auto_control.utils.bidi_check.*", - "je_auto_control.utils.bulkhead", - "je_auto_control.utils.bulkhead.*", - "je_auto_control.utils.callback", - "je_auto_control.utils.callback.*", - "je_auto_control.utils.cancellable_process", - "je_auto_control.utils.canonical_log", - "je_auto_control.utils.canonical_log.*", - "je_auto_control.utils.change_localize", - "je_auto_control.utils.change_localize.*", - "je_auto_control.utils.chaos", - "je_auto_control.utils.chaos.*", - "je_auto_control.utils.chatops", - "je_auto_control.utils.chatops.*", - "je_auto_control.utils.checkpoint", - "je_auto_control.utils.checkpoint.*", - "je_auto_control.utils.checksum", - "je_auto_control.utils.checksum.*", - "je_auto_control.utils.ci_annotations", - "je_auto_control.utils.ci_annotations.*", - "je_auto_control.utils.cli_output", - "je_auto_control.utils.clipboard", - "je_auto_control.utils.clipboard.*", - "je_auto_control.utils.clipboard_files", - "je_auto_control.utils.clipboard_files.*", - "je_auto_control.utils.clipboard_formats", - "je_auto_control.utils.clipboard_formats.*", - "je_auto_control.utils.clipboard_history", - "je_auto_control.utils.clipboard_history.*", - "je_auto_control.utils.clipboard_rich_formats", - "je_auto_control.utils.clipboard_rich_formats.*", - "je_auto_control.utils.codegen", - "je_auto_control.utils.codegen.*", - "je_auto_control.utils.color_match", - "je_auto_control.utils.color_match.*", - "je_auto_control.utils.color_region", - "je_auto_control.utils.color_region.*", - "je_auto_control.utils.color_stats", - "je_auto_control.utils.color_stats.*", - "je_auto_control.utils.column_layout", - "je_auto_control.utils.column_layout.*", - "je_auto_control.utils.compliance", - "je_auto_control.utils.compliance.*", - "je_auto_control.utils.config_bundle", - "je_auto_control.utils.config_bundle.*", - "je_auto_control.utils.config_redaction", - "je_auto_control.utils.config_redaction.*", - "je_auto_control.utils.config_schema", - "je_auto_control.utils.config_schema.*", - "je_auto_control.utils.config_sync", - "je_auto_control.utils.config_sync.*", - "je_auto_control.utils.confusables", - "je_auto_control.utils.confusables.*", - "je_auto_control.utils.contrast_map", - "je_auto_control.utils.contrast_map.*", - "je_auto_control.utils.control_patterns", - "je_auto_control.utils.control_patterns.*", - "je_auto_control.utils.cookie_jar", - "je_auto_control.utils.cookie_jar.*", - "je_auto_control.utils.coordinate_space", - "je_auto_control.utils.coordinate_space.*", - "je_auto_control.utils.cost_telemetry", - "je_auto_control.utils.cost_telemetry.*", - "je_auto_control.utils.critic_features", - "je_auto_control.utils.critic_features.*", - "je_auto_control.utils.critical_exit", - "je_auto_control.utils.critical_exit.*", - "je_auto_control.utils.cua_action", - "je_auto_control.utils.cua_action.*", - "je_auto_control.utils.cv2_utils", - "je_auto_control.utils.cv2_utils.*", - "je_auto_control.utils.cvd_simulate", - "je_auto_control.utils.cvd_simulate.*", - "je_auto_control.utils.dag", - "je_auto_control.utils.dag.*", - "je_auto_control.utils.data_drift", - "je_auto_control.utils.data_drift.*", - "je_auto_control.utils.data_profile", - "je_auto_control.utils.data_profile.*", - "je_auto_control.utils.data_quality", - "je_auto_control.utils.data_quality.*", - "je_auto_control.utils.data_source", - "je_auto_control.utils.data_source.*", - "je_auto_control.utils.dataset_diff", - "je_auto_control.utils.dataset_diff.*", - "je_auto_control.utils.dbus_client", - "je_auto_control.utils.dbus_client.*", - "je_auto_control.utils.decision_table", - "je_auto_control.utils.decision_table.*", - "je_auto_control.utils.dedup_window", - "je_auto_control.utils.dedup_window.*", - "je_auto_control.utils.deprecation", - "je_auto_control.utils.deterministic", - "je_auto_control.utils.deterministic.*", - "je_auto_control.utils.device_matrix", - "je_auto_control.utils.device_matrix.*", - "je_auto_control.utils.diagnostics", - "je_auto_control.utils.diagnostics.*", - "je_auto_control.utils.dotenv", - "je_auto_control.utils.dotenv.*", - "je_auto_control.utils.edge_lines", - "je_auto_control.utils.edge_lines.*", - "je_auto_control.utils.edge_match", - "je_auto_control.utils.edge_match.*", - "je_auto_control.utils.egress", - "je_auto_control.utils.egress.*", - "je_auto_control.utils.element_diff", - "je_auto_control.utils.element_diff.*", - "je_auto_control.utils.element_parse", - "je_auto_control.utils.element_parse.*", - "je_auto_control.utils.element_proposal", - "je_auto_control.utils.element_proposal.*", - "je_auto_control.utils.element_repository", - "je_auto_control.utils.element_repository.*", - "je_auto_control.utils.element_scoring", - "je_auto_control.utils.element_scoring.*", - "je_auto_control.utils.email_send", - "je_auto_control.utils.email_send.*", - "je_auto_control.utils.ensure_state", - "je_auto_control.utils.ensure_state.*", - "je_auto_control.utils.events", - "je_auto_control.utils.events.*", - "je_auto_control.utils.exception", - "je_auto_control.utils.exception.*", - "je_auto_control.utils.executor", - "je_auto_control.utils.executor.*", - "je_auto_control.utils.expect_poll", - "je_auto_control.utils.expect_poll.*", - "je_auto_control.utils.failure_bundle", - "je_auto_control.utils.failure_bundle.*", - "je_auto_control.utils.failure_hooks", - "je_auto_control.utils.failure_hooks.*", - "je_auto_control.utils.failure_signature", - "je_auto_control.utils.failure_signature.*", - "je_auto_control.utils.feature_flags", - "je_auto_control.utils.feature_flags.*", - "je_auto_control.utils.feature_match", - "je_auto_control.utils.feature_match.*", - "je_auto_control.utils.field_entry", - "je_auto_control.utils.field_entry.*", - "je_auto_control.utils.file_assoc", - "je_auto_control.utils.file_assoc.*", - "je_auto_control.utils.file_dialog", - "je_auto_control.utils.file_dialog.*", - "je_auto_control.utils.file_drop", - "je_auto_control.utils.file_drop.*", - "je_auto_control.utils.file_process", - "je_auto_control.utils.file_process.*", - "je_auto_control.utils.flake_cluster", - "je_auto_control.utils.flake_cluster.*", - "je_auto_control.utils.flakiness", - "je_auto_control.utils.flakiness.*", - "je_auto_control.utils.flow_debugger", - "je_auto_control.utils.flow_debugger.*", - "je_auto_control.utils.focus_order", - "je_auto_control.utils.focus_order.*", - "je_auto_control.utils.form_fields", - "je_auto_control.utils.form_fields.*", - "je_auto_control.utils.fuzzy", - "je_auto_control.utils.fuzzy.*", - "je_auto_control.utils.gamepad", - "je_auto_control.utils.gamepad.*", - "je_auto_control.utils.generate_report", - "je_auto_control.utils.generate_report.*", - "je_auto_control.utils.gettext_catalog", - "je_auto_control.utils.gettext_catalog.*", - "je_auto_control.utils.governance", - "je_auto_control.utils.governance.*", - "je_auto_control.utils.grid_locator", - "je_auto_control.utils.grid_locator.*", - "je_auto_control.utils.grounding_consensus", - "je_auto_control.utils.grounding_consensus.*", - "je_auto_control.utils.guardrail", - "je_auto_control.utils.guardrail.*", - "je_auto_control.utils.heading_segment", - "je_auto_control.utils.heading_segment.*", - "je_auto_control.utils.heal_analytics", - "je_auto_control.utils.heal_analytics.*", - "je_auto_control.utils.hotkey", - "je_auto_control.utils.hotkey.*", - "je_auto_control.utils.hsv_segment", - "je_auto_control.utils.hsv_segment.*", - "je_auto_control.utils.http_cassette", - "je_auto_control.utils.http_cassette.*", - "je_auto_control.utils.http_client", - "je_auto_control.utils.http_client.*", - "je_auto_control.utils.http_conditional", - "je_auto_control.utils.http_conditional.*", - "je_auto_control.utils.http_content", - "je_auto_control.utils.http_content.*", - "je_auto_control.utils.http_headers", - "je_auto_control.utils.http_problem", - "je_auto_control.utils.http_problem.*", - "je_auto_control.utils.humanize", - "je_auto_control.utils.humanize.*", - "je_auto_control.utils.i18n_test", - "je_auto_control.utils.i18n_test.*", - "je_auto_control.utils.icon_classify", - "je_auto_control.utils.icon_classify.*", - "je_auto_control.utils.idempotency", - "je_auto_control.utils.idempotency.*", - "je_auto_control.utils.idle_keepawake", - "je_auto_control.utils.idle_keepawake.*", - "je_auto_control.utils.image_dedup", - "je_auto_control.utils.image_dedup.*", - "je_auto_control.utils.image_quality", - "je_auto_control.utils.image_quality.*", - "je_auto_control.utils.ime_state", - "je_auto_control.utils.ime_state.*", - "je_auto_control.utils.img_histogram", - "je_auto_control.utils.img_histogram.*", - "je_auto_control.utils.input_macro", - "je_auto_control.utils.input_macro.*", - "je_auto_control.utils.input_reach", - "je_auto_control.utils.input_reach.*", - "je_auto_control.utils.json", - "je_auto_control.utils.json.*", - "je_auto_control.utils.json_contract", - "je_auto_control.utils.json_contract.*", - "je_auto_control.utils.json_patch", - "je_auto_control.utils.json_patch.*", - "je_auto_control.utils.json_schema", - "je_auto_control.utils.json_schema.*", - "je_auto_control.utils.json_store", - "je_auto_control.utils.json_store.*", - "je_auto_control.utils.jsonpath", - "je_auto_control.utils.jsonpath.*", - "je_auto_control.utils.jwt", - "je_auto_control.utils.jwt.*", - "je_auto_control.utils.key_hold", - "je_auto_control.utils.key_hold.*", - "je_auto_control.utils.keyboard_layout", - "je_auto_control.utils.keyboard_layout.*", - "je_auto_control.utils.layered_config", - "je_auto_control.utils.layered_config.*", - "je_auto_control.utils.legacy_accessible", - "je_auto_control.utils.legacy_accessible.*", - "je_auto_control.utils.license_policy", - "je_auto_control.utils.license_policy.*", - "je_auto_control.utils.link_header", - "je_auto_control.utils.link_header.*", - "je_auto_control.utils.list_format", - "je_auto_control.utils.list_format.*", - "je_auto_control.utils.llm", - "je_auto_control.utils.llm.*", - "je_auto_control.utils.locale_collation", - "je_auto_control.utils.locale_collation.*", - "je_auto_control.utils.locale_parse", - "je_auto_control.utils.locale_parse.*", - "je_auto_control.utils.locator_chain", - "je_auto_control.utils.locator_chain.*", - "je_auto_control.utils.locator_repair", - "je_auto_control.utils.locator_repair.*", - "je_auto_control.utils.lock_session", - "je_auto_control.utils.lock_session.*", - "je_auto_control.utils.logging", - "je_auto_control.utils.logging.secret_scope", - "je_auto_control.utils.loop_guard", - "je_auto_control.utils.loop_guard.*", - "je_auto_control.utils.marks_layout", - "je_auto_control.utils.marks_layout.*", - "je_auto_control.utils.match_autothresh", - "je_auto_control.utils.match_autothresh.*", - "je_auto_control.utils.match_ensemble", - "je_auto_control.utils.match_ensemble.*", - "je_auto_control.utils.match_stability", - "je_auto_control.utils.match_stability.*", - "je_auto_control.utils.match_trust", - "je_auto_control.utils.match_trust.*", - "je_auto_control.utils.mcp_registry", - "je_auto_control.utils.mcp_registry.*", - "je_auto_control.utils.mcp_server", - "je_auto_control.utils.mcp_server.__main__", - "je_auto_control.utils.mcp_server._argument_policy", - "je_auto_control.utils.mcp_server._authz", - "je_auto_control.utils.mcp_server._call_authority", - "je_auto_control.utils.mcp_server._call_run", - "je_auto_control.utils.mcp_server._client_requests", - "je_auto_control.utils.mcp_server._disclosure_server", - "je_auto_control.utils.mcp_server._http_origin", - "je_auto_control.utils.mcp_server._http_responses", - "je_auto_control.utils.mcp_server._http_stateless", - "je_auto_control.utils.mcp_server._input_required", - "je_auto_control.utils.mcp_server._origin_policies", - "je_auto_control.utils.mcp_server._protocol", - "je_auto_control.utils.mcp_server._stateless", - "je_auto_control.utils.mcp_server._subscriptions", - "je_auto_control.utils.mcp_server._tool_calls", - "je_auto_control.utils.mcp_server._tool_notifications", - "je_auto_control.utils.mcp_server.audit", - "je_auto_control.utils.mcp_server.context", - "je_auto_control.utils.mcp_server.disclosure", - "je_auto_control.utils.mcp_server.discovery", - "je_auto_control.utils.mcp_server.fake_backend", - "je_auto_control.utils.mcp_server.http_sessions", - "je_auto_control.utils.mcp_server.http_transport", - "je_auto_control.utils.mcp_server.log_bridge", - "je_auto_control.utils.mcp_server.plugin_watcher", - "je_auto_control.utils.mcp_server.prompts", - "je_auto_control.utils.mcp_server.rate_limit", - "je_auto_control.utils.mcp_server.resources", - "je_auto_control.utils.mcp_server.server", - "je_auto_control.utils.mcp_server.stdio", - "je_auto_control.utils.mcp_server.tools", - "je_auto_control.utils.mcp_server.tools._agent_tasks", - "je_auto_control.utils.mcp_server.tools._base", - "je_auto_control.utils.mcp_server.tools._capabilities", - "je_auto_control.utils.mcp_server.tools._diagnostics", - "je_auto_control.utils.mcp_server.tools._discovery", - "je_auto_control.utils.mcp_server.tools._factories", - "je_auto_control.utils.mcp_server.tools._handlers_accessibility_executor", - "je_auto_control.utils.mcp_server.tools._handlers_automation_executor", - "je_auto_control.utils.mcp_server.tools._handlers_data_executor", - "je_auto_control.utils.mcp_server.tools._handlers_desktop_executor", - "je_auto_control.utils.mcp_server.tools._handlers_input", - "je_auto_control.utils.mcp_server.tools._handlers_journal", - "je_auto_control.utils.mcp_server.tools._handlers_locators", - "je_auto_control.utils.mcp_server.tools._handlers_mobile_executor", - "je_auto_control.utils.mcp_server.tools._handlers_operations", - "je_auto_control.utils.mcp_server.tools._handlers_qa", - "je_auto_control.utils.mcp_server.tools._handlers_remote", - "je_auto_control.utils.mcp_server.tools._handlers_runs", - "je_auto_control.utils.mcp_server.tools._handlers_scheduling", - "je_auto_control.utils.mcp_server.tools._handlers_screen", - "je_auto_control.utils.mcp_server.tools._handlers_system", - "je_auto_control.utils.mcp_server.tools._handlers_vision_executor", - "je_auto_control.utils.mcp_server.tools._healing_evaluation", - "je_auto_control.utils.mcp_server.tools._healing_run", - "je_auto_control.utils.mcp_server.tools._healing_source", - "je_auto_control.utils.mcp_server.tools._readonly", - "je_auto_control.utils.mcp_server.tools._template_candidates", - "je_auto_control.utils.mcp_server.tools._validation", - "je_auto_control.utils.mcp_server.tools.plugin_tools", - "je_auto_control.utils.media_assert", - "je_auto_control.utils.media_assert.*", - "je_auto_control.utils.message_format", - "je_auto_control.utils.message_format.*", - "je_auto_control.utils.modifier_state", - "je_auto_control.utils.modifier_state.*", - "je_auto_control.utils.monitor_layout", - "je_auto_control.utils.monitor_layout.*", - "je_auto_control.utils.motion_regions", - "je_auto_control.utils.motion_regions.*", - "je_auto_control.utils.mouse_path", - "je_auto_control.utils.mouse_path.*", - "je_auto_control.utils.mouse_relative", - "je_auto_control.utils.mouse_relative.*", - "je_auto_control.utils.multipart", - "je_auto_control.utils.multipart.*", - "je_auto_control.utils.near_dup", - "je_auto_control.utils.near_dup.*", - "je_auto_control.utils.notify", - "je_auto_control.utils.notify.*", - "je_auto_control.utils.notify_channels", - "je_auto_control.utils.notify_channels.*", - "je_auto_control.utils.observability", - "je_auto_control.utils.observability.*", - "je_auto_control.utils.observation", - "je_auto_control.utils.observation.*", - "je_auto_control.utils.observation_delta", - "je_auto_control.utils.observation_delta.*", - "je_auto_control.utils.observer", - "je_auto_control.utils.observer.*", - "je_auto_control.utils.ocr", - "je_auto_control.utils.ocr.*", - "je_auto_control.utils.office", - "je_auto_control.utils.office.*", - "je_auto_control.utils.optimistic", - "je_auto_control.utils.optimistic.*", - "je_auto_control.utils.otlp_export", - "je_auto_control.utils.otlp_export.*", - "je_auto_control.utils.otp", - "je_auto_control.utils.otp.*", - "je_auto_control.utils.outbox", - "je_auto_control.utils.outbox.*", - "je_auto_control.utils.package_manager", - "je_auto_control.utils.package_manager.*", - "je_auto_control.utils.path_guard", - "je_auto_control.utils.path_guard.*", - "je_auto_control.utils.pdf", - "je_auto_control.utils.pdf.*", - "je_auto_control.utils.percentiles", - "je_auto_control.utils.percentiles.*", - "je_auto_control.utils.perceptual_diff", - "je_auto_control.utils.perceptual_diff.*", - "je_auto_control.utils.pii_text", - "je_auto_control.utils.pii_text.*", - "je_auto_control.utils.platform_id", - "je_auto_control.utils.platform_id.*", - "je_auto_control.utils.plugin_loader", - "je_auto_control.utils.plugin_loader.*", - "je_auto_control.utils.plugin_sdk", - "je_auto_control.utils.plugin_sdk.*", - "je_auto_control.utils.postcondition", - "je_auto_control.utils.postcondition.*", - "je_auto_control.utils.preprocess", - "je_auto_control.utils.preprocess.*", - "je_auto_control.utils.process_doc", - "je_auto_control.utils.process_doc.*", - "je_auto_control.utils.process_memory", - "je_auto_control.utils.process_memory.*", - "je_auto_control.utils.process_mining", - "je_auto_control.utils.process_mining.*", - "je_auto_control.utils.profiler", - "je_auto_control.utils.profiler.*", - "je_auto_control.utils.project", - "je_auto_control.utils.project.*", - "je_auto_control.utils.provenance", - "je_auto_control.utils.provenance.*", - "je_auto_control.utils.pytest_plugin", - "je_auto_control.utils.pytest_plugin.*", - "je_auto_control.utils.qr", - "je_auto_control.utils.qr.*", - "je_auto_control.utils.quarantine", - "je_auto_control.utils.quarantine.*", - "je_auto_control.utils.rate_limit", - "je_auto_control.utils.rate_limit.*", - "je_auto_control.utils.rbac", - "je_auto_control.utils.rbac.*", - "je_auto_control.utils.readability", - "je_auto_control.utils.readability.*", - "je_auto_control.utils.reading_flow", - "je_auto_control.utils.reading_flow.*", - "je_auto_control.utils.recording_edit", - "je_auto_control.utils.recording_edit.*", - "je_auto_control.utils.recurrence", - "je_auto_control.utils.recurrence.*", - "je_auto_control.utils.redaction", - "je_auto_control.utils.redaction.*", - "je_auto_control.utils.referential", - "je_auto_control.utils.referential.*", - "je_auto_control.utils.remote_desktop", - "je_auto_control.utils.remote_desktop._export_bindings", - "je_auto_control.utils.remote_desktop._optional", - "je_auto_control.utils.remote_desktop._optional.*", - "je_auto_control.utils.remote_desktop.adaptive_bitrate", - "je_auto_control.utils.remote_desktop.address_book", - "je_auto_control.utils.remote_desktop.audio", - "je_auto_control.utils.remote_desktop.audio_retirement", - "je_auto_control.utils.remote_desktop.audit_log", - "je_auto_control.utils.remote_desktop.auth", - "je_auto_control.utils.remote_desktop.clipboard_delivery", - "je_auto_control.utils.remote_desktop.clipboard_sync", - "je_auto_control.utils.remote_desktop.connect_coordinator", - "je_auto_control.utils.remote_desktop.file_receipts", - "je_auto_control.utils.remote_desktop.file_sync", - "je_auto_control.utils.remote_desktop.file_transfer", - "je_auto_control.utils.remote_desktop.fingerprint", - "je_auto_control.utils.remote_desktop.host", - "je_auto_control.utils.remote_desktop.host_access", - "je_auto_control.utils.remote_desktop.host_capture", - "je_auto_control.utils.remote_desktop.host_client", - "je_auto_control.utils.remote_desktop.host_id", - "je_auto_control.utils.remote_desktop.host_service", - "je_auto_control.utils.remote_desktop.input_dispatch", - "je_auto_control.utils.remote_desktop.input_send_queue", - "je_auto_control.utils.remote_desktop.jpeg_recorder", - "je_auto_control.utils.remote_desktop.jpeg_recorder_encrypted", - "je_auto_control.utils.remote_desktop.lan_discovery", - "je_auto_control.utils.remote_desktop.media_retirement", - "je_auto_control.utils.remote_desktop.multi_viewer", - "je_auto_control.utils.remote_desktop.permissions", - "je_auto_control.utils.remote_desktop.presence", - "je_auto_control.utils.remote_desktop.protocol", - "je_auto_control.utils.remote_desktop.rate_limit", - "je_auto_control.utils.remote_desktop.registry", - "je_auto_control.utils.remote_desktop.relay", - "je_auto_control.utils.remote_desktop.resume_tokens", - "je_auto_control.utils.remote_desktop.session_actions", - "je_auto_control.utils.remote_desktop.session_quality_cache", - "je_auto_control.utils.remote_desktop.session_recorder", - "je_auto_control.utils.remote_desktop.signaling_client", - "je_auto_control.utils.remote_desktop.signaling_server", - "je_auto_control.utils.remote_desktop.totp", - "je_auto_control.utils.remote_desktop.transport", - "je_auto_control.utils.remote_desktop.trust_list", - "je_auto_control.utils.remote_desktop.turn_config", - "je_auto_control.utils.remote_desktop.video_codec", - "je_auto_control.utils.remote_desktop.viewer", - "je_auto_control.utils.remote_desktop.viewer_id", - "je_auto_control.utils.remote_desktop.wake_on_lan", - "je_auto_control.utils.remote_desktop.webrtc_audio", - "je_auto_control.utils.remote_desktop.webrtc_file_callbacks", - "je_auto_control.utils.remote_desktop.webrtc_file_commit", - "je_auto_control.utils.remote_desktop.webrtc_file_receive", - "je_auto_control.utils.remote_desktop.webrtc_file_tasks", - "je_auto_control.utils.remote_desktop.webrtc_file_write", - "je_auto_control.utils.remote_desktop.webrtc_files", - "je_auto_control.utils.remote_desktop.webrtc_host", - "je_auto_control.utils.remote_desktop.webrtc_host_auth", - "je_auto_control.utils.remote_desktop.webrtc_host_media", - "je_auto_control.utils.remote_desktop.webrtc_inspector", - "je_auto_control.utils.remote_desktop.webrtc_media_owners", - "je_auto_control.utils.remote_desktop.webrtc_mic", - "je_auto_control.utils.remote_desktop.webrtc_peer_cleanup", - "je_auto_control.utils.remote_desktop.webrtc_retirement", - "je_auto_control.utils.remote_desktop.webrtc_stats", - "je_auto_control.utils.remote_desktop.webrtc_transport", - "je_auto_control.utils.remote_desktop.webrtc_viewer", - "je_auto_control.utils.remote_desktop.ws_host", - "je_auto_control.utils.remote_desktop.ws_protocol", - "je_auto_control.utils.remote_desktop.ws_viewer", - "je_auto_control.utils.resilience", - "je_auto_control.utils.resilience.*", - "je_auto_control.utils.rest_api", - "je_auto_control.utils.rest_api.*", - "je_auto_control.utils.retry_budget", - "je_auto_control.utils.retry_budget.*", - "je_auto_control.utils.rich_clipboard", - "je_auto_control.utils.rich_clipboard.*", - "je_auto_control.utils.rotated_match", - "je_auto_control.utils.rotated_match.*", - "je_auto_control.utils.run_diff", - "je_auto_control.utils.run_diff.*", - "je_auto_control.utils.run_history", - "je_auto_control.utils.run_history.*", - "je_auto_control.utils.saga", - "je_auto_control.utils.saga.*", - "je_auto_control.utils.saliency", - "je_auto_control.utils.saliency.*", - "je_auto_control.utils.sarif", - "je_auto_control.utils.sarif.*", - "je_auto_control.utils.sbom", - "je_auto_control.utils.sbom.*", - "je_auto_control.utils.scale_detect", - "je_auto_control.utils.scale_detect.*", - "je_auto_control.utils.scheduler", - "je_auto_control.utils.scheduler.*", - "je_auto_control.utils.schema_compat", - "je_auto_control.utils.schema_compat.*", - "je_auto_control.utils.screen_grid", - "je_auto_control.utils.screen_grid.*", - "je_auto_control.utils.screen_state", - "je_auto_control.utils.screen_state.*", - "je_auto_control.utils.script_vars", - "je_auto_control.utils.script_vars.*", - "je_auto_control.utils.scroll_find", - "je_auto_control.utils.scroll_find.*", - "je_auto_control.utils.search_index", - "je_auto_control.utils.search_index.*", - "je_auto_control.utils.secret_ref", - "je_auto_control.utils.secret_ref.*", - "je_auto_control.utils.secrets", - "je_auto_control.utils.secrets.*", - "je_auto_control.utils.secrets_scan", - "je_auto_control.utils.secrets_scan.*", - "je_auto_control.utils.selection_view", - "je_auto_control.utils.selection_view.*", - "je_auto_control.utils.self_healing", - "je_auto_control.utils.self_healing.*", - "je_auto_control.utils.semantic_recording", - "je_auto_control.utils.semantic_recording.*", - "je_auto_control.utils.sequence_gap", - "je_auto_control.utils.sequence_gap.*", - "je_auto_control.utils.session_guard", - "je_auto_control.utils.session_guard.*", - "je_auto_control.utils.set_of_marks", - "je_auto_control.utils.set_of_marks.*", - "je_auto_control.utils.settle_detector", - "je_auto_control.utils.settle_detector.*", - "je_auto_control.utils.shape_locator", - "je_auto_control.utils.shape_locator.*", - "je_auto_control.utils.shell_open", - "je_auto_control.utils.shell_open.*", - "je_auto_control.utils.shell_process", - "je_auto_control.utils.shell_process.*", - "je_auto_control.utils.skill_library", - "je_auto_control.utils.skill_library.*", - "je_auto_control.utils.slo", - "je_auto_control.utils.slo.*", - "je_auto_control.utils.smart_waits", - "je_auto_control.utils.smart_waits.*", - "je_auto_control.utils.smoothing", - "je_auto_control.utils.smoothing.*", - "je_auto_control.utils.socket_server", - "je_auto_control.utils.socket_server.*", - "je_auto_control.utils.soft_assert", - "je_auto_control.utils.soft_assert.*", - "je_auto_control.utils.sql", - "je_auto_control.utils.sql.*", - "je_auto_control.utils.sqlite_support", - "je_auto_control.utils.sse_client", - "je_auto_control.utils.sse_client.*", - "je_auto_control.utils.ssim", - "je_auto_control.utils.ssim.*", - "je_auto_control.utils.start_exe", - "je_auto_control.utils.start_exe.*", - "je_auto_control.utils.state_machine", - "je_auto_control.utils.state_machine.*", - "je_auto_control.utils.stats", - "je_auto_control.utils.stats.*", - "je_auto_control.utils.step_repair", - "je_auto_control.utils.step_repair.*", - "je_auto_control.utils.step_timeline", - "je_auto_control.utils.step_timeline.*", - "je_auto_control.utils.stubs", - "je_auto_control.utils.stubs.*", - "je_auto_control.utils.subpixel_match", - "je_auto_control.utils.subpixel_match.*", - "je_auto_control.utils.system_volume", - "je_auto_control.utils.system_volume.*", - "je_auto_control.utils.table_grid_fill", - "je_auto_control.utils.table_pattern", - "je_auto_control.utils.table_pattern.*", - "je_auto_control.utils.test_data", - "je_auto_control.utils.test_data.*", - "je_auto_control.utils.test_record", - "je_auto_control.utils.test_record.*", - "je_auto_control.utils.test_select", - "je_auto_control.utils.test_select.*", - "je_auto_control.utils.test_shard", - "je_auto_control.utils.test_shard.*", - "je_auto_control.utils.test_suite", - "je_auto_control.utils.test_suite.*", - "je_auto_control.utils.text_blocks", - "je_auto_control.utils.text_blocks.*", - "je_auto_control.utils.text_diff", - "je_auto_control.utils.text_diff.*", - "je_auto_control.utils.text_normalize", - "je_auto_control.utils.text_normalize.*", - "je_auto_control.utils.text_regions", - "je_auto_control.utils.text_regions.*", - "je_auto_control.utils.text_similarity", - "je_auto_control.utils.text_similarity.*", - "je_auto_control.utils.text_unicode", - "je_auto_control.utils.text_unicode.*", - "je_auto_control.utils.theme_normalize", - "je_auto_control.utils.theme_normalize.*", - "je_auto_control.utils.thread_bound", - "je_auto_control.utils.time_travel", - "je_auto_control.utils.time_travel.*", - "je_auto_control.utils.timeouts", - "je_auto_control.utils.timeseries", - "je_auto_control.utils.timeseries.*", - "je_auto_control.utils.tls_acme", - "je_auto_control.utils.tls_acme.*", - "je_auto_control.utils.tool_use_schema", - "je_auto_control.utils.trace_context", - "je_auto_control.utils.trace_context.*", - "je_auto_control.utils.trajectory_eval", - "je_auto_control.utils.trajectory_eval.*", - "je_auto_control.utils.transform_window", - "je_auto_control.utils.transform_window.*", - "je_auto_control.utils.trash", - "je_auto_control.utils.trash.*", - "je_auto_control.utils.triggers", - "je_auto_control.utils.triggers.*", - "je_auto_control.utils.tween_drag", - "je_auto_control.utils.tween_drag.*", - "je_auto_control.utils.url_canon", - "je_auto_control.utils.url_canon.*", - "je_auto_control.utils.usb", - "je_auto_control.utils.usb.*", - "je_auto_control.utils.usbip", - "je_auto_control.utils.usbip.*", - "je_auto_control.utils.verify_field", - "je_auto_control.utils.verify_field.*", - "je_auto_control.utils.vex", - "je_auto_control.utils.vex.*", - "je_auto_control.utils.video_report", - "je_auto_control.utils.video_report.*", - "je_auto_control.utils.virtualized", - "je_auto_control.utils.virtualized.*", - "je_auto_control.utils.vision", - "je_auto_control.utils.vision.backends", - "je_auto_control.utils.vision.backends._parse", - "je_auto_control.utils.vision.backends.base", - "je_auto_control.utils.vision.backends.null_backend", - "je_auto_control.utils.vision.frame_capture", - "je_auto_control.utils.vision.vlm_api", - "je_auto_control.utils.visual_match", - "je_auto_control.utils.visual_match.*", - "je_auto_control.utils.visual_regression", - "je_auto_control.utils.visual_regression.*", - "je_auto_control.utils.voice", - "je_auto_control.utils.voice.*", - "je_auto_control.utils.vuln_scan", - "je_auto_control.utils.vuln_scan.*", - "je_auto_control.utils.watchdog", - "je_auto_control.utils.watchdog.*", - "je_auto_control.utils.watcher", - "je_auto_control.utils.watcher.*", - "je_auto_control.utils.webrunner_bridge", - "je_auto_control.utils.webrunner_bridge.*", - "je_auto_control.utils.window_capture", - "je_auto_control.utils.window_capture.*", - "je_auto_control.utils.window_geometry", - "je_auto_control.utils.window_geometry.*", - "je_auto_control.utils.window_layout", - "je_auto_control.utils.window_layout.*", - "je_auto_control.utils.window_zorder", - "je_auto_control.utils.window_zorder.*", - "je_auto_control.utils.work_queue", - "je_auto_control.utils.work_queue.*", - "je_auto_control.utils.xml", - "je_auto_control.utils.xml.*", - "je_auto_control.windows", - "je_auto_control.windows.*", - "je_auto_control.wrapper", - "je_auto_control.wrapper._input_observer", - "je_auto_control.wrapper._platform_linux", - "je_auto_control.wrapper._platform_osx", - "je_auto_control.wrapper._platform_wayland", - "je_auto_control.wrapper._platform_windows", - "je_auto_control.wrapper.auto_control_image", - "je_auto_control.wrapper.auto_control_keyboard", - "je_auto_control.wrapper.auto_control_mouse", - "je_auto_control.wrapper.auto_control_record", - "je_auto_control.wrapper.auto_control_screen", - "je_auto_control.wrapper.auto_control_window", - "je_auto_control.wrapper.capabilities", - "je_auto_control.wrapper.device_context", - "je_auto_control.wrapper.device_frame", - "je_auto_control.wrapper.mobile_commands", - "je_auto_control.wrapper.mobile_extensions", - "je_auto_control.wrapper.platform_wrapper", - "je_auto_control.wrapper.window_backends", - "je_auto_control.wrapper.window_backends.*", + "je_auto_control.*", "je_auto_control_pytest", ] disallow_untyped_defs = true diff --git a/test/unit_test/headless/test_parsers_and_codecs_audit.py b/test/unit_test/headless/test_parsers_and_codecs_audit.py index 636eca4a3..e686efa4e 100644 --- a/test/unit_test/headless/test_parsers_and_codecs_audit.py +++ b/test/unit_test/headless/test_parsers_and_codecs_audit.py @@ -158,3 +158,15 @@ def close(self): provider._stream, provider._container = _Stream(), _Container() provider.close() assert closed == [True] + + +@pytest.mark.parametrize("bit_rate", [None, 0]) +def test_an_unset_encoder_bit_rate_reopens_instead_of_raising(bit_rate): + """PyAV reports an unset bit rate as None; dividing by it raised TypeError.""" + pytest.importorskip("av") + from je_auto_control.utils.remote_desktop import hw_codec + frame = types.SimpleNamespace(width=640, height=480) + codec = types.SimpleNamespace(width=640, height=480, bit_rate=bit_rate) + assert hw_codec._shape_changed(codec, frame, 1_000_000) is True + assert hw_codec._shape_changed(types.SimpleNamespace(width=640, height=480, bit_rate=1_000_000), + frame, 1_050_000) is False diff --git a/test/unit_test/headless/test_tween_drag_batch.py b/test/unit_test/headless/test_tween_drag_batch.py index 221fa5442..424212182 100644 --- a/test/unit_test/headless/test_tween_drag_batch.py +++ b/test/unit_test/headless/test_tween_drag_batch.py @@ -51,3 +51,13 @@ def test_facade_exports(): for attr in ("tween_points", "tween_drag", "easing_names"): assert hasattr(ac, attr) assert attr in ac.__all__ + + +def test_the_mcp_handler_wants_two_coordinates_per_point(): + """``tuple(start)`` passed a three-value point on, which failed deep in the path maths.""" + import pytest + from je_auto_control.utils.mcp_server.tools import _handlers + with pytest.raises(ValueError, match="start must be"): + _handlers.tween_drag([1, 2, 3], [4, 5]) + with pytest.raises(ValueError, match="end must be"): + _handlers.tween_drag([1, 2], [4]) diff --git a/test/verify/typing_strict_baseline.txt b/test/verify/typing_strict_baseline.txt index 15d462df7..e38ec650d 100644 --- a/test/verify/typing_strict_baseline.txt +++ b/test/verify/typing_strict_baseline.txt @@ -13,17 +13,3 @@ # * A deleted or renamed module loses its line in the same change; a module # written later under the same name is new and therefore strict. # -je_auto_control.android.client -je_auto_control.gui.vlm_tab -je_auto_control.ios.client -je_auto_control.linux_wayland.libei -je_auto_control.utils.accessibility.accessibility_api -je_auto_control.utils.actionability.actionability -je_auto_control.utils.logging.logging_instance -je_auto_control.utils.mcp_server.tools._handlers -je_auto_control.utils.remote_desktop.hw_codec -je_auto_control.utils.table_grid_fill.table_grid_fill -je_auto_control.utils.tool_use_schema.schema -je_auto_control.utils.vision.backends.anthropic_backend -je_auto_control.utils.vision.backends.openai_backend -je_auto_control.wrapper.backend_contract From b9b6226443215a43d35a2c943ccbc356e15f5f05 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 17:08:56 +0800 Subject: [PATCH 134/161] Mark the dashboard asset write as a reviewed taint false positive SonarCloud's next analysis traced the same S5131 issue from read_bytes() itself: the rule treats any file's content as tainted, so serving a packaged asset always reaches the sink. The request can only pick a name from the table of shipped files. --- architecture_explore.md | 14 +++++++------- docs/updates/2026-11-b.md | 1 + je_auto_control/utils/rest_api/rest_server.py | 4 +++- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/architecture_explore.md b/architecture_explore.md index d9592659c..2d393f9b0 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 238,099 | +| 程式碼總行數 | 238,101 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,591 行。 +> 24 個套件、約 7,593 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -584,7 +584,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/otp/` | 37 | TOTP 一次性密碼產生(自動化 2FA 登入) | | `utils/outbox/` | 107 | 交易式 outbox,保證至少一次的事件投遞 | | `utils/pytest_plugin/` | 283 | pytest 外掛 + BDD step library(`pytest11` entry point) | -| `utils/rest_api/` | 2,234 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | +| `utils/rest_api/` | 2,236 | 純標準庫 REST 前端:路由、Bearer 驗證、限流、Prometheus 指標、OpenAPI 3.1 產生 | | `utils/socket_server/` | 164 | 執行 action JSON 的執行緒式 TCP 指令伺服器(預設綁 127.0.0.1) | | `utils/sse_client/` | 142 | Server-Sent Events 用戶端解析 | | `utils/tls_acme/` | 475 | TLS 自動化:HTTP-01 挑戰伺服器、金鑰/CSR、自動續期 | @@ -906,11 +906,11 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `usbip/libusb_backend.py` | 224 | 以 PyUSB/libusb 執行 URB 的正式後端。 | | `usbip/backend.py` | 87 | 可插拔 URB 執行後端。 | -#### `utils/rest_api/`(2,234 行) +#### `utils/rest_api/`(2,236 行) | 檔案 | 行數 | 職責 | | --- | ---: | --- | -| `rest_server.py` | 719 | HTTP 前端主體;相容 check-only gate,RBAC 必須帶使用者身分。 | +| `rest_server.py` | 721 | HTTP 前端主體;相容 check-only gate,RBAC 必須帶使用者身分。 | | `rest_handlers.py` | 539 | 端點實作。 | | `rest_openapi.py` | 503 | 走訪路由表產生 OpenAPI 3.1 規格。 | | `rest_auth.py` | 227 | Bearer token 驗證 + 逐 client 限流閘門。 | @@ -1558,7 +1558,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/accessibility/` | 16 | 3,384 | | `wrapper/` | 25 | 6,065 | | `windows/` | 24 | 2,363 | -| `utils/rest_api/` | 8 | 2,234 | +| `utils/rest_api/` | 8 | 2,236 | | `utils/agent/` | 13 | 2,254 | | `linux_with_x11/` | 19 | 1,382 | | `linux_wayland/` | 24 | 4,455 | @@ -1570,7 +1570,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,724 | -| **總計** | **1,533** | **237,354** | +| **總計** | **1,533** | **237,356** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 39f0250dd..05c1dd9a2 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -760,6 +760,7 @@ - **Change:** `_dashboard_assets()` reads every file in `dashboard/` with a known type once (`lru_cache`) into name → (body, MIME type); `_load_dashboard_asset()` only looks the requested name up, so traversal, hidden files, sub-directories and `.py` files are names missing from the table. Dashboard responses add `X-Content-Type-Options: nosniff`. The name regex and the `re` import are gone. - **Tests:** `test_dashboard.py` gains two (the table is exactly the shipped assets; `nosniff` is sent); with the REST OpenAPI and route-sweep tests, the typing contract, complexity and broad-except gates: 217 passed. - **Files:** `utils/rest_api/rest_server.py`, `test_dashboard.py`, `architecture_explore.md` (re-measured), `CHANGELOG.md`. +- **Follow-up:** the next analysis kept the same issue and moved its source to `read_bytes()` itself: the rule treats the content of any file read as tainted, so serving a packaged file always reaches the sink. The sink carries `# NOSONAR pythonsecurity:S5131` with the reason; the request still only picks a name from the table. ## U-20261115-16 · 2026-11-15 · The last 14 modules join the strict tier: the whole package is strict · #done #typing diff --git a/je_auto_control/utils/rest_api/rest_server.py b/je_auto_control/utils/rest_api/rest_server.py index 78c0c9207..61d22cbd2 100644 --- a/je_auto_control/utils/rest_api/rest_server.py +++ b/je_auto_control/utils/rest_api/rest_server.py @@ -161,7 +161,9 @@ def _serve_dashboard(self, path: str) -> None: # Static assets — safe to cache briefly inside the same session. self.send_header("Cache-Control", "private, max-age=60") self.end_headers() - self.wfile.write(body) + # body is one of the files shipped in dashboard/, read once into _dashboard_assets(); + # the request only picks a name from that table, so it cannot choose the content. + self.wfile.write(body) # NOSONAR pythonsecurity:S5131 # reason: packaged static asset, see above self._metrics().record_request("GET", _PATH_DASHBOARD, status) def _serve_metrics(self) -> None: From b3c346b692766ac1b1454fe7317584f22f2937fa Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 17:57:11 +0800 Subject: [PATCH 135/161] Give process-memory resolvers a bounded view of the retained handle A resolver saw only the process identity, so it could not find a module base that moves between launches or check that reported locations belong to the process being read. Its reads now go through the reader's checked, budgeted path, the main image is measured from the retained handle, and a failure from the reader's own checks cannot be swallowed into a plan. --- Progress.md | 3 +- architecture_explore.md | 20 ++-- docs/process_memory_contract.md | 18 ++- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + .../utils/process_memory/models.py | 24 +++- .../utils/process_memory/reader.py | 77 +++++++++++-- .../utils/process_memory/windows.py | 36 +++++- .../utils/process_memory/windows_native.py | 10 ++ .../headless/test_process_memory_reader.py | 104 +++++++++++++++++- .../headless/test_process_memory_windows.py | 63 ++++++++++- 11 files changed, 331 insertions(+), 33 deletions(-) diff --git a/Progress.md b/Progress.md index 9c787aa09..0528b99d9 100644 --- a/Progress.md +++ b/Progress.md @@ -640,8 +640,9 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報資訊,不能充當 OS 出生身分或可信 resolver。 typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 handle 的注入測試; 應用身分仍須由明確受審的 attestor 提供,沒有預設信任或由期望身分反填的實作。 +resolver 已能透過保留 handle 取得主映像基址與大小並做有預算的讀取(U-20261115-17,維護者 2026-11-15 選定有界 view;只有注入測試)。 仍缺實際載入映像與啟動關係綁定、受審 runtime/固定程式碼交付、可信 executable/version attestor、 -ASLR resolver、fixture 的原生身分核對與頁面故障注入、runtime grant/helper +fixture 標頭挑戰(父程序給的 nonce 寫進 fixture 自己的記憶體,經 view 讀回比對)、fixture 的原生身分核對與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 diff --git a/architecture_explore.md b/architecture_explore.md index 2d393f9b0..03a6105b1 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 238,101 | +| 程式碼總行數 | 238,222 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,867 行。 +> 15 個套件、約 4,988 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -340,7 +340,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 198 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | -| `utils/process_memory/` | 1,063 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測與失敗 handle 回收;檔案證據不等於載入程式碼身分,可信啟動及 runtime 整合待完成 | +| `utils/process_memory/` | 1,184 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測與失敗 handle 回收;檔案證據不等於載入程式碼身分,可信啟動及 runtime 整合待完成 | | `utils/shell_process/` | 280 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -731,18 +731,18 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 上表以子套件為單位;以下把行數最大的幾個子系統展開到檔案層。 -#### `utils/process_memory/`(1,063 行/8 檔) +#### `utils/process_memory/`(1,184 行/8 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `__init__.py` | 1 | Internal reviewed process observations; no native provider or public command registration. | -| `models.py` | 181 | Closed identities, reviewed probes and safe semantic observation results. | -| `reader.py` | 253 | Adapter-owned semantic observations with bounded reads and retained cleanup ownership. | -| `windows.py` | 162 | Owned Windows read handles with measured native facts and reviewed application attestation. | +| `models.py` | 203 | Closed identities, reviewed probes and safe semantic observation results. | +| `reader.py` | 310 | Adapter-owned semantic observations with bounded reads and retained cleanup ownership. | +| `windows.py` | 194 | Owned Windows read handles with measured native facts and reviewed application attestation. | | `windows_facts.py` | 55 | Measure native birth, session and architecture through a retained process handle. | | `windows_image.py` | 246 | Observe an image file while retaining its process and deny-write/delete file leases. | | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | -| `windows_native.py` | 103 | Typed Win32 query/read bindings and caller-sized memory information layouts. | +| `windows_native.py` | 113 | Typed Win32 query/read bindings and caller-sized memory information layouts. | #### `utils/executor/`(10,765 行)— 執行核心 @@ -1569,8 +1569,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,724 | -| **總計** | **1,533** | **237,356** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,845 | +| **總計** | **1,533** | **237,477** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index a6b61ba65..ac06259d1 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -132,7 +132,23 @@ The reviewed resolver runs anew for each observation. It supplies one private payload range and optionally an eight-byte sequence range. A native adapter must resolve its current module/fixture location from the retained target relationship; it cannot cache an absolute address across launches or trust a path string as -executable identity. That native resolution remains unimplemented. +executable identity. + +The resolver is called as `resolve(identity, view)`. The view is its only reach +into the target and is valid for that one call; afterwards every call on it fails. +`view.read(address, size)` goes through the same checked path as payload reads and +is charged to the same byte, region and deadline budget. `view.main_module()` +returns a `ModuleSpan` (base and size, hidden from representations) measured from +the retained handle: on Windows the first module `K32EnumProcessModulesEx` lists, +which Microsoft documents as the executable, with `LIST_MODULES_32BIT` for a WOW64 +target seen from a 64-bit caller, and `K32GetModuleInformation` repeating the same +base. The reader then requires that base to start the allocation of a committed, +readable mapping. A failure raised by the reader's own checks inside the view +(budget, deadline, changed target, the live checkpoint) is kept and raised again +after `resolve` returns, so a resolver that catches it cannot still produce a plan. +Only injected tests exercise this; native module resolution is unverified, and the +fixture header challenge that would bind bootstrap locations to the retained +process is not implemented yet. The reader visits only intersecting regions. Each region must be committed, readable and unguarded. Addresses, lengths and pointer-width arithmetic are diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 05c1dd9a2..ae4308a2d 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -769,3 +769,11 @@ - **Found:** `hw_codec._shape_changed` divided by PyAV's `bit_rate`, which is `None` (or 0) when unset: the next frame raised `TypeError` / `ZeroDivisionError`; an unset rate now counts as changed, so the encoder is reopened at the target rate, and the comparison multiplies instead of dividing. The MCP `tween_drag` handler passed `tuple(start)` on, so a three-value point failed inside the path maths; `_xy()` raises `ValueError` naming the argument, and the `ac_tween_drag` schema says `minItems`/`maxItems` 2. `MouseKeycode` was `Any` and its comment said macOS used ints: macOS button codes are strings (`"Left"`), and the macOS backend and `DarwinMouseBackend` declared `mouse_button: int` while comparing against them. `MouseKeycode` is now spelt per platform with literal `sys.platform` checks (the only form mypy narrows; `platform_id` stays the run-time decision); `platform_wrapper` takes each backend's table as `Any` and gives it the contract on the way out, as it already did for `keyboard` and `mouse`; `mouse_preprocess` and the `AC_mouse_*` aliases carry the type. The generated `actions.pyi` was stale (bare `dict`/`list` from before the sources were typed) and fell under the strict tier with the package; it is regenerated (876 signatures). - **Tests:** two new: an unset encoder bit rate reopens (`test_parsers_and_codecs_audit.py`; fails on the old division), and the MCP handler's two-coordinate check (`test_tween_drag_batch.py`). The tests for every changed module, the MCP adapter sweep, the stub generator, the typing contract and the complexity and broad-except gates: 2,333 passed, 25 skipped. `typing_contract_verify.py` with and without `--extras`: 0 modules failing on win32, linux and darwin. - **Files:** the 14 modules, `linux_wayland/oeffis.py`, `osx/mouse/osx_mouse.py`, `wrapper/{platform_wrapper,auto_control_mouse}.py`, `utils/executor/{action_executor,mouse_aliases}.py`, `utils/mcp_server/tools/_factories.py`, `actions.pyi`, `pyproject.toml`, both typing lists, the two tests, `architecture_explore.md` (re-measured), `CHANGELOG.md`, `Progress.md`. + +## U-20261115-17 · 2026-11-15 · Process-memory resolvers get a bounded view of the retained handle · #done #process-memory + +- **What:** `Progress.md` › process-memory observation listed an ASLR resolver as missing. A reviewed probe's resolver received only the process identity, so it could neither find a module base that moves between launches nor confirm that bootstrap-reported locations belong to the process the reader holds. The maintainer chose (2026-11-15) a bounded view over keeping resolvers identity-only or pausing the track. +- **Change:** `ReviewedProbe.resolve` is now `resolve(identity, view)`. `ResolverView` offers `read(address, size)`, through the reader's checked read path and charged to the probe's byte, region and deadline budget, and `main_module()`, a `ModuleSpan` the reader binds to the mapping it claims (the base must start a committed, readable allocation). The view is dead once `resolve` returns. A failure from the reader's own checks inside the view is recorded and raised again after `resolve`, so a resolver that swallows a budget, deadline or checkpoint failure cannot still return a plan; checkpoint authority errors keep their identity. `WindowsProcessHandle.main_module()` takes the first module `K32EnumProcessModulesEx` lists (Microsoft documents it as the executable; `LIST_MODULES_32BIT` for a WOW64 target from a 64-bit caller) and requires `K32GetModuleInformation` to repeat its base; access denied stays `ACCESS_DENIED`, anything else unmeasurable is `UNREADABLE_REGION`. The resolve step moved out of `_collect` into `_resolve()` (complexity limit), and the reader's `_fail` is `NoReturn`. +- **Tests:** `test_process_memory_reader.py` (budgeted view reads, a swallowed budget failure, a swallowed checkpoint failure, main-module binding, a view kept past `resolve`) and `test_process_memory_windows.py` (the PSAPI calls and their signatures, the WOW64 filter, five fail-closed cases, an image-relative plan end to end); with the image and fixture tests and the typing, complexity and broad-except gates: 228 passed. Injected native calls only; nothing ran against a real process. +- **Files:** `utils/process_memory/{models,reader,windows,windows_native}.py`, both tests, `docs/process_memory_contract.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** `Progress.md` › process-memory observation (the fixture header challenge, attestation, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index e9e1d8ad4..268b3f7bb 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-17 | 2026-11-15 | Process-memory resolvers get a bounded view of the retained handle | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-16 | 2026-11-15 | The last 14 modules join the strict tier: the whole package is strict | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-15 | 2026-11-15 | Dashboard assets served from a table, not a request-chosen path | #done #security #rest-api | [2026-11-b](2026-11-b.md) | | U-20261115-14 | 2026-11-15 | The 18 largest modules typed; a non-string WebRTC control type is ignored | #done #typing #remote-desktop | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/process_memory/models.py b/je_auto_control/utils/process_memory/models.py index db7cd55b8..ab443e744 100644 --- a/je_auto_control/utils/process_memory/models.py +++ b/je_auto_control/utils/process_memory/models.py @@ -107,6 +107,26 @@ class ReadPlan: sequence_address: int | None = field(default=None, repr=False) +@dataclass(frozen=True) +class ModuleSpan: + """The target's main executable image as mapped now, measured from the retained handle.""" + + base: int = field(repr=False) + size: int = field(repr=False) + + +class ResolverView(Protocol): + """A resolver's only reach into the target, valid for one ``resolve`` call. + + Both calls go through the retained handle under the probe's byte, region + and deadline budget; nothing else about the process is exposed. + """ + + def main_module(self) -> ModuleSpan: ... + + def read(self, address: int, size: int) -> bytes: ... + + @dataclass(frozen=True) class ReviewedProbe: """Immutable host-owned ceiling and trusted version-specific resolver/decoder.""" @@ -121,7 +141,7 @@ class ReviewedProbe: max_regions: int timeout: float max_value_bytes: int - resolve: Callable[[ProcessIdentity], ReadPlan] = field(repr=False, compare=False) + resolve: Callable[[ProcessIdentity, ResolverView], ReadPlan] = field(repr=False, compare=False) decode: Callable[[bytes, tuple[str, ...]], Mapping[str, Scalar]] = field(repr=False, compare=False) def __post_init__(self) -> None: @@ -146,6 +166,8 @@ def query_region(self, address: int) -> MemoryRegion: ... def read(self, address: int, size: int) -> bytes: ... + def main_module(self) -> ModuleSpan: ... + def close(self) -> None: ... diff --git a/je_auto_control/utils/process_memory/reader.py b/je_auto_control/utils/process_memory/reader.py index 18059084e..14ed3c38a 100644 --- a/je_auto_control/utils/process_memory/reader.py +++ b/je_auto_control/utils/process_memory/reader.py @@ -4,14 +4,14 @@ from dataclasses import dataclass import threading import time -from typing import Callable, Mapping, TypeVar +from typing import Callable, Mapping, NoReturn, TypeVar from uuid import uuid4 from je_auto_control.utils.exception.cancellation import cancellation_checkpoint from je_auto_control.utils.exception.control_signals import raise_if_run_interrupted from je_auto_control.utils.executor.run_control import ExecutionStopped from je_auto_control.utils.process_memory.models import ( - FailureReason, MemoryObservationError, MemoryRegion, Observation, ObservationFailure, + FailureReason, MemoryObservationError, MemoryRegion, ModuleSpan, Observation, ObservationFailure, ObservationResult, ProcessHandle, ProcessIdentity, ProcessProvider, ReadPlan, ReviewedProbe, Scalar, _identifier, ) @@ -42,7 +42,7 @@ def _provider_call(call: Callable[[], _T]) -> _T: raise _ObservationFailed(reason) from None -def _fail(reason: FailureReason) -> None: +def _fail(reason: FailureReason) -> NoReturn: raise _ObservationFailed(reason) @@ -122,6 +122,69 @@ def read(self, handle: ProcessHandle, address: int, size: int) -> bytes: return bytes(collected) + def module(self, handle: ProcessHandle) -> ModuleSpan: + """The main image, bound to the mapping it claims: its base must start an allocation.""" + self.identity(handle) + value = _provider_call(handle.main_module) + self.check() + if not isinstance(value, ModuleSpan): + _fail(FailureReason.UNREADABLE_REGION) + _range(value.base, value.size, self.expected.pointer_bits) + if self.region(handle, value.base).allocation != value.base: + _fail(FailureReason.TARGET_CHANGED) + self.identity(handle) + return value + + +class _ResolverView: + """Budgeted reads and the measured main module for one ``resolve`` call, then nothing. + + A failure raised by the reader's own checks (budget, deadline, changed + target, the live checkpoint) is kept, so a resolver that catches it cannot + turn it into a plan: the reader raises it again once ``resolve`` returns. + """ + + def __init__(self, operation: _Operation, handle: ProcessHandle) -> None: + self._operation, self._handle = operation, handle + self.failure: BaseException | None = None + self.live = True + + def _call(self, call: Callable[[], _T]) -> _T: + if not self.live: + _fail(FailureReason.UNSUPPORTED) + try: + return call() + except BaseException as error: # reason: recorded and re-raised by the reader after resolve() + if self.failure is None: + self.failure = error + raise + + def main_module(self) -> ModuleSpan: + return self._call(lambda: self._operation.module(self._handle)) + + def read(self, address: int, size: int) -> bytes: + return self._call(lambda: self._operation.read(self._handle, address, size)) + + +def _resolve(operation: _Operation, handle: ProcessHandle) -> ReadPlan: + """Run the reviewed resolver with a one-call view; a failure of the reader's own checks wins.""" + view = _ResolverView(operation, handle) + try: + plan = operation.probe.resolve(operation.expected, view) + except Exception as error: # reason: resolver failures must not disclose private addresses + if view.failure is None: + _preserve_interruption(error) + raise _ObservationFailed(FailureReason.UNSUPPORTED) from None + plan = None + finally: + view.live = False + if view.failure is not None: + raise view.failure + if not isinstance(plan, ReadPlan): + _fail(FailureReason.UNSUPPORTED) + return plan + + def _values(decoded: Mapping[str, Scalar], fields: tuple[str, ...], limit: int) -> tuple[tuple[str, Scalar], ...]: if set(decoded) != set(fields): _fail(FailureReason.DECODE_FAILED) @@ -223,13 +286,7 @@ def _collect(self, handle: ProcessHandle, operation: _Operation, fields: tuple[s target_id: str, started: float) -> Observation: operation.identity(handle) probe = operation.probe - try: - plan = probe.resolve(operation.expected) - except Exception as error: # reason: resolver failures must not disclose private addresses - _preserve_interruption(error) - raise _ObservationFailed(FailureReason.UNSUPPORTED) from None - if not isinstance(plan, ReadPlan): - _fail(FailureReason.UNSUPPORTED) + plan = _resolve(operation, handle) operation.check() before: bytes | None = None if plan.sequence_address is not None: diff --git a/je_auto_control/utils/process_memory/windows.py b/je_auto_control/utils/process_memory/windows.py index 0d9e74f69..802a7f4c0 100644 --- a/je_auto_control/utils/process_memory/windows.py +++ b/je_auto_control/utils/process_memory/windows.py @@ -5,13 +5,16 @@ import threading from typing import Callable, NoReturn -from .models import FailureReason, MemoryObservationError, MemoryRegion, ProcessIdentity -from .windows_native import Kernel, MemoryInfo32, MemoryInfo64, SIZE, bind, load +from .models import FailureReason, MemoryObservationError, MemoryRegion, ModuleSpan, ProcessIdentity +from .windows_native import PTR, U32, Kernel, MemoryInfo32, MemoryInfo64, ModuleInfo, SIZE, bind, load from .windows_facts import NativeProcessFacts as NativeProcessFacts, measure_process _ACCESS = 0x00100000 | 0x0400 | 0x0010 _READABLE = frozenset({0x02, 0x04, 0x08, 0x20, 0x40, 0x80}) _MAX_READ = 1 << 20 +# EnumProcessModulesEx filters: a 64-bit caller lists a WOW64 target's own +# 32-bit modules; otherwise the default list is the target's native one. +_LIST_MODULES_DEFAULT, _LIST_MODULES_32BIT = 0x00, 0x01 Attestor = Callable[[NativeProcessFacts], ProcessIdentity] @@ -122,6 +125,35 @@ def read(self, address: int, size: int) -> bytes: _fail(FailureReason.TARGET_CHANGED) return raw + def main_module(self) -> ModuleSpan: + """The executable's image: the first module PSAPI lists, measured through the retained handle. + + Microsoft documents the executable as the first entry. Its HMODULE is + its load address, which MODULEINFO must repeat; the reader then checks + the mapping at that address starts an allocation. + """ + with self._lock: + facts = self._facts() + wow64 = facts.pointer_bits < self._caller_bits + first, needed = PTR(), U32() + if not self._kernel.K32EnumProcessModulesEx( + self._owned(), ctypes.byref(first), ctypes.sizeof(PTR), ctypes.byref(needed), + _LIST_MODULES_32BIT if wow64 else _LIST_MODULES_DEFAULT): + self._error(FailureReason.UNREADABLE_REGION) + if needed.value < ctypes.sizeof(PTR) or not first.value: + _fail(FailureReason.UNREADABLE_REGION) + info = ModuleInfo() + if not self._kernel.K32GetModuleInformation(self._owned(), first, ctypes.byref(info), + ctypes.sizeof(info)): + self._error(FailureReason.UNREADABLE_REGION) + base = info.base or 0 + if base != first.value: + _fail(FailureReason.UNREADABLE_REGION) + _range(base, info.size, facts.pointer_bits) + if self._facts() != facts: + _fail(FailureReason.TARGET_CHANGED) + return ModuleSpan(base, info.size) + def close(self) -> None: """Retain ownership on failure; successful repeated closes are harmless.""" with self._lock: diff --git a/je_auto_control/utils/process_memory/windows_native.py b/je_auto_control/utils/process_memory/windows_native.py index 62cbe6100..cc79fae51 100644 --- a/je_auto_control/utils/process_memory/windows_native.py +++ b/je_auto_control/utils/process_memory/windows_native.py @@ -36,6 +36,12 @@ class MemoryInfo64(ctypes.Structure): ("protection", U32), ("kind", U32), ("alignment2", U32)] +class ModuleInfo(ctypes.Structure): + """PSAPI MODULEINFO in the caller's pointer width: base, image size, entry point.""" + + _fields_ = [("base", PTR), ("size", U32), ("entry", PTR)] + + class NativeFunction(Protocol): """A ctypes function with an explicitly installed native signature.""" @@ -62,6 +68,8 @@ class Kernel(ProcessKernel, Protocol): VirtualQueryEx: NativeFunction ReadProcessMemory: NativeFunction + K32EnumProcessModulesEx: NativeFunction + K32GetModuleInformation: NativeFunction def bind_process(kernel: ProcessKernel) -> None: @@ -86,6 +94,8 @@ def bind(kernel: Kernel) -> None: signatures: tuple[tuple[NativeFunction, list[object], object], ...] = ( (kernel.VirtualQueryEx, [PTR, PTR, PTR, SIZE], SIZE), (kernel.ReadProcessMemory, [PTR, PTR, PTR, SIZE, ctypes.POINTER(SIZE)], BOOL), + (kernel.K32EnumProcessModulesEx, [PTR, ctypes.POINTER(PTR), U32, ctypes.POINTER(U32), U32], BOOL), + (kernel.K32GetModuleInformation, [PTR, PTR, ctypes.POINTER(ModuleInfo), U32], BOOL), ) for function, arguments, result in signatures: function.argtypes, function.restype = arguments, result diff --git a/test/unit_test/headless/test_process_memory_reader.py b/test/unit_test/headless/test_process_memory_reader.py index 2bd306a53..5c2b457e6 100644 --- a/test/unit_test/headless/test_process_memory_reader.py +++ b/test/unit_test/headless/test_process_memory_reader.py @@ -10,7 +10,7 @@ from je_auto_control.utils.exception.control_signals import OperationCancelledError from je_auto_control.utils.executor.run_control import ExecutionStopped from je_auto_control.utils.process_memory.models import ( - FailureReason, MemoryObservationError, MemoryRegion, Observation, ObservationFailure, + FailureReason, MemoryObservationError, MemoryRegion, ModuleSpan, Observation, ObservationFailure, ProcessIdentity, ReadPlan, ReviewedProbe, ) from je_auto_control.utils.process_memory.reader import ProcessMemoryReader @@ -36,7 +36,7 @@ def decode(raw, fields): def probe(**changes): original = ReviewedProbe("fixture-document", "1", IDENTITY.executable, ("1",), ("x64",), ("document_id", "job_status"), 64, 8, 1.0, 32, - lambda identity: ReadPlan(ADDRESS, SCHEMA.size), decode) + lambda identity, view: ReadPlan(ADDRESS, SCHEMA.size), decode) return replace(original, **changes) @@ -51,6 +51,7 @@ def __init__(self): self.fail_close = False self.after_read = lambda: None self.transform = lambda value: value + self.module = ModuleSpan(ADDRESS - 8, 8 + SCHEMA.size) def identity(self): return self.current_identity @@ -64,6 +65,9 @@ def read(self, address, size): self.after_read() return self.transform(value) + def main_module(self): + return self.module + def close(self): self.closed += 1 if self.fail_close: @@ -183,13 +187,13 @@ def test_short_read_fails_and_closes(): @pytest.mark.parametrize("address,size", [(True, 1), (1 << 64, 1), ((1 << 64) - 1, 2), (ADDRESS, 0)]) def test_invalid_private_plan_range_cannot_reach_read(address, size): handle = Handle() - assert observe(Provider(handle), probe(resolve=lambda identity: ReadPlan(address, size))).reason == ( + assert observe(Provider(handle), probe(resolve=lambda identity, view: ReadPlan(address, size))).reason == ( FailureReason.UNREADABLE_REGION) assert not handle.reads def test_stable_even_sequence_is_required_and_charged(): - reviewed = probe(resolve=lambda identity: ReadPlan(ADDRESS, SCHEMA.size, ADDRESS - 8)) + reviewed = probe(resolve=lambda identity, view: ReadPlan(ADDRESS, SCHEMA.size, ADDRESS - 8)) handle = Handle() result = observe(Provider(handle), reviewed) assert result.consistency == "sequence_checked" and result.bytes_read == 32 @@ -201,7 +205,7 @@ def test_stable_even_sequence_is_required_and_charged(): def test_odd_sequence_rejects_without_reading_payload(): handle = Handle() handle.memory[ADDRESS - 8] = 3 - reviewed = probe(resolve=lambda identity: ReadPlan(ADDRESS, SCHEMA.size, ADDRESS - 8)) + reviewed = probe(resolve=lambda identity, view: ReadPlan(ADDRESS, SCHEMA.size, ADDRESS - 8)) assert observe(Provider(handle), reviewed).reason == FailureReason.INCONSISTENT_SNAPSHOT assert handle.reads == [(ADDRESS - 8, 8)] @@ -361,7 +365,7 @@ def checkpoint(): def test_sequence_reads_share_the_payload_budget(): handle = Handle() - reviewed = probe(max_bytes=31, resolve=lambda identity: ReadPlan(ADDRESS, SCHEMA.size, ADDRESS - 8)) + reviewed = probe(max_bytes=31, resolve=lambda identity, view: ReadPlan(ADDRESS, SCHEMA.size, ADDRESS - 8)) assert observe(Provider(handle), reviewed).reason == FailureReason.BUDGET_EXCEEDED assert sum(size for _, size in handle.reads) == 24 @@ -524,3 +528,91 @@ def close(): release.set() thread.join(3) assert not thread.is_alive() and results == [True] and not reader.pending_cleanup + + +HEADER = (2).to_bytes(8, "little") # the eight bytes the fake maps at ADDRESS - 8 + + +def test_a_resolver_reads_through_the_view_under_the_probe_budget(): + """The header read binds the plan to this process, and it is charged like any other read.""" + seen = [] + + def resolve(identity, view): + seen.append(view.read(ADDRESS - 8, 8)) + return ReadPlan(ADDRESS, SCHEMA.size) + + handle = Handle() + result = observe(Provider(handle), probe(resolve=resolve)) + assert seen == [HEADER] + assert result.bytes_read == 8 + SCHEMA.size and result.regions_read == 2 + assert handle.reads == [(ADDRESS - 8, 8), (ADDRESS, SCHEMA.size)] + + +def test_a_resolver_cannot_swallow_a_budget_failure(): + def resolve(identity, view): + try: + view.read(ADDRESS - 8, 8 + SCHEMA.size) + except MemoryObservationError: + pass + return ReadPlan(ADDRESS, SCHEMA.size) + + handle = Handle() + assert observe(Provider(handle), probe(max_bytes=16, resolve=resolve)).reason == FailureReason.BUDGET_EXCEEDED + assert handle.reads == [] and handle.closed == 1 + + +def test_a_checkpoint_failure_inside_the_view_propagates_even_when_the_resolver_catches_it(): + failure = PermissionError("authority revoked") + armed = [] + + def checkpoint(): + if armed: + raise failure + + def resolve(identity, view): + armed.append(True) + try: + view.read(ADDRESS - 8, 8) + except PermissionError: + pass + return ReadPlan(ADDRESS, SCHEMA.size) + + handle = Handle() + with pytest.raises(PermissionError) as caught: + observe(Provider(handle), probe(resolve=resolve), checkpoint=checkpoint) + assert caught.value is failure and handle.closed == 1 + + +def test_the_main_module_is_bound_to_the_allocation_it_claims(): + spans = [] + + def resolve(identity, view): + spans.append(view.main_module()) + return ReadPlan(ADDRESS, SCHEMA.size) + + handle = Handle() + assert isinstance(observe(Provider(handle), probe(resolve=resolve)), Observation) + assert spans == [ModuleSpan(ADDRESS - 8, 8 + SCHEMA.size)] + assert str(ADDRESS) not in repr(spans[0]) + moved = Handle() + moved.module = ModuleSpan(ADDRESS, SCHEMA.size) # inside the mapping, not where its allocation starts + assert observe(Provider(moved), probe(resolve=resolve)).reason == FailureReason.TARGET_CHANGED + wrong = Handle() + wrong.module = (ADDRESS - 8, 8) + assert observe(Provider(wrong), probe(resolve=resolve)).reason == FailureReason.UNREADABLE_REGION + + +def test_a_view_kept_past_resolve_reads_nothing(): + kept = [] + + def resolve(identity, view): + kept.append(view) + return ReadPlan(ADDRESS, SCHEMA.size) + + handle = Handle() + assert isinstance(observe(Provider(handle), probe(resolve=resolve)), Observation) + with pytest.raises(MemoryObservationError): + kept[0].read(ADDRESS, SCHEMA.size) + with pytest.raises(MemoryObservationError): + kept[0].main_module() + assert handle.reads == [(ADDRESS, SCHEMA.size)] diff --git a/test/unit_test/headless/test_process_memory_windows.py b/test/unit_test/headless/test_process_memory_windows.py index 70e4c641c..72460b6d2 100644 --- a/test/unit_test/headless/test_process_memory_windows.py +++ b/test/unit_test/headless/test_process_memory_windows.py @@ -6,7 +6,7 @@ import pytest from je_auto_control.utils.process_memory.models import ( - FailureReason, MemoryObservationError, Observation, ObservationFailure, + FailureReason, MemoryObservationError, ModuleSpan, Observation, ObservationFailure, ProcessIdentity, ReadPlan, ReviewedProbe, ) from je_auto_control.utils.process_memory.reader import ProcessMemoryReader @@ -39,6 +39,7 @@ def __init__(self): self.after_read = lambda: None self.regions = [(0x1000, 8), (0x1008, 8)] self.payload = struct.pack(" Date: Sun, 15 Nov 2026 17:59:10 +0800 Subject: [PATCH 136/161] Bind the memory fixture's bootstrap to the process with a header challenge The fixture reported its buffer locations as self-reports that nothing tied to the process the reader holds. The parent now passes a challenge at launch, the fixture writes it into its own header beside its locations, and the reviewed resolver returns a plan only when that header reads back through the retained handle and matches the bootstrap. --- Progress.md | 2 +- docs/process_memory_contract.md | 18 ++- docs/updates/2026-11-b.md | 8 ++ docs/updates/README.md | 1 + test/fixtures/process_memory_fixture.py | 69 ++++++++++- .../headless/test_process_memory_fixture.py | 111 ++++++++++++++++++ 6 files changed, 200 insertions(+), 9 deletions(-) diff --git a/Progress.md b/Progress.md index 0528b99d9..55ff9cfba 100644 --- a/Progress.md +++ b/Progress.md @@ -642,7 +642,7 @@ typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 應用身分仍須由明確受審的 attestor 提供,沒有預設信任或由期望身分反填的實作。 resolver 已能透過保留 handle 取得主映像基址與大小並做有預算的讀取(U-20261115-17,維護者 2026-11-15 選定有界 view;只有注入測試)。 仍缺實際載入映像與啟動關係綁定、受審 runtime/固定程式碼交付、可信 executable/version attestor、 -fixture 標頭挑戰(父程序給的 nonce 寫進 fixture 自己的記憶體,經 view 讀回比對)、fixture 的原生身分核對與頁面故障注入、runtime grant/helper +fixture 的原生身分核對(標頭挑戰已有,U-20261115-18,只在本行程內驗過)與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index ac06259d1..794cdce1b 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -146,9 +146,7 @@ base. The reader then requires that base to start the allocation of a committed, readable mapping. A failure raised by the reader's own checks inside the view (budget, deadline, changed target, the live checkpoint) is kept and raised again after `resolve` returns, so a resolver that catches it cannot still produce a plan. -Only injected tests exercise this; native module resolution is unverified, and the -fixture header challenge that would bind bootstrap locations to the retained -process is not implemented yet. +Only injected tests exercise this; native module resolution is unverified. The reader visits only intersecting regions. Each region must be committed, readable and unguarded. Addresses, lengths and pointer-width arithmetic are @@ -240,6 +238,20 @@ a fresh launch nonce as unverified self-reports. The nonce is not OS process bir and the source digest is not measured executable identity. No reviewed probe may trust these records without the future provider's independent identity checks. +The parent binds the reported locations with a header challenge. It chooses 16 +random bytes and launches the fixture with `--challenge <32 hex digits>`. The +fixture writes a 40-byte header into its own memory (`<8s16sQQ`: magic `JEPMFIX1`, +the challenge, the payload address, the sequence address) and reports the header's +location in the bootstrap. `challenge_resolver(challenge, bootstrap)` in the fixture +module is the reviewed resolver: it requires the identity's PID to equal the +bootstrap PID, reads the header through the resolver view, compares the challenge +in constant time, requires the header's locations to equal the bootstrap's, and only +then returns the plan. Any mismatch produces no plan. This proves the locations are +in the process the retained handle reads; it does not attest the executable, which +remains the attestor's job. Headless tests run it through the real reader against +the fixture's own buffers in the test process; a cross-process native run is still +paused. + Headless tests exercise exact local buffer layout and real hidden child-process communication, invalid requests, EOF and shutdown. These checks do not establish cross-process memory readback, ASLR resolution, native publication guarantees or diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index ae4308a2d..b1d59a52b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -777,3 +777,11 @@ - **Tests:** `test_process_memory_reader.py` (budgeted view reads, a swallowed budget failure, a swallowed checkpoint failure, main-module binding, a view kept past `resolve`) and `test_process_memory_windows.py` (the PSAPI calls and their signatures, the WOW64 filter, five fail-closed cases, an image-relative plan end to end); with the image and fixture tests and the typing, complexity and broad-except gates: 228 passed. Injected native calls only; nothing ran against a real process. - **Files:** `utils/process_memory/{models,reader,windows,windows_native}.py`, both tests, `docs/process_memory_contract.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** `Progress.md` › process-memory observation (the fixture header challenge, attestation, native acceptance). + +## U-20261115-18 · 2026-11-15 · The memory fixture's bootstrap is bound by a header challenge · #done #process-memory + +- **What:** the second half of the resolver work the maintainer chose on 2026-11-15 (U-20261115-17). The fixture's bootstrap reports its buffer locations as unverified self-reports, and nothing tied them to the process the reader holds. +- **Change:** `test/fixtures/process_memory_fixture.py` accepts `--challenge <32 hex digits>` from the parent (anything else exits 2 before the bootstrap). It writes a 40-byte header into its own memory (magic `JEPMFIX1`, the challenge, the payload and sequence addresses) and reports `header_address` / `header_size`. Without the flag the header's challenge is all zero, which no resolver accepts. `challenge_resolver(challenge, bootstrap)` is the reviewed resolver. It refuses an all-zero or malformed challenge and non-integer locations up front. On each call it requires the identity's PID to be the bootstrap's, reads the header through the view, compares the challenge with `hmac.compare_digest`, requires the header's locations to equal the bootstrap's, and only then returns the plan (payload plus sequence). +- **Tests:** `test_process_memory_fixture.py` gains 10: the header layout, an observation through the real `ProcessMemoryReader` against the fixture's own ctypes buffers (`sequence_checked`, exact values, header read first), four tampering cases that produce no plan and read only the header, three refused challenges, and a hidden child launched with the flag, plus one with a malformed flag. 35 passed. Nothing read another process. +- **Files:** `test/fixtures/process_memory_fixture.py`, `test_process_memory_fixture.py`, `docs/process_memory_contract.md`, `Progress.md`. +- **Open items:** `Progress.md` › process-memory observation (executable attestation, a native cross-process run of the challenge, page-fault injection). diff --git a/docs/updates/README.md b/docs/updates/README.md index 268b3f7bb..ddbfff10e 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-18 | 2026-11-15 | The memory fixture's bootstrap is bound by a header challenge | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-17 | 2026-11-15 | Process-memory resolvers get a bounded view of the retained handle | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-16 | 2026-11-15 | The last 14 modules join the strict tier: the whole package is strict | #done #typing | [2026-11-b](2026-11-b.md) | | U-20261115-15 | 2026-11-15 | Dashboard assets served from a table, not a request-chosen path | #done #security #rest-api | [2026-11-b](2026-11-b.md) | diff --git a/test/fixtures/process_memory_fixture.py b/test/fixtures/process_memory_fixture.py index 64c9ec10c..b46e09186 100644 --- a/test/fixtures/process_memory_fixture.py +++ b/test/fixtures/process_memory_fixture.py @@ -3,17 +3,22 @@ import ctypes import hashlib +import hmac import json import os from pathlib import Path import secrets import struct import sys -from typing import BinaryIO +from typing import Any, BinaryIO, Callable PAYLOAD = struct.Struct(" None: + def __init__(self, challenge: bytes = bytes(CHALLENGE_BYTES)) -> None: + if type(challenge) is not bytes or len(challenge) != CHALLENGE_BYTES: + raise ValueError("challenge must be 16 bytes") self.payload = ctypes.create_string_buffer(PAYLOAD.size) self.sequence = ctypes.create_string_buffer(SEQUENCE.size) + # Written once by this process; the parent reads it back through its own + # handle, which is what ties the bootstrap report to this process. + self.header = ctypes.create_string_buffer(HEADER.pack( + MAGIC, challenge, ctypes.addressof(self.payload), ctypes.addressof(self.sequence)), HEADER.size) self._generation = 0 self._document_id = 17 self._job_status = "ready" @@ -40,6 +51,7 @@ def bootstrap(self) -> dict[str, object]: "launch_nonce": self._launch_nonce, "payload_address": ctypes.addressof(self.payload), "payload_size": PAYLOAD.size, "sequence_address": ctypes.addressof(self.sequence), "sequence_size": SEQUENCE.size, + "header_address": ctypes.addressof(self.header), "header_size": HEADER.size, } def snapshot(self) -> dict[str, object]: @@ -64,6 +76,48 @@ def set_state(self, document_id: object, job_status: object) -> dict[str, object return self.snapshot() +def challenge_resolver(challenge: bytes, bootstrap: dict[str, object]) -> Callable[[Any, Any], Any]: + """A reviewed resolver for this fixture: trust the bootstrap only once its header reads back. + + The parent chose ``challenge`` and passed it at launch; the fixture wrote + it into its own header. Reading that header through the retained handle's + view, and finding the same locations the bootstrap reported, binds those + self-reported locations to the process being read. Raises ``ValueError`` + on any mismatch, which the reader reports as an unsupported probe. + """ + from je_auto_control.utils.process_memory.models import ReadPlan + + if type(challenge) is not bytes or len(challenge) != CHALLENGE_BYTES or not any(challenge): + raise ValueError("challenge must be 16 bytes, not all zero") + locations = [bootstrap.get(name) for name in ("pid", "header_address", "payload_address", "sequence_address")] + if any(type(value) is not int for value in locations): + raise ValueError("bootstrap locations must be integers") + pid, header_address, payload_address, sequence_address = locations + + def resolve(identity: Any, view: Any) -> Any: + if identity.pid != pid: + raise ValueError("bootstrap from another process") + magic, seen, payload, sequence = HEADER.unpack(view.read(header_address, HEADER.size)) + if (magic != MAGIC or not hmac.compare_digest(seen, challenge) + or (payload, sequence) != (payload_address, sequence_address)): + raise ValueError("header does not match the launch") + return ReadPlan(payload, PAYLOAD.size, sequence) + + return resolve + + +def _challenge(argv: list[str]) -> bytes: + """``--challenge <32 hex digits>`` from the parent, or none (an all-zero header).""" + if not argv: + return bytes(CHALLENGE_BYTES) + if len(argv) != 2 or argv[0] != "--challenge": + raise ValueError("usage: --challenge <32 hex digits>") + value = bytes.fromhex(argv[1]) + if len(value) != CHALLENGE_BYTES: + raise ValueError("usage: --challenge <32 hex digits>") + return value + + def _error(code: str) -> dict[str, object]: return {"kind": "error", "code": code} @@ -95,9 +149,9 @@ def _emit(output: BinaryIO, record: dict[str, object]) -> None: output.flush() -def serve(source: BinaryIO, output: BinaryIO) -> int: +def serve(source: BinaryIO, output: BinaryIO, challenge: bytes = bytes(CHALLENGE_BYTES)) -> int: """Serve inherited pipes until stop, EOF or an oversized frame.""" - state = FixtureState() + state = FixtureState(challenge) _emit(output, state.bootstrap()) while True: line = source.readline(MAX_REQUEST_BYTES + 1) @@ -121,4 +175,9 @@ def serve(source: BinaryIO, output: BinaryIO) -> int: if __name__ == "__main__": - raise SystemExit(serve(sys.stdin.buffer, sys.stdout.buffer)) + try: + launch_challenge = _challenge(sys.argv[1:]) + except ValueError as usage: + print(usage, file=sys.stderr) + raise SystemExit(2) from None + raise SystemExit(serve(sys.stdin.buffer, sys.stdout.buffer, launch_challenge)) diff --git a/test/unit_test/headless/test_process_memory_fixture.py b/test/unit_test/headless/test_process_memory_fixture.py index 4999f8006..46f8da9ee 100644 --- a/test/unit_test/headless/test_process_memory_fixture.py +++ b/test/unit_test/headless/test_process_memory_fixture.py @@ -145,3 +145,114 @@ def test_clean_eof_and_fresh_launch_identity(): assert len(first) == len(second) == 1 assert first[0]["launch_nonce"] != second[0]["launch_nonce"] assert first[0]["source_sha256"] == second[0]["source_sha256"] + + +CHALLENGE = bytes(range(1, 17)) + + +class _OwnBuffers: + """A provider over this process's own fixture buffers: the reader's real code, no other process.""" + + def __init__(self, state, identity): + self._identity = identity + self._buffers = [state.header, state.payload, state.sequence] + self.reads = [] + + def open_readonly(self, identity): + return self + + def identity(self): + return self._identity + + def query_region(self, address): + from je_auto_control.utils.process_memory.models import MemoryRegion + for buffer in self._buffers: + base = ctypes.addressof(buffer) + if base <= address < base + ctypes.sizeof(buffer): + return MemoryRegion(base, ctypes.sizeof(buffer), base, 4, True, True, False) + raise OSError("not a fixture buffer") + + def read(self, address, size): + self.reads.append((address, size)) + return ctypes.string_at(address, size) + + def main_module(self): + raise OSError("not used") + + def close(self): + pass + + +def _observe_own(state, resolve, pid=None): + from je_auto_control.utils.process_memory.models import ProcessIdentity, ReviewedProbe + from je_auto_control.utils.process_memory.reader import ProcessMemoryReader + identity = ProcessIdentity("host", "session", pid or os.getpid(), 1, "fixture", "1", "x64", 64) + + def decode(raw, fields): + document_id, status = fixture_module.PAYLOAD.unpack(raw) + values = {"document_id": document_id, "job_status": status.rstrip(b"\0").decode("ascii")} + return {name: values[name] for name in fields} + + probe = ReviewedProbe("fixture", "1", "fixture", ("1",), ("x64",), ("document_id", "job_status"), + 256, 8, 5.0, 32, resolve, decode) + provider = _OwnBuffers(state, identity) + result = ProcessMemoryReader(provider).observe(identity, probe, ("document_id", "job_status"), target_id="fixture") + return result, provider + + +def test_the_header_records_the_challenge_and_where_the_buffers_are(): + state = fixture_module.FixtureState(CHALLENGE) + magic, challenge, payload, sequence = fixture_module.HEADER.unpack(state.header.raw) + assert (magic, challenge) == (b"JEPMFIX1", CHALLENGE) + assert (payload, sequence) == (ctypes.addressof(state.payload), ctypes.addressof(state.sequence)) + bootstrap = state.bootstrap() + assert (bootstrap["header_address"], bootstrap["header_size"]) == (ctypes.addressof(state.header), 40) + + +def test_a_header_that_reads_back_binds_the_bootstrap_locations(): + from je_auto_control.utils.process_memory.models import Observation + state = fixture_module.FixtureState(CHALLENGE) + state.set_state(23, "busy") + resolve = fixture_module.challenge_resolver(CHALLENGE, state.bootstrap()) + result, provider = _observe_own(state, resolve) + assert isinstance(result, Observation) and result.consistency == "sequence_checked" + assert result.fields == (("document_id", 23), ("job_status", "busy")) + assert provider.reads[0] == (ctypes.addressof(state.header), 40) + + +@pytest.mark.parametrize("tamper", ["challenge", "magic", "payload_address", "pid"]) +def test_a_header_that_does_not_match_the_launch_yields_no_plan(tamper): + from je_auto_control.utils.process_memory.models import FailureReason + state = fixture_module.FixtureState(CHALLENGE) + bootstrap = state.bootstrap() + challenge, pid = CHALLENGE, None + if tamper == "challenge": + challenge = bytes(range(2, 18)) + elif tamper == "magic": + state.header.raw = b"NOTMAGIC" + state.header.raw[8:] + elif tamper == "payload_address": + bootstrap["payload_address"] += 1 + else: + pid = os.getpid() + 1 + resolve = fixture_module.challenge_resolver(challenge, bootstrap) + result, provider = _observe_own(state, resolve, pid) + assert result.reason == FailureReason.UNSUPPORTED + assert all(address == ctypes.addressof(state.header) for address, _size in provider.reads) + + +@pytest.mark.parametrize("challenge", [bytes(16), b"short", "0" * 16]) +def test_an_unusable_challenge_is_refused_before_any_read(challenge): + with pytest.raises(ValueError): + fixture_module.challenge_resolver(challenge, fixture_module.FixtureState().bootstrap()) + + +def test_the_child_writes_the_parents_challenge_into_its_own_header(): + flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0 + child = subprocess.run([sys.executable, "-I", "-u", str(FIXTURE_PATH), "--challenge", CHALLENGE.hex()], + input=b'{"command":"stop"}\n', capture_output=True, timeout=10, creationflags=flags) + bootstrap = json.loads(child.stdout.splitlines()[0]) + assert child.returncode == 0 and bootstrap["header_size"] == 40 + assert type(bootstrap["header_address"]) is int + refused = subprocess.run([sys.executable, "-I", "-u", str(FIXTURE_PATH), "--challenge", "zz"], + input=b"", capture_output=True, timeout=10, creationflags=flags) + assert refused.returncode == 2 and refused.stdout == b"" From 72335301dced805433b9c050e667880213eccfa6 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 18:19:57 +0800 Subject: [PATCH 137/161] Attest an owned launch by leasing and pinning its image file WindowsProcessProvider needs an attestor and had none, so no probe could be used for real. The host now leases the image read-only, checks its SHA-256 against the pin before starting it, and confirms the child it started maps that same leased file before naming the process. --- Progress.md | 3 +- architecture_explore.md | 19 +- docs/process_memory_contract.md | 31 +++ docs/updates/2026-11-b.md | 24 +++ docs/updates/README.md | 1 + .../utils/process_memory/windows_image.py | 68 ++++++- .../utils/process_memory/windows_launch.py | 183 ++++++++++++++++++ .../headless/test_process_memory_launch.py | 153 +++++++++++++++ 8 files changed, 469 insertions(+), 13 deletions(-) create mode 100644 je_auto_control/utils/process_memory/windows_launch.py create mode 100644 test/unit_test/headless/test_process_memory_launch.py diff --git a/Progress.md b/Progress.md index 55ff9cfba..9850e3b74 100644 --- a/Progress.md +++ b/Progress.md @@ -641,7 +641,8 @@ bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報 typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 handle 的注入測試; 應用身分仍須由明確受審的 attestor 提供,沒有預設信任或由期望身分反填的實作。 resolver 已能透過保留 handle 取得主映像基址與大小並做有預算的讀取(U-20261115-17,維護者 2026-11-15 選定有界 view;只有注入測試)。 -仍缺實際載入映像與啟動關係綁定、受審 runtime/固定程式碼交付、可信 executable/version attestor、 +自有啟動 attestor 已有(U-20261115-19:啟動前租用並雜湊映像檔、比對主機釘選的 SHA-256、啟動後再觀測子程序映像須為同一檔案;維護者 2026-11-15 選定;只有注入測試)。 +仍缺實際載入映像綁定(目前證明的是映射期間磁碟上的位元組,不是正在執行的程式碼)、以 Popen handle 量測 PID/birth 的真實 launcher、受審 runtime/固定程式碼交付、非自有啟動程序的 attestor、 fixture 的原生身分核對(標頭挑戰已有,U-20261115-18,只在本行程內驗過)與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 diff --git a/architecture_explore.md b/architecture_explore.md index 03a6105b1..95dd6e2d3 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -18,7 +18,7 @@ CI 以 `python scripts/generate_facade_exports.py --check` 檢查一致性。六 ## 1. 專案定位與規模 `test/fixtures/process_memory_fixture.py` 由子程序持有固定 payload 與 sequence 緩衝區, -以有界管線提供已知語意狀態及更新。bootstrap 僅自報資訊,原生身分綁定與實際讀回驗收仍未完成。 +以有界管線提供已知語意狀態及更新。bootstrap 的位置由父程序給的標頭挑戰綁定到被讀的行程;實際跨行程讀回驗收仍未完成。 `je_auto_control` 是一套跨平台 GUI 自動化框架,涵蓋 Windows(Win32 API)、macOS(pyobjc/Quartz)、 Linux X11(python-Xlib)與 Linux Wayland(libei / ydotool),並延伸到 Android(ADB / uiautomator2)與 @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,545 | -| 程式碼總行數 | 238,222 | +| Python 模組總數(含周邊子專案) | 1,546 | +| 程式碼總行數 | 238,467 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 4,988 行。 +> 15 個套件、約 5,233 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -340,7 +340,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 198 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | -| `utils/process_memory/` | 1,184 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測與失敗 handle 回收;檔案證據不等於載入程式碼身分,可信啟動及 runtime 整合待完成 | +| `utils/process_memory/` | 1,429 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測、自有啟動加釘選雜湊的 attestor 與失敗 handle 回收;檔案證據不等於載入程式碼身分,原生驗收及 runtime 整合待完成 | | `utils/shell_process/` | 280 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -731,7 +731,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 上表以子套件為單位;以下把行數最大的幾個子系統展開到檔案層。 -#### `utils/process_memory/`(1,184 行/8 檔) +#### `utils/process_memory/`(1,429 行/9 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -740,8 +740,9 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `reader.py` | 310 | Adapter-owned semantic observations with bounded reads and retained cleanup ownership. | | `windows.py` | 194 | Owned Windows read handles with measured native facts and reviewed application attestation. | | `windows_facts.py` | 55 | Measure native birth, session and architecture through a retained process handle. | -| `windows_image.py` | 246 | Observe an image file while retaining its process and deny-write/delete file leases. | +| `windows_image.py` | 308 | Observe an image file while retaining its process and deny-write/delete file leases. | | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | +| `windows_launch.py` | 183 | Attest a process this host launched itself, from an image file pinned by SHA-256. | | `windows_native.py` | 113 | Typed Win32 query/read bindings and caller-sized memory information layouts. | #### `utils/executor/`(10,765 行)— 執行核心 @@ -1569,8 +1570,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,008 | 103,845 | -| **總計** | **1,533** | **237,477** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,090 | +| **總計** | **1,534** | **237,722** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index 794cdce1b..31caf416f 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -68,6 +68,37 @@ and measures facts again after attestation. A path string, fixture nonce, self-r digest or a callback that merely echoes an expected identity is not an attestation. The production attestor and trusted fixture bootstrap matching remain unimplemented. +### Owned-launch attestation + +`windows_launch.py` is the first attestor, chosen by the maintainer on 2026-11-15. +It attests only a process the host launches itself. `PinnedExecutable` is host +configuration: the host and session labels, the executable and version identifiers, +and the SHA-256 of the image bytes (64 lowercase hex digits). `launch_attested` then: + +1. leases the image file with a fresh `WindowsImageObserver.lease(path, ...)`: opened + with `GENERIC_READ` and only `FILE_SHARE_READ`, digested from its actual bytes, with + the file facts rechecked around every chunk, and the lease kept open; +2. requires that digest to equal the pin, in constant time, before anything is started; +3. calls the caller's launcher, which must return a `LaunchRecord` holding the PID and + birth it measured from the new process's own handle (the launcher owns the child and + ends it if attestation fails); +4. observes the child's image with a second fresh observer and requires the same + volume, 128-bit file ID, size and digest as the lease, and the same PID and birth as + the record. + +Only then does it return an `OwnedLaunch` whose `OwnedLaunchAttestor` mints a +`ProcessIdentity` for those native facts and refuses any other (a different birth, PID +or session). One deadline covers both measurements. On failure both observers are closed +and the original error propagates; launcher exceptions become `unsupported` without their +message, and cancellation signals propagate unchanged. + +What it proves: the bytes on disk, held against writers from before the launch until +the observation, are the pinned ones, and the child the host started maps that same +file. It does not prove the code running now (in-memory patching, loaded DLLs), and it +cannot attest a process the host did not start. The real launcher (measuring PID and +birth from the `Popen` handle) and a native run are not implemented yet; tests drive the +real observer code through injected native calls. + ### Observed image-file evidence `windows_image.py` adds a separate one-shot `WindowsImageObserver`. It acquires diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index b1d59a52b..2984bb92b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -785,3 +785,27 @@ - **Tests:** `test_process_memory_fixture.py` gains 10: the header layout, an observation through the real `ProcessMemoryReader` against the fixture's own ctypes buffers (`sequence_checked`, exact values, header read first), four tampering cases that produce no plan and read only the header, three refused challenges, and a hidden child launched with the flag, plus one with a malformed flag. 35 passed. Nothing read another process. - **Files:** `test/fixtures/process_memory_fixture.py`, `test_process_memory_fixture.py`, `docs/process_memory_contract.md`, `Progress.md`. - **Open items:** `Progress.md` › process-memory observation (executable attestation, a native cross-process run of the challenge, page-fault injection). + +## U-20261115-19 · 2026-11-15 · Owned-launch attestor: lease, pinned SHA-256, re-observed child · #done #process-memory #security + +- **What:** `Progress.md` › process-memory observation listed a trusted executable/version attestor as missing; `WindowsProcessProvider` requires one and ships none. The maintainer chose (2026-11-15) an owned launch with a pinned hash over an Authenticode publisher check or deferring. +- **Change:** `WindowsImageObserver.lease(path, ...)` is a second acquisition mode: it opens the file read-only, sharing only reads, digests its actual bytes with the file facts rechecked around each chunk, and keeps the lease. It refuses an empty path, a NUL, a non-string and a path of 32,768 UTF-16 units or more before opening anything. The digest loop is shared with `observe` (`_digest`). New `windows_launch.py`: + - `PinnedExecutable` holds the labels and a lowercase SHA-256. + - `LaunchRecord` holds the PID and birth measured from the launch's own handle. + - `launch_attested()` leases and digests the file and checks the pin in constant time before launching. It calls the caller's launcher, then re-observes the child's image with a second observer. It requires the same volume, file ID, size and digest, and the record's PID and birth. + - The `OwnedLaunchAttestor` it returns mints an identity for exactly those native facts. + - On failure both observers are closed. Launcher exceptions become `unsupported` with no message; cancellation propagates. +- **Tests:** new `test_process_memory_launch.py`, 19 tests over the real observer code with injected native calls: + - the lease takes no process handle and its path checks; + - a file change during the lease; + - a successful attestation, holding both leases until `close`; + - the attestor refusing another birth, PID or session; + - a pin mismatch, which never launches; + - a child running a different file; + - four bad launch records; + - launcher secrets kept out of the error, and cancellation propagating; + - pin validation. + + With the other process-memory tests and the typing, complexity, broad-except and file-length gates: 262 passed. Nothing was launched or read. +- **Files:** `utils/process_memory/{windows_image,windows_launch}.py`, the test, `docs/process_memory_contract.md`, `architecture_explore.md`, `Progress.md`. +- **Open items:** `Progress.md` › process-memory observation (loaded-image binding, the real `Popen` launcher, attesting processes the host did not start, native acceptance). diff --git a/docs/updates/README.md b/docs/updates/README.md index ddbfff10e..8621ed750 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-19 | 2026-11-15 | Owned-launch attestor: lease, pinned SHA-256, re-observed child | #done #process-memory #security | [2026-11-b](2026-11-b.md) | | U-20261115-18 | 2026-11-15 | The memory fixture's bootstrap is bound by a header challenge | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-17 | 2026-11-15 | Process-memory resolvers get a bounded view of the retained handle | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-16 | 2026-11-15 | The last 14 modules join the strict tier: the whole package is strict | #done #typing | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/process_memory/windows_image.py b/je_auto_control/utils/process_memory/windows_image.py index 0999a6c23..63a397df0 100644 --- a/je_auto_control/utils/process_memory/windows_image.py +++ b/je_auto_control/utils/process_memory/windows_image.py @@ -32,6 +32,16 @@ class ObservedImageFile: sha256: str = field(repr=False) +@dataclass(frozen=True) +class LeasedImageFile: + """An image file measured before any process runs it, while writes stay excluded.""" + + volume: int = field(repr=False) + file_id: bytes = field(repr=False) + size: int + sha256: str = field(repr=False) + + @dataclass(frozen=True) class _FileFacts: volume: int @@ -69,6 +79,10 @@ def _fail(reason: FailureReason) -> NoReturn: def _bounds(pid: int, max_bytes: int, timeout: float) -> None: if type(pid) is not int or not 0 < pid <= 0xFFFFFFFF: _fail(FailureReason.UNSUPPORTED) + _limits(max_bytes, timeout) + + +def _limits(max_bytes: int, timeout: float) -> None: if type(max_bytes) is not int or not 0 < max_bytes <= _MAX_IMAGE_BYTES: _fail(FailureReason.BUDGET_EXCEEDED) if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0: @@ -196,17 +210,65 @@ def _measure(self, pid: int, max_bytes: int, deadline: float, file = self._file_facts(image) if file.size > max_bytes: _fail(FailureReason.BUDGET_EXCEEDED) + digest = self._digest(image, file, deadline, checkpoint, + lambda: self._unchanged(process, image, path, facts, file)) + return ObservedImageFile(facts, file.volume, file.file_id, file.size, digest) + + def _digest(self, image: int, file: _FileFacts, deadline: float, checkpoint: Callable[[], None], + unchanged: Callable[[], None]) -> str: + """SHA-256 of the file's actual bytes, rechecking ``unchanged`` around every chunk.""" digest, remaining = hashlib.sha256(), file.size - self._unchanged(process, image, path, facts, file) + unchanged() while remaining: self._check(deadline, checkpoint) size = min(remaining, _CHUNK_BYTES) digest.update(self._read(image, size)) self._check(deadline, checkpoint) - self._unchanged(process, image, path, facts, file) + unchanged() remaining -= size self._check(deadline, checkpoint) - return ObservedImageFile(facts, file.volume, file.file_id, file.size, digest.hexdigest()) + return digest.hexdigest() + + def _lease(self, path: str, max_bytes: int, deadline: float, + checkpoint: Callable[[], None]) -> LeasedImageFile: + self._check(deadline, checkpoint) + image = self._file(path) + self._check(deadline, checkpoint) + file = self._file_facts(image) + if file.size > max_bytes: + _fail(FailureReason.BUDGET_EXCEEDED) + + def unchanged() -> None: + if self._file_facts(image) != file: + _fail(FailureReason.TARGET_CHANGED) + + digest = self._digest(image, file, deadline, checkpoint, unchanged) + return LeasedImageFile(file.volume, file.file_id, file.size, digest) + + def lease(self, path: str, *, max_bytes: int, timeout: float, + checkpoint: Callable[[], None]) -> LeasedImageFile: + """Open ``path`` read-only, sharing only reads, and digest it; keep the lease until close. + + For an owned launch: taken before the process starts, the lease keeps + ordinary writers and deleters out while the image is mapped. Like + :meth:`observe`, one acquisition per observer, and a failure retires it. + """ + with self._lock: + if self._state is not _State.NEW: + _fail(FailureReason.TARGET_CHANGED) + if (not isinstance(path, str) or not path or "\0" in path + or len(path.encode("utf-16-le", "surrogatepass")) // 2 >= _PATH_CHARACTERS): + _fail(FailureReason.UNSUPPORTED) + _limits(max_bytes, timeout) + self._state = _State.ACTIVE + try: + return self._lease(path, max_bytes, self._clock() + timeout, checkpoint) + except BaseException: + try: + self.close() + except MemoryObservationError: + pass + raise def observe(self, pid: int, *, max_bytes: int, timeout: float, checkpoint: Callable[[], None]) -> ObservedImageFile: diff --git a/je_auto_control/utils/process_memory/windows_launch.py b/je_auto_control/utils/process_memory/windows_launch.py new file mode 100644 index 000000000..4dae0692d --- /dev/null +++ b/je_auto_control/utils/process_memory/windows_launch.py @@ -0,0 +1,183 @@ +"""Attest a process this host launched itself, from an image file pinned by SHA-256. + +The only identity this module mints is for a launch the host performed: the +image file is leased read-only (writers and deleters excluded) and digested +before the process starts, the digest must equal the host-configured pin, and +after the launch the process's own image is observed again and must be the +same leased file with the same digest. The resulting attestor names only that +process, by the PID and birth measured from the launch's own handle. + +It proves which bytes were on disk while the image was mapped, not which code +is running now. A process the host did not launch cannot be attested here. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +import hmac +import re +import time +from typing import Callable, NoReturn, Protocol + +from je_auto_control.utils.exception.control_signals import raise_if_run_interrupted +from je_auto_control.utils.executor.run_control import ExecutionStopped + +from .models import FailureReason, MemoryObservationError, ProcessIdentity, _identifier +from .windows_facts import NativeProcessFacts +from .windows_image import LeasedImageFile, ObservedImageFile + +_SHA256 = re.compile(r"[0-9a-f]{64}") + + +def _fail(reason: FailureReason) -> NoReturn: + raise MemoryObservationError(reason) + + +@dataclass(frozen=True) +class PinnedExecutable: + """Host configuration: the image bytes an identity names, and the labels it carries.""" + + host: str = field(repr=False) + session: str = field(repr=False) + executable: str + version: str + sha256: str = field(repr=False) + + def __post_init__(self) -> None: + for value in (self.host, self.session, self.executable, self.version): + _identifier(value) + if not isinstance(self.sha256, str) or not _SHA256.fullmatch(self.sha256): + _fail(FailureReason.UNSUPPORTED) + + +@dataclass(frozen=True) +class LaunchRecord: + """PID and birth measured from the process handle the launch itself returned.""" + + pid: int = field(repr=False) + birth: int = field(repr=False) + + +class ImageLease(Protocol): + """The pre-launch half of :class:`~.windows_image.WindowsImageObserver`.""" + + def lease(self, path: str, *, max_bytes: int, timeout: float, + checkpoint: Callable[[], None]) -> LeasedImageFile: ... + + def close(self) -> None: ... + + +class ImageObserver(Protocol): + """The post-launch half of :class:`~.windows_image.WindowsImageObserver`.""" + + def observe(self, pid: int, *, max_bytes: int, timeout: float, + checkpoint: Callable[[], None]) -> ObservedImageFile: ... + + def close(self) -> None: ... + + +#: Starts ``path`` and returns what it measured from the new process's own +#: handle. The caller's launcher owns the child: when attestation fails it is +#: the caller that ends it. +Launcher = Callable[[str], LaunchRecord] + + +class OwnedLaunchAttestor: + """Attest the one launched process, and only while its facts are those attested.""" + + def __init__(self, pin: PinnedExecutable, record: LaunchRecord, observed: ObservedImageFile) -> None: + self._pin, self._record, self._observed = pin, record, observed + + def __call__(self, facts: NativeProcessFacts) -> ProcessIdentity: + if (not isinstance(facts, NativeProcessFacts) or facts != self._observed.process + or (facts.pid, facts.birth) != (self._record.pid, self._record.birth)): + _fail(FailureReason.TARGET_CHANGED) + pin = self._pin + return ProcessIdentity(pin.host, pin.session, facts.pid, facts.birth, pin.executable, + pin.version, facts.architecture, facts.pointer_bits) + + +@dataclass +class OwnedLaunch: + """An attested launch. Both file leases stay open until :meth:`close` succeeds.""" + + identity: ProcessIdentity + attestor: OwnedLaunchAttestor = field(repr=False) + record: LaunchRecord = field(repr=False) + _lease: ImageLease = field(repr=False) + _observer: ImageObserver = field(repr=False) + + def close(self) -> None: + """Close both leases; a failure leaves the rest to a later ``close``.""" + _close_all(self._observer, self._lease) + + +def _close_all(*owners: ImageLease | ImageObserver) -> None: + failed = False + for owner in owners: + try: + owner.close() + except MemoryObservationError: + failed = True + if failed: + _fail(FailureReason.CLEANUP_FAILED) + + +def _launch(launch: Launcher, path: str) -> LaunchRecord: + try: + record = launch(path) + except MemoryObservationError: + raise + except Exception as error: # reason: launcher detail (paths, arguments) must not reach the failure + if isinstance(error, ExecutionStopped): + raise + raise_if_run_interrupted(error) + _fail(FailureReason.UNSUPPORTED) + if (not isinstance(record, LaunchRecord) or type(record.pid) is not int + or type(record.birth) is not int or record.pid <= 0 or record.birth <= 0): + _fail(FailureReason.TARGET_CHANGED) + return record + + +def _same_file(leased: LeasedImageFile, observed: ObservedImageFile) -> bool: + return ((observed.volume, observed.file_id, observed.size) == (leased.volume, leased.file_id, leased.size) + and hmac.compare_digest(observed.sha256, leased.sha256)) + + +def launch_attested(pin: PinnedExecutable, path: str, launch: Launcher, *, + lease: ImageLease, observer: ImageObserver, max_bytes: int, timeout: float, + checkpoint: Callable[[], None], clock: Callable[[], float] = time.monotonic) -> OwnedLaunch: + """Lease and digest ``path``, check the pin, launch, then confirm the child runs that file. + + ``lease`` and ``observer`` are two fresh image observers; one deadline + covers both measurements. On any failure both are closed (a failed close + still surfaces as the original error), and the launched child, if any, is + left to the caller's launcher. + """ + if not isinstance(pin, PinnedExecutable): + _fail(FailureReason.UNSUPPORTED) + deadline = clock() + timeout + try: + leased = lease.lease(path, max_bytes=max_bytes, timeout=timeout, checkpoint=checkpoint) + if not hmac.compare_digest(leased.sha256, pin.sha256): + _fail(FailureReason.UNSUPPORTED) + checkpoint() + record = _launch(launch, path) + remaining = deadline - clock() + if remaining <= 0: + _fail(FailureReason.DEADLINE_EXCEEDED) + observed = observer.observe(record.pid, max_bytes=max_bytes, timeout=remaining, checkpoint=checkpoint) + if not _same_file(leased, observed): + _fail(FailureReason.TARGET_CHANGED) + attestor = OwnedLaunchAttestor(pin, record, observed) + identity = attestor(observed.process) + except BaseException: + try: + _close_all(observer, lease) + except MemoryObservationError: + pass + raise + return OwnedLaunch(identity, attestor, record, lease, observer) + + +__all__ = ["ImageLease", "ImageObserver", "LaunchRecord", "Launcher", "OwnedLaunch", + "OwnedLaunchAttestor", "PinnedExecutable", "launch_attested"] diff --git a/test/unit_test/headless/test_process_memory_launch.py b/test/unit_test/headless/test_process_memory_launch.py new file mode 100644 index 000000000..c4d7ad6b2 --- /dev/null +++ b/test/unit_test/headless/test_process_memory_launch.py @@ -0,0 +1,153 @@ +"""Owned-launch attestation through fake native buffers: no process is started or read.""" +import hashlib + +import pytest + +from je_auto_control.utils.exception.control_signals import OperationCancelledError +from je_auto_control.utils.process_memory.models import FailureReason, MemoryObservationError +from je_auto_control.utils.process_memory.windows_launch import ( + LaunchRecord, PinnedExecutable, launch_attested, +) +from headless.test_process_memory_image import ImageKernel, observer +from headless.test_process_memory_windows import Function + + +class LaunchKernel(ImageKernel): + """Every CreateFileW starts reading the image from its first byte.""" + + def __init__(self): + super().__init__() + self.CreateFileW = Function(self.open_file) + + def open_file(self, *args): + self.position = 0 + return self.file_handle + + +def pin(kernel, **changes): + values = {"host": "owned-host", "session": "owned-session", "executable": "fixture", + "version": "1", "sha256": hashlib.sha256(kernel.data).hexdigest()} + values.update(changes) + return PinnedExecutable(**values) + + +def lease_only(kernel): + return observer(kernel).lease(kernel.image_path, max_bytes=1 << 20, timeout=5, checkpoint=lambda: None) + + +def attest(kernel, launcher=None, pinned=None, **options): + launched = [] + + def launch(path): + launched.append(path) + return LaunchRecord(42, kernel.birth) + + lease, watch = observer(kernel), observer(kernel) + result = launch_attested(pinned or pin(kernel), kernel.image_path, launcher or launch, + lease=lease, observer=watch, max_bytes=1 << 20, timeout=5, + checkpoint=lambda: None, **options) + return result, launched, lease, watch + + +def test_a_lease_digests_the_file_before_any_process_exists(): + kernel = LaunchKernel() + leased = lease_only(kernel) + assert leased.sha256 == hashlib.sha256(kernel.data).hexdigest() + assert (leased.volume, leased.file_id, leased.size) == (9, b"f" * 16, len(kernel.data)) + assert kernel.CreateFileW.calls == [(kernel.image_path, 0x80000000, 1, None, 3, 0, None)] + assert not kernel.OpenProcess.calls and not kernel.CloseHandle.calls + assert leased.sha256 not in repr(leased) + + +@pytest.mark.parametrize("path", ["", "C:\\owned\\py" + chr(0) + ".exe", None, "x" * 32768], + ids=["empty", "nul", "none", "too-long"]) +def test_a_lease_refuses_an_unusable_path_before_opening_it(path): + kernel = LaunchKernel() + with pytest.raises(MemoryObservationError, match="unsupported"): + observer(kernel).lease(path, max_bytes=1 << 20, timeout=5, checkpoint=lambda: None) + assert not kernel.CreateFileW.calls + + +def test_a_lease_that_sees_the_file_change_publishes_nothing(): + kernel = LaunchKernel() + kernel.after_file_read = lambda: setattr(kernel, "changed", 12) + owner = observer(kernel) + with pytest.raises(MemoryObservationError, match="target_changed"): + owner.lease(kernel.image_path, max_bytes=1 << 20, timeout=5, checkpoint=lambda: None) + assert kernel.CloseHandle.calls == [(92,)] and not owner.pending_cleanup + + +def test_an_owned_launch_of_the_pinned_file_is_attested(): + kernel = LaunchKernel() + launch, launched, lease, watch = attest(kernel) + identity = launch.identity + assert launched == [kernel.image_path] + assert (identity.host, identity.session, identity.executable, identity.version) == ( + "owned-host", "owned-session", "fixture", "1") + assert (identity.pid, identity.birth, identity.architecture) == (42, kernel.birth, "x64") + assert kernel.CloseHandle.calls == [] # both leases are held until close + launch.close() + assert sorted(kernel.CloseHandle.calls) == [(91,), (92,), (92,)] + + +def test_the_attestor_names_only_the_launched_process(): + from dataclasses import replace + kernel = LaunchKernel() + launch, *_ = attest(kernel) + facts = launch.attestor._observed.process + assert launch.attestor(facts) == launch.identity + for change in ({"birth": facts.birth + 1}, {"pid": 43}, {"session_id": facts.session_id + 1}): + with pytest.raises(MemoryObservationError, match="target_changed"): + launch.attestor(replace(facts, **change)) + + +def test_a_file_that_does_not_match_the_pin_is_never_launched(): + kernel = LaunchKernel() + with pytest.raises(MemoryObservationError, match="unsupported"): + attest(kernel, pinned=pin(kernel, sha256="0" * 64)) + assert kernel.CloseHandle.calls == [(92,)] # the lease is closed; no process was opened + assert not kernel.OpenProcess.calls + + +def test_a_child_running_a_different_file_than_the_leased_one_is_refused(): + kernel = LaunchKernel() + + def launch(path): + kernel.file_id = b"g" * 16 # the image the child runs is another file + return LaunchRecord(42, kernel.birth) + + with pytest.raises(MemoryObservationError, match="target_changed"): + attest(kernel, launcher=launch) + + +@pytest.mark.parametrize("record", [LaunchRecord(43, 1), LaunchRecord(42, 1), (42, 1), LaunchRecord(0, 1)]) +def test_a_launch_record_that_is_not_the_observed_child_is_refused(record): + kernel = LaunchKernel() + with pytest.raises(MemoryObservationError, match="target_changed"): + attest(kernel, launcher=lambda path: record) + + +def test_launcher_failures_are_closed_and_interruptions_propagate(): + kernel = LaunchKernel() + + def broken(path): + raise RuntimeError("SECRET C:\\owned\\python.exe --token abc") + + with pytest.raises(MemoryObservationError) as caught: + attest(kernel, launcher=broken) + assert caught.value.reason == FailureReason.UNSUPPORTED and "SECRET" not in str(caught.value) + signal = OperationCancelledError("stop") + + def cancelled(path): + raise signal + + with pytest.raises(OperationCancelledError) as interrupted: + attest(LaunchKernel(), launcher=cancelled) + assert interrupted.value is signal + + +@pytest.mark.parametrize("changes", [{"sha256": "A" * 64}, {"sha256": "0" * 63}, {"host": "bad host"}, + {"version": ""}]) +def test_a_pin_must_be_a_lowercase_sha256_and_identifiers(changes): + with pytest.raises(MemoryObservationError, match="unsupported"): + pin(LaunchKernel(), **changes) From 2accead0674d77563adf971ebe476c16948905a2 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 18:22:34 +0800 Subject: [PATCH 138/161] Measure the owned child through the handle Popen already holds Reopening the child by PID could land on another process that reused the number. The launcher now reads PID and birth from the handle CreateProcess returned, and refuses a second launch so the child it reports is unambiguous. --- Progress.md | 2 +- architecture_explore.md | 14 ++--- docs/process_memory_contract.md | 12 +++-- docs/updates/2026-11-b.md | 7 +++ docs/updates/README.md | 1 + .../utils/process_memory/windows_launch.py | 48 +++++++++++++++-- .../headless/test_process_memory_launch.py | 54 +++++++++++++++++++ 7 files changed, 124 insertions(+), 14 deletions(-) diff --git a/Progress.md b/Progress.md index 9850e3b74..7bbfa2162 100644 --- a/Progress.md +++ b/Progress.md @@ -642,7 +642,7 @@ typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 應用身分仍須由明確受審的 attestor 提供,沒有預設信任或由期望身分反填的實作。 resolver 已能透過保留 handle 取得主映像基址與大小並做有預算的讀取(U-20261115-17,維護者 2026-11-15 選定有界 view;只有注入測試)。 自有啟動 attestor 已有(U-20261115-19:啟動前租用並雜湊映像檔、比對主機釘選的 SHA-256、啟動後再觀測子程序映像須為同一檔案;維護者 2026-11-15 選定;只有注入測試)。 -仍缺實際載入映像綁定(目前證明的是映射期間磁碟上的位元組,不是正在執行的程式碼)、以 Popen handle 量測 PID/birth 的真實 launcher、受審 runtime/固定程式碼交付、非自有啟動程序的 attestor、 +仍缺實際載入映像綁定(目前證明的是映射期間磁碟上的位元組,不是正在執行的程式碼)、`PopenLauncher`(U-20261115-20)的原生執行、受審 runtime/固定程式碼交付、非自有啟動程序的 attestor、 fixture 的原生身分核對(標頭挑戰已有,U-20261115-18,只在本行程內驗過)與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 diff --git a/architecture_explore.md b/architecture_explore.md index 95dd6e2d3..b4d20f143 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,467 | +| 程式碼總行數 | 238,509 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 5,233 行。 +> 15 個套件、約 5,275 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -340,7 +340,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 198 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | -| `utils/process_memory/` | 1,429 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測、自有啟動加釘選雜湊的 attestor 與失敗 handle 回收;檔案證據不等於載入程式碼身分,原生驗收及 runtime 整合待完成 | +| `utils/process_memory/` | 1,471 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測、自有啟動加釘選雜湊的 attestor 與失敗 handle 回收;檔案證據不等於載入程式碼身分,原生驗收及 runtime 整合待完成 | | `utils/shell_process/` | 280 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -731,7 +731,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 上表以子套件為單位;以下把行數最大的幾個子系統展開到檔案層。 -#### `utils/process_memory/`(1,429 行/9 檔) +#### `utils/process_memory/`(1,471 行/9 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -742,7 +742,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_facts.py` | 55 | Measure native birth, session and architecture through a retained process handle. | | `windows_image.py` | 308 | Observe an image file while retaining its process and deny-write/delete file leases. | | `windows_image_native.py` | 62 | Typed process-image filename and read-only file acquisition calls. | -| `windows_launch.py` | 183 | Attest a process this host launched itself, from an image file pinned by SHA-256. | +| `windows_launch.py` | 225 | Attest a process this host launched itself, from an image file pinned by SHA-256. | | `windows_native.py` | 113 | Typed Win32 query/read bindings and caller-sized memory information layouts. | #### `utils/executor/`(10,765 行)— 執行核心 @@ -1570,8 +1570,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,090 | -| **總計** | **1,534** | **237,722** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,132 | +| **總計** | **1,534** | **237,764** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index 31caf416f..0d10f06af 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -95,9 +95,15 @@ message, and cancellation signals propagate unchanged. What it proves: the bytes on disk, held against writers from before the launch until the observation, are the pinned ones, and the child the host started maps that same file. It does not prove the code running now (in-memory patching, loaded DLLs), and it -cannot attest a process the host did not start. The real launcher (measuring PID and -birth from the `Popen` handle) and a native run are not implemented yet; tests drive the -real observer code through injected native calls. +cannot attest a process the host did not start. + +`PopenLauncher(arguments, **popen_options)` is the launcher. It starts the image from an +argv list (`shell` is refused) and measures PID and birth from the handle `Popen` holds, +the one `CreateProcess` returned, so the measurement cannot land on a process that +reused the PID. It refuses a measured PID that differs from `Popen.pid` and a second +launch, and keeps the child as `child` for the caller to wait on or end. Tests drive +the real observer and launcher code through injected native calls and a fake `Popen`; +nothing has been launched natively. ### Observed image-file evidence diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 2984bb92b..1d0655559 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -809,3 +809,10 @@ With the other process-memory tests and the typing, complexity, broad-except and file-length gates: 262 passed. Nothing was launched or read. - **Files:** `utils/process_memory/{windows_image,windows_launch}.py`, the test, `docs/process_memory_contract.md`, `architecture_explore.md`, `Progress.md`. - **Open items:** `Progress.md` › process-memory observation (loaded-image binding, the real `Popen` launcher, attesting processes the host did not start, native acceptance). + +## U-20261115-20 · 2026-11-15 · PopenLauncher measures the owned child through Popen's own handle · #done #process-memory + +- **What:** U-20261115-19 left the owned-launch attestor without a real launcher: `launch_attested` takes any callable returning a `LaunchRecord`. +- **Change:** `windows_launch.PopenLauncher(arguments, *, kernel=None, ..., popen=subprocess.Popen, **options)` starts the leased path from an argv list (a non-string argument or a `shell` option is refused at construction) and measures PID and birth with `measure_process` on `Popen._handle`, the handle `CreateProcess` returned, never a handle reopened by PID. A measured PID that is not `Popen.pid` is `target_changed`; a second launch on the same launcher is refused, so `child` always names the one process started. The child stays the caller's to wait on or end, including after a failed attestation. +- **Tests:** `test_process_memory_launch.py` gains 5 (the argv, options and measured handle; no `OpenProcess`; another PID; a second launch; argument and `shell` refusal; an attestation end to end through the launcher): 24 passed. A fake `Popen` and injected native calls; nothing was started. +- **Files:** `utils/process_memory/windows_launch.py`, the test, `docs/process_memory_contract.md`, `architecture_explore.md` (re-measured), `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 8621ed750..d2b7f1db4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-20 | 2026-11-15 | PopenLauncher measures the owned child through Popen's own handle | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-19 | 2026-11-15 | Owned-launch attestor: lease, pinned SHA-256, re-observed child | #done #process-memory #security | [2026-11-b](2026-11-b.md) | | U-20261115-18 | 2026-11-15 | The memory fixture's bootstrap is bound by a header challenge | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-17 | 2026-11-15 | Process-memory resolvers get a bounded view of the retained handle | #done #process-memory | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/process_memory/windows_launch.py b/je_auto_control/utils/process_memory/windows_launch.py index 4dae0692d..642ed8111 100644 --- a/je_auto_control/utils/process_memory/windows_launch.py +++ b/je_auto_control/utils/process_memory/windows_launch.py @@ -12,18 +12,21 @@ """ from __future__ import annotations +import ctypes from dataclasses import dataclass, field import hmac import re +import subprocess # nosec B404 # reason: the owned launch starts the pinned, leased image itself import time -from typing import Callable, NoReturn, Protocol +from typing import Any, Callable, NoReturn, Protocol, Sequence from je_auto_control.utils.exception.control_signals import raise_if_run_interrupted from je_auto_control.utils.executor.run_control import ExecutionStopped from .models import FailureReason, MemoryObservationError, ProcessIdentity, _identifier -from .windows_facts import NativeProcessFacts +from .windows_facts import NativeProcessFacts, measure_process from .windows_image import LeasedImageFile, ObservedImageFile +from .windows_native import ProcessKernel, bind_process, load _SHA256 = re.compile(r"[0-9a-f]{64}") @@ -81,6 +84,45 @@ def close(self) -> None: ... Launcher = Callable[[str], LaunchRecord] +class PopenLauncher: + """Start the image with ``subprocess`` and measure PID and birth from the handle Popen holds. + + The handle is the one ``CreateProcess`` returned, so the measurement cannot + land on another process that reused the PID; opening the PID afresh could. + The started child is kept as :attr:`child` (``None`` before a launch) for + the caller to wait on or end, including when attestation fails. + """ + + def __init__(self, arguments: Sequence[str] = (), *, kernel: ProcessKernel | None = None, + last_error: Callable[[], int] | None = None, caller_bits: int | None = None, + popen: Callable[..., Any] = subprocess.Popen, **options: Any) -> None: + if any(not isinstance(argument, str) for argument in arguments) or "shell" in options: + _fail(FailureReason.UNSUPPORTED) + bits = ctypes.sizeof(ctypes.c_void_p) * 8 if caller_bits is None else caller_bits + if kernel is None: + loaded, last_error = load() + kernel = loaded + elif last_error is None: + _fail(FailureReason.UNSUPPORTED) + else: + bind_process(kernel) + self._arguments, self._options, self._popen = tuple(arguments), options, popen + self._kernel, self._last_error, self._bits = kernel, last_error, bits + self.child: Any = None + + def __call__(self, path: str) -> LaunchRecord: + if self.child is not None: + _fail(FailureReason.UNSUPPORTED) # one launch per launcher, so ``child`` is unambiguous + # An argv list, never a shell; ``path`` is the file the caller leased and pinned. + self.child = self._popen([path, *self._arguments], shell=False, **self._options) + # Popen keeps the CreateProcess handle as ``_handle`` on Windows. + handle = int(getattr(self.child, "_handle")) + facts = measure_process(self._kernel, handle, self._last_error, self._bits) + if facts.pid != self.child.pid: + _fail(FailureReason.TARGET_CHANGED) + return LaunchRecord(facts.pid, facts.birth) + + class OwnedLaunchAttestor: """Attest the one launched process, and only while its facts are those attested.""" @@ -180,4 +222,4 @@ def launch_attested(pin: PinnedExecutable, path: str, launch: Launcher, *, __all__ = ["ImageLease", "ImageObserver", "LaunchRecord", "Launcher", "OwnedLaunch", - "OwnedLaunchAttestor", "PinnedExecutable", "launch_attested"] + "OwnedLaunchAttestor", "PinnedExecutable", "PopenLauncher", "launch_attested"] diff --git a/test/unit_test/headless/test_process_memory_launch.py b/test/unit_test/headless/test_process_memory_launch.py index c4d7ad6b2..db48376c9 100644 --- a/test/unit_test/headless/test_process_memory_launch.py +++ b/test/unit_test/headless/test_process_memory_launch.py @@ -151,3 +151,57 @@ def cancelled(path): def test_a_pin_must_be_a_lowercase_sha256_and_identifiers(changes): with pytest.raises(MemoryObservationError, match="unsupported"): pin(LaunchKernel(), **changes) + + +class _Child: + def __init__(self, pid, handle): + self.pid, self._handle = pid, handle + + +def _popen_launcher(kernel, child_pid=42, **options): + from je_auto_control.utils.process_memory.windows_launch import PopenLauncher + started = [] + + def popen(argv, **kwargs): + started.append((argv, kwargs)) + return _Child(child_pid, 77) + + launcher = PopenLauncher(("--challenge", "00" * 16), kernel=kernel, last_error=lambda: kernel.error, + caller_bits=64, popen=popen, **options) + return launcher, started + + +def test_the_popen_launcher_measures_the_handle_popen_holds(): + kernel = LaunchKernel() + launcher, started = _popen_launcher(kernel, creationflags=0x08000000) + record = launcher(kernel.image_path) + assert record == LaunchRecord(42, kernel.birth) + assert started == [([kernel.image_path, "--challenge", "00" * 16], {"shell": False, "creationflags": 0x08000000})] + assert {call[0] for call in kernel.GetProcessTimes.calls} == {77} # never a handle reopened by PID + assert not kernel.OpenProcess.calls + assert launcher.child.pid == 42 + + +def test_the_popen_launcher_refuses_a_handle_for_another_pid_and_a_second_launch(): + kernel = LaunchKernel() + launcher, _ = _popen_launcher(kernel, child_pid=43) + with pytest.raises(MemoryObservationError, match="target_changed"): + launcher(kernel.image_path) + assert launcher.child.pid == 43 # still the caller's to end + with pytest.raises(MemoryObservationError, match="unsupported"): + launcher(kernel.image_path) + + +@pytest.mark.parametrize("arguments,options", [((1,), {}), ((), {"shell": True})]) +def test_the_popen_launcher_takes_only_an_argv_list(arguments, options): + from je_auto_control.utils.process_memory.windows_launch import PopenLauncher + kernel = LaunchKernel() + with pytest.raises(MemoryObservationError, match="unsupported"): + PopenLauncher(arguments, kernel=kernel, last_error=lambda: 0, **options) + + +def test_an_owned_launch_through_the_popen_launcher_is_attested(): + kernel = LaunchKernel() + launcher, _ = _popen_launcher(kernel) + launch, *_ = attest(kernel, launcher=launcher) + assert launch.identity.pid == 42 and launch.record == LaunchRecord(42, kernel.birth) From 69eb4ae7faa414d27144d7f4c3b4376625d02f7e Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 20:25:57 +0800 Subject: [PATCH 139/161] Decode GUI frames through loadFromData instead of ignoring the fromData stub PySide6 6.12 still types QImage.fromData's format as bytes while the binding rejects bytes; loadFromData's stub and binding agree on str, so one typed helper replaces five type-ignores. --- Progress.md | 2 -- architecture_explore.md | 18 +++++------ docs/updates/2026-11-b.md | 7 ++++ docs/updates/README.md | 1 + je_auto_control/gui/_qt_typed.py | 18 +++++++++-- je_auto_control/gui/admin_console_tab.py | 5 +-- .../gui/remote_desktop/connection_screen.py | 7 ++-- .../gui/remote_desktop/host_panel.py | 5 +-- .../gui/remote_desktop/viewer_panel.py | 3 +- test/unit_test/headless/test_gui_qt_typed.py | 32 +++++++++++++++++-- 10 files changed, 74 insertions(+), 24 deletions(-) diff --git a/Progress.md b/Progress.md index 7bbfa2162..ad2d1ddc4 100644 --- a/Progress.md +++ b/Progress.md @@ -117,8 +117,6 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 系統匣路徑在 offscreen 下沒有 tray,`_on_tray_open` 是直接呼叫測的。基準(`benchmarks/gui_*.py`)CI 仍不設門檻。 - **把 Python 建的 widget 放進分頁列在結束時崩潰**:已查明觸發條件——分頁列按鈕上接了 Python callable、又有排隊中的 `deleteLater()`、而行程經 `os._exit` 離開; 先把 deferred delete 沖掉就不會。機制(Qt 在行程結束時釋放那個 slot)是推論,沒有 C 堆疊可看。`_tab_close_icon.py` 沒有改回自訂按鈕。 -- **Qt binding 與 stub 的差異**:`QImage.fromData(x, "JPEG")` 的 5 處仍保留 `# type: ignore[arg-type]`: - stub 要 bytes,實際的 binding 對 bytes 丟 `ValueError`。 - 遠端桌面的輸入改成佇列送出後,`AC_remote_send_input` 回的 `{"sent": True}` 意思是「已排入」;`SO_SNDTIMEO` 的 POSIX 包法與經 TLS socket 的行為沒在這台機器上驗過。 - 沒在 macOS/Linux 上看過新的關閉鈕、捲動與重設樣式;沒在真的多螢幕桌面試過視窗位置還原;PyBreeze 沒有對這一版跑過;各語系新增的字串(日文、簡體中文)沒有母語者看過。 diff --git a/architecture_explore.md b/architecture_explore.md index b4d20f143..f86d2c240 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,509 | +| 程式碼總行數 | 238,525 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1392,10 +1392,10 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | dag_runner | `dag_tab.py` | 367 | 編輯、驗證、執行跨主機 DAG。 | | chatops | `chatops_tab.py` | 140 | 在接上 Slack 前先本機測試 slash 指令。 | | trace_replay | `trace_replay_tab.py` | 194 | 拖曳捲動時光回溯錄製內容。 | -| remote_desktop | `remote_desktop/`(40 檔) | 8,577 | 見下。 | +| remote_desktop | `remote_desktop/`(40 檔) | 8,580 | 見下。 | | presence | `presence_tab.py` | 171 | 多檢視者在場名單。 | | rest_api | `rest_api_tab.py` | 256 | 啟停 HTTP 前端並顯示 URL、實際驗證模式與可用 token。 | -| admin_console | `admin_console_tab.py` | 330 | 管理多個遠端 AutoControl REST 端點。 | +| admin_console | `admin_console_tab.py` | 331 | 管理多個遠端 AutoControl REST 端點。 | | audit_log | `audit_log_tab.py` | 193 | 瀏覽並驗證防竄改雜湊鏈。 | | inspector | `inspector_tab.py` | 133 | WebRTC 檢測器:即時摘要與近期統計取樣。 | | usb_devices | `usb_devices_tab.py` | 176 | 唯讀列舉 + 熱插拔監看控制。 | @@ -1410,7 +1410,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | --- | ---: | --- | | `gui/diagnostics_capabilities.py` | 60 | 只呈現既有不可變能力快照與四語狀態;不探測、不連線,不持有原生物件。 | -#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,577 行) +#### 遠端桌面 GUI(`gui/remote_desktop/`,41 檔/8,580 行) | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1425,10 +1425,10 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `webrtc_dialogs.py` | 533 | WebRTC GUI 用的自訂對話框與清單元件(待審檢視者、信任清單、通訊錄、遠端檔案表、稽核記錄、LAN 瀏覽)。 | | `advanced_group.py` | 99 | 兩個 WebRTC 面板共用的 Advanced STUN/TURN(含選用硬體編碼器)群組,含分離的 STUN/TURN 與選用主機硬體編碼器 Protocol。 | | `trusted_group.py` | 75 | WebRTC host 面板的信任 viewer 清單群組(移除/清空/匯入/匯出),含它寫回面板的 Protocol。 | -| `connection_screen.py` | 723 | Quick Connect —— AnyDesk 風格單畫面入口。 | -| `viewer_panel.py` | 617 | 「控制另一台機器」子分頁。 | +| `connection_screen.py` | 724 | Quick Connect —— AnyDesk 風格單畫面入口。 | +| `viewer_panel.py` | 618 | 「控制另一台機器」子分頁。 | | `webrtc_known_hosts.py` | 345 | TOFU 釘選庫瀏覽器:`KnownHostsDialog` 與帶外釘選用的小表單。由 `webrtc_dialogs` 再匯出。 | -| `host_panel.py` | 396 | 「分享這台機器」子分頁。 | +| `host_panel.py` | 397 | 「分享這台機器」子分頁。 | | `_host_ops.py` | 39 | Start and stop the machine's remote-desktop host on a worker thread. Host 面板與 Quick Connect 共用的 `replace_host`/`stop_host`/`release_host`。 | | `frame_display.py` | 229 | 繪製 JPEG 影格並發出遠端輸入事件的元件。 | | `webrtc_workers.py` | 253 | 訊令流程的背景 worker(`DaemonThread`,長輪詢比面板或程式活得久也不會中止行程)。 | @@ -1550,7 +1550,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,934 | +| `gui/` | 166 | 43,950 | | `utils/mcp_server/` | 63 | 22,322 | | `utils/remote_desktop/` | 77 | 16,938 | | `utils/executor/` | 11 | 10,765 | @@ -1571,7 +1571,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,132 | -| **總計** | **1,534** | **237,764** | +| **總計** | **1,534** | **237,780** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 1d0655559..71329fbd7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -816,3 +816,10 @@ - **Change:** `windows_launch.PopenLauncher(arguments, *, kernel=None, ..., popen=subprocess.Popen, **options)` starts the leased path from an argv list (a non-string argument or a `shell` option is refused at construction) and measures PID and birth with `measure_process` on `Popen._handle`, the handle `CreateProcess` returned, never a handle reopened by PID. A measured PID that is not `Popen.pid` is `target_changed`; a second launch on the same launcher is refused, so `child` always names the one process started. The child stays the caller's to wait on or end, including after a failed attestation. - **Tests:** `test_process_memory_launch.py` gains 5 (the argv, options and measured handle; no `OpenProcess`; another PID; a second launch; argument and `shell` refusal; an attestation end to end through the launcher): 24 passed. A fake `Popen` and injected native calls; nothing was started. - **Files:** `utils/process_memory/windows_launch.py`, the test, `docs/process_memory_contract.md`, `architecture_explore.md` (re-measured), `Progress.md`. + +## U-20261115-21 · 2026-11-15 · Decode GUI frames through loadFromData; drop the five fromData type-ignores · #done #typing #gui + +- **What:** `Progress.md` › GUI gaps listed five `QImage.fromData(x, "JPEG")` / `"PNG"` calls kept under `# type: ignore[arg-type]`: the stub types the format as bytes, and the binding rejects bytes with `ValueError`. Re-probed on PySide6 6.12.0: `fromData` still rejects bytes, bytearray and memoryview and accepts only `str`; `loadFromData(data, "JPEG")` accepts `str` and its stub says `str`. +- **Change:** `gui/_qt_typed.decoded_image(data, image_format)` decodes through `QImage().loadFromData` and returns a null image when the bytes do not decode, as `fromData` did. The admin console thumbnails, the connection screen (two sites), the host preview and the viewer panel call it; the five ignores and three now-unused `QImage` imports are gone. +- **Tests:** `test_gui_qt_typed.py` gains 6 tests (PNG and JPEG frames decode to their size; empty, garbage and a truncated JPEG header give a null image; a guard that fails once the binding accepts the bytes format its stub asks for). With the admin-console thumbnail, remote-desktop GUI, view-retirement, quick-connect, off-thread and audit tests: 75 passed. `typing_contract_verify.py --extras` (real PySide6 6.12.0): 0 failing on win32, linux and darwin. +- **Files:** `gui/_qt_typed.py`, `gui/admin_console_tab.py`, `gui/remote_desktop/{connection_screen,host_panel,viewer_panel}.py`, the test, `architecture_explore.md` (re-measured), `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index d2b7f1db4..1f5ccb6b3 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-21 | 2026-11-15 | Decode GUI frames through loadFromData; drop the five fromData type-ignores | #done #typing #gui | [2026-11-b](2026-11-b.md) | | U-20261115-20 | 2026-11-15 | PopenLauncher measures the owned child through Popen's own handle | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-19 | 2026-11-15 | Owned-launch attestor: lease, pinned SHA-256, re-observed child | #done #process-memory #security | [2026-11-b](2026-11-b.md) | | U-20261115-18 | 2026-11-15 | The memory fixture's bootstrap is bound by a header challenge | #done #process-memory | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/_qt_typed.py b/je_auto_control/gui/_qt_typed.py index 352b08a11..e376fb8e2 100644 --- a/je_auto_control/gui/_qt_typed.py +++ b/je_auto_control/gui/_qt_typed.py @@ -1,6 +1,6 @@ -"""Two typed accessors for what Qt's own signatures cannot express. +"""Typed accessors for what Qt's own signatures cannot express. -Both exist so the GUI type-checks against the real PySide6 types +They exist so the GUI type-checks against the real PySide6 types (``test/verify/typing_contract_verify.py --extras``) without a cast at every call site: @@ -10,9 +10,14 @@ * ``QTableWidget.item()`` may answer ``None``, but a tab that fills every cell of a row itself knows the cell is there. :func:`filled_item` returns the item, and reports a cell that is missing as the bug it would be. +* ``QImage.fromData(data, "JPEG")`` is what the binding accepts, but its stub + types the format as bytes, which the binding rejects with ``ValueError``. + :func:`decoded_image` decodes through ``loadFromData``, whose stub and + binding agree on a ``str`` format. """ from typing import cast +from PySide6.QtGui import QImage from PySide6.QtWidgets import QTableWidget, QTableWidgetItem, QWidget from je_auto_control.utils.exception.exceptions import AutoControlException @@ -31,4 +36,11 @@ def filled_item(table: QTableWidget, row: int, column: int) -> QTableWidgetItem: return item -__all__ = ["as_widget", "filled_item"] +def decoded_image(data: bytes, image_format: str) -> QImage: + """``data`` decoded as ``image_format`` (``"PNG"``, ``"JPEG"``); a null image when it does not decode.""" + image = QImage() + image.loadFromData(data, image_format) + return image + + +__all__ = ["as_widget", "decoded_image", "filled_item"] diff --git a/je_auto_control/gui/admin_console_tab.py b/je_auto_control/gui/admin_console_tab.py index 740a6ff18..8386bf3b4 100644 --- a/je_auto_control/gui/admin_console_tab.py +++ b/je_auto_control/gui/admin_console_tab.py @@ -15,7 +15,7 @@ from typing import Any, Callable, Dict, List, Optional, Tuple from PySide6.QtCore import QSize, QTimer, Qt -from PySide6.QtGui import QIcon, QImage, QPixmap +from PySide6.QtGui import QIcon, QPixmap from PySide6.QtWidgets import ( QGroupBox, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QSpinBox, QTableWidget, @@ -24,6 +24,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._qt_typed import decoded_image from je_auto_control.gui._tab_task import TabTask from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.responsive import ResponsiveBox @@ -282,7 +283,7 @@ def _apply_thumbnails(self, png_by_label: Dict[str, Optional[bytes]]) -> None: def _icon_for(png: Optional[bytes]) -> Optional[QIcon]: if not png: return None - image = QImage.fromData(png, "PNG") # type: ignore[arg-type] # reason: the stub says bytes; PySide6 raises ValueError for bytes + image = decoded_image(png, "PNG") if image.isNull(): return None scaled = image.scaled( diff --git a/je_auto_control/gui/remote_desktop/connection_screen.py b/je_auto_control/gui/remote_desktop/connection_screen.py index 582daa157..e25f2e1a4 100644 --- a/je_auto_control/gui/remote_desktop/connection_screen.py +++ b/je_auto_control/gui/remote_desktop/connection_screen.py @@ -21,13 +21,14 @@ from typing import Any, Callable, List, Optional from PySide6.QtCore import Qt, QTimer, Signal -from PySide6.QtGui import QGuiApplication, QImage +from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import ( QGroupBox, QHBoxLayout, QLabel, QLineEdit, QListWidget, QMessageBox, QPushButton, QVBoxLayout, QWidget, ) from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._qt_typed import decoded_image from je_auto_control.gui.adaptive.responsive import ResponsiveBox from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui._dispose import release_resources @@ -598,7 +599,7 @@ def _on_frame(self, payload: bytes) -> None: window = self._screen_window if window is None: return - image = QImage.fromData(payload, "JPEG") # type: ignore[arg-type] # reason: the stub says bytes; PySide6 raises ValueError for bytes + image = decoded_image(payload, "JPEG") if not image.isNull(): window.set_image(image) @@ -620,7 +621,7 @@ def _open_screen_window(self, title: str) -> None: # If frames arrived before this window existed (race with the # motion-dedup capture path), apply the most recent now. if self._pending_frame is not None: - image = QImage.fromData(self._pending_frame, "JPEG") # type: ignore[arg-type] # reason: the stub says bytes; PySide6 raises ValueError for bytes + image = decoded_image(self._pending_frame, "JPEG") if not image.isNull(): self._screen_window.set_image(image) self._screen_window.show() diff --git a/je_auto_control/gui/remote_desktop/host_panel.py b/je_auto_control/gui/remote_desktop/host_panel.py index cf4f63c84..39a721f3c 100644 --- a/je_auto_control/gui/remote_desktop/host_panel.py +++ b/je_auto_control/gui/remote_desktop/host_panel.py @@ -5,7 +5,7 @@ from typing import Any, Optional from PySide6.QtCore import QTimer, Signal -from PySide6.QtGui import QGuiApplication, QImage +from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import ( QCheckBox, QComboBox, QFileDialog, QFormLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMessageBox, QPushButton, QSpinBox, QVBoxLayout, QWidget, @@ -13,6 +13,7 @@ from je_auto_control.gui._dispose import release_resources from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._qt_typed import decoded_image from je_auto_control.gui._slow_op import SlowOp from je_auto_control.gui.adaptive.flow_layout import field_pair, flow_of from je_auto_control.gui.adaptive.surfaces import Card, set_role @@ -391,6 +392,6 @@ def _refresh_preview(self) -> None: frame = host.latest_frame() if frame is None: return - image = QImage.fromData(frame, "JPEG") # type: ignore[arg-type] # reason: the stub says bytes; PySide6 raises ValueError for bytes + image = decoded_image(frame, "JPEG") if not image.isNull(): self._preview.set_image(image) diff --git a/je_auto_control/gui/remote_desktop/viewer_panel.py b/je_auto_control/gui/remote_desktop/viewer_panel.py index 6b45d55ef..8537a4d44 100644 --- a/je_auto_control/gui/remote_desktop/viewer_panel.py +++ b/je_auto_control/gui/remote_desktop/viewer_panel.py @@ -16,6 +16,7 @@ from je_auto_control.gui.adaptive.surfaces import set_role from je_auto_control.gui.remote_desktop.view_lifetime import ViewLifetime from je_auto_control.gui._i18n_helpers import TranslatableMixin +from je_auto_control.gui._qt_typed import decoded_image from je_auto_control.gui._dispose import release_resources from je_auto_control.gui.remote_desktop._connect_task import connect_viewer from je_auto_control.gui.remote_desktop._helpers import ( @@ -466,7 +467,7 @@ def _on_session_error(self, session: int, message: str) -> None: self._on_error_main(message) def _on_frame_main(self, payload: bytes) -> None: - image = QImage.fromData(payload, "JPEG") # type: ignore[arg-type] # reason: the stub says bytes; PySide6 raises ValueError for bytes + image = decoded_image(payload, "JPEG") if image.isNull(): return if self._screen_window is None: diff --git a/test/unit_test/headless/test_gui_qt_typed.py b/test/unit_test/headless/test_gui_qt_typed.py index eed90b89d..2459b021b 100644 --- a/test/unit_test/headless/test_gui_qt_typed.py +++ b/test/unit_test/headless/test_gui_qt_typed.py @@ -6,11 +6,12 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) -from PySide6.QtCore import Qt # noqa: E402 +from PySide6.QtCore import QBuffer, QByteArray, QIODevice, Qt # noqa: E402 +from PySide6.QtGui import QImage # noqa: E402 from PySide6.QtWidgets import QAbstractItemView, QApplication, QLabel, QPushButton, QTableWidget, QTableWidgetItem # noqa: E402 from je_auto_control.gui._i18n_helpers import TranslatableMixin # noqa: E402 -from je_auto_control.gui._qt_typed import as_widget, filled_item # noqa: E402 +from je_auto_control.gui._qt_typed import as_widget, decoded_image, filled_item # noqa: E402 from je_auto_control.utils.exception.exceptions import AutoControlException # noqa: E402 @@ -53,3 +54,30 @@ def test_the_scoped_enum_spellings_are_the_members_the_short_ones_named(): assert QAbstractItemView.EditTrigger.NoEditTriggers is QAbstractItemView.NoEditTriggers assert Qt.ItemFlag.ItemIsEditable is Qt.ItemIsEditable assert Qt.ItemDataRole.UserRole is Qt.UserRole + + +def _encoded(image_format: str) -> bytes: + image = QImage(6, 4, QImage.Format.Format_RGB32) + image.fill(0xFF2040) + data = QByteArray() + buffer = QBuffer(data) + buffer.open(QIODevice.OpenModeFlag.WriteOnly) + assert image.save(buffer, image_format) + return bytes(data) + + +@pytest.mark.parametrize("image_format", ["PNG", "JPEG"]) +def test_an_encoded_frame_decodes_to_its_image(image_format): + image = decoded_image(_encoded(image_format), image_format) + assert not image.isNull() and (image.width(), image.height()) == (6, 4) + + +@pytest.mark.parametrize("payload", [b"", b"not an image", bytes([0xFF, 0xD8, 0xFF]) + bytes(16)]) +def test_bytes_that_do_not_decode_are_a_null_image(payload): + assert decoded_image(payload, "JPEG").isNull() + + +def test_the_binding_still_rejects_the_bytes_format_its_stub_asks_for(): + """When this stops raising, ``QImage.fromData`` can be called directly again.""" + with pytest.raises(ValueError): + QImage.fromData(_encoded("PNG"), b"PNG") From 8503be2ce89195b2897fed16458984f9b3757c68 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 20:35:01 +0800 Subject: [PATCH 140/161] Verify the audit chain read-only so ac_diagnose creates no audit database The READ_ONLY diagnosis opened the default log through AuditLog, which made ~/.je_auto_control/audit.db, its schema and the one-off chain backfill on a machine that had none. --- CHANGELOG.md | 6 + Progress.md | 1 - architecture_explore.md | 20 +-- .../operations_layer/operations_layer_doc.rst | 4 +- .../operations_layer/operations_layer_doc.rst | 3 +- docs/updates/2026-11-b.md | 21 ++++ docs/updates/README.md | 1 + .../utils/diagnostics/diagnostics.py | 11 +- .../utils/remote_desktop/audit_log.py | 90 +++++++++----- .../headless/test_audit_chain_read_only.py | 114 ++++++++++++++++++ 10 files changed, 227 insertions(+), 44 deletions(-) create mode 100644 test/unit_test/headless/test_audit_chain_read_only.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c15b7fcb5..5f83a40a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- Diagnostics (`run_diagnostics`, `ac_diagnose`): the `audit_chain` check verifies the audit log + through a read-only SQLite connection (`verify_audit_chain_read_only`) and no longer creates + `~/.je_auto_control/audit.db`, its schema or the one-off chain backfill. With no chained log yet + it reports `ok` with "no chained audit log yet; diagnostics does not create one" instead of + "chain verified (0 rows)". + - Typing: the whole package is held to the strict mypy tier. `MouseKeycode` is now the platform's own button type (a tuple of three Win32 flags on Windows, a string such as `"Left"` on macOS, an int on X11 and Wayland) instead of `Any`. The macOS backend's `press_mouse` / `release_mouse` / diff --git a/Progress.md b/Progress.md index ad2d1ddc4..eb69edab7 100644 --- a/Progress.md +++ b/Progress.md @@ -132,7 +132,6 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 私鑰支援選用通行碼加密,未設定時仍是明文 PEM(0600,Windows 上沒驗權限位元);遷移模式開著時 HMAC 簽章會被接受。 - **RBAC**(`JE_AUTOCONTROL_RBAC_USERS`,預設關閉): - `ac_list_plugins` 的外掛 factory,以及 `ac_web_list_commands`/`ac_web_current_url` 的實際相依版本初始化契約尚待審查;目前不列入唯讀目錄,完整目錄仍要求 `read_data`。本機 sibling 原始碼不代表部署版本驗收。 - - `ac_diagnose` 的預設 audit-log 初始化可能建立固定目錄及 SQLite schema;全域零寫入診斷與外部 SDK 初始化副作用仍未驗證。 - 沒對真的 client(Claude Desktop、VS Code、內建 dashboard)試過;回送測試的 SSE、無狀態、`subscriptions/listen` 與 TLS 結果不代表真實客戶端通過。 - **MCP 路徑根目錄**(`JE_AUTOCONTROL_MCP_PATH_ROOTS`,預設關閉):`path-or-other` 已檢查 `ac_open_path`/`ac_plan_open`/`ac_file_association`/`ac_act_in_view` 的 `target` 與 `ac_handle_file_dialog` 的 `path`, diff --git a/architecture_explore.md b/architecture_explore.md index f86d2c240..a837cb7b8 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,525 | +| 程式碼總行數 | 238,564 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,14 +324,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 5,275 行。 +> 15 個套件、約 5,282 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/callback/` | 215 | Observer 模式:`callback_executor` 以字串名觸發功能;trigger 與 callback 共用秘密遮罩至錯誤處理結束 | | `utils/config_bundle/` | 424 | 使用者設定的單檔匯出/匯入 | | `utils/critical_exit/` | 132 | 監看緊急停止鍵的守護執行緒,用於中止失控腳本 | -| `utils/diagnostics/` | 358 | 跨子系統的「一切正常嗎」健檢,附 `python -m` 進入點 | +| `utils/diagnostics/` | 365 | 跨子系統的「一切正常嗎」健檢,附 `python -m` 進入點 | | `utils/dbus_client/` | 827 | 只用標準函式庫的 D-Bus session bus 客戶端。原本在 `linux_wayland/` 為 portal 交握而寫,AT-SPI 無障礙後端成為第二個使用者後搬到這裡(`utils/` 在分層上在各 OS 套件之上) | | `utils/exception/` | 377 | **例外階層根**。框架錯誤繼承 `AutoControlException`;`control_signals.py` 共用無 executor 相依的取消載體/分類,保留 MCP 與 history 舊匯入別名;`cancellation.py` 提供 Qt-free 協作式 token 與 immutable progress;另有集中式錯誤訊息(`exception_tags`)。 | | `utils/failure_bundle/` | 229 | 可攜、已遮蔽的失敗診斷 ZIP(截圖 + 診斷 + log 尾段) | @@ -537,14 +537,14 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.10 遠端桌面與 USB -> 6 個套件、約 32,266 行。 +> 6 個套件、約 32,298 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/admin/` | 473 | 多主機管理主控台:平行輪詢 N 個 AutoControl REST 端點 | | `utils/config_sync/` | 8,577 | 持久化設定與條件交易:`contract.py` 管理有限 JSON 與協定例外;`store.py` 以 SQLite 原子比較版本/記錄重送收據;`routes.py` 提供第二版 HTTP 與明確盲寫相容;`commands.py` 共用 AC/MCP/Builder;`client.py` 條件提交,另有因果模型、peer ledger 與本機 SQLite outbox;第三版 /causal 交易已接上確認/退休/回收與刪除憑證;client/outbox 已接上原請求重送、有界 CAS 重合併及原子快照確認;持久化控制、原子本機 full-resync/舊待送退役與歷史收據已接上。本機資產工具另提供 manifest、整版雜湊驗證與不可變目錄發布;七種來源 adapters 保存可攜因果 profiles;workspace INI 與 GUI 共用偏好正規化。來源/outbox 與原子 full-resync 基準已由 SyncWorkspace 協調;引用資產以不可變分塊/完整 hash 收據、具驗證 HTTP 與完整 profile 串流發布接上;Sync UI 仍屬 C3。 | | `utils/device_matrix/` | 201 | 行動裝置矩陣:同一 action list 於多台裝置平行執行 | -| `utils/remote_desktop/` | 16,938 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | +| `utils/remote_desktop/` | 16,970 | **遠端桌面子系統**:TCP/WebSocket/WebRTC 三條傳輸路徑、主機與檢視端、訊令伺服器、TURN/中繼、多檢視者、錄影、信任清單、TOTP、稽核鏈;私有選用功能模組保留整組匯入結果。 | | `utils/usb/` | 5,069 | 跨平台 USB 列舉/熱插拔/裝置直通(WinUSB、IOKit、libusb 後端 + ACL + WebRTC DataChannel 通道) | | `utils/usbip/` | 1,008 | USB/IP 線路協定主機端(協定封包、TCP 伺服器、libusb URB 後端) | @@ -818,7 +818,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rate_limit.py` | 48 | 工具呼叫的 token bucket 限流。 | | `__main__.py` | 126 | `je_auto_control_mcp` console script 進入點。 | -#### `utils/remote_desktop/`(16,938 行/77 檔) +#### `utils/remote_desktop/`(16,970 行/77 檔) 三條傳輸路徑並存:**TCP**(JPEG 影格)、**WebSocket**(同協定換傳輸)、**WebRTC**(aiortc 視訊 + DataChannel)。 `_export_bindings.py` 保存產生的來源對照;`_optional/` 分別管理 WebRTC、錄影、多檢視者、 @@ -840,7 +840,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `webrtc_transport.py` | 422 | 共用 WebRTC 管線:asyncio 橋接執行緒、螢幕視訊軌、設定。 | | `multi_viewer.py` | 523 | 每個連入檢視端各跑一個 `WebRTCDesktopHost` 的協調器。 | | `signaling_server.py` | 393 | WebRTC SDP rendezvous、持久化設定及具驗證的資產 chunk/blob 路由;CLI 提供 config/asset store 路徑與明確舊版寫入相容。 | -| `audit_log.py` | 355 | SQLite 雜湊鏈稽核記錄。 | +| `audit_log.py` | 387 | SQLite 雜湊鏈稽核記錄。 | | `host_capture.py` | 324 | TCP 主機的影格與游標產生:螢幕列舉、監視器索引轉擷取區域、預設 JPEG/游標 provider,以及 `FrameProductionMixin`(游標輪詢、擷取迴圈、上線編碼)。 | | `ws_protocol.py` | 318 | 最小 RFC 6455 WebSocket 框架與握手。 | | `file_transfer.py` | 484 | 分塊檔案傳輸。 | @@ -1552,7 +1552,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | --- | ---: | ---: | | `gui/` | 166 | 43,950 | | `utils/mcp_server/` | 63 | 22,322 | -| `utils/remote_desktop/` | 77 | 16,938 | +| `utils/remote_desktop/` | 77 | 16,970 | | `utils/executor/` | 11 | 10,765 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | @@ -1570,8 +1570,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,132 | -| **總計** | **1,534** | **237,780** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,139 | +| **總計** | **1,534** | **237,819** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst index 32211ed25..ab5a5e0d8 100644 --- a/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Eng/doc/operations_layer/operations_layer_doc.rst @@ -635,7 +635,9 @@ Bundled checks: - ``optional_deps`` — inventory of optional modules (aiortc, av, pyusb, pyaudio, pytesseract, cv2, PySide6) with available/missing breakdown - ``executor`` — count of registered ``AC_*`` commands -- ``audit_chain`` — chain integrity (uses ``verify_chain()``) +- ``audit_chain`` — chain integrity, read-only (``verify_audit_chain_read_only()``: never creates + ``~/.je_auto_control/audit.db``, its schema or the one-off backfill; reports "no chained audit + log yet" when there is none) - ``screenshot`` — captures a real screen image - ``mouse`` — reads current mouse position - ``disk_space`` — free space in user home (warn <1 GB, error <100 MB) diff --git a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst index 00af2ed81..0d186000c 100644 --- a/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst +++ b/docs/source/Zh/doc/operations_layer/operations_layer_doc.rst @@ -566,7 +566,8 @@ GUI:*USB Devices* 分頁加上 *Auto-refresh + watch hotplug* 勾選, - ``optional_deps`` — 選用模組清單(aiortc、av、pyusb、pyaudio、 pytesseract、cv2、PySide6),提供已裝/缺少的明細 - ``executor`` — 已註冊的 ``AC_*`` 指令數 -- ``audit_chain`` — 雜湊鏈完整性(使用 ``verify_chain()``) +- ``audit_chain`` — 雜湊鏈完整性,唯讀(``verify_audit_chain_read_only()``:不會建立 + ``~/.je_auto_control/audit.db``、它的 schema 或一次性補鏈;沒有紀錄時回報「尚無雜湊鏈稽核紀錄」) - ``screenshot`` — 實際擷取一張螢幕影像 - ``mouse`` — 讀取目前滑鼠座標 - ``disk_space`` — 使用者家目錄剩餘空間(<1 GB warn、<100 MB error) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 71329fbd7..987aa1fd6 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -823,3 +823,24 @@ - **Change:** `gui/_qt_typed.decoded_image(data, image_format)` decodes through `QImage().loadFromData` and returns a null image when the bytes do not decode, as `fromData` did. The admin console thumbnails, the connection screen (two sites), the host preview and the viewer panel call it; the five ignores and three now-unused `QImage` imports are gone. - **Tests:** `test_gui_qt_typed.py` gains 6 tests (PNG and JPEG frames decode to their size; empty, garbage and a truncated JPEG header give a null image; a guard that fails once the binding accepts the bytes format its stub asks for). With the admin-console thumbnail, remote-desktop GUI, view-retirement, quick-connect, off-thread and audit tests: 75 passed. `typing_contract_verify.py --extras` (real PySide6 6.12.0): 0 failing on win32, linux and darwin. - **Files:** `gui/_qt_typed.py`, `gui/admin_console_tab.py`, `gui/remote_desktop/{connection_screen,host_panel,viewer_panel}.py`, the test, `architecture_explore.md` (re-measured), `Progress.md`. + +## U-20261115-22 · 2026-11-15 · ac_diagnose verifies the audit chain read-only and creates no audit database · #done #diagnostics #security + +- **What:** `Progress.md` › follow-ups › RBAC said `ac_diagnose`'s default audit-log initialization might create a fixed directory and a SQLite schema, and that whole-diagnosis zero-write behavior was unverified. Measured with a fresh `HOME`/`USERPROFILE`/`TEMP` in a child process: the READ_ONLY tool created `~/.je_auto_control/audit.db` (schema, indexes, `chain_meta`, `user_version`) through `default_audit_log()`. The only other file was `~/.je_auto_control/logs/AutoControlGUI.log`, holding the one INFO line the package's action logger writes for `get_mouse_position`. That is the normal action log, which `JE_AUTOCONTROL_LOG_FILE` redirects, not a diagnostics side effect. The optional-dependency imports wrote nothing to the home or temp directory. +- **Change:** new `remote_desktop.audit_log.verify_audit_chain_read_only(path=None)`: + - It opens the file with `mode=ro` and returns `None` when there is no file, or when the log predates the chain (`user_version` below 1), which only a writable `AuditLog` open would backfill. + - It asks the in-process default instance when that is already open on the same path, and raises `AuditLogError` for a file SQLite cannot read. + - The chain walk is shared with `AuditLog.verify_chain` (`_read_chain`/`_check_chain`), so both report the same broken row. + - The `audit_chain` diagnostic uses it and reports "no chained audit log yet; diagnostics does not create one" for `None`. +- **Tests:** new `test_audit_chain_read_only.py`, 8 tests: + - a missing log (parent not created); + - an intact chain (file bytes unchanged); + - a tampered row, reported identically by the writable open; + - a pre-chain log, left unbackfilled and unchanged; + - an unreadable file; + - the already-open default instance; + - the diagnostic check; + - `ac_diagnose` in a child process with a fresh home, leaving no `~/.je_auto_control`. + + With the audit-log, audit-chain, diagnostics, cancellable-diagnostics and capability-parity tests: 59 passed. The typing contract (three platforms), complexity, broad-except and bandit are clean. +- **Files:** `utils/remote_desktop/audit_log.py`, `utils/diagnostics/diagnostics.py`, the test, `docs/source/{Eng,Zh}/doc/operations_layer/operations_layer_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 1f5ccb6b3..8000c88b3 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-22 | 2026-11-15 | ac_diagnose verifies the audit chain read-only and creates no audit database | #done #diagnostics #security | [2026-11-b](2026-11-b.md) | | U-20261115-21 | 2026-11-15 | Decode GUI frames through loadFromData; drop the five fromData type-ignores | #done #typing #gui | [2026-11-b](2026-11-b.md) | | U-20261115-20 | 2026-11-15 | PopenLauncher measures the owned child through Popen's own handle | #done #process-memory | [2026-11-b](2026-11-b.md) | | U-20261115-19 | 2026-11-15 | Owned-launch attestor: lease, pinned SHA-256, re-observed child | #done #process-memory #security | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/diagnostics/diagnostics.py b/je_auto_control/utils/diagnostics/diagnostics.py index 016eac717..2da671ee6 100644 --- a/je_auto_control/utils/diagnostics/diagnostics.py +++ b/je_auto_control/utils/diagnostics/diagnostics.py @@ -139,7 +139,7 @@ def _check_optional_deps() -> Check: def _check_audit_chain() -> Check: - from je_auto_control.utils.remote_desktop.audit_log import default_audit_log + from je_auto_control.utils.remote_desktop.audit_log import verify_audit_chain_read_only from je_auto_control.utils.sqlite_support import sqlite3_available # Without sqlite3 there is no chain to verify. Reporting that as a @@ -149,7 +149,14 @@ def _check_audit_chain() -> Check: name="audit_chain", ok=True, severity=_SEVERITY_WARN, detail="no audit log on this Python: it has no sqlite3", ) - result = default_audit_log().verify_chain() + # Read-only: a diagnosis must not create ~/.je_auto_control/audit.db, + # its schema, or run the one-off chain backfill. + result = verify_audit_chain_read_only() + if result is None: + return Check( + name="audit_chain", ok=True, severity=_SEVERITY_INFO, + detail="no chained audit log yet; diagnostics does not create one", + ) if result.ok: return Check( name="audit_chain", ok=True, severity=_SEVERITY_INFO, diff --git a/je_auto_control/utils/remote_desktop/audit_log.py b/je_auto_control/utils/remote_desktop/audit_log.py index 7be618699..aeaa3060b 100644 --- a/je_auto_control/utils/remote_desktop/audit_log.py +++ b/je_auto_control/utils/remote_desktop/audit_log.py @@ -164,10 +164,7 @@ def _backfill_chain_locked(self) -> None: def _read_anchor_locked(self) -> str: """The hash the first row must point at: genesis, or the last pruned row.""" - row = self._conn.execute( - "SELECT value FROM chain_meta WHERE key = 'anchor'" - ).fetchone() - return row[0] if row and row[0] else _GENESIS_HASH + return _read_anchor(self._conn) def _set_anchor_locked(self, value: str) -> None: self._conn.execute( @@ -256,30 +253,8 @@ def query(self, *, def verify_chain(self) -> ChainVerification: """Walk the chain top-to-bottom; return the first broken link.""" with self._lock: - cur = self._conn.execute( - "SELECT id, ts, event_type, host_id, viewer_id, detail," - " prev_hash, row_hash FROM events ORDER BY id ASC" - ) - rows = cur.fetchall() - anchor = self._read_anchor_locked() - if not rows: - return ChainVerification(ok=True, broken_at_id=None, total_rows=0) - prev_hash = anchor - for row in rows: - row_id, ts, event_type, host_id, viewer_id, detail, ph, rh = row - if ph != prev_hash: - return ChainVerification( - ok=False, broken_at_id=row_id, total_rows=len(rows), - ) - expected = _compute_row_hash( - ph, ts, event_type, host_id, viewer_id, detail, - ) - if expected != rh: - return ChainVerification( - ok=False, broken_at_id=row_id, total_rows=len(rows), - ) - prev_hash = rh - return ChainVerification(ok=True, broken_at_id=None, total_rows=len(rows)) + rows, anchor = _read_chain(self._conn) + return _check_chain(rows, anchor) def clear(self) -> int: """Wipe the table, leaving one ``audit_log_cleared`` event. Returns the rows deleted. @@ -314,6 +289,63 @@ def _compute_row_hash(prev_hash: Optional[str], ts: str, event_type: str, return hashlib.sha256(canonical.encode("utf-8")).hexdigest() +def _read_anchor(conn: Any) -> str: + row = conn.execute("SELECT value FROM chain_meta WHERE key = 'anchor'").fetchone() + return row[0] if row and row[0] else _GENESIS_HASH + + +def _read_chain(conn: Any) -> Tuple[List[Any], str]: + rows = conn.execute( + "SELECT id, ts, event_type, host_id, viewer_id, detail," + " prev_hash, row_hash FROM events ORDER BY id ASC" + ).fetchall() + return rows, _read_anchor(conn) + + +def _check_chain(rows: List[Any], anchor: str) -> ChainVerification: + prev_hash = anchor + for row in rows: + row_id, ts, event_type, host_id, viewer_id, detail, ph, rh = row + if ph != prev_hash or _compute_row_hash(ph, ts, event_type, host_id, viewer_id, detail) != rh: + return ChainVerification(ok=False, broken_at_id=row_id, total_rows=len(rows)) + prev_hash = rh + return ChainVerification(ok=True, broken_at_id=None, total_rows=len(rows)) + + +def verify_audit_chain_read_only(path: Optional[Path] = None) -> Optional[ChainVerification]: + """Verify a chained audit log without creating, migrating or writing it. + + ``None`` when there is nothing to verify that way: no file at ``path`` + (default: :func:`default_audit_log_path`), or a log written before the + chain existed, which only opening it with :class:`AuditLog` would + backfill. When this process already holds the default log open, that + instance is asked instead. A file SQLite cannot read raises + :class:`AuditLogError`. + """ + target = Path(path) if path is not None else default_audit_log_path() + with _default_lock: + opened = _default_audit_log + if opened is not None and opened._path == target: + return opened.verify_chain() + driver = require_sqlite3() + if not target.is_file(): + return None + try: + conn = driver.connect(f"{target.resolve().as_uri()}?mode=ro", uri=True) + except SQLITE_ERRORS as error: + raise AuditLogError(f"cannot open audit log {target}: {error}") from error + try: + (version,) = conn.execute("PRAGMA user_version").fetchone() + if int(version) < _CHAIN_SCHEMA_VERSION: + return None + rows, anchor = _read_chain(conn) + except SQLITE_ERRORS as error: + raise AuditLogError(f"cannot read audit log {target}: {error}") from error + finally: + conn.close() + return _check_chain(rows, anchor) + + _QUERY_SQL = ( "SELECT id, ts, event_type, host_id, viewer_id, detail" " FROM events" @@ -351,5 +383,5 @@ def default_audit_log() -> AuditLog: __all__ = [ "AuditLog", "ChainVerification", - "default_audit_log", "default_audit_log_path", + "default_audit_log", "default_audit_log_path", "verify_audit_chain_read_only", ] diff --git a/test/unit_test/headless/test_audit_chain_read_only.py b/test/unit_test/headless/test_audit_chain_read_only.py new file mode 100644 index 000000000..18db82620 --- /dev/null +++ b/test/unit_test/headless/test_audit_chain_read_only.py @@ -0,0 +1,114 @@ +"""The diagnosis verifies the audit chain without creating, migrating or writing the log. + +``ac_diagnose`` is annotated read-only, but its audit check opened the default +log through ``AuditLog``, which made ``~/.je_auto_control``, created the +SQLite schema and ran the one-off chain backfill on a machine that had none. +""" +import hashlib +import os +import sqlite3 +import subprocess +import sys + +import pytest + +from je_auto_control.utils.diagnostics import diagnostics +from je_auto_control.utils.remote_desktop import audit_log as audit_module +from je_auto_control.utils.remote_desktop.audit_log import ( + AuditLog, AuditLogError, verify_audit_chain_read_only, +) + + +def _digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@pytest.fixture +def chained(tmp_path): + path = tmp_path / "audit.db" + log = AuditLog(path) + for index in range(3): + log.log("auth_ok", host_id="h", viewer_id=f"v{index}") + log.close() + return path + + +def test_a_missing_log_is_nothing_to_verify_and_is_not_created(tmp_path): + path = tmp_path / "nested" / "audit.db" + assert verify_audit_chain_read_only(path) is None + assert not path.parent.exists() + + +def test_an_intact_chain_verifies_and_the_file_is_untouched(chained): + before = _digest(chained) + result = verify_audit_chain_read_only(chained) + assert (result.ok, result.total_rows) == (True, 3) + assert _digest(chained) == before + + +def test_a_tampered_row_is_reported_as_the_writable_open_reports_it(chained): + connection = sqlite3.connect(chained) + connection.execute("UPDATE events SET detail = 'forged' WHERE id = 2") + connection.commit() + connection.close() + result = verify_audit_chain_read_only(chained) + assert (result.ok, result.broken_at_id, result.total_rows) == (False, 2, 3) + log = AuditLog(chained) + try: + assert log.verify_chain() == result + finally: + log.close() + + +def test_a_log_from_before_the_chain_is_not_backfilled(tmp_path): + path = tmp_path / "audit.db" + connection = sqlite3.connect(path) + connection.execute("CREATE TABLE events (id INTEGER PRIMARY KEY, ts TEXT, event_type TEXT," + " host_id TEXT, viewer_id TEXT, detail TEXT)") + connection.execute("INSERT INTO events (ts, event_type) VALUES ('t', 'auth_ok')") + connection.commit() + connection.close() + before = _digest(path) + assert verify_audit_chain_read_only(path) is None + assert _digest(path) == before + + +def test_a_file_sqlite_cannot_read_is_an_audit_log_error(tmp_path): + path = tmp_path / "audit.db" + path.write_bytes(b"not a database" * 100) + with pytest.raises(AuditLogError): + verify_audit_chain_read_only(path) + + +def test_the_open_default_log_is_asked_directly(monkeypatch, chained): + log = AuditLog(chained) + monkeypatch.setattr(audit_module, "_default_audit_log", log) + monkeypatch.setattr(audit_module, "default_audit_log_path", lambda: chained) + try: + assert verify_audit_chain_read_only().total_rows == 3 + finally: + log.close() + + +def test_the_diagnostic_check_reports_no_log_without_making_one(monkeypatch, tmp_path): + path = tmp_path / "home" / ".je_auto_control" / "audit.db" + monkeypatch.setattr(audit_module, "_default_audit_log", None) + monkeypatch.setattr(audit_module, "default_audit_log_path", lambda: path) + check = diagnostics._check_audit_chain() + assert (check.ok, check.severity) == (True, "info") and "does not create" in check.detail + assert not (tmp_path / "home").exists() + + +def test_ac_diagnose_leaves_no_audit_database_in_a_fresh_home(tmp_path): + home = tmp_path / "home" + home.mkdir() + env = {**os.environ, "HOME": str(home), "USERPROFILE": str(home), + "JE_AUTOCONTROL_LOG_FILE": str(tmp_path / "log" / "run.log")} + code = ("from je_auto_control.utils.mcp_server.tools._diagnostics import _diagnose\n" + "report = _diagnose()\n" + "print([c['detail'] for c in report['checks'] if c['name'] == 'audit_chain'][0])\n") + done = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True, + timeout=240, check=False) + assert done.returncode == 0, done.stderr[-2000:] + assert "does not create" in done.stdout + assert not (home / ".je_auto_control").exists() From 86f981c69715beb4442bfca7d9563ea364390ade Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 20:41:37 +0800 Subject: [PATCH 141/161] Kill a captured shell command when its run is stopped or cancelled run_captured waited in one communicate(timeout), so a stop, ac_stop_execution or notifications/cancelled reached AC_shell_to_var and ac_shell only after the program or its timeout ended. --- CHANGELOG.md | 5 + Progress.md | 2 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 10 +- docs/updates/2026-11-b.md | 14 +++ docs/updates/README.md | 1 + .../utils/shell_process/shell_exec.py | 36 ++++++- test/unit_test/headless/test_mcp_call_run.py | 15 +++ .../headless/test_shell_captured_stop.py | 102 ++++++++++++++++++ 11 files changed, 180 insertions(+), 11 deletions(-) create mode 100644 test/unit_test/headless/test_shell_captured_stop.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f83a40a6..5fdc6040a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- `AC_shell_to_var` and MCP `ac_shell`: inside a stoppable run or a cancellation scope, a stop, + `ac_stop_execution` or `notifications/cancelled` kills the command's process tree within about + 0.1 s and ends the call (`ExecutionStopped`, or `-32800` for a client cancel), instead of waiting + for the program or its timeout. Outside a run the single bounded wait is unchanged. + - Diagnostics (`run_diagnostics`, `ac_diagnose`): the `audit_chain` check verifies the audit log through a read-only SQLite connection (`verify_audit_chain_read_only`) and no longer creates `~/.je_auto_control/audit.db`, its schema or the one-off chain backfill. With no chained log yet diff --git a/Progress.md b/Progress.md index eb69edab7..df1fbe67f 100644 --- a/Progress.md +++ b/Progress.md @@ -108,7 +108,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求、shell 指令)、單一手勢內的節奏 sleep; +- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求;擷取輸出的 shell 指令已可停止,U-20261115-23)、單一手勢內的節奏 sleep; 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/README.md b/README.md index 917bd76a4..48b43248a 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Host-requested file sends remain owned until their sender worker exits, includin MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. -An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first. +An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first, except a captured shell command (`ac_shell`, `AC_shell_to_var`): its process tree is killed and the call ends. REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. USB enumeration/events, retained inspector statistics and process metrics also require `read_data`, as do `AC_list_usb_devices`, `AC_usb_recent_events`, `AC_inspector_recent` and `AC_inspector_summary`. Dashboard panels report missing capabilities independently and clear stale rows. A successful session refresh also clears its previous error status. Unlisted executor-command authorization remains a separate audit scope. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 565fbca1d..9562c3c61 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -79,7 +79,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStop MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 -MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完。 +MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完;只有捕获输出的 shell 指令(`ac_shell`、`AC_shell_to_var`)例外:它的进程树会被结束,调用随即结束。 REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。USB 枚举/事件、保留的 inspector 统计与进程 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同样检查此权限。Dashboard 各面板分别显示缺少的权限并清除旧数据;session 刷新成功后也会清除先前的错误状态。未列入权限表的 executor 命令仍属于另一项审查范围。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index fb6430369..97b478b13 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -79,7 +79,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStop MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 -MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完。 +MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完;只有擷取輸出的 shell 指令(`ac_shell`、`AC_shell_to_var`)例外:它的行程樹會被結束,呼叫隨即結束。 REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。USB 列舉/事件、保留的 inspector 統計與程序 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同樣檢查此權限。Dashboard 各面板分別顯示缺少的權限並清除舊資料;session 重新整理成功後也會清除先前的錯誤狀態。未列入權限表格的 executor 指令仍屬另一項審查範圍。 diff --git a/architecture_explore.md b/architecture_explore.md index a837cb7b8..b12a1c6f6 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,564 | +| 程式碼總行數 | 238,596 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 5,282 行。 +> 15 個套件、約 5,314 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -341,7 +341,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | | `utils/process_memory/` | 1,471 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測、自有啟動加釘選雜湊的 attestor 與失敗 handle 回收;檔案證據不等於載入程式碼身分,原生驗收及 runtime 整合待完成 | -| `utils/shell_process/` | 280 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | +| `utils/shell_process/` | 312 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | ### 5.4.3 排程、觸發與背景監看 @@ -1570,8 +1570,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,139 | -| **總計** | **1,534** | **237,819** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,171 | +| **總計** | **1,534** | **237,851** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 987aa1fd6..76793226b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -844,3 +844,17 @@ With the audit-log, audit-chain, diagnostics, cancellable-diagnostics and capability-parity tests: 59 passed. The typing contract (three platforms), complexity, broad-except and bandit are clean. - **Files:** `utils/remote_desktop/audit_log.py`, `utils/diagnostics/diagnostics.py`, the test, `docs/source/{Eng,Zh}/doc/operations_layer/operations_layer_doc.rst`, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. + +## U-20261115-23 · 2026-11-15 · A stop or cancel kills a captured shell command instead of waiting for it · #done #executor #mcp + +- **What:** `Progress.md` › GUI gaps › "stop 還叫不醒的" listed a shell command among the single backend calls a stop could not reach. `AC_shell_command` already returns at once (it starts the program and reads it on threads), but `run_captured`, behind `AC_shell_to_var` and MCP `ac_shell`, waited in one `communicate(timeout=...)`: a stop landed only after the program ended or the whole timeout (default 30 s, here 60 s) passed. +- **Change:** `shell_exec.run_captured` waits through `_communicate_stoppable`. + - Inside a stoppable run (`run_control`) or a cancellation scope it polls every 0.1 s and checks both mechanisms between waits. Input is handed over on the first wait only, since `communicate` refuses it twice. + - A stop, a cancellation, the timeout or any other escape kills the whole process tree (`_kill_tree`), reaps the process and re-raises. + - Outside both it is the single bounded wait it was. +- **Tests:** + - New `test_shell_captured_stop.py`, 6 tests: a stop and a cancellation each end a 60 s sleeper and kill it; input and output still arrive whole inside a run; the timeout still applies; one wait outside a run; a stopped `AC_shell_to_var` ends the script promptly and skips the next action (measured 0.71 s against the 60 s timeout). + - `test_mcp_call_run.py` gains a `notifications/cancelled` test that ends a running `ac_shell` with `-32800`. + - With the MCP call-run, console-encoding, executor-containment, shell/clipboard and data-command tests: 48 passed, 1 skipped. Typing contract, complexity, broad-except and bandit are clean. +- **Files:** `utils/shell_process/shell_exec.py`, the two tests, `README.md` and both translations, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. +- **Open items:** `Progress.md` › GUI gaps (image search, OCR and HTTP requests already inside a backend; rhythm sleeps within one gesture). diff --git a/docs/updates/README.md b/docs/updates/README.md index 8000c88b3..c4b8267cd 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-23 | 2026-11-15 | A stop or cancel kills a captured shell command instead of waiting for it | #done #executor #mcp | [2026-11-b](2026-11-b.md) | | U-20261115-22 | 2026-11-15 | ac_diagnose verifies the audit chain read-only and creates no audit database | #done #diagnostics #security | [2026-11-b](2026-11-b.md) | | U-20261115-21 | 2026-11-15 | Decode GUI frames through loadFromData; drop the five fromData type-ignores | #done #typing #gui | [2026-11-b](2026-11-b.md) | | U-20261115-20 | 2026-11-15 | PopenLauncher measures the owned child through Popen's own handle | #done #process-memory | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/shell_process/shell_exec.py b/je_auto_control/utils/shell_process/shell_exec.py index 3116c0e1f..793918967 100644 --- a/je_auto_control/utils/shell_process/shell_exec.py +++ b/je_auto_control/utils/shell_process/shell_exec.py @@ -5,10 +5,15 @@ import signal import subprocess # nosec B404 # reason: ShellManager intentionally invokes user-supplied subprocesses without shell import sys +import time from threading import Thread from typing import IO, List, Optional +from je_auto_control.utils.exception.cancellation import ( + cancellation_checkpoint, current_cancellation_token, +) from je_auto_control.utils.exception.exceptions import AutoControlActionException +from je_auto_control.utils.executor.run_control import checkpoint, current_stop_token from je_auto_control.utils.logging.logging_instance import autocontrol_logger @@ -100,6 +105,28 @@ def _kill_tree(process: subprocess.Popen[bytes]) -> None: pass +_STOP_POLL_SECONDS = 0.1 + + +def _communicate_stoppable(process: subprocess.Popen[bytes], argv: str | List[str], timeout_s: float, + input_bytes: Optional[bytes]) -> tuple[bytes, bytes]: + """``communicate`` within ``timeout_s``, checking for a stop or a cancellation between short waits.""" + if current_stop_token() is None and current_cancellation_token() is None: + return process.communicate(input_bytes, timeout=timeout_s) + deadline = time.monotonic() + timeout_s + pending = input_bytes + while True: + cancellation_checkpoint() + checkpoint() + remaining = deadline - time.monotonic() + if remaining <= 0: + raise subprocess.TimeoutExpired(argv, timeout_s) + try: + return process.communicate(pending, timeout=min(remaining, _STOP_POLL_SECONDS)) + except subprocess.TimeoutExpired: + pending = None # communicate keeps feeding what it was given; it refuses input a second time + + def run_captured(argv: str | List[str], timeout_s: float, input_bytes: Optional[bytes] = None) -> subprocess.CompletedProcess[bytes]: """Run ``argv`` (no shell), capturing stdout and stderr as bytes, for at most ``timeout_s``. @@ -109,6 +136,11 @@ def run_captured(argv: str | List[str], timeout_s: float, program that started one of its own (``cmd /c ping -n 9 ...`` took 8 s with a 1 s timeout) held the caller until it ended. On timeout the whole process tree is killed, then ``TimeoutExpired`` is raised. + + Inside a stoppable run or a cancellation scope the wait wakes every + ``_STOP_POLL_SECONDS``: a stop or a cancellation kills the tree the same + way and propagates (``ExecutionStopped`` / the token's own error) instead + of holding the caller until the program or the timeout ends. """ # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit.dangerous-subprocess-use-audit process = subprocess.Popen(argv, stdin=subprocess.PIPE if input_bytes is not None else None, # nosec B603 # reason: argv list or CreateProcess line, never a shell @@ -116,8 +148,8 @@ def run_captured(argv: str | List[str], timeout_s: float, # its own process group on POSIX, so the timeout can end all of it start_new_session=sys.platform != "win32") try: - stdout, stderr = process.communicate(input_bytes, timeout=timeout_s) - except subprocess.TimeoutExpired: + stdout, stderr = _communicate_stoppable(process, argv, timeout_s, input_bytes) + except BaseException: # reason: end the tree on a timeout, a stop or any other escape, then re-raise _kill_tree(process) try: process.communicate(timeout=5) diff --git a/test/unit_test/headless/test_mcp_call_run.py b/test/unit_test/headless/test_mcp_call_run.py index ad66aa40d..85a52e7c0 100644 --- a/test/unit_test/headless/test_mcp_call_run.py +++ b/test/unit_test/headless/test_mcp_call_run.py @@ -169,3 +169,18 @@ def broken(): assert "RuntimeError: boom" in result["content"][0]["text"] assert "(error screenshot saved to shot.png)" in result["content"][0]["text"] assert shots == ["broken"] + + +def test_cancel_ends_an_ac_shell_command_mid_run(): + import subprocess + import sys + tools = [tool for tool in build_default_tool_registry() if tool.name == "ac_shell"] + server = MCPServer(tools=tools) + command = subprocess.list2cmdline([sys.executable, "-c", "import time; time.sleep(60)"]) + thread, holder = _start(server, 21, "ac_shell", {"command": command, "timeout": 60}) + _cancel(server, 21) + thread.join(timeout=20.0) + assert not thread.is_alive() + assert holder["response"]["error"]["code"] == -32800 + assert holder["finished"] - holder["started"] < 20.0 + assert active_executions() == [] diff --git a/test/unit_test/headless/test_shell_captured_stop.py b/test/unit_test/headless/test_shell_captured_stop.py new file mode 100644 index 000000000..f0a4645e0 --- /dev/null +++ b/test/unit_test/headless/test_shell_captured_stop.py @@ -0,0 +1,102 @@ +"""A captured shell command (``AC_shell_to_var``, ``ac_shell``) ends when its run is stopped or cancelled. + +``run_captured`` waited in one ``communicate(timeout=...)``: a stop reached +the run only after the program ended or the whole timeout passed. +""" +import subprocess +from concurrent.futures import CancelledError +import sys +import threading +import time + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.executor.run_control import ExecutionStopped, StopToken, stoppable_run +from je_auto_control.utils.shell_process import shell_exec +from je_auto_control.utils.shell_process.shell_exec import run_captured + +_SLEEPER = [sys.executable, "-c", "import time; time.sleep(60)"] + + +def _later(action, delay=0.3): + timer = threading.Timer(delay, action) + timer.start() + return timer + + +def _spy_kills(monkeypatch): + killed = [] + real = shell_exec._kill_tree + + def spy(process): + killed.append(process) + real(process) + + monkeypatch.setattr(shell_exec, "_kill_tree", spy) + return killed + + +def test_a_stop_ends_the_command_and_kills_it(monkeypatch): + killed = _spy_kills(monkeypatch) + token = StopToken("captured-stop") + started = time.monotonic() + with stoppable_run(token=token): + _later(lambda: token.stop("test")) + with pytest.raises(ExecutionStopped): + run_captured(_SLEEPER, 60) + assert time.monotonic() - started < 15 + assert len(killed) == 1 and killed[0].poll() is not None + + +def test_a_cancellation_ends_the_command_and_kills_it(monkeypatch): + killed = _spy_kills(monkeypatch) + token = CancellationToken(7) + started = time.monotonic() + with cancellation_scope(token): + _later(token.cancel) + with pytest.raises(CancelledError): + run_captured(_SLEEPER, 60) + assert time.monotonic() - started < 15 + assert len(killed) == 1 and killed[0].poll() is not None + + +def test_inside_a_run_output_and_input_still_arrive_whole(): + echo = [sys.executable, "-c", "import sys; data = sys.stdin.buffer.read(); sys.stdout.buffer.write(data[::-1])"] + with stoppable_run(token=StopToken("captured-echo")): + done = run_captured(echo, 30, input_bytes=b"abc" * 1000) + assert done.returncode == 0 and done.stdout == (b"abc" * 1000)[::-1] + + +def test_inside_a_run_the_timeout_still_applies(monkeypatch): + killed = _spy_kills(monkeypatch) + with stoppable_run(token=StopToken("captured-timeout")): + with pytest.raises(subprocess.TimeoutExpired): + run_captured(_SLEEPER, 0.5) + assert len(killed) == 1 + + +def test_outside_any_run_one_wait_is_used(monkeypatch): + waits = [] + real = subprocess.Popen.communicate + + def spy(self, input=None, timeout=None): + waits.append(timeout) + return real(self, input, timeout) + + monkeypatch.setattr(subprocess.Popen, "communicate", spy) + done = run_captured([sys.executable, "-c", "print('ok')"], 30) + assert done.stdout.strip() == b"ok" and waits == [30] + + +def test_a_stopped_ac_shell_to_var_ends_the_script_promptly(): + from je_auto_control.utils.executor.action_executor import Executor + executor = Executor() + token = StopToken("captured-script") + started = time.monotonic() + _later(lambda: token.stop("test")) + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + executor.execute_action([["AC_shell_to_var", {"command": _SLEEPER, "timeout": 60}], + ["AC_set_var", {"name": "after", "value": 1}]]) + assert time.monotonic() - started < 15 + assert executor.variables.get("after") is None From ab490b268ceaca360e66f3815777852b16e2039b Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Sun, 15 Nov 2026 20:54:31 +0800 Subject: [PATCH 142/161] Wake the presence probe the watch waits on when the reader closes close() joins the reader threads within 0.25 s while the watch thread could still be parked in a probe for its own 0.25 s deadline; a slow macOS runner failed the teardown of the PR #552 run on that race. --- architecture_explore.md | 14 ++++----- docs/updates/2026-11-b.md | 13 ++++++++ docs/updates/README.md | 1 + .../utils/agent_runtime/presence_reader.py | 21 +++++++++++-- .../headless/test_agent_presence_reader.py | 31 +++++++++++++++++++ 5 files changed, 71 insertions(+), 9 deletions(-) diff --git a/architecture_explore.md b/architecture_explore.md index b12a1c6f6..b5f2c659f 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,596 | +| 程式碼總行數 | 238,613 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -516,13 +516,13 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.9 AI / Agent / LLM -> 14 個套件、約 53,169 行。 +> 14 個套件、約 53,186 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/a2a/` | 92 | A2A(agent-to-agent)agent card 產生 | | `utils/agent/` | 2,254 | 閉環 Computer-Use Agent 主迴圈 + Anthropic/OpenAI/Computer-Use 三後端 | -| `utils/agent_runtime/` | 26,084 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | +| `utils/agent_runtime/` | 26,101 | 受管任務、服務、控制權世代、結果驗證與本機推論;所有入口共用執行層。 | | `utils/agent_memory/` | 166 | agent 的持久化情節記憶(goal → trajectory → outcome) | | `utils/agent_replay/` | 67 | 可攜的 agent 軌跡追蹤(記錄 observation→action 並重播) | | `utils/agent_trace/` | 172 | agent 可觀測性:OpenTelemetry GenAI 慣例的 LLM span | @@ -1046,7 +1046,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | -#### `utils/agent_runtime/`(26,084 行/182 檔) +#### `utils/agent_runtime/`(26,101 行/182 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -1146,7 +1146,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `presence_pipe_windows.py` | 209 | Secured local byte pipes for owned helpers; no desktop observation or runtime binding. | | `presence_pool.py` | 404 | Host-only shared presence ownership; task cancellation never cancels another runtime's source. | | `presence_protocol.py` | 74 | Per-connection sequences and issued-token ownership; shared source lifetime remains separate. | -| `presence_reader.py` | 229 | Fresh presence checks inside owned input helpers, with bounded callers and an independent watchdog. | +| `presence_reader.py` | 246 | Fresh presence checks inside owned input helpers, with bounded callers and an independent watchdog. | | `presence_security_windows.py` | 220 | Query-only endpoint identity and noninheritable current-user/System security descriptors. | | `presence_session_windows.py` | 83 | Query-only current physical-console support checks; remote or unknown sessions fail closed. | | `presence_server.py` | 182 | One reserved session source with sixteen authenticated connections and token-only cleanup. | @@ -1570,8 +1570,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,171 | -| **總計** | **1,534** | **237,851** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,188 | +| **總計** | **1,534** | **237,868** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 76793226b..08170b76b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -858,3 +858,16 @@ - With the MCP call-run, console-encoding, executor-containment, shell/clipboard and data-command tests: 48 passed, 1 skipped. Typing contract, complexity, broad-except and bandit are clean. - **Files:** `utils/shell_process/shell_exec.py`, the two tests, `README.md` and both translations, `CHANGELOG.md`, `architecture_explore.md` (re-measured), `Progress.md`. - **Open items:** `Progress.md` › GUI gaps (image search, OCR and HTTP requests already inside a backend; rhythm sleeps within one gesture). + +## U-20261115-24 · 2026-11-15 · close() wakes the presence probe the watch is waiting on · #incident #agent #ci #test + +- **Run.** Quality run 43703787273 on `2accead0` (PR #552). macOS 15 / 3.14: 18,683 passed and 1 error, at teardown of `test_agent_presence_reader.py::test_physical_revision_revokes_reader_between_actions_and_never_rearms`. `PresenceReader.close()` raised `physical presence reader retirement is unproven`. The other squares passed. +- **Cause (reproduced).** `close()` sets `stop` and joins the reader's threads within 0.25 s. The watch thread can be parked in `_probe`, waiting on `probe.done` until that probe's own deadline, also at most 0.25 s, and `stop` did not wake it. The two budgets end almost together, so a slow runner joined the watch a little too late. With the probe queue left unserved, the unfixed reader's `close()` returned 0.8 ms after the waiting probe's deadline. +- **Change:** `utils/agent_runtime/presence_reader.py`: + - The reader tracks the probes being waited on: `_Probe` is identity-hashed (`eq=False`), and the wait is split out as `_await`. + - `close()` sets each waiting probe's `done` after `stop`. + - A probe woken on a closed reader raises "unavailable" through `_require()` before any deadline check. It never reads as ready, and it does not count as a lost reader (no takeover notice). + - Other wake orders and messages, such as "deadline exhausted", are unchanged. +- **Tests:** `test_agent_presence_reader.py` gains `test_close_wakes_a_probe_the_watch_is_still_waiting_on`. It fails on the old reader (close returned after the deadline) and passed 5 of 5 runs with the fix. The presence reader, reader IPC, runtime IPC, endpoint flow, Windows, Linux service and Android scope tests: 230 passed, 3 skipped. Typing contract, complexity and broad-except are clean. +- **Files:** `utils/agent_runtime/presence_reader.py`, the test, `architecture_explore.md` (re-measured). +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index c4b8267cd..4593e5459 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261115-24 | 2026-11-15 | close() wakes the presence probe the watch is waiting on | #incident #agent #ci #test | [2026-11-b](2026-11-b.md) | | U-20261115-23 | 2026-11-15 | A stop or cancel kills a captured shell command instead of waiting for it | #done #executor #mcp | [2026-11-b](2026-11-b.md) | | U-20261115-22 | 2026-11-15 | ac_diagnose verifies the audit chain read-only and creates no audit database | #done #diagnostics #security | [2026-11-b](2026-11-b.md) | | U-20261115-21 | 2026-11-15 | Decode GUI frames through loadFromData; drop the five fromData type-ignores | #done #typing #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/agent_runtime/presence_reader.py b/je_auto_control/utils/agent_runtime/presence_reader.py index 6a64f1fd4..16c9106e0 100644 --- a/je_auto_control/utils/agent_runtime/presence_reader.py +++ b/je_auto_control/utils/agent_runtime/presence_reader.py @@ -17,7 +17,7 @@ from je_auto_control.utils.agent_runtime.presence_pipe_linux import endpoint_from_wire, endpoint_to_wire -@dataclass +@dataclass(eq=False) # tracked by identity while it waits class _Probe: deadline: float done: threading.Event = field(default_factory=threading.Event) @@ -67,6 +67,7 @@ def __init__(self, binding: dict[str, Any], takeover: Callable[[], None], *, pip self._state.retired.set() self._mutex = threading.RLock() self._probes: queue.Queue[_Probe] = queue.Queue(maxsize=16) + self._waiting: set[_Probe] = set() @property def retired(self) -> bool: @@ -125,12 +126,24 @@ def _probe(self, deadline: float | None = None) -> None: self._require() deadline = min(time.monotonic() + 0.25, deadline) if deadline is not None else time.monotonic() + 0.25 probe = _Probe(deadline) + with self._mutex: + self._waiting.add(probe) + try: + self._await(probe, deadline) + finally: + with self._mutex: + self._waiting.discard(probe) + + def _await(self, probe: _Probe, deadline: float) -> None: try: self._probes.put_nowait(probe) except queue.Full as error: self._fail(error) raise AgentTaskError('physical presence reader capacity is busy') from error - if not probe.done.wait(max(0.0, deadline - time.monotonic())) or time.monotonic() >= deadline: + woken = probe.done.wait(max(0.0, deadline - time.monotonic())) + if self._state.closed: + self._require() # close() woke this probe: a closed reader answers unavailable, never ready + if not woken or time.monotonic() >= deadline: expired = AgentTaskError('physical presence reader deadline exhausted') self._fail(expired) raise expired @@ -219,6 +232,10 @@ def close(self) -> None: with self._mutex: self._state.closed = True self._state.stop.set() + # A probe waits up to its own 0.25 s deadline; without this wake the watch thread could + # still be parked in one when the join below runs out of the same 0.25 s budget. + for waiting in self._waiting: + waiting.done.set() if (not any(thread.is_alive() for thread in self._state.threads) and not self.retired and (self._wire.peer is not None or self._wire.connection is not None)): self._launch(self._retire, 'PresenceReaderRetire') diff --git a/test/unit_test/headless/test_agent_presence_reader.py b/test/unit_test/headless/test_agent_presence_reader.py index 7967b7a92..6c2bd4410 100644 --- a/test/unit_test/headless/test_agent_presence_reader.py +++ b/test/unit_test/headless/test_agent_presence_reader.py @@ -370,3 +370,34 @@ def test_reader_loss_does_not_block_worker_owned_release_only_ack_cleanup(harnes assert 'cleaned' in boundary.events with pytest.raises(AgentTaskError): harness.reader.check() + + +class _UnservedProbes: + """Takes probes and never hands them to the I/O thread, so a caller waits on its own deadline.""" + + def __init__(self): + import queue + self.empty = queue.Empty + self.taken = [] + self.arrived = threading.Event() + + def put_nowait(self, probe): + self.taken.append(probe) + self.arrived.set() + + def get(self, timeout): + time.sleep(timeout) + raise self.empty + + +def test_close_wakes_a_probe_the_watch_is_still_waiting_on(harness): + """The watch's probe waits up to 0.25 s, the same budget close() has to join it (macOS 3.14 CI teardown).""" + harness.reader.ready() + unserved = _UnservedProbes() + harness.reader._probes = unserved + assert unserved.arrived.wait(2) + waiting = unserved.taken[0] + harness.reader.close() + assert time.monotonic() < waiting.deadline # woken by close, not by its own deadline + assert harness.reader.retired + assert harness.events.count('notice') == 0 # a closed reader is not a lost one From 9796d5905083b1f8168e062b5b603bdc0aea081f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 00:09:48 +0800 Subject: [PATCH 143/161] Justify three B105 command-name hits and steady two Windows CI tests Bandit flags the AC_lease_secret / AC_secret_* review notes as passwords; they are command names. The script-runs test posted to the GUI thread with QTimer.singleShot from a plain worker thread, the likeliest cause of an abort on Windows 3.14, so it emits a GUI-thread signal like the tabs do. The presence source test now retries a check that missed the 0.25 s request cap, as lease() already does. --- architecture_explore.md | 10 +++---- docs/updates/2026-11-b.md | 24 +++++++++++++++ docs/updates/README.md | 1 + je_auto_control/utils/rbac/command_review.py | 12 ++++++-- .../headless/test_agent_presence_windows.py | 24 ++++++++++++--- .../headless/test_gui_script_runs.py | 30 +++++++++++++++++-- 6 files changed, 86 insertions(+), 15 deletions(-) diff --git a/architecture_explore.md b/architecture_explore.md index b5f2c659f..906d1582e 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,613 | +| 程式碼總行數 | 238,619 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -665,7 +665,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.14 安全、機密與合規 -> 13 個套件、約 4,757 行。 +> 13 個套件、約 4,763 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -674,7 +674,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/governance/` | 263 | 治理:maker-checker 核准閘門與即時憑證租約 | | `utils/license_policy/` | 240 | 以 SBOM 元件評估 SPDX 授權允許/拒絕政策 | | `utils/provenance/` | 126 | SLSA 建置來源證明(in-toto v1) | -| `utils/rbac/` | 1,985 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data;command_review.py 記錄 `COMMAND_CAPABILITIES` 以外每個 `AC_*` 指令的審查(只需提交入口的 drive_input),新指令未分類時 CI 失敗 | +| `utils/rbac/` | 1,991 | 角色型存取控制:使用者與權杖驗證、REST/MCP/executor 的能力政策,`deferred.py` 將背景工作綁定註冊者並在觸發時重新驗證來源 store;不保存 bearer token。;MCP 的 tool_classification.py 擁有明確畫面/呼叫者資料清單、標準別名與混合參數權限;未知唯讀提示要求 read_data;command_review.py 記錄 `COMMAND_CAPABILITIES` 以外每個 `AC_*` 指令的審查(只需提交入口的 drive_input),新指令未分類時 CI 失敗 | | `utils/redaction/` | 508 | 截圖遮蔽層:規則偵測 + 政策 + 協調器(上傳 VLM 前先遮) | | `utils/sbom/` | 170 | SBOM(CycloneDX)產生 | | `utils/secret_ref/` | 242 | URI scheme 形式的值參照解析 | @@ -1570,8 +1570,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,188 | -| **總計** | **1,534** | **237,868** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,194 | +| **總計** | **1,534** | **237,874** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 08170b76b..d2b6fa5b1 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -871,3 +871,27 @@ - **Tests:** `test_agent_presence_reader.py` gains `test_close_wakes_a_probe_the_watch_is_still_waiting_on`. It fails on the old reader (close returned after the deadline) and passed 5 of 5 runs with the fix. The presence reader, reader IPC, runtime IPC, endpoint flow, Windows, Linux service and Android scope tests: 230 passed, 3 skipped. Typing contract, complexity and broad-except are clean. - **Files:** `utils/agent_runtime/presence_reader.py`, the test, `architecture_explore.md` (re-measured). - **Open items:** none. + +## U-20261116-01 · 2026-11-16 · PR #552 CI: bandit B105 on three RBAC notes and two timing-sensitive tests · #incident #ci #test #security + +- **Runs.** Quality runs 43713819936, 43714600349, 43715148004 and 43716232950 (PR #552, `69eb4ae7` to `ab490b26`). + - `security` failed on every one. + - Windows failed on three different tests, one per run, each green on the other runs. +- **security (deterministic).** + - Bandit 1.9.4 reported `B105:hardcoded_password_string` at `utils/rbac/command_review.py` lines 50, 65 and 66, with Low severity and Medium confidence. + - The keys `AC_lease_secret`, `AC_secret_list` and `AC_secret_status` are command names. Their values are review notes, not credentials. + - Each entry now carries `# nosec B105 # reason: an AC_* command name, not a credential` on its key line. The note text is unchanged, and local bandit is clean. +- **Windows 3.14, `test_gui_script_runs.py::test_a_script_that_clicks_this_tabs_run_does_not_deadlock_or_nest`.** + - The interpreter aborted (`Fatal Python error: Aborted`, exit 3) about 10 ms into the test. + - The test posted to the GUI thread with `QTimer.singleShot(0, host, ...)` from the script's worker, a plain `threading.Thread`. The tabs already avoid that pattern (`presence_tab._registry_changed`). + - That and the stop test now emit a signal of a GUI-thread `QObject`, `_GuiThread`. + - Not reproduced locally: the module passed 6 of 6 runs before the change and 4 of 4 after, and 3,000 cross-thread `singleShot` calls ran cleanly. The cause is the likeliest one, not a proven one. +- **Windows 3.12, `test_agent_presence_windows.py::test_source_keeps_one_generation_and_revalidates_fresh_physical_events`.** + - It got `deadline exhausted` where it expected `resume`. + - The test's `check` requests share the 0.25 s request cap that `lease()` already retries. A missed check is refused before dispatch or answered late, and it changes no state. + - A `check()` helper now retries a missed deadline the same way. The module passes 26 of 26. +- **Windows 3.12, `test_agent_dag_retention.py::test_completed_batch_keeps_its_gate_when_related_work_is_unsettled[fresh_delivery]`, once, on `69eb4ae7`.** + - The set-up `run_dag` failed. The managed-task `submit` call ran past its 5 s per-call cap (`_TaskWaiter._timeout`) on a loaded runner, and the client dropped the connection (WinError 10053), so the outcome was `unknown`. + - Not changed: the cap is product behaviour and the test passed on every other run. +- **Files:** `utils/rbac/command_review.py`, the two tests, `architecture_explore.md` (re-measured). +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 4593e5459..49282d8b4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-01 | 2026-11-16 | PR #552 CI: bandit B105 on three RBAC notes and two timing-sensitive tests | #incident #ci #test #security | [2026-11-b](2026-11-b.md) | | U-20261115-24 | 2026-11-15 | close() wakes the presence probe the watch is waiting on | #incident #agent #ci #test | [2026-11-b](2026-11-b.md) | | U-20261115-23 | 2026-11-15 | A stop or cancel kills a captured shell command instead of waiting for it | #done #executor #mcp | [2026-11-b](2026-11-b.md) | | U-20261115-22 | 2026-11-15 | ac_diagnose verifies the audit chain read-only and creates no audit database | #done #diagnostics #security | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/rbac/command_review.py b/je_auto_control/utils/rbac/command_review.py index 3b0406b61..707330553 100644 --- a/je_auto_control/utils/rbac/command_review.py +++ b/je_auto_control/utils/rbac/command_review.py @@ -47,7 +47,9 @@ "Fernet with a caller passphrase or the per-user key; the content is the caller's own file" ), "AC_lease_active": "lists leases without values", - "AC_lease_secret": "a lease token carries no value; redeeming one is Python-only", + "AC_lease_secret": ( # nosec B105 # reason: an AC_* command name, not a credential + "a lease token carries no value; redeeming one is Python-only" + ), "AC_lease_valid": "as AC_lease_secret", "AC_list_plugins": "lists entry points; loading them needs manage_hosts", "AC_parallel": ( @@ -62,8 +64,12 @@ "AC_presence_unregister": "as AC_presence_register", "AC_repair_approve": "accepts a locator-repair suggestion: workflow data, not host policy", "AC_revoke_lease": "as AC_lease_secret", - "AC_secret_list": "names only; vault administration (init, set, remove, lock, unlock) needs manage_hosts", - "AC_secret_status": "path and lock state only, as AC_secret_list", + "AC_secret_list": ( # nosec B105 # reason: an AC_* command name, not a credential + "names only; vault administration (init, set, remove, lock, unlock) needs manage_hosts" + ), + "AC_secret_status": ( # nosec B105 # reason: an AC_* command name, not a credential + "path and lock state only, as AC_secret_list" + ), "AC_usb_acl_list": "the stored ACL, read_data as ac_usb_acl_list and GET /usb/acl", "AC_usb_loopback_open": ( "matches POST /usb/loopback/open (drive_input); the ACL and the passthrough switch need manage_hosts" diff --git a/test/unit_test/headless/test_agent_presence_windows.py b/test/unit_test/headless/test_agent_presence_windows.py index d47a92410..7f0b35647 100644 --- a/test/unit_test/headless/test_agent_presence_windows.py +++ b/test/unit_test/headless/test_agent_presence_windows.py @@ -70,6 +70,22 @@ def lease(source): pytest.fail('synthetic observer never acquired its verified sixty-second idle') +def check(source, token): + # The same 0.25 s cap as ``lease``. A check that misses it read nothing and + # changed nothing: it was refused before dispatch, or its late answer (the + # same one a retry gets) was dropped. So a deadline miss is retried too. + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + try: + return source.request('check', token) + except AgentControlBusy: + threading.Event().wait(0.001) + except AgentTaskError as error: + if 'deadline exhausted' not in str(error): + raise + pytest.fail('synthetic observer never answered a check inside its deadline') + + def test_inert_inspection_does_not_create_a_native_api_or_thread(): api = FakeAPI() source = actor(api) @@ -88,15 +104,15 @@ def test_source_keeps_one_generation_and_revalidates_fresh_physical_events(): try: source.start() first = lease(source) - assert source.request('check', first)['state'] == 'monitoring' + assert check(source, first)['state'] == 'monitoring' api.emit = True with pytest.raises(AgentTaskError, match='resume'): - source.request('check', first) + check(source, first) second = lease(source) assert first['generation'] == second['generation'] assert first['lease_id'] != second['lease_id'] assert source.request('release', first) == {'released': True} - assert source.request('check', second)['native_evidence'] == 'not_recorded' + assert check(source, second)['native_evidence'] == 'not_recorded' finally: source.close() assert api.opened == api.closed == 1 @@ -158,7 +174,7 @@ def test_timed_out_request_does_not_allocate_a_late_lease(): api.allow.set() source.request('inspect', {}) assert len(source._state._leases) == 1 - assert source.request('check', first)['state'] == 'monitoring' + assert check(source, first)['state'] == 'monitoring' finally: api.allow.set() source.close() diff --git a/test/unit_test/headless/test_gui_script_runs.py b/test/unit_test/headless/test_gui_script_runs.py index 0a3a403e2..ee0d00f73 100644 --- a/test/unit_test/headless/test_gui_script_runs.py +++ b/test/unit_test/headless/test_gui_script_runs.py @@ -13,7 +13,7 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) -from PySide6.QtCore import QCoreApplication, QEvent, QTimer # noqa: E402 +from PySide6.QtCore import QCoreApplication, QEvent, QObject, Signal, Slot # noqa: E402 from PySide6.QtWidgets import QApplication, QMessageBox, QWidget # noqa: E402 from headless._qt_settle import settle # noqa: E402 @@ -176,6 +176,28 @@ def test_the_auto_click_stop_also_stops_scripts(script): # --- re-entrancy: a script that drives this window ---------------------------------------------------------- +class _GuiThread(QObject): + """Run a callable on the GUI thread, posted from the script's worker thread. + + The worker is a plain ``threading.Thread``: ``QTimer.singleShot`` called there + makes Qt timer state on a thread Qt never started and that ends with the + script; it is the likeliest cause of an abort this test once hit on Windows / + Python 3.14, about 10 ms in. A signal + of an object made on the GUI thread is queued there, as the tabs themselves + do it (``presence_tab._registry_changed``). + """ + + posted = Signal(object) + + def __init__(self) -> None: + super().__init__() + self.posted.connect(self._run) + + @Slot(object) + def _run(self, call) -> None: + call() + + def test_a_script_that_clicks_this_tabs_run_does_not_deadlock_or_nest(script, monkeypatch): """The script asks the GUI thread to run again and waits for the answer. @@ -183,6 +205,7 @@ def test_a_script_that_clicks_this_tabs_run_does_not_deadlock_or_nest(script, mo is free: it answers (and refuses the nested run) while the script waits. """ host = ScriptHost() + gui = _GuiThread() answered = threading.Event() seen = [] @@ -191,7 +214,7 @@ def on_gui_thread() -> None: host._execute_manual_script() seen.append(host.script_result_text.toPlainText()) answered.set() - QTimer.singleShot(0, host, on_gui_thread) + gui.posted.emit(on_gui_thread) return "answered" if answered.wait(_WAIT) else "the GUI thread never answered" monkeypatch.setitem(executor.event_dict, "AC_fake_click_run", click_run_again) @@ -206,9 +229,10 @@ def on_gui_thread() -> None: def test_a_script_that_clicks_stop_stops_itself(script, monkeypatch): host = ScriptHost() + gui = _GuiThread() def click_stop() -> None: - QTimer.singleShot(0, host, host._stop_script) + gui.posted.emit(host._stop_script) monkeypatch.setitem(executor.event_dict, "AC_fake_click_stop", click_stop) host.script_editor.setPlainText(json.dumps( From 7b25f057b07e0d46ee4ef5797e1d56a63579d330 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 01:43:59 +0800 Subject: [PATCH 144/161] Keep Qt's fatal message in the CI artifact when a test aborts Windows 3.14 aborts inside test_gui_script_runs with only 'Fatal Python error: Aborted': no minidump for a handled abort(), and Qt's reason went to the stderr pytest's fd capture held. The diagnostics runner now names its artifact folder to the child, and the headless conftest records Qt's messages there, so the next abort says why. The earlier singleShot change did not stop it; the open cause is tracked in Progress.md. --- Progress.md | 16 ++++++++ docs/updates/2026-11-b.md | 17 +++++++++ docs/updates/README.md | 1 + scripts/ci_native_diagnostics.py | 5 ++- test/unit_test/headless/conftest.py | 38 +++++++++++++++++++ .../headless/test_ci_native_diagnostics.py | 8 ++++ 6 files changed, 84 insertions(+), 1 deletion(-) diff --git a/Progress.md b/Progress.md index df1fbe67f..1ae95be46 100644 --- a/Progress.md +++ b/Progress.md @@ -216,6 +216,22 @@ Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_ --- +## Windows 3.14:`test_gui_script_runs.py` 在完整 suite 中 abort + +`WIP` — `test/unit_test/headless/test_gui_script_runs.py::test_a_script_that_clicks_this_tabs_run_does_not_deadlock_or_nest` +在 Windows 2022 / Python 3.14.10 / PySide6 6.12.0 的 `coverage run -m pytest` 中連兩輪 `Fatal Python error: Aborted`(exit 3), +都在測試開始約 10 ms、主執行緒停在 `_qt_settle.py:22`(3.14 的 eval breaker 會在這種點跑循環回收), +其餘方格與更早的 3.14 輪次都通過(run 43716232950 於 `ab490b26`、43733918302 於 `9796d590`)。 +已排除:`QTimer.singleShot` 跨執行緒呼叫(U-20261116-01 換成 GUI 執行緒 signal 後照樣 abort); +單獨跑這個模組、或依 CI 順序只跑前面 25 個 GUI 模組,本機 Windows 3.14.7 都通過。 +abort 不經 WER 所以沒有 minidump,Qt 寫到 stderr 的原因被 pytest 的 fd capture 吞掉; +U-20261116-02 起 `ci_native_diagnostics.py` 把 artifact 目錄交給子程序,headless conftest 把 Qt 訊息寫進 +`native-windows-2022-3.14` artifact 的 `qt-messages.log`。 +待辦:下次 abort 時讀那份檔案的最後一行找出原因;若是 PySide6 6.12.0 的參考計數問題(同上一節), +比照 3.11 的處理評估 3.14 的固定版本。 + +--- + ## Agent 電腦接管與任務自動化 `WIP` — **依使用者恢復目標繼續交付;個別原生/真機/24 小時驗收仍暫緩。** diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index d2b6fa5b1..37f5bc9d3 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -886,6 +886,7 @@ - The test posted to the GUI thread with `QTimer.singleShot(0, host, ...)` from the script's worker, a plain `threading.Thread`. The tabs already avoid that pattern (`presence_tab._registry_changed`). - That and the stop test now emit a signal of a GUI-thread `QObject`, `_GuiThread`. - Not reproduced locally: the module passed 6 of 6 runs before the change and 4 of 4 after, and 3,000 cross-thread `singleShot` calls ran cleanly. The cause is the likeliest one, not a proven one. + - **Correction:** it was not the cause. The abort recurred on `9796d590` with the signal in place (run 43733918302); see U-20261116-02. - **Windows 3.12, `test_agent_presence_windows.py::test_source_keeps_one_generation_and_revalidates_fresh_physical_events`.** - It got `deadline exhausted` where it expected `resume`. - The test's `check` requests share the 0.25 s request cap that `lease()` already retries. A missed check is refused before dispatch or answered late, and it changes no state. @@ -895,3 +896,19 @@ - Not changed: the cap is product behaviour and the test passed on every other run. - **Files:** `utils/rbac/command_review.py`, the two tests, `architecture_explore.md` (re-measured). - **Open items:** none. + +## U-20261116-02 · 2026-11-16 · Keep Qt's fatal message when a CI test aborts the interpreter · #ci #test #diagnostics + +- **Why.** On Windows 3.14, `test_gui_script_runs.py::test_a_script_that_clicks_this_tabs_run_does_not_deadlock_or_nest` aborted again (run 43733918302, `9796d590`), at the same point as before. The `singleShot` change of U-20261116-01 did not help. +- **Evidence left.** + - The step log and `native-windows-2022-3.14` hold only `Fatal Python error: Aborted` and the Python stacks. The main thread is at `_qt_settle.py:22`, an eval-breaker point where 3.14 runs cyclic GC, about 10 ms into the test. + - There is no minidump: a handled `abort()` exits with code 3 and Windows Error Reporting never sees a crash. + - Whatever Qt printed went to the stderr pytest's fd capture held, and was lost with the process. +- **Change.** + - `scripts/ci_native_diagnostics.py` passes its artifact folder to the child as `AUTOCONTROL_NATIVE_ARTIFACT_DIR`. + - The headless `conftest.py`, when that variable is set and Qt is loaded, installs a Qt message handler once. The handler appends each message to `qt-messages.log` in that folder, tagged with its type and `PYTEST_CURRENT_TEST`, opening and closing the file per line. + - Qt calls the handler before a `qFatal` aborts, so the reason reaches the uploaded artifact. Checked with a real `qFatal`: the line is on disk after the process dies. + - Without the variable, local runs, nothing is installed and Qt keeps printing to stderr. +- **Tests:** `test_ci_native_diagnostics.py` gains `test_the_child_is_told_where_to_leave_its_own_evidence`. With the variable set, `test_gui_qt_typed.py`, `test_gui_script_runs.py` and `test_ci_native_diagnostics.py` give 35 passed and 5 skipped, and the log records their Qt warnings. +- **Files:** `scripts/ci_native_diagnostics.py`, `test/unit_test/headless/conftest.py`, `test_ci_native_diagnostics.py`, `Progress.md`. +- **Open items:** the abort's cause, in `Progress.md` ("Windows 3.14:`test_gui_script_runs.py` 在完整 suite 中 abort"). diff --git a/docs/updates/README.md b/docs/updates/README.md index 49282d8b4..0a19bfb46 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-02 | 2026-11-16 | Keep Qt's fatal message when a CI test aborts the interpreter | #ci #test #diagnostics | [2026-11-b](2026-11-b.md) | | U-20261116-01 | 2026-11-16 | PR #552 CI: bandit B105 on three RBAC notes and two timing-sensitive tests | #incident #ci #test #security | [2026-11-b](2026-11-b.md) | | U-20261115-24 | 2026-11-15 | close() wakes the presence probe the watch is waiting on | #incident #agent #ci #test | [2026-11-b](2026-11-b.md) | | U-20261115-23 | 2026-11-15 | A stop or cancel kills a captured shell command instead of waiting for it | #done #executor #mcp | [2026-11-b](2026-11-b.md) | diff --git a/scripts/ci_native_diagnostics.py b/scripts/ci_native_diagnostics.py index 570fcad15..23c48406f 100644 --- a/scripts/ci_native_diagnostics.py +++ b/scripts/ci_native_diagnostics.py @@ -66,7 +66,10 @@ def run(command: Sequence[str], directory: Path, *, native: bool = False) -> int } report = directory / 'runtime.json' report.write_text(json.dumps(record, indent=2), encoding='utf-8') - environment = dict(os.environ, PYTHONFAULTHANDLER='1', PYTHONUNBUFFERED='1') + # The child may add evidence of its own here (the headless conftest writes Qt's + # fatal messages, which pytest's fd capture would otherwise lose with the process). + environment = dict(os.environ, PYTHONFAULTHANDLER='1', PYTHONUNBUFFERED='1', + AUTOCONTROL_NATIVE_ARTIFACT_DIR=str(directory.resolve())) started = time.monotonic() with ( _debugger_argv(command, debugger) as actual, diff --git a/test/unit_test/headless/conftest.py b/test/unit_test/headless/conftest.py index 399ce94b1..da49ecea9 100644 --- a/test/unit_test/headless/conftest.py +++ b/test/unit_test/headless/conftest.py @@ -1,4 +1,5 @@ """Shared teardown for the headless suite.""" +import os import sys import pytest @@ -17,6 +18,42 @@ def _live_qt_application(): return widgets.QApplication.instance() +_QT_EVIDENCE_DIR = "AUTOCONTROL_NATIVE_ARTIFACT_DIR" +_qt_log = [] + + +def _record_qt_messages(): + """In CI, append Qt's own messages to ``qt-messages.log`` in the native artifact folder. + + A ``qFatal`` aborts the interpreter right after Qt prints its reason to + stderr, and pytest's fd capture holds that stderr until the test ends -- + which it never does. Windows 3.14 has lost the reason that way + ("Fatal Python error: Aborted" and nothing else, in + ``test_gui_script_runs.py``). Qt calls the handler before it aborts, and + each line is written and closed at once, so the reason survives the + process. Installed once, the first time a test finds Qt loaded, and only + when ``scripts/ci_native_diagnostics.py`` names the folder. + """ + folder = os.environ.get(_QT_EVIDENCE_DIR) + if _qt_log or not folder: + return + core = sys.modules.get("PySide6.QtCore") + if core is None: + return + path = os.path.join(folder, "qt-messages.log") + _qt_log.append(path) + + def handler(mode, _context, message): + test = os.environ.get("PYTEST_CURRENT_TEST", "") + try: + with open(path, "a", encoding="utf-8") as log: + log.write(f"{getattr(mode, 'name', mode)} [{test}] {message}\n") + except OSError: + return + + core.qInstallMessageHandler(handler) + + @pytest.fixture(autouse=True) def flush_qt_deferred_deletes(): """Run Qt's queued ``deleteLater()`` work at the end of every test. @@ -37,6 +74,7 @@ def flush_qt_deferred_deletes(): and therefore torn down *after* it — the module's own ``deleteLater()`` calls have already been made by the time this runs. """ + _record_qt_messages() yield app = _live_qt_application() if app is None: diff --git a/test/unit_test/headless/test_ci_native_diagnostics.py b/test/unit_test/headless/test_ci_native_diagnostics.py index 02f0f4307..4be94a844 100644 --- a/test/unit_test/headless/test_ci_native_diagnostics.py +++ b/test/unit_test/headless/test_ci_native_diagnostics.py @@ -42,6 +42,14 @@ def test_child_result_output_and_runtime_versions_survive_the_wrapper(tmp_path, assert 'AC_CONTROLLED_PRIVATE_TEST_VALUE' not in log + raw +def test_the_child_is_told_where_to_leave_its_own_evidence(tmp_path): + directory = tmp_path / 'evidence' + code = "import os;print('dir=' + os.environ['AUTOCONTROL_NATIVE_ARTIFACT_DIR'])" + result = run_child(directory, code) + assert result.returncode == 0, result.stdout + result.stderr + assert f'dir={directory.resolve()}' in result.stdout + + @pytest.mark.skipif(sys.platform != 'linux' or shutil.which('gdb') is None, reason='requires Linux GDB') def test_real_native_abort_retains_a_backtrace_and_fails(tmp_path): directory = tmp_path / 'native-abort' From 3b0ce4f167758c4c61383ae118f5757dbb88217f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 03:25:17 +0800 Subject: [PATCH 145/161] Keep a transfer-payload test under MAX_PATH on a local Windows basetemp The owned source's evidence cache nests two hash directories and a temp file; under 'independent-source' the path reached 263 characters and the child failed where long paths are off. CI was unaffected. --- docs/updates/2026-11-b.md | 10 ++++++++++ docs/updates/README.md | 1 + .../unit_test/headless/test_agent_transfer_payloads.py | 5 ++++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 37f5bc9d3..5ebe0e573 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -912,3 +912,13 @@ - **Tests:** `test_ci_native_diagnostics.py` gains `test_the_child_is_told_where_to_leave_its_own_evidence`. With the variable set, `test_gui_qt_typed.py`, `test_gui_script_runs.py` and `test_ci_native_diagnostics.py` give 35 passed and 5 skipped, and the log records their Qt warnings. - **Files:** `scripts/ci_native_diagnostics.py`, `test/unit_test/headless/conftest.py`, `test_ci_native_diagnostics.py`, `Progress.md`. - **Open items:** the abort's cause, in `Progress.md` ("Windows 3.14:`test_gui_script_runs.py` 在完整 suite 中 abort"). + +## U-20261116-03 · 2026-11-16 · A transfer-payload test no longer passes Windows MAX_PATH on a local basetemp · #test #windows + +- **Symptom.** On a local Windows machine with `LongPathsEnabled` = 0, both cases of `test_agent_transfer_payloads.py::test_independent_source_expiry_refuses_surviving_chunks_without_expiring_the_destination` failed with "owned transfer fixture failed". This happened standalone too. CI passed. +- **Cause.** The owned source process writes its evidence cache under `/independent-source/source/.agent-evidence-cache/<64 hex>/<32 hex>/` plus a temp file. Under the default basetemp (`C:\Users\\AppData\Local\Temp\pytest-of-\pytest-NNNN\…`) that path is 263 characters, over MAX_PATH. The child's `mkstemp` failed (WinError 206 / Errno 2). +- **Change.** The test's own directory is `src` instead of `independent-source`. That saves 15 characters, so the same path is 248, and the test's purpose is unchanged. +- **Not changed:** the product's evidence-cache layout. A real runtime directory sits under a home folder far shallower than a pytest basetemp. +- **Tests:** `test_agent_transfer_payloads.py`, 7 passed (it was 2 failed and 5 passed). +- **Files:** `test/unit_test/headless/test_agent_transfer_payloads.py`. +- **Open items:** none. diff --git a/docs/updates/README.md b/docs/updates/README.md index 0a19bfb46..d541e1ff2 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-03 | 2026-11-16 | A transfer-payload test no longer passes Windows MAX_PATH on a local basetemp | #test #windows | [2026-11-b](2026-11-b.md) | | U-20261116-02 | 2026-11-16 | Keep Qt's fatal message when a CI test aborts the interpreter | #ci #test #diagnostics | [2026-11-b](2026-11-b.md) | | U-20261116-01 | 2026-11-16 | PR #552 CI: bandit B105 on three RBAC notes and two timing-sensitive tests | #incident #ci #test #security | [2026-11-b](2026-11-b.md) | | U-20261115-24 | 2026-11-15 | close() wakes the presence probe the watch is waiting on | #incident #agent #ci #test | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/test_agent_transfer_payloads.py b/test/unit_test/headless/test_agent_transfer_payloads.py index be9584008..244dd80ac 100644 --- a/test/unit_test/headless/test_agent_transfer_payloads.py +++ b/test/unit_test/headless/test_agent_transfer_payloads.py @@ -113,7 +113,10 @@ def transport(batches, host, binding, path, body, timeout): @pytest.mark.parametrize('boundary', ['before-chunks', 'after-cache']) def test_independent_source_expiry_refuses_surviving_chunks_without_expiring_the_destination( tmp_path, monkeypatch, boundary): - source_directory = tmp_path / 'independent-source' + # Short on purpose: the child's evidence cache nests a 64- and a 32-hex directory and a temp + # file under it, which under 'independent-source' reached 263 characters on a local Windows + # basetemp and failed with WinError 206 / Errno 2 where long paths are off (MAX_PATH 260). + source_directory = tmp_path / 'src' with owned_transfer_process(source_directory, 'headless._transfer_source_process', {}) as source: with import_hosts(tmp_path, monkeypatch) as (host, server, _unused, _body, token, root, _actor): book = admin_client.AdminConsoleClient(persist_path=root / 'independent-source-hosts.json') From 12c9350c22fdedc2825b6cb55ab43138a1994b35 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 05:06:04 +0800 Subject: [PATCH 146/161] Collect leaked Qt objects on the GUI thread before workers can A minidump of the Windows 3.14 abort showed PySide's deferred deletion (runDeletionInMainThread) destroying a leaked top-level QWidget that a worker thread's GC had collected, and QObject::~QObject aborting. The headless conftest now collects on the main thread at each module start, and the script-runs module collects and deletes its widgets per test. A full CI-order local run that aborted 3 of 3 times now passes; the GUI-side risk is left as a decision in Progress.md. --- Progress.md | 24 ++++++------- docs/updates/2026-11-b.md | 17 +++++++++ docs/updates/README.md | 1 + test/unit_test/headless/conftest.py | 21 +++++++++++ .../headless/test_gui_script_runs.py | 35 +++++++++++++++---- 5 files changed, 79 insertions(+), 19 deletions(-) diff --git a/Progress.md b/Progress.md index 1ae95be46..96433fd1f 100644 --- a/Progress.md +++ b/Progress.md @@ -216,19 +216,17 @@ Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_ --- -## Windows 3.14:`test_gui_script_runs.py` 在完整 suite 中 abort - -`WIP` — `test/unit_test/headless/test_gui_script_runs.py::test_a_script_that_clicks_this_tabs_run_does_not_deadlock_or_nest` -在 Windows 2022 / Python 3.14.10 / PySide6 6.12.0 的 `coverage run -m pytest` 中連兩輪 `Fatal Python error: Aborted`(exit 3), -都在測試開始約 10 ms、主執行緒停在 `_qt_settle.py:22`(3.14 的 eval breaker 會在這種點跑循環回收), -其餘方格與更早的 3.14 輪次都通過(run 43716232950 於 `ab490b26`、43733918302 於 `9796d590`)。 -已排除:`QTimer.singleShot` 跨執行緒呼叫(U-20261116-01 換成 GUI 執行緒 signal 後照樣 abort); -單獨跑這個模組、或依 CI 順序只跑前面 25 個 GUI 模組,本機 Windows 3.14.7 都通過。 -abort 不經 WER 所以沒有 minidump,Qt 寫到 stderr 的原因被 pytest 的 fd capture 吞掉; -U-20261116-02 起 `ci_native_diagnostics.py` 把 artifact 目錄交給子程序,headless conftest 把 Qt 訊息寫進 -`native-windows-2022-3.14` artifact 的 `qt-messages.log`。 -待辦:下次 abort 時讀那份檔案的最後一行找出原因;若是 PySide6 6.12.0 的參考計數問題(同上一節), -比照 3.11 的處理評估 3.14 的固定版本。 +## PySide6 6.12 跨執行緒回收的延後刪除會在 `QObject::~QObject` abort(GUI 本身的風險) + +`DECIDE` — 原因已由本機 minidump 確認(U-20261116-04):Python 擁有的 Qt 物件若被 worker 執行緒的循環回收收走, +PySide6 6.12 不在那裡刪,而是排進 `Shiboken::BindingManager::runDeletionInMainThread` 之後在主執行緒刪; +其中一個被留下的頂層 `QWidget`(`wasWidget`、`wasDeleted` 已設、無 parent、無 Qt 訊息)在 `QObject::~QObject` 裡呼叫 `abort()`。 +測試端已處理:headless conftest 在每個模組開始時於主執行緒 `gc.collect()`,`test_gui_script_runs.py` 每個測試先回收、結束時刪掉自己建的 widget; +照 CI 順序的完整本機重跑由 3/3 abort 變成 8,856 通過。 +未解:觸發的確切前提還沒用最小範例重現(單純跨執行緒回收、留下的 `TabTask` owner、兩種雙重刪除順序都正常), +所以產品 GUI 在 worker 執行緒跑 Python 時(`_worker_thread`、`DaemonThread`、`tab_task_controller`)仍可能遇到同一條路徑。 +待決定:(1) 是否向 PySide 回報(附 minidump 的堆疊與物件狀態);(2) 是否比照 3.11 把 3.14 固定回 PySide6 6.11.2 +(6.11.1 起就有延後刪除,但升到 6.12 前 3.14 沒有出現過這個 abort);(3) 或在 GUI 端讓主執行緒定期回收、減少留給 worker 的垃圾。 --- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 5ebe0e573..daf1721a7 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -922,3 +922,20 @@ - **Tests:** `test_agent_transfer_payloads.py`, 7 passed (it was 2 failed and 5 passed). - **Files:** `test/unit_test/headless/test_agent_transfer_payloads.py`. - **Open items:** none. + +## U-20261116-04 · 2026-11-16 · Leaked widgets are collected on the GUI thread so a deferred delete cannot abort the suite · #incident #ci #test #gui + +- **Cause, from a local minidump.** It is the Windows 3.14 abort in `test_gui_script_runs.py`, from runs 43716232950 and 43733918302 and three local full CI-order runs. + - A scratch pytest plugin wrote a minidump from the `SIGABRT` handler. Scanning the stack and naming frames by the nearest export gave `ucrtbase!abort` ← `Qt6Core!QObject::~QObject` ← `shiboken6!Shiboken::BindingManager::runDeletionInMainThread`. + - The object's `QObjectData` read from the dump: `wasWidget` = 1, `willBeWidget` = 1, `wasDeleted` = 1, no parent, no children, nothing posted. `qt-messages.log` had no fatal line. + - So PySide 6.12 was deleting, on the main thread, a leaked top-level `QWidget` that a worker thread's cyclic GC had collected (deferred deletion, PYSIDE-3288 since 6.11.1). The delete aborted. + - The earlier "GC on the main thread" and FFmpeg ideas were ruled out: a GC phase marker showed no collection running, and FFmpeg logged nothing near the abort. The `QThreadStorage: entry 0 destroyed before end of thread` warning seen once before an abort fits corruption on the same path. +- **Change.** + - The headless `conftest.py` gains a module-scoped autouse fixture, `collect_qt_garbage_on_the_gui_thread`. Once Qt is loaded it runs `gc.collect()` on the main thread at the start of each module, about 40 ms on a 600,000-object heap. + - `test_gui_script_runs.py` gains `widgets_die_on_the_gui_thread`. It collects before each test and wraps the test in `deleting(_Owner, ScriptHost, RecordHost, AutoClickTab)`. Plain `QWidget()` owners became `_Owner()` so they are recorded. +- **Verification.** + - The same full CI-order local run (517 modules, then the script-runs module) had aborted 3 of 3 times. With the change: 8,856 passed and 105 skipped, with no abort and no `QThreadStorage` warning. + - The module alone passed 3 of 3 runs. +- **Not reproduced minimally:** plain cross-thread GC of cyclic widgets, leaked `TabTask` owners collected on a worker, and pending versus flushed `deleteLater` with deferred deletion all ran clean. The exact precondition is unknown. +- **Files:** `test/unit_test/headless/conftest.py`, `test/unit_test/headless/test_gui_script_runs.py`, `Progress.md`. +- **Open items:** the product GUI can still take the same path. Whether to report it upstream, pin 3.14 to 6.11.2, or collect periodically on the GUI thread is in `Progress.md` ("PySide6 6.12 跨執行緒回收的延後刪除…"). diff --git a/docs/updates/README.md b/docs/updates/README.md index d541e1ff2..c6dbec60d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-04 | 2026-11-16 | Leaked widgets are collected on the GUI thread so a deferred delete cannot abort the suite | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-03 | 2026-11-16 | A transfer-payload test no longer passes Windows MAX_PATH on a local basetemp | #test #windows | [2026-11-b](2026-11-b.md) | | U-20261116-02 | 2026-11-16 | Keep Qt's fatal message when a CI test aborts the interpreter | #ci #test #diagnostics | [2026-11-b](2026-11-b.md) | | U-20261116-01 | 2026-11-16 | PR #552 CI: bandit B105 on three RBAC notes and two timing-sensitive tests | #incident #ci #test #security | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/conftest.py b/test/unit_test/headless/conftest.py index da49ecea9..0d212b841 100644 --- a/test/unit_test/headless/conftest.py +++ b/test/unit_test/headless/conftest.py @@ -1,4 +1,5 @@ """Shared teardown for the headless suite.""" +import gc import os import sys @@ -54,6 +55,26 @@ def handler(mode, _context, message): core.qInstallMessageHandler(handler) +@pytest.fixture(autouse=True, scope="module") +def collect_qt_garbage_on_the_gui_thread(): + """Collect what earlier modules left, on the main thread, before this module starts any worker. + + Cyclic garbage is collected by whichever thread happens to allocate when + the collector runs. A Python-owned Qt object collected on a worker thread + is not deleted there: PySide 6.12 queues it and deletes it later on the + main thread (``Shiboken::BindingManager::runDeletionInMainThread``). On + Windows / Python 3.14 one such deferred delete of a leaked top-level + ``QWidget`` aborted the interpreter inside ``QObject::~QObject`` -- a + minidump showed that frame, the object's ``wasWidget`` / ``wasDeleted`` + bits and no Qt message -- in ``test_gui_script_runs.py``, whose scripts run + long Python work on worker threads. Collecting here keeps leaked widgets on + the thread that owns them. About 40 ms a module, and only once Qt is loaded. + """ + if "PySide6.QtCore" in sys.modules: + gc.collect() + yield + + @pytest.fixture(autouse=True) def flush_qt_deferred_deletes(): """Run Qt's queued ``deleteLater()`` work at the end of every test. diff --git a/test/unit_test/headless/test_gui_script_runs.py b/test/unit_test/headless/test_gui_script_runs.py index ee0d00f73..4d0e16a22 100644 --- a/test/unit_test/headless/test_gui_script_runs.py +++ b/test/unit_test/headless/test_gui_script_runs.py @@ -3,6 +3,7 @@ Offscreen Qt. Every command a script runs here is a fake registered on the executor for the test: nothing touches the mouse, the keyboard or the screen. """ +import gc import json import os import threading @@ -16,7 +17,7 @@ from PySide6.QtCore import QCoreApplication, QEvent, QObject, Signal, Slot # noqa: E402 from PySide6.QtWidgets import QApplication, QMessageBox, QWidget # noqa: E402 -from headless._qt_settle import settle # noqa: E402 +from headless._qt_settle import deleting, settle # noqa: E402 from headless._tab_hosts import RecordHost, ScriptHost # noqa: E402 from je_auto_control.gui._tab_task import TabTask, stop_all_script_runs, was_stopped # noqa: E402 from je_auto_control.gui.language_wrapper.multi_language_wrapper import language_wrapper # noqa: E402 @@ -67,6 +68,28 @@ def after(self) -> None: self.calls.append("after") +class _Owner(QWidget): + """A tab stand-in, its own class so :func:`deleting` can find every one a test built.""" + + +@pytest.fixture(autouse=True) +def widgets_die_on_the_gui_thread(): + """Collect, then delete what each test built, on the GUI thread and never on a script's worker. + + The scripts here run long Python work on worker threads, and cyclic garbage + is collected by whichever thread allocates when the collector runs. A + leaked widget collected there is queued by PySide and deleted later on the + main thread; on Windows / Python 3.14 one such deferred delete aborted the + interpreter inside ``QObject::~QObject`` (see ``conftest.py``, + ``collect_qt_garbage_on_the_gui_thread``). So each test starts with nothing + left to collect and ends with its widgets scheduled for deletion here. + """ + from je_auto_control.gui._auto_click_tab import AutoClickTab + gc.collect() + with deleting(_Owner, ScriptHost, RecordHost, AutoClickTab): + yield + + @pytest.fixture def script(monkeypatch): _app = QApplication.instance() or QApplication([]) @@ -86,7 +109,7 @@ def script(monkeypatch): # --- TabTask --------------------------------------------------------------------------------------------- def test_one_run_at_a_time_and_the_outcome_arrives_on_the_gui_thread(script): - owner = QWidget() + owner = _Owner() runs = TabTask(owner) delivered = [] runs.result.connect(lambda value: delivered.append((threading.get_ident(), value))) @@ -110,7 +133,7 @@ def test_one_run_at_a_time_and_the_outcome_arrives_on_the_gui_thread(script): def test_stop_ends_a_waiting_script_and_reports_it_once_the_worker_has_unwound(script): - owner = QWidget() + owner = _Owner() runs = TabTask(owner) errors, finished = [], [] runs.error.connect(errors.append) @@ -131,7 +154,7 @@ def test_stop_ends_a_waiting_script_and_reports_it_once_the_worker_has_unwound(s def test_destroying_the_owner_stops_its_script(script): - owner = QWidget() + owner = _Owner() runs = TabTask(owner) seen = [] @@ -149,7 +172,7 @@ def work(): def test_ctrl_4_stops_every_running_script(script): - first, second = QWidget(), QWidget() + first, second = _Owner(), _Owner() runs = [TabTask(first), TabTask(second)] for run in runs: assert run.start_script(lambda: executor.execute_action([["AC_sleep", {"seconds": 60}]])) @@ -160,7 +183,7 @@ def test_ctrl_4_stops_every_running_script(script): def test_the_auto_click_stop_also_stops_scripts(script): from je_auto_control.gui._auto_click_tab import AutoClickTab - owner = QWidget() + owner = _Owner() runs = TabTask(owner) errors = [] runs.error.connect(errors.append) From a73d26844ed81d702f9439a24442ee864eae208f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 08:44:49 +0800 Subject: [PATCH 147/161] Collect on the GUI thread after every Qt test, not only per module Windows 3.12 aborted in test_gui_offthread_sites with the same deferred- deletion signature: the garbage came from that module's own earlier tests, which the per-module collection cannot reach. PySide6 6.12 stays, as the maintainer decided; the GUI-side risk is tracked in Progress.md. --- Progress.md | 13 ++++++------ docs/updates/2026-11-b.md | 10 ++++++++++ docs/updates/README.md | 1 + test/unit_test/headless/conftest.py | 31 ++++++++++++++++++++++++++++- 4 files changed, 48 insertions(+), 7 deletions(-) diff --git a/Progress.md b/Progress.md index 96433fd1f..826e7aa76 100644 --- a/Progress.md +++ b/Progress.md @@ -218,15 +218,16 @@ Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_ ## PySide6 6.12 跨執行緒回收的延後刪除會在 `QObject::~QObject` abort(GUI 本身的風險) -`DECIDE` — 原因已由本機 minidump 確認(U-20261116-04):Python 擁有的 Qt 物件若被 worker 執行緒的循環回收收走, +`TODO` — 原因已由本機 minidump 確認(U-20261116-04):Python 擁有的 Qt 物件若被 worker 執行緒的循環回收收走, PySide6 6.12 不在那裡刪,而是排進 `Shiboken::BindingManager::runDeletionInMainThread` 之後在主執行緒刪; 其中一個被留下的頂層 `QWidget`(`wasWidget`、`wasDeleted` 已設、無 parent、無 Qt 訊息)在 `QObject::~QObject` 裡呼叫 `abort()`。 -測試端已處理:headless conftest 在每個模組開始時於主執行緒 `gc.collect()`,`test_gui_script_runs.py` 每個測試先回收、結束時刪掉自己建的 widget; -照 CI 順序的完整本機重跑由 3/3 abort 變成 8,856 通過。 +Windows 上 3.11(`test_gui_offthread_sites.py`,3.11 因此留在 6.11.2)、3.12(同一個測試,run 43761784549)與 3.14 +(`test_gui_script_runs.py`)都出現過,abort 前都有 `QThreadStorage: entry 0 destroyed before end of thread`。 +維護者 2026-11-16 決定保留 6.12、擴大測試端的處理(U-20261116-05):headless conftest 在每個模組開始時、 +以及每個用到 Qt 的模組(原始碼提到 `PySide6` 或 `je_auto_control.gui`)的每個測試結束後,都在主執行緒 `gc.collect()`。 未解:觸發的確切前提還沒用最小範例重現(單純跨執行緒回收、留下的 `TabTask` owner、兩種雙重刪除順序都正常), -所以產品 GUI 在 worker 執行緒跑 Python 時(`_worker_thread`、`DaemonThread`、`tab_task_controller`)仍可能遇到同一條路徑。 -待決定:(1) 是否向 PySide 回報(附 minidump 的堆疊與物件狀態);(2) 是否比照 3.11 把 3.14 固定回 PySide6 6.11.2 -(6.11.1 起就有延後刪除,但升到 6.12 前 3.14 沒有出現過這個 abort);(3) 或在 GUI 端讓主執行緒定期回收、減少留給 worker 的垃圾。 +所以產品 GUI 在 worker 執行緒跑 Python 時(`_worker_thread`、`DaemonThread`、`tab_task_controller`)仍可能走到同一條路徑。 +待辦:向 PySide 回報(附 minidump 的堆疊與物件狀態);之後的 6.12.x 出來時重跑完整矩陣,乾淨就拿掉每個測試的回收。 --- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index daf1721a7..4266576f4 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -939,3 +939,13 @@ - **Not reproduced minimally:** plain cross-thread GC of cyclic widgets, leaked `TabTask` owners collected on a worker, and pending versus flushed `deleteLater` with deferred deletion all ran clean. The exact precondition is unknown. - **Files:** `test/unit_test/headless/conftest.py`, `test/unit_test/headless/test_gui_script_runs.py`, `Progress.md`. - **Open items:** the product GUI can still take the same path. Whether to report it upstream, pin 3.14 to 6.11.2, or collect periodically on the GUI thread is in `Progress.md` ("PySide6 6.12 跨執行緒回收的延後刪除…"). + +## U-20261116-05 · 2026-11-16 · Collect after every Qt test, not only per module, on the GUI thread · #incident #ci #test #gui + +- **Run.** Quality run 43761784549 on `12c9350c` (PR #552): Windows 2022 / Python 3.12.10 aborted in `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_and_a_disconnect_is_not`. `qt-messages.log` first shows `QThreadStorage: entry 0 destroyed before end of thread`, the same signature as the 3.14 abort of U-20261116-04. 3.11 had aborted in this same test under PySide6 6.12.0, which is why 3.11 stays on 6.11.2. +- **Why the per-module collection missed it.** U-20261116-04 collects at the start of each module. Here the garbage came from the module's own earlier tests, and its later workers collected it. +- **Decision (maintainer, 2026-11-16).** Keep PySide6 6.12.0 on Python 3.12+ and widen the test-side fix. The options not taken were pinning back to 6.11.2, or waiting on an upstream fix. +- **Change.** In the headless `conftest.py`, `flush_qt_deferred_deletes` now takes `request`. After its `DeferredDelete` flush, in a module whose source mentions `PySide6` or `je_auto_control.gui` (read once per file), it runs `gc.collect()` on the main thread and flushes `DeferredDelete` again. That covers 126 modules and about 1,150 tests, about 40 ms each. +- **Tests:** `test_gui_offthread_sites.py`, `test_gui_script_runs.py`, `test_usb_acl_prompt.py`, `test_admin_console_thumbnails_gui.py` and `test_ci_native_diagnostics.py`: 55 passed and 5 skipped. A full CI-order local run was still in progress when this was pushed. +- **Files:** `test/unit_test/headless/conftest.py`, `Progress.md`. +- **Open items:** the GUI-side risk and an upstream report, in `Progress.md` ("PySide6 6.12 跨執行緒回收的延後刪除…"). diff --git a/docs/updates/README.md b/docs/updates/README.md index c6dbec60d..6f782572a 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-05 | 2026-11-16 | Collect after every Qt test, not only per module, on the GUI thread | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-04 | 2026-11-16 | Leaked widgets are collected on the GUI thread so a deferred delete cannot abort the suite | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-03 | 2026-11-16 | A transfer-payload test no longer passes Windows MAX_PATH on a local basetemp | #test #windows | [2026-11-b](2026-11-b.md) | | U-20261116-02 | 2026-11-16 | Keep Qt's fatal message when a CI test aborts the interpreter | #ci #test #diagnostics | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/conftest.py b/test/unit_test/headless/conftest.py index 0d212b841..95bb75115 100644 --- a/test/unit_test/headless/conftest.py +++ b/test/unit_test/headless/conftest.py @@ -75,8 +75,26 @@ def collect_qt_garbage_on_the_gui_thread(): yield +_qt_modules: dict = {} + + +def _module_uses_qt(module) -> bool: + """Whether a test module's source imports Qt or the GUI package; read once per file.""" + path = getattr(module, "__file__", None) + if path is None: + return False + if path not in _qt_modules: + try: + with open(path, encoding="utf-8") as source: + text = source.read() + except OSError: + text = "" + _qt_modules[path] = "PySide6" in text or "je_auto_control.gui" in text + return _qt_modules[path] + + @pytest.fixture(autouse=True) -def flush_qt_deferred_deletes(): +def flush_qt_deferred_deletes(request): """Run Qt's queued ``deleteLater()`` work at the end of every test. ``deleteLater()`` does nothing until an event loop runs, and almost no GUI @@ -94,6 +112,14 @@ def flush_qt_deferred_deletes(): to remember. Being autouse, this is set up before any test-local fixture and therefore torn down *after* it — the module's own ``deleteLater()`` calls have already been made by the time this runs. + + In a module that uses Qt, the test's garbage is then collected here, on the + main thread, for the reason ``collect_qt_garbage_on_the_gui_thread`` gives: + collecting once per module was not enough, because a module's own earlier + tests leave widgets that its later workers collect. Windows / Python 3.12 + aborted that way inside ``test_gui_offthread_sites.py`` (run 43761784549, + the same ``QThreadStorage`` warning first). About 40 ms a test, for the + ~1,150 tests in those modules. """ _record_qt_messages() yield @@ -103,6 +129,9 @@ def flush_qt_deferred_deletes(): from PySide6.QtCore import QCoreApplication, QEvent QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) app.processEvents() + if _module_uses_qt(request.module): + gc.collect() + QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) # Backend calls that move the pointer or type on the real desktop. From 4edf84340e3bad1d16bc86cf9cf2d71ec393fa88 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 11:02:12 +0800 Subject: [PATCH 148/161] Pause automatic GC per Qt module instead of collecting after every test Collecting after each test cost about 0.4 s a test on CI across ~5,800 tests, doubled the suite time and pushed a Windows job past its 120-minute limit. With automatic collection paused inside the 379 modules that import Qt or the GUI package, no worker thread can start a collection at all; the module's garbage is collected once, on the main thread, at its end. --- Progress.md | 6 +- docs/updates/2026-11-b.md | 19 +++++ docs/updates/README.md | 1 + test/unit_test/headless/conftest.py | 83 +++++++++++-------- .../headless/test_gui_script_runs.py | 18 ++-- 5 files changed, 78 insertions(+), 49 deletions(-) diff --git a/Progress.md b/Progress.md index 826e7aa76..7b41de10e 100644 --- a/Progress.md +++ b/Progress.md @@ -223,11 +223,11 @@ PySide6 6.12 不在那裡刪,而是排進 `Shiboken::BindingManager::runDeleti 其中一個被留下的頂層 `QWidget`(`wasWidget`、`wasDeleted` 已設、無 parent、無 Qt 訊息)在 `QObject::~QObject` 裡呼叫 `abort()`。 Windows 上 3.11(`test_gui_offthread_sites.py`,3.11 因此留在 6.11.2)、3.12(同一個測試,run 43761784549)與 3.14 (`test_gui_script_runs.py`)都出現過,abort 前都有 `QThreadStorage: entry 0 destroyed before end of thread`。 -維護者 2026-11-16 決定保留 6.12、擴大測試端的處理(U-20261116-05):headless conftest 在每個模組開始時、 -以及每個用到 Qt 的模組(原始碼提到 `PySide6` 或 `je_auto_control.gui`)的每個測試結束後,都在主執行緒 `gc.collect()`。 +維護者 2026-11-16 決定保留 6.12、擴大測試端的處理:U-20261116-05 每個測試後回收太慢(CI 時間約翻倍、Windows 撞 120 分鐘上限), +U-20261116-06 改成在每個 import Qt 或 GUI 套件的模組(379 個)裡暫停自動回收、模組結束時在主執行緒回收一次,worker 不會再觸發回收。 未解:觸發的確切前提還沒用最小範例重現(單純跨執行緒回收、留下的 `TabTask` owner、兩種雙重刪除順序都正常), 所以產品 GUI 在 worker 執行緒跑 Python 時(`_worker_thread`、`DaemonThread`、`tab_task_controller`)仍可能走到同一條路徑。 -待辦:向 PySide 回報(附 minidump 的堆疊與物件狀態);之後的 6.12.x 出來時重跑完整矩陣,乾淨就拿掉每個測試的回收。 +待辦:向 PySide 回報(附 minidump 的堆疊與物件狀態);之後的 6.12.x 出來時重跑完整矩陣,乾淨就拿掉 conftest 的 `no_worker_collects_qt_garbage`。 --- diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 4266576f4..6b9bb7f9b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -949,3 +949,22 @@ - **Tests:** `test_gui_offthread_sites.py`, `test_gui_script_runs.py`, `test_usb_acl_prompt.py`, `test_admin_console_thumbnails_gui.py` and `test_ci_native_diagnostics.py`: 55 passed and 5 skipped. A full CI-order local run was still in progress when this was pushed. - **Files:** `test/unit_test/headless/conftest.py`, `Progress.md`. - **Open items:** the GUI-side risk and an upstream report, in `Progress.md` ("PySide6 6.12 跨執行緒回收的延後刪除…"). + +## U-20261116-06 · 2026-11-16 · Pause automatic GC per Qt module instead of collecting after every test · #incident #ci #test #gui + +- **Run.** PR #552 on `a73d2684`. + - Every Quality job passed, and no abort recurred. + - But the per-test collection of U-20261116-05 roughly doubled test time: Windows 3.12 went from 56 to 107 minutes, Ubuntu 3.14 from 34 to 77, macOS 3.14 from 36 to 57. + - Dev CI's Windows 3.14 job hit its `timeout-minutes: 120` at 84% and was cancelled (run 43782197835). +- **Why it was slow.** + - The "uses Qt" test matched any module whose text mentions `PySide6` or `je_auto_control.gui`: 395 modules and 5,771 tests, not the ~1,150 estimated. + - A full collection late in the suite costs about 0.4 s on CI, not the 40 ms measured on a small heap. +- **Change** (headless `conftest.py`): + - `no_worker_collects_qt_garbage`, a module-scoped autouse fixture, replaces both the per-module start collection of U-20261116-04 and the per-test collection. + - In a module whose source has a `PySide6` or `je_auto_control.gui` import line (lazy ones too), or an `importorskip("PySide6")`, it disables automatic collection for the module. That is 379 modules. + - At the module's end it re-enables collection if it was on, collects once on the main thread, and flushes `DeferredDelete`. + - While collection is paused no worker thread can start a collection. Explicit `gc.collect()` still works, and the three tests that pause it themselves restore the state they found. + - `test_gui_script_runs.py` keeps only its per-test `deleting(...)`. +- **Tests:** all 379 modules, 5,436 passed and 16 skipped in 8 min 56 s locally, with no abort and no `QThreadStorage` warning. The earlier full CI-order run with per-test collection had passed 8,856. +- **Files:** `test/unit_test/headless/conftest.py`, `test/unit_test/headless/test_gui_script_runs.py`, `Progress.md`. +- **Open items:** the GUI-side risk and an upstream report, in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 6f782572a..bfd671382 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-06 | 2026-11-16 | Pause automatic GC per Qt module instead of collecting after every test | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-05 | 2026-11-16 | Collect after every Qt test, not only per module, on the GUI thread | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-04 | 2026-11-16 | Leaked widgets are collected on the GUI thread so a deferred delete cannot abort the suite | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-03 | 2026-11-16 | A transfer-payload test no longer passes Windows MAX_PATH on a local basetemp | #test #windows | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/conftest.py b/test/unit_test/headless/conftest.py index 95bb75115..8d982e310 100644 --- a/test/unit_test/headless/conftest.py +++ b/test/unit_test/headless/conftest.py @@ -1,6 +1,7 @@ """Shared teardown for the headless suite.""" import gc import os +import re import sys import pytest @@ -55,46 +56,68 @@ def handler(mode, _context, message): core.qInstallMessageHandler(handler) -@pytest.fixture(autouse=True, scope="module") -def collect_qt_garbage_on_the_gui_thread(): - """Collect what earlier modules left, on the main thread, before this module starts any worker. - - Cyclic garbage is collected by whichever thread happens to allocate when - the collector runs. A Python-owned Qt object collected on a worker thread - is not deleted there: PySide 6.12 queues it and deletes it later on the - main thread (``Shiboken::BindingManager::runDeletionInMainThread``). On - Windows / Python 3.14 one such deferred delete of a leaked top-level - ``QWidget`` aborted the interpreter inside ``QObject::~QObject`` -- a - minidump showed that frame, the object's ``wasWidget`` / ``wasDeleted`` - bits and no Qt message -- in ``test_gui_script_runs.py``, whose scripts run - long Python work on worker threads. Collecting here keeps leaked widgets on - the thread that owns them. About 40 ms a module, and only once Qt is loaded. - """ - if "PySide6.QtCore" in sys.modules: - gc.collect() - yield - - +_QT_IMPORT = re.compile(r"^\s*(?:from|import)\s+(?:PySide6|je_auto_control\.gui)\b" + r"|importorskip\(\s*['\"]PySide6", re.MULTILINE) _qt_modules: dict = {} def _module_uses_qt(module) -> bool: - """Whether a test module's source imports Qt or the GUI package; read once per file.""" + """Whether a test module imports Qt or the GUI package anywhere (lazily, too); read once per file.""" path = getattr(module, "__file__", None) if path is None: return False if path not in _qt_modules: try: with open(path, encoding="utf-8") as source: - text = source.read() + _qt_modules[path] = bool(_QT_IMPORT.search(source.read())) except OSError: - text = "" - _qt_modules[path] = "PySide6" in text or "je_auto_control.gui" in text + _qt_modules[path] = False return _qt_modules[path] +@pytest.fixture(autouse=True, scope="module") +def no_worker_collects_qt_garbage(request): + """In a module that uses Qt, pause automatic collection; collect once, on the main thread, at its end. + + Cyclic garbage is collected by whichever thread happens to allocate when + the collector runs. A Python-owned Qt object collected on a worker thread + is not deleted there: PySide 6.12 queues it and deletes it later on the + main thread (``Shiboken::BindingManager::runDeletionInMainThread``), and on + Windows one such deferred delete of a leaked top-level ``QWidget`` aborted + the interpreter inside ``QObject::~QObject`` -- a minidump showed that frame, + the object's ``wasWidget`` / ``wasDeleted`` bits and no Qt message. It hit + 3.14 in ``test_gui_script_runs.py`` and 3.12 (and, earlier, 3.11) in + ``test_gui_offthread_sites.py``, each time after a ``QThreadStorage: entry 0 + destroyed before end of thread`` warning. + + With automatic collection paused no worker can start a collection at all; + an explicit ``gc.collect()`` still works, and tests that pause it + themselves restore what they found. The module's garbage is collected here + instead, on the main thread, and any deletes that queues are flushed. + Collecting after every test instead cost about 0.4 s a test on CI and + pushed the Windows jobs past their 120-minute limit; this is one + collection per module. + """ + if not _module_uses_qt(request.module): + yield + return + paused = gc.isenabled() + gc.disable() + try: + yield + finally: + if paused: + gc.enable() + gc.collect() + app = _live_qt_application() + if app is not None: + from PySide6.QtCore import QCoreApplication, QEvent + QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) + app.processEvents() + + @pytest.fixture(autouse=True) -def flush_qt_deferred_deletes(request): +def flush_qt_deferred_deletes(): """Run Qt's queued ``deleteLater()`` work at the end of every test. ``deleteLater()`` does nothing until an event loop runs, and almost no GUI @@ -113,13 +136,6 @@ def flush_qt_deferred_deletes(request): and therefore torn down *after* it — the module's own ``deleteLater()`` calls have already been made by the time this runs. - In a module that uses Qt, the test's garbage is then collected here, on the - main thread, for the reason ``collect_qt_garbage_on_the_gui_thread`` gives: - collecting once per module was not enough, because a module's own earlier - tests leave widgets that its later workers collect. Windows / Python 3.12 - aborted that way inside ``test_gui_offthread_sites.py`` (run 43761784549, - the same ``QThreadStorage`` warning first). About 40 ms a test, for the - ~1,150 tests in those modules. """ _record_qt_messages() yield @@ -129,9 +145,6 @@ def flush_qt_deferred_deletes(request): from PySide6.QtCore import QCoreApplication, QEvent QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) app.processEvents() - if _module_uses_qt(request.module): - gc.collect() - QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) # Backend calls that move the pointer or type on the real desktop. diff --git a/test/unit_test/headless/test_gui_script_runs.py b/test/unit_test/headless/test_gui_script_runs.py index 4d0e16a22..d46d36377 100644 --- a/test/unit_test/headless/test_gui_script_runs.py +++ b/test/unit_test/headless/test_gui_script_runs.py @@ -3,7 +3,6 @@ Offscreen Qt. Every command a script runs here is a fake registered on the executor for the test: nothing touches the mouse, the keyboard or the screen. """ -import gc import json import os import threading @@ -74,18 +73,15 @@ class _Owner(QWidget): @pytest.fixture(autouse=True) def widgets_die_on_the_gui_thread(): - """Collect, then delete what each test built, on the GUI thread and never on a script's worker. - - The scripts here run long Python work on worker threads, and cyclic garbage - is collected by whichever thread allocates when the collector runs. A - leaked widget collected there is queued by PySide and deleted later on the - main thread; on Windows / Python 3.14 one such deferred delete aborted the - interpreter inside ``QObject::~QObject`` (see ``conftest.py``, - ``collect_qt_garbage_on_the_gui_thread``). So each test starts with nothing - left to collect and ends with its widgets scheduled for deletion here. + """Delete what each test built, on the GUI thread, instead of leaving it for a collector. + + The scripts here run long Python work on worker threads. A leaked widget + that a worker's collection reaches is queued by PySide and deleted later on + the main thread, and on Windows / Python 3.14 one such deferred delete + aborted the interpreter inside ``QObject::~QObject`` (``conftest.py``, + ``no_worker_collects_qt_garbage``, which also pauses automatic collection here). """ from je_auto_control.gui._auto_click_tab import AutoClickTab - gc.collect() with deleting(_Owner, ScriptHost, RecordHost, AutoClickTab): yield From ca02a79339a74a2dc3c5e2e6a063a59b2b8d7b3a Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 12:17:29 +0800 Subject: [PATCH 149/161] Draft the PySide deferred-deletion abort report from the dump evidence The report is for the maintainer to file; it keeps the native stack, the destroyed widget's QObjectData state, what did not reproduce it and the workaround in the repository rather than in a session log. --- Progress.md | 2 +- .../pyside6-6.12-deferred-deletion-abort.md | 100 ++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 docs/upstream/pyside6-6.12-deferred-deletion-abort.md diff --git a/Progress.md b/Progress.md index 7b41de10e..c06199527 100644 --- a/Progress.md +++ b/Progress.md @@ -227,7 +227,7 @@ Windows 上 3.11(`test_gui_offthread_sites.py`,3.11 因此留在 6.11.2) U-20261116-06 改成在每個 import Qt 或 GUI 套件的模組(379 個)裡暫停自動回收、模組結束時在主執行緒回收一次,worker 不會再觸發回收。 未解:觸發的確切前提還沒用最小範例重現(單純跨執行緒回收、留下的 `TabTask` owner、兩種雙重刪除順序都正常), 所以產品 GUI 在 worker 執行緒跑 Python 時(`_worker_thread`、`DaemonThread`、`tab_task_controller`)仍可能走到同一條路徑。 -待辦:向 PySide 回報(附 minidump 的堆疊與物件狀態);之後的 6.12.x 出來時重跑完整矩陣,乾淨就拿掉 conftest 的 `no_worker_collects_qt_garbage`。 +待辦:向 PySide 回報——草稿(堆疊、物件狀態、未重現的情境與 workaround)在 `docs/upstream/pyside6-6.12-deferred-deletion-abort.md`,由維護者送到 bugreports.qt.io;之後的 6.12.x 出來時重跑完整矩陣,乾淨就拿掉 conftest 的 `no_worker_collects_qt_garbage`。 --- diff --git a/docs/upstream/pyside6-6.12-deferred-deletion-abort.md b/docs/upstream/pyside6-6.12-deferred-deletion-abort.md new file mode 100644 index 000000000..84433f4ca --- /dev/null +++ b/docs/upstream/pyside6-6.12-deferred-deletion-abort.md @@ -0,0 +1,100 @@ +# Draft report for Qt for Python: abort in `QObject::~QObject` from `BindingManager::runDeletionInMainThread` + +Status: **draft, not filed.** The maintainer files it at (project PYSIDE). +The evidence below was collected in this repository between 2026-11-15 and 2026-11-16. The records are +U-20261116-01 through -06 in `docs/updates/2026-11-b.md`, and the open item is in `Progress.md`. + +--- + +**Title:** Windows: interpreter aborts in `QObject::~QObject` when a widget collected by a non-GUI thread's GC is deleted by `runDeletionInMainThread` (6.12.0) + +**Component:** Shiboken / PySide6 object lifetime (deferred deletion, the PYSIDE-3288 change in 6.11.1) + +**Environment** + +- PySide6 / shiboken6 **6.12.0** (wheels from PyPI) +- Windows Server 2022 (GitHub-hosted `windows-2022`) and Windows 11 Pro 10.0.26200 +- CPython **3.12.10**, **3.14.7** and **3.14.10**, x64. CPython 3.11 had aborted the same way earlier. +- `QT_QPA_PLATFORM=offscreen` + +**What happens** + +Our headless test suite (~19,000 tests, several hundred of which build widgets) intermittently dies with +`Fatal Python error: Aborted` (exit code 3). faulthandler marks the **main thread** as the one that +called `abort()`. Its Python frame is at a blocking call: `time.sleep`, a `threading.Event.wait`, or +`QApplication.processEvents`. Other threads are Python workers running ordinary Python code +(logging, a test-only script executor). Qt prints no fatal message. + +It is intermittent in CI: 3 of 5 consecutive Windows runs aborted, on 3.12 and on 3.14. Locally it was +reliable when the same module order ran. It never reproduced from a single module or from any half of +that order. + +In several of the aborts, Qt's last message before the abort was: + +``` +QThreadStorage: entry 0 destroyed before end of thread 0x... +``` + +This line never appeared in passing runs. + +**Native stack of the aborting (main) thread** + +The stack came from a minidump written by a `SIGABRT` handler. These are return addresses found by +scanning the stack, each named by the nearest export, innermost first: + +``` +ucrtbase!raise +ucrtbase!abort +Qt6Core!QObject::~QObject (??1QObject@@UEAA@XZ + 0x836) +shiboken6! +shiboken6!Shiboken::BindingManager::runDeletionInMainThread +python314!... (pending call / eval breaker) +``` + +**State of the object being destroyed** + +The object was read from the dump: its `QObject` pointer, then its `QObjectData`. + +- The vtable pointer is already `QObject`'s, which is normal partway through a destructor chain. The + second vtable is QPaintDevice's, so the object is a `QWidget`. +- `q_ptr` points back at the object. `parent` = null. `children` is empty. +- Flags: `wasDeleted = 1`, `wasWidget = 1`, `willBeWidget = 1`, `isWindow = 0`, `deleteLaterCalled = 0`. +- `postedEvents = 0`, `metaObject = null`. + +So a top-level widget that Python owned was being deleted by the deferred-deletion queue on the main +thread when `~QObject` called `abort()`. + +**How the widgets reach that path** + +The tests create top-level `QWidget`s, and tab widgets built on them, without parents. Some of them +end up in reference cycles, so only the cyclic GC frees them. Meanwhile the test runs long Python work +on plain `threading.Thread` workers. That work emits Qt signals to GUI-thread objects, which makes the +workers Qt-adopted threads. Whichever thread allocates when a collection is due runs it, so a worker +collects the leaked widgets. Since 6.11.1 shiboken does not delete those on the worker; it queues them +and deletes them later on the main thread. + +**What did not reproduce it** (each run hundreds to thousands of times) + +- Cyclic, Python-owned widgets, with a layout, children and a running child `QTimer`, created on the main + thread, collected by `gc.collect()` on a worker, followed by `processEvents()` on the main thread. +- The same with widgets that had `deleteLater()` pending, or already flushed, before the worker + collected them. +- Worker threads that call `QThread.currentThread()`, keep the wrapper, and emit to a GUI-thread + object before exiting. + +**Workaround that removes it** + +The workaround is to pause automatic collection (`gc.disable()`) while widgets and worker threads +coexist, and run `gc.collect()` on the main thread at a safe point. + +- With it, the full Windows matrix (3.11 to 3.14) passed, and the local order that aborted 3 of 3 + times passed 8,856 tests. +- Collecting on the main thread after every test also removed the abort, but it was too slow for CI. + +**Questions for the maintainers** + +1. Can a pointer queued for `runDeletionInMainThread` be destroyed by Qt before the queue runs, so the + queued delete runs on freed or reused memory? The `QThreadStorage` warning and an abort with no message + suggest corruption rather than a `qFatal`. +2. Is deferring a top-level `QWidget`'s deletion from an adopted non-GUI thread expected to be safe? Or + should applications keep the collector off non-GUI threads, as above? From 9244ab7c80e9dc75a1e3d47b87bb66953d30e48c Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 14:25:08 +0800 Subject: [PATCH 150/161] Collect cyclic garbage on the GUI thread only while the GUI runs PySide6 6.12 defers the delete of a Qt object a worker thread's collection reaches, and one such deferred delete aborted the process on Windows. The GUI now switches automatic collection off and collects from a GUI-thread timer at the interpreter's thresholds, giving it back on quit; library use without the GUI is unchanged. --- CHANGELOG.md | 6 + Progress.md | 22 ++- README.md | 2 + README/README_zh-CN.md | 2 + README/README_zh-TW.md | 2 + architecture_explore.md | 11 +- .../Eng/doc/installation/installation_doc.rst | 5 + .../Zh/doc/installation/installation_doc.rst | 4 + docs/updates/2026-11-b.md | 21 +++ docs/updates/README.md | 1 + je_auto_control/gui/__init__.py | 10 +- je_auto_control/gui/_gui_thread_gc.py | 66 ++++++++ test/unit_test/headless/test_gui_thread_gc.py | 160 ++++++++++++++++++ 13 files changed, 294 insertions(+), 18 deletions(-) create mode 100644 je_auto_control/gui/_gui_thread_gc.py create mode 100644 test/unit_test/headless/test_gui_thread_gc.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fdc6040a..96d3ac0d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- GUI (`start_autocontrol_gui()`): while the window is open, automatic cyclic garbage collection is + switched off and a GUI-thread timer collects instead (`gui/_gui_thread_gc.py`), at the interpreter's + thresholds; it is switched back on when the app quits. Worker threads no longer collect Qt objects, + which PySide6 6.12 deletes late and which has aborted the process on Windows. An explicit + `gc.collect()` still works; importing `je_auto_control` without the GUI is unchanged. + - `AC_shell_to_var` and MCP `ac_shell`: inside a stoppable run or a cancellation scope, a stop, `ac_stop_execution` or `notifications/cancelled` kills the command's process tree within about 0.1 s and ends the call (`ExecutionStopped`, or `-32800` for a client cancel), instead of waiting diff --git a/Progress.md b/Progress.md index c06199527..6c40880f5 100644 --- a/Progress.md +++ b/Progress.md @@ -216,18 +216,16 @@ Windows 3.11 在 `test_gui_offthread_sites.py::test_a_failed_upload_is_reported_ --- -## PySide6 6.12 跨執行緒回收的延後刪除會在 `QObject::~QObject` abort(GUI 本身的風險) - -`TODO` — 原因已由本機 minidump 確認(U-20261116-04):Python 擁有的 Qt 物件若被 worker 執行緒的循環回收收走, -PySide6 6.12 不在那裡刪,而是排進 `Shiboken::BindingManager::runDeletionInMainThread` 之後在主執行緒刪; -其中一個被留下的頂層 `QWidget`(`wasWidget`、`wasDeleted` 已設、無 parent、無 Qt 訊息)在 `QObject::~QObject` 裡呼叫 `abort()`。 -Windows 上 3.11(`test_gui_offthread_sites.py`,3.11 因此留在 6.11.2)、3.12(同一個測試,run 43761784549)與 3.14 -(`test_gui_script_runs.py`)都出現過,abort 前都有 `QThreadStorage: entry 0 destroyed before end of thread`。 -維護者 2026-11-16 決定保留 6.12、擴大測試端的處理:U-20261116-05 每個測試後回收太慢(CI 時間約翻倍、Windows 撞 120 分鐘上限), -U-20261116-06 改成在每個 import Qt 或 GUI 套件的模組(379 個)裡暫停自動回收、模組結束時在主執行緒回收一次,worker 不會再觸發回收。 -未解:觸發的確切前提還沒用最小範例重現(單純跨執行緒回收、留下的 `TabTask` owner、兩種雙重刪除順序都正常), -所以產品 GUI 在 worker 執行緒跑 Python 時(`_worker_thread`、`DaemonThread`、`tab_task_controller`)仍可能走到同一條路徑。 -待辦:向 PySide 回報——草稿(堆疊、物件狀態、未重現的情境與 workaround)在 `docs/upstream/pyside6-6.12-deferred-deletion-abort.md`,由維護者送到 bugreports.qt.io;之後的 6.12.x 出來時重跑完整矩陣,乾淨就拿掉 conftest 的 `no_worker_collects_qt_garbage`。 +## PySide6 6.12 跨執行緒回收的延後刪除會在 `QObject::~QObject` abort:等上游修正 + +`BLOCKED`(上游)— 原因由本機 minidump 確認(U-20261116-04):Python 擁有的 Qt 物件若被 worker 執行緒的循環回收收走, +PySide6 6.12 會排進 `Shiboken::BindingManager::runDeletionInMainThread` 之後在主執行緒刪, +其中一個被留下的頂層 `QWidget` 在 `QObject::~QObject` 裡呼叫 `abort()`;Windows 3.11/3.12/3.14 都出現過。 +現況:測試端由 conftest 的 `no_worker_collects_qt_garbage` 在用到 Qt 的模組裡暫停自動回收(U-20261116-06), +GUI 由 `gui/_gui_thread_gc.py` 的 `GuiThreadCollector` 只在 GUI 執行緒回收(U-20261116-07),兩邊都不會讓 worker 觸發回收。 +待辦:(1) 維護者把 `docs/upstream/pyside6-6.12-deferred-deletion-abort.md` 送到 bugreports.qt.io(PYSIDE); +(2) 修正版 6.12.x 出來後重跑完整矩陣,乾淨就拿掉 conftest 的 `no_worker_collects_qt_garbage` 並評估是否保留 `GuiThreadCollector`, +同時處理上一節 3.11 的固定版本。 --- diff --git a/README.md b/README.md index 48b43248a..f649044c5 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ python -m pip install "je_auto_control[gui]" python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" ``` +While the window is open, the app collects Python's cyclic garbage on the GUI thread, from a timer, with automatic collection switched off; it is switched back on when the app quits. This keeps a worker thread from reaching a Qt object that PySide6 6.12 would then delete late, which has aborted the process on Windows. Scripts that only `import je_auto_control` are unaffected. + ## What you can do - Automate mouse, keyboard and window operations. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 9562c3c61..7e3d98e6c 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -27,6 +27,8 @@ python -m pip install "je_auto_control[gui]" python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" ``` +窗口打开时,程序会关闭自动回收,改由 GUI 线程上的定时器回收 Python 的循环垃圾,退出时再打开。这是为了不让 worker 线程碰到 PySide6 6.12 会延后删除的 Qt 对象;那条路径在 Windows 上曾让进程 abort。只 `import je_auto_control` 的脚本不受影响。 + ## 可以做什么 - 操作鼠标、键盘与窗口。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 97b478b13..aac6b5559 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -27,6 +27,8 @@ python -m pip install "je_auto_control[gui]" python -c "import je_auto_control; je_auto_control.start_autocontrol_gui()" ``` +視窗開著時,程式會關閉自動回收,改由 GUI 執行緒上的計時器回收 Python 的循環垃圾,結束時再打開。這是為了不讓 worker 執行緒碰到 PySide6 6.12 會延後刪除的 Qt 物件;那條路徑在 Windows 上曾讓程序 abort。只 `import je_auto_control` 的腳本不受影響。 + ## 可以做什麼 - 操作滑鼠、鍵盤與視窗。 diff --git a/architecture_explore.md b/architecture_explore.md index 906d1582e..69d133832 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,546 | -| 程式碼總行數 | 238,619 | +| Python 模組總數(含周邊子專案) | 1,547 | +| 程式碼總行數 | 238,693 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -1295,7 +1295,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | 模組 | 行數 | 職責 | | --- | ---: | --- | -| `gui/__init__.py` | 25 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | +| `gui/__init__.py` | 33 | `start_autocontrol_gui()`:**唯一**會延遲匯入 PySide6 的地方,維持頂層套件 Qt-free。 | | `main_window.py` | 465 | `QMainWindow`:選單列(File/Actions/View/…)、左側導覽面板 dock(`Ctrl+K` 搜尋、`Ctrl+B` 收合,窄視窗時改為抽屜,由 `adaptive_window.py` 安排)、即時語言切換、字級預設、深色/淺色主題(`theme.py` 的 token,不再用 qt-material)。分頁分為 core/editing/detection/automation/system 五類。 | | `main_widget.py` | 86 | Configured application workspace preserving the embedded-widget entry point. `AutoControlGUIWidget` 以單一 registry 註冊既有分頁,保留 Remote Desktop factory 與嵌入相容入口。 | | `tab_registry.py` | 234 | 分頁表:每個分頁一筆 `TabSpec`(鍵、標題鍵、分類、模組與類別名),`TabEntry` 在第一次存取 `widget` 時才呼叫 factory。`TabRegistry.open/close` 快取或釋放 factory 面板,保留 metadata 與外部提供的 widget;不匯入 Qt。 | @@ -1333,6 +1333,7 @@ GUI 是**選用 extra**(`pip install je_auto_control[gui]`,只需要 PySide6 | `_screen_geometry.py` | 55 | Qt 邏輯座標與截圖用的原生像素互轉:`native_region()`、`screen_at_native()`、`logical_point()`(每個螢幕的左上角在兩者相同,螢幕內依 device pixel ratio 縮放)。區域選取與主機端標註覆蓋層都用它。 | | `_daemon_thread.py` | 79 | `DaemonThread`:`QThread` 的替代品,保留遠端桌面 worker 用到的介面(`start`/`run`/`isRunning`/`wait`/`requestInterruption`/`started`/`finished`),但 `run()` 跑在 daemon `threading.Thread` 上,刪除物件或程式結束都不會銷毀執行中的執行緒。 | | `_worker_thread.py` | 273 | `start_worker()`:在 daemon `threading.Thread` 上執行 `QObject` worker 的 `run()`(沒有 `QThread` 可被銷毀),並經由分頁擁有的中繼物件回報結果(回呼一律在 GUI 執行緒;worker 沒處理的例外也送到 `on_fail`);worker 留在模組登錄表直到 GUI 執行緒看到它結束,啟動失敗回復登記並保留原失敗;回傳 `WorkerHandle`(`isRunning()`);程式結束時先呼叫 worker 的 `request_stop()`,最多等 10 秒,仍在跑的隨行程結束。 | +| `_gui_thread_gc.py` | 66 | `GuiThreadCollector`:GUI 開著時關掉自動循環回收,改由 GUI 執行緒上的 `QTimer` 依直譯器門檻回收(第 0 代、每 threshold[1] 次第 1 代、每 threshold[1]×threshold[2] 次完整回收),結束時恢復;讓 worker 執行緒不會收走 PySide6 6.12 會延後刪除的 Qt 物件。 | | `task_controller.py` | 270 | 共用 owner-bound task/typed outcome-progress;獨立 token、弱回呼、dispatch 身分更新與銷毀後結果隔離。工作綁定獨立 cancellation scope;其餘面板遷移另列進度。 | | `template_candidate_panel.py` | 247 | 預覽原始/候選縮圖、檢視驗證並明確接受/回復。 | | `template_candidate_worker.py` | 125 | 背景檔案操作、延後權限檢查與提交前取消;完成寫入不重標為取消。 | @@ -1550,7 +1551,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | 層/子系統 | 檔案數 | 行數 | | --- | ---: | ---: | -| `gui/` | 166 | 43,950 | +| `gui/` | 167 | 44,024 | | `utils/mcp_server/` | 63 | 22,322 | | `utils/remote_desktop/` | 77 | 16,970 | | `utils/executor/` | 11 | 10,765 | @@ -1571,7 +1572,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | | 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,194 | -| **總計** | **1,534** | **237,874** | +| **總計** | **1,535** | **237,948** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/source/Eng/doc/installation/installation_doc.rst b/docs/source/Eng/doc/installation/installation_doc.rst index 084a83d58..f37a92cb7 100644 --- a/docs/source/Eng/doc/installation/installation_doc.rst +++ b/docs/source/Eng/doc/installation/installation_doc.rst @@ -22,6 +22,11 @@ With GUI Support pip install je_auto_control[gui] +While the GUI (``start_autocontrol_gui()``) is open, cyclic garbage is collected on the GUI +thread from a timer and automatic collection is switched off; it is switched back on when the +app quits. A worker thread then never reaches a Qt object that PySide6 6.12 would delete late, +which has aborted the process on Windows. Importing ``je_auto_control`` alone changes nothing. + Linux Prerequisites =================== diff --git a/docs/source/Zh/doc/installation/installation_doc.rst b/docs/source/Zh/doc/installation/installation_doc.rst index 5c1e0481e..f32828942 100644 --- a/docs/source/Zh/doc/installation/installation_doc.rst +++ b/docs/source/Zh/doc/installation/installation_doc.rst @@ -22,6 +22,10 @@ pip install je_auto_control[gui] +GUI(``start_autocontrol_gui()``)開著時,自動回收會關閉,改由 GUI 執行緒上的計時器回收循環垃圾, +程式結束時再打開。這樣 worker 執行緒不會碰到 PySide6 6.12 會延後刪除的 Qt 物件(那條路徑在 Windows 上曾讓程序 abort)。 +只 import ``je_auto_control`` 不會改變任何事。 + Linux 前置套件 ============== diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 6b9bb7f9b..19ee081f0 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -968,3 +968,24 @@ - **Tests:** all 379 modules, 5,436 passed and 16 skipped in 8 min 56 s locally, with no abort and no `QThreadStorage` warning. The earlier full CI-order run with per-test collection had passed 8,856. - **Files:** `test/unit_test/headless/conftest.py`, `test/unit_test/headless/test_gui_script_runs.py`, `Progress.md`. - **Open items:** the GUI-side risk and an upstream report, in `Progress.md`. + +## U-20261116-07 · 2026-11-16 · The GUI collects cyclic garbage on its own thread only · #gui #pyside6 #done + +- **Why.** The PySide6 6.12 deferred-deletion abort (U-20261116-04, `docs/upstream/pyside6-6.12-deferred-deletion-abort.md`) is not test-only. In the real GUI, any worker thread that runs Python can be the one that collects a leaked widget. The maintainer chose (2026-11-16) to keep the collector off worker threads in the GUI process as well. +- **Change.** + - New `je_auto_control/gui/_gui_thread_gc.py` provides `GuiThreadCollector`, a `QObject`. It disables automatic collection and, from a 500 ms `QTimer` on the GUI thread, collects at the interpreter's own thresholds: generation 0 once `gc.get_count()[0]` passes `threshold[0]`, generation 1 every `threshold[1]` young collections, and a full collection every `threshold[1] × threshold[2]`. + - A first threshold of 0 is respected (no collection). `stop()` is idempotent and switches automatic collection back on only if it was on. + - `start_autocontrol_gui()` creates it with the `QApplication` as parent and connects `aboutToQuit` to `stop()`. + - Importing `je_auto_control` stays Qt-free and leaves the collector alone. +- **Tests:** new `test_gui_thread_gc.py`, 8 cases: + - collection is off while it runs and restored as found, whether it was on or off; + - nothing is collected below the threshold; + - the generation cadence is exactly 90 / 9 / 1 over 100 checks at (700, 10, 10); + - a first threshold of 0 stays off; + - a real cycle is freed by the timer, and every collection runs on the GUI thread; + - `start_autocontrol_gui()` installs it under the app and `aboutToQuit` restores collection; + - `import je_auto_control` still loads no PySide6. + - It passed 3 of 3 runs. Docs counts, line counts, complexity, broad-except and file-length gates: 52 passed. `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean. +- **Docs:** README, both translations and both installation guides (`docs/source/{Eng,Zh}/doc/installation/installation_doc.rst`) describe the behaviour under the GUI launch instructions. There is a CHANGELOG entry, and `architecture_explore.md` has a row for the new module (re-measured). +- **Files:** `je_auto_control/gui/_gui_thread_gc.py`, `je_auto_control/gui/__init__.py`, `test/unit_test/headless/test_gui_thread_gc.py`, `README.md`, `README/README_zh-TW.md`, `README/README_zh-CN.md`, the two installation guides, `CHANGELOG.md`, `architecture_explore.md`, `Progress.md`. +- **Open items:** the upstream report and removing the workarounds once a fixed 6.12.x ships, in `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index bfd671382..727b742d4 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-07 | 2026-11-16 | The GUI collects cyclic garbage on its own thread only | #gui #pyside6 #done | [2026-11-b](2026-11-b.md) | | U-20261116-06 | 2026-11-16 | Pause automatic GC per Qt module instead of collecting after every test | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-05 | 2026-11-16 | Collect after every Qt test, not only per module, on the GUI thread | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-04 | 2026-11-16 | Leaked widgets are collected on the GUI thread so a deferred delete cannot abort the suite | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/gui/__init__.py b/je_auto_control/gui/__init__.py index 931f3e884..721333030 100644 --- a/je_auto_control/gui/__init__.py +++ b/je_auto_control/gui/__init__.py @@ -10,16 +10,24 @@ def start_autocontrol_gui() -> None: - """Open the AutoControl GUI; pulls in PySide6 + WebRTC stack lazily.""" + """Open the AutoControl GUI; pulls in PySide6 + WebRTC stack lazily. + + While the window runs, cyclic garbage is collected on the GUI thread only + (:class:`~je_auto_control.gui._gui_thread_gc.GuiThreadCollector`), so a + worker thread never reaches a Qt object PySide would then delete late. + """ import sys from PySide6.QtWidgets import QApplication + from je_auto_control.gui import _gui_thread_gc from je_auto_control.gui.main_window import AutoControlGUIUI from je_auto_control.gui.theme import prepare_application app = QApplication(sys.argv) prepare_application(app) + collector = _gui_thread_gc.GuiThreadCollector(app) + app.aboutToQuit.connect(collector.stop) window = AutoControlGUIUI() window.show() sys.exit(app.exec()) diff --git a/je_auto_control/gui/_gui_thread_gc.py b/je_auto_control/gui/_gui_thread_gc.py new file mode 100644 index 000000000..ff52bdb93 --- /dev/null +++ b/je_auto_control/gui/_gui_thread_gc.py @@ -0,0 +1,66 @@ +"""Run the cyclic garbage collector on the GUI thread only, while the window is up. + +PySide6 6.12 does not delete a Python-owned Qt object that a non-GUI thread's +collection reaches: it queues the delete and runs it later on the GUI thread +(``Shiboken::BindingManager::runDeletionInMainThread``). On Windows one such +deferred delete of a top-level widget aborted the interpreter inside +``QObject::~QObject`` (``docs/upstream/pyside6-6.12-deferred-deletion-abort.md``). +Automatic collection runs on whichever thread happens to allocate when it is +due, and the GUI's workers run Python, so :class:`GuiThreadCollector` switches +it off and collects from a timer on the GUI thread instead. + +It keeps the interpreter's own thresholds: a young collection once +allocations pass ``threshold[0]``, an older one every ``threshold[1]`` young +ones and a full one every ``threshold[1] * threshold[2]``. A first threshold of +0 (collection switched off by the application) is respected. An explicit +``gc.collect()`` anywhere still works, and :meth:`GuiThreadCollector.stop` +gives automatic collection back as it was found. +""" +import gc +from typing import Optional + +from PySide6.QtCore import QObject, QTimer + +_INTERVAL_MS = 500 + + +class GuiThreadCollector(QObject): + """Collect garbage from a GUI-thread timer while automatic collection is off.""" + + def __init__(self, parent: Optional[QObject] = None, interval_ms: int = _INTERVAL_MS) -> None: + super().__init__(parent) + self._was_enabled = gc.isenabled() + self._young = 0 + self._stopped = False + self.collections = [0, 0, 0] + gc.disable() + self._timer = QTimer(self) + self._timer.timeout.connect(self.check) + self._timer.start(interval_ms) + + def check(self) -> Optional[int]: + """Collect the generation the allocation count calls for; the generation, or None if none was due.""" + first, middle, oldest = gc.get_threshold() + if first <= 0 or gc.get_count()[0] <= first: + return None + self._young += 1 + generation = 0 + if self._young % (max(1, middle) * max(1, oldest)) == 0: + generation = 2 + elif self._young % max(1, middle) == 0: + generation = 1 + gc.collect(generation) + self.collections[generation] += 1 + return generation + + def stop(self) -> None: + """Stop collecting here and switch automatic collection back on if it was on; idempotent.""" + if self._stopped: + return + self._stopped = True + self._timer.stop() + if self._was_enabled: + gc.enable() + + +__all__ = ["GuiThreadCollector"] diff --git a/test/unit_test/headless/test_gui_thread_gc.py b/test/unit_test/headless/test_gui_thread_gc.py new file mode 100644 index 000000000..36ec9c1d4 --- /dev/null +++ b/test/unit_test/headless/test_gui_thread_gc.py @@ -0,0 +1,160 @@ +"""The GUI collects cyclic garbage on its own thread, from a timer, while automatic collection is off (offscreen Qt).""" +import gc +import os +import sys +import threading +import weakref + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +pytest.importorskip("PySide6.QtWidgets", exc_type=ImportError) + +from PySide6.QtWidgets import QApplication # noqa: E402 + +from headless._qt_settle import pump_until # noqa: E402 +from je_auto_control.gui import _gui_thread_gc # noqa: E402 +from je_auto_control.gui._gui_thread_gc import GuiThreadCollector # noqa: E402 + + +class _Node: + """A cycle member the collector has to free, observable through a weak reference.""" + + def __init__(self) -> None: + self.me = self + + +@pytest.fixture +def qapp(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def collector_state(): + """Each test sets the collector state it needs; the one found is restored afterwards.""" + enabled, threshold = gc.isenabled(), gc.get_threshold() + made = [] + yield made + for collector in made: + collector.stop() + collector.deleteLater() + gc.set_threshold(*threshold) + (gc.enable if enabled else gc.disable)() + + +def _make(made, *args, **kwargs): + collector = GuiThreadCollector(*args, **kwargs) + made.append(collector) + return collector + + +@pytest.mark.parametrize("was_enabled", [True, False]) +def test_automatic_collection_is_off_while_it_runs_and_given_back_as_found(qapp, collector_state, was_enabled): + (gc.enable if was_enabled else gc.disable)() + collector = _make(collector_state, qapp) + assert not gc.isenabled() + collector.stop() + assert gc.isenabled() is was_enabled + collector.stop() # idempotent: a second stop changes nothing + assert gc.isenabled() is was_enabled + + +def test_nothing_is_collected_below_the_first_threshold(qapp, collector_state, monkeypatch): + collector = _make(collector_state, qapp) + calls = [] + monkeypatch.setattr(gc, "collect", lambda generation=2: calls.append(generation) or 0) + monkeypatch.setattr(gc, "get_count", lambda: (5, 0, 0)) + assert collector.check() is None + assert calls == [] + + +def test_generations_follow_the_interpreters_thresholds(qapp, collector_state, monkeypatch): + gc.set_threshold(700, 10, 10) + collector = _make(collector_state, qapp) + calls = [] + monkeypatch.setattr(gc, "collect", lambda generation=2: calls.append(generation) or 0) + monkeypatch.setattr(gc, "get_count", lambda: (701, 0, 0)) + for _ in range(100): + collector.check() + assert calls.count(2) == 1 and calls[99] == 2 # every 10 * 10 young collections + assert calls.count(1) == 9 # every 10th, the 100th being full + assert calls.count(0) == 90 + assert collector.collections == [90, 9, 1] + + +def test_a_first_threshold_of_zero_stays_switched_off(qapp, collector_state, monkeypatch): + gc.set_threshold(0) + collector = _make(collector_state, qapp) + monkeypatch.setattr(gc, "get_count", lambda: (10 ** 6, 0, 0)) + assert collector.check() is None + + +def test_cyclic_garbage_is_freed_by_the_timer_on_the_gui_thread(qapp, collector_state, monkeypatch): + gc.set_threshold(100, 10, 10) + threads = [] + real_collect = gc.collect + + def collect(generation=2): + threads.append(threading.get_ident()) + return real_collect(generation) + + monkeypatch.setattr(gc, "collect", collect) + collector = _make(collector_state, qapp, interval_ms=5) + node = _Node() + freed = weakref.ref(node) + del node + junk = [[index] for index in range(500)] # past the first threshold + del junk + assert pump_until(lambda: freed() is None, timeout=5.0) + assert collector.collections[0] >= 1 + assert set(threads) == {threading.get_ident()} + + +def test_start_autocontrol_gui_installs_it_and_stops_it_on_quit(qapp, collector_state, monkeypatch): + from PySide6 import QtWidgets + + from je_auto_control.gui import main_window, theme + import je_auto_control.gui as gui_package + + installed = [] + + class _Recorded(GuiThreadCollector): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + installed.append(self) + collector_state.append(self) + + class _Window: + def show(self): + return None + + monkeypatch.setattr(_gui_thread_gc, "GuiThreadCollector", _Recorded) + class _ExistingApp: + """``QApplication(argv)`` hands back the test's application; ``instance()`` still works.""" + + def __new__(cls, _argv): + return qapp + + instance = staticmethod(lambda: qapp) + + monkeypatch.setattr(QtWidgets, "QApplication", _ExistingApp) + monkeypatch.setattr(main_window, "AutoControlGUIUI", _Window) + monkeypatch.setattr(theme, "prepare_application", lambda app: None) + monkeypatch.setattr(qapp, "exec", lambda: 0) + gc.enable() + with pytest.raises(SystemExit) as exited: + gui_package.start_autocontrol_gui() + assert exited.value.code == 0 + assert len(installed) == 1 and installed[0].parent() is qapp + assert not gc.isenabled() + qapp.aboutToQuit.emit() + assert gc.isenabled() + qapp.aboutToQuit.disconnect(installed[0].stop) + + +def test_the_top_level_package_still_imports_no_qt(): + import subprocess + code = "import sys, je_auto_control; print(any('PySide6' in m for m in sys.modules))" + done = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, # nosec B603 # reason: fixed argv + timeout=120, check=False) + assert done.stdout.strip() == "False", done.stdout + done.stderr From 30e10d054c9a30f838e716eb8541f4baf7b3c576 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 16:04:04 +0800 Subject: [PATCH 151/161] End an in-flight HTTP request when its run is stopped or cancelled perform_call checked only the cancellation scope, and only before sending and after the reply, so a stopped script still sent its request and a stop waited out the reply or the 30-second timeout. Inside a run or scope the request now runs on a helper thread whose sockets a stop shuts, and the run's stop token is checked too; outside a run nothing changes. --- CHANGELOG.md | 8 + Progress.md | 2 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 10 +- docs/updates/2026-11-b.md | 23 +++ docs/updates/README.md | 1 + .../utils/http_client/http_client.py | 145 +++++++++++++++- test/unit_test/headless/test_http_stop.py | 157 ++++++++++++++++++ 10 files changed, 335 insertions(+), 17 deletions(-) create mode 100644 test/unit_test/headless/test_http_stop.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 96d3ac0d0..d1ab25d62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- HTTP requests through the shared client (`AC_http_request`, MCP `ac_http_request`, assertions, + webhooks, config sync, signaling): inside a stoppable run or a cancellation scope, nothing is sent once + the run is stopped, and a stop, `ac_stop_execution` or `notifications/cancelled` while the request is out + shuts its sockets within about 0.1 s and ends the call (`ExecutionStopped`, `CancelledError`, or + `-32800` for an MCP client cancel), instead of waiting for the reply or the timeout. A TCP connect or + name lookup already in progress still runs to its timeout, and its result is discarded. Outside a run + the request is unchanged. + - GUI (`start_autocontrol_gui()`): while the window is open, automatic cyclic garbage collection is switched off and a GUI-thread timer collects instead (`gui/_gui_thread_gc.py`), at the interpreter's thresholds; it is switched back on when the app quits. Worker threads no longer collect Qt objects, diff --git a/Progress.md b/Progress.md index 6c40880f5..55c58d5dd 100644 --- a/Progress.md +++ b/Progress.md @@ -108,7 +108,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR、HTTP 請求;擷取輸出的 shell 指令已可停止,U-20261115-23)、單一手勢內的節奏 sleep; +- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR;擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求已可停止,U-20261116-08,但正在進行的 TCP 連線/DNS 查詢仍只能等到逾時)、單一手勢內的節奏 sleep; 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/README.md b/README.md index f649044c5..8d3f34c58 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Host-requested file sends remain owned until their sender worker exits, includin MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. -An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first, except a captured shell command (`ac_shell`, `AC_shell_to_var`): its process tree is killed and the call ends. +An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first, except a captured shell command (`ac_shell`, `AC_shell_to_var`), whose process tree is killed, and an HTTP request (`AC_http_request`, `ac_http_request`, and the other clients built on the shared HTTP client), whose sockets are shut; either way the call ends. REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. USB enumeration/events, retained inspector statistics and process metrics also require `read_data`, as do `AC_list_usb_devices`, `AC_usb_recent_events`, `AC_inspector_recent` and `AC_inspector_summary`. Dashboard panels report missing capabilities independently and clear stale rows. A successful session refresh also clears its previous error status. Unlisted executor-command authorization remains a separate audit scope. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 7e3d98e6c..4f837f7d3 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -81,7 +81,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStop MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 -MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完;只有捕获输出的 shell 指令(`ac_shell`、`AC_shell_to_var`)例外:它的进程树会被结束,调用随即结束。 +MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完;例外的是捕获输出的 shell 指令(`ac_shell`、`AC_shell_to_var`),它的进程树会被结束;以及 HTTP 请求(`AC_http_request`、`ac_http_request` 与其他走共用 HTTP client 的调用),它的 socket 会被关闭;两者的调用都随即结束。 REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。USB 枚举/事件、保留的 inspector 统计与进程 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同样检查此权限。Dashboard 各面板分别显示缺少的权限并清除旧数据;session 刷新成功后也会清除先前的错误状态。未列入权限表的 executor 命令仍属于另一项审查范围。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index aac6b5559..3ee1ffec4 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -81,7 +81,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStop MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 -MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完;只有擷取輸出的 shell 指令(`ac_shell`、`AC_shell_to_var`)例外:它的行程樹會被結束,呼叫隨即結束。 +MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完;例外的是擷取輸出的 shell 指令(`ac_shell`、`AC_shell_to_var`),它的行程樹會被結束;以及 HTTP 請求(`AC_http_request`、`ac_http_request` 與其他走共用 HTTP client 的呼叫),它的 socket 會被關閉;兩者的呼叫都隨即結束。 REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。USB 列舉/事件、保留的 inspector 統計與程序 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同樣檢查此權限。Dashboard 各面板分別顯示缺少的權限並清除舊資料;session 重新整理成功後也會清除先前的錯誤狀態。未列入權限表格的 executor 指令仍屬另一項審查範圍。 diff --git a/architecture_explore.md b/architecture_explore.md index 69d133832..2b4dc83d1 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,547 | -| 程式碼總行數 | 238,693 | +| 程式碼總行數 | 238,822 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,593 行。 +> 24 個套件、約 7,722 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -572,7 +572,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/email_send/` | 118 | SMTP 寄信(email 觸發器的發送端搭檔) | | `utils/events/` | 106 | 對外 CloudEvents 發送(執行生命週期事件) | | `utils/http_cassette/` | 200 | 錄製/重播 HTTP 互動,做離線決定性 API 測試 | -| `utils/http_client/` | 276 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | +| `utils/http_client/` | 405 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | | `utils/http_conditional/` | 148 | 條件式 HTTP 請求與快取驗證器 | | `utils/http_content/` | 158 | HTTP 內容協商與回應解壓縮 | | `utils/http_problem/` | 122 | RFC 9457 problem+json 解析 | @@ -1571,8 +1571,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,194 | -| **總計** | **1,535** | **237,948** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,323 | +| **總計** | **1,535** | **238,077** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 19ee081f0..fc30ebd5a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -989,3 +989,26 @@ - **Docs:** README, both translations and both installation guides (`docs/source/{Eng,Zh}/doc/installation/installation_doc.rst`) describe the behaviour under the GUI launch instructions. There is a CHANGELOG entry, and `architecture_explore.md` has a row for the new module (re-measured). - **Files:** `je_auto_control/gui/_gui_thread_gc.py`, `je_auto_control/gui/__init__.py`, `test/unit_test/headless/test_gui_thread_gc.py`, `README.md`, `README/README_zh-TW.md`, `README/README_zh-CN.md`, the two installation guides, `CHANGELOG.md`, `architecture_explore.md`, `Progress.md`. - **Open items:** the upstream report and removing the workarounds once a fixed 6.12.x ships, in `Progress.md`. + +## U-20261116-08 · 2026-11-16 · A stop or cancel ends an HTTP request that is already out · #done #executor #mcp #http + +- **What.** This is part of the `Progress.md` item "stop 還叫不醒的" (GUI:留下的缺口). Before this change, `perform_call`, the one path the package's HTTP clients take, checked only the cancellation scope, before sending and after the reply. It never checked the executor's stop token, so a stopped script sent the request anyway. Once a request was out, a stop waited for the reply or the full timeout (30 s by default). +- **Change** (`utils/http_client/http_client.py`). + - **Stop before sending.** `perform_call` checks the cancellation scope and the run's stop (`run_control.checkpoint`) before sending and after the reply. + - **Waiting in slices.** Inside a stoppable run or a cancellation scope, the transport runs on a helper thread under the caller's copied context. The caller waits in 0.1 s slices and checks both after each one. + - **On a stop or cancel.** The sockets the request opened are shut and the stop's own error is raised (`ExecutionStopped` / `CancelledError`). The thread gets 1 s to notice. + - **Recording connections.** The module's two openers now carry `_RecordingHTTPHandler` / `_RecordingHTTPSHandler`. Their `do_open` wraps the connection class only while a stoppable request is active on that thread (a thread-local), so redirects are covered. A connection that finishes connecting after the stop is shut before it sends. + - **Unchanged.** Outside a run, the request stays one call on the caller's thread. `urllib_transport`'s signature is unchanged, so injected transports keep working. +- **Not covered:** a TCP connect or name lookup already in progress cannot be interrupted. It ends at the call's timeout and its result is discarded. +- **Tests.** + - New `test_http_stop.py` (7 cases, real sockets on 127.0.0.1): + - a stop, and separately a cancellation, ends a request whose server never answers within 5 s, and the server sees the hang-up; + - a stopped run opens no connection; + - inside a run a reply still arrives whole and the timeout still applies; + - outside a run the transport stays on the calling thread; + - a stopped `AC_http_request` ends the script before the next action. + - The three stop, cancel and send-nothing cases fail against the previous code. + - Every test module that touches the HTTP client (26), plus `test_mcp_call_run.py` and the complexity, broad-except and file-length gates: 432 passed, 17 skipped. + - `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean. +- **Files:** `je_auto_control/utils/http_client/http_client.py`, `test/unit_test/headless/test_http_stop.py`, `README.md` with both translations (line 84), `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). +- **Open items:** in `Progress.md`, single backend calls (image search, OCR) and the connect / DNS phase of a request. diff --git a/docs/updates/README.md b/docs/updates/README.md index 727b742d4..272a8dccb 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-08 | 2026-11-16 | A stop or cancel ends an HTTP request that is already out | #done #executor #mcp #http | [2026-11-b](2026-11-b.md) | | U-20261116-07 | 2026-11-16 | The GUI collects cyclic garbage on its own thread only | #gui #pyside6 #done | [2026-11-b](2026-11-b.md) | | U-20261116-06 | 2026-11-16 | Pause automatic GC per Qt module instead of collecting after every test | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | | U-20261116-05 | 2026-11-16 | Collect after every Qt test, not only per module, on the GUI thread | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/http_client/http_client.py b/je_auto_control/utils/http_client/http_client.py index 2b6c38ad6..86470a46b 100644 --- a/je_auto_control/utils/http_client/http_client.py +++ b/je_auto_control/utils/http_client/http_client.py @@ -8,8 +8,11 @@ ``PySide6`` and only allows http/https schemes (Bandit B310). """ import base64 +import contextvars import http.client import json +import socket +import threading import urllib.error import urllib.parse import urllib.request @@ -188,8 +191,92 @@ def _origin(url: str) -> "tuple[str, str]": return parts.scheme.lower(), (parts.netloc or "").lower() -_OPENER = urllib.request.build_opener(_CheckedRedirectHandler) -_NO_REDIRECT_OPENER = urllib.request.build_opener(_RefusingRedirectHandler) +# How often a stoppable request looks at its stop and cancellation, and how long +# a stop waits for the request's thread to notice its sockets were shut. +_STOP_POLL_SECONDS = 0.1 +_ABORT_WAIT_SECONDS = 1.0 +_recording = threading.local() + + +class _Connections: + """The connections one stoppable request opened, so a stop can shut their sockets. + + Shutting the socket ends a ``recv`` that is waiting for the reply at once; + a connection that finishes connecting after the stop is shut before it + sends anything. A connect (or name lookup) already in progress cannot be + interrupted: it ends at the call's timeout and its result is discarded. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self._opened: list[Any] = [] + self._aborted = False + + def wrap(self, http_class: Any) -> Any: + """A stand-in for ``http_class`` that records every connection it makes.""" + def make(*args: Any, **kwargs: Any) -> Any: + connection = http_class(*args, **kwargs) + connect = connection.connect + + def checked_connect() -> None: + connect() + if self._is_aborted(): + _shut(connection) + raise urllib.error.URLError("request stopped") + + connection.connect = checked_connect + with self._lock: + if self._aborted: + raise urllib.error.URLError("request stopped") + self._opened.append(connection) + return connection + return make + + def _is_aborted(self) -> bool: + with self._lock: + return self._aborted + + def abort(self) -> None: + """Shut every socket this request opened; later connections are refused.""" + with self._lock: + self._aborted = True + opened = list(self._opened) + for connection in opened: + _shut(connection) + + +def _shut(connection: Any) -> None: + sock = getattr(connection, "sock", None) + if sock is None: + return + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + return # already closed or never connected: nothing left to wake + + +def _recorded(http_class: Any) -> Any: + connections = getattr(_recording, "active", None) + return http_class if connections is None else connections.wrap(http_class) + + +class _RecordingHTTPHandler(urllib.request.HTTPHandler): + """``HTTPHandler`` whose connections a stoppable request on this thread can shut.""" + + def do_open(self, http_class: Any, req: Any, **kwargs: Any) -> Any: # noqa: D102 + return super().do_open(_recorded(http_class), req, **kwargs) + + +class _RecordingHTTPSHandler(urllib.request.HTTPSHandler): + """``HTTPSHandler`` whose connections a stoppable request on this thread can shut.""" + + def do_open(self, http_class: Any, req: Any, **kwargs: Any) -> Any: # noqa: D102 + return super().do_open(_recorded(http_class), req, **kwargs) + + +_OPENER = urllib.request.build_opener(_CheckedRedirectHandler, _RecordingHTTPHandler, _RecordingHTTPSHandler) +_NO_REDIRECT_OPENER = urllib.request.build_opener( + _RefusingRedirectHandler, _RecordingHTTPHandler, _RecordingHTTPSHandler) def urllib_transport(call: Mapping[str, Any]) -> Dict[str, Any]: @@ -260,11 +347,53 @@ def perform_call(call: Mapping[str, Any]) -> Dict[str, Any]: instead of following it. """ from je_auto_control.utils.egress.egress_policy import get_egress_policy + from je_auto_control.utils.exception.cancellation import current_cancellation_token + from je_auto_control.utils.executor.run_control import current_stop_token get_egress_policy().check(call["url"]) # allow-all unless an operator locked it down - # Inside a cancelled scope (a GUI task stopped or past its deadline) the - # request is not sent, and a reply that arrives after the cancellation is - # not handed on; the request itself cannot be interrupted once it is out. - cancellation_checkpoint() - response = urllib_transport(call) - cancellation_checkpoint() + # Inside a stoppable run or a cancellation scope (a script, an MCP call, a + # GUI task) nothing is sent once it is stopped, a stop while the request is + # out shuts its sockets and ends the call, and a reply that arrives after + # the stop is not handed on. Outside both the call is one plain request. + _checkpoints() + if current_stop_token() is None and current_cancellation_token() is None: + response = urllib_transport(call) + else: + response = _stoppable_transport(call) + _checkpoints() return response + + +def _checkpoints() -> None: + from je_auto_control.utils.executor.run_control import checkpoint + cancellation_checkpoint() + checkpoint() + + +def _stoppable_transport(call: Mapping[str, Any]) -> Dict[str, Any]: + """``urllib_transport`` on a helper thread, waited on in slices that look at the stop.""" + connections = _Connections() + outcome: Dict[str, Any] = {} + done = threading.Event() + context = contextvars.copy_context() + + def run() -> None: + _recording.active = connections + try: + outcome["response"] = context.run(urllib_transport, call) + except BaseException as error: # reason: handed to the waiting caller, which raises it + outcome["error"] = error + finally: + _recording.active = None + done.set() + + threading.Thread(target=run, name="http-request", daemon=True).start() + while not done.wait(_STOP_POLL_SECONDS): + try: + _checkpoints() + except BaseException: + connections.abort() + done.wait(_ABORT_WAIT_SECONDS) + raise + if "error" in outcome: + raise outcome["error"] + return outcome["response"] diff --git a/test/unit_test/headless/test_http_stop.py b/test/unit_test/headless/test_http_stop.py new file mode 100644 index 000000000..234005799 --- /dev/null +++ b/test/unit_test/headless/test_http_stop.py @@ -0,0 +1,157 @@ +"""A stop or a cancellation ends an HTTP request that is already out, instead of waiting for its timeout. + +Real sockets on 127.0.0.1: one server reads the request and never answers (and +notes when the client hangs up), one answers at once. +""" +import socket +import threading +import time +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.executor.run_control import ExecutionStopped, StopToken, stoppable_run +from je_auto_control.utils.http_client import http_client + +_BODY = b'{"ok": true}' +_REPLY = (b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n" + b"Content-Length: " + str(len(_BODY)).encode() + b"\r\n\r\n" + _BODY) + + +class _Server: + """One listening socket on 127.0.0.1 that serves each connection with ``answer``.""" + + def __init__(self, answer: bool) -> None: + self._answer = answer + self._listener = socket.socket() + self._listener.bind(("127.0.0.1", 0)) + self._listener.listen(8) + self._listener.settimeout(0.2) + self.port = self._listener.getsockname()[1] + self.connections = 0 + self.requested = threading.Event() + self.hung_up = threading.Event() + self._closing = threading.Event() + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.port}/slow" # NOSONAR python:S5332 # reason: local test server + + def _serve(self) -> None: + while not self._closing.is_set(): + try: + client, _address = self._listener.accept() + except OSError: + continue + self.connections += 1 + with client: + client.settimeout(10) + if client.recv(65536): + self.requested.set() + if self._answer: + client.sendall(_REPLY) + continue + try: + if client.recv(1) == b"": # the client shut its side + self.hung_up.set() + except OSError: + self.hung_up.set() + + def close(self) -> None: + self._closing.set() + self._thread.join(timeout=5) + self._listener.close() + + +@pytest.fixture +def silent(): + server = _Server(answer=False) + yield server + server.close() + + +@pytest.fixture +def answering(): + server = _Server(answer=True) + yield server + server.close() + + +def _later(action, delay: float = 0.3) -> None: + timer = threading.Timer(delay, action) + timer.daemon = True + timer.start() + + +def _call(url: str, timeout: float = 30.0): + return http_client.perform_call(http_client.build_call(url, "GET", timeout=timeout)) + + +def test_a_stop_ends_a_request_waiting_for_its_reply(silent): + token = StopToken("http-stop") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + _call(silent.url) + assert time.monotonic() - started < 5 # not the 30 s timeout + assert silent.requested.is_set() + assert silent.hung_up.wait(5), "the request's socket was left open" + + +def test_a_cancellation_ends_a_request_waiting_for_its_reply(silent): + token = CancellationToken(task_id=41) + _later(token.cancel) + started = time.monotonic() + with cancellation_scope(token), pytest.raises(CancelledError): + _call(silent.url) + assert time.monotonic() - started < 5 + assert silent.hung_up.wait(5) + + +def test_a_stopped_run_sends_nothing(silent): + token = StopToken("http-stopped") + token.stop("before") + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + _call(silent.url) + time.sleep(0.3) + assert silent.connections == 0 + + +def test_inside_a_run_a_reply_still_arrives_whole(answering): + with stoppable_run(token=StopToken("http-answer")): + response = _call(answering.url) + assert response["status"] == 200 and response["json"] == {"ok": True} + + +def test_inside_a_run_the_timeout_still_applies(silent): + with stoppable_run(token=StopToken("http-timeout")), pytest.raises(OSError): + _call(silent.url, timeout=0.5) + + +def test_outside_any_run_the_request_stays_on_the_calling_thread(answering, monkeypatch): + seen = [] + real = http_client.urllib_transport + + def transport(call): + seen.append(threading.current_thread()) + return real(call) + + monkeypatch.setattr(http_client, "urllib_transport", transport) + assert _call(answering.url)["status"] == 200 + assert seen == [threading.current_thread()] + + +def test_a_stopped_ac_http_request_ends_the_script_promptly(silent): + from je_auto_control.utils.executor.action_executor import Executor + executor = Executor() + token = StopToken("http-script") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + executor.execute_action([["AC_http_request", {"url": silent.url, "timeout": 30}], + ["AC_set_var", {"name": "after", "value": 1}]]) + assert time.monotonic() - started < 10 + assert executor.variables.get("after") is None From 4f25aa5d91ec8c011278c4ee530870f6bf620219 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 18:17:17 +0800 Subject: [PATCH 152/161] Record that MCP roots from roots/list stay opt-in The maintainer confirmed the rule chosen during implementation: client- reported roots count only with JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT, since any HTTP caller can report them. --- Progress.md | 1 - docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Progress.md b/Progress.md index 55c58d5dd..c583e95b3 100644 --- a/Progress.md +++ b/Progress.md @@ -139,7 +139,6 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 仍管不到執行動作清單的工具、`ac_launch_process`/`ac_shell` 的 `argv`/`command`、 自由格式物件裡的路徑(`ac_run_suite` 的 `spec`、`ac_run_dag` 的 `definition`、`ac_assert_all` 的 `specs`)與沒標註的外掛工具。 檔案 symlink 的跳脫在這台機器上建不出來(只跑了目錄 junction);POSIX 的 `:` 分隔與 `~` 沒在 Linux/macOS 跑。 - `roots/list` 來的根目錄要另外開 `JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT` 才算數——這是實作時定的,請維護者確認。 - **USB passthrough 實機驗收**:仍須對真的舊版 host、WebRTC 通道與 USB 裝置驗證長時間 transfer、 裝置逾時、通道 ERROR、晚到回覆與重新連線。現有 fake channel/backend 測試不能代替這項驗收。 - **變數範圍**:free-threaded 原生執行緒繼承與同時存取範圍的行為尚未實測。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index fc30ebd5a..4056e6334 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1012,3 +1012,10 @@ - `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean. - **Files:** `je_auto_control/utils/http_client/http_client.py`, `test/unit_test/headless/test_http_stop.py`, `README.md` with both translations (line 84), `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). - **Open items:** in `Progress.md`, single backend calls (image search, OCR) and the connect / DNS phase of a request. + +## U-20261116-09 · 2026-11-16 · MCP roots from roots/list stay opt-in · #done #mcp #security #decision + +- **Decision (maintainer, 2026-11-16).** `Progress.md` had asked the maintainer to confirm a rule set during implementation. The rule: the directories an MCP client reports through `roots/list` count toward the path-root check only when `JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT` is on. The maintainer confirmed it stays opt-in. +- **Why.** Over HTTP any caller that can reach the server can report roots, so a client's own description of its workspace is not trusted by default. With the variable on, the check is enabled by itself, and until the client answers, every file argument is refused rather than let through. +- **Change:** none in code. The rule is already documented under `JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT` in `docs/source/{Eng,Zh}/doc/mcp_server/mcp_server_doc.rst`. The confirmation request is removed from `Progress.md`; the rest of that MCP path-root entry, which is about coverage gaps, stays. +- **Files:** `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 272a8dccb..522c46a74 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-09 | 2026-11-16 | MCP roots from roots/list stay opt-in | #done #mcp #security #decision | [2026-11-b](2026-11-b.md) | | U-20261116-08 | 2026-11-16 | A stop or cancel ends an HTTP request that is already out | #done #executor #mcp #http | [2026-11-b](2026-11-b.md) | | U-20261116-07 | 2026-11-16 | The GUI collects cyclic garbage on its own thread only | #gui #pyside6 #done | [2026-11-b](2026-11-b.md) | | U-20261116-06 | 2026-11-16 | Pause automatic GC per Qt module instead of collecting after every test | #incident #ci #test #gui | [2026-11-b](2026-11-b.md) | From 92b9b7b5764a205d39a000ad37ac20e3cac694f6 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 18:23:38 +0800 Subject: [PATCH 153/161] Wait for an HTTP request's TCP handshake in slices a stop can end A stopped request that was still connecting waited out its timeout. The recorded connections now open their socket with a non-blocking connect polled every 0.1 s against the stop; only a name lookup in progress still runs on. --- CHANGELOG.md | 6 +- Progress.md | 2 +- architecture_explore.md | 10 +-- docs/updates/2026-11-b.md | 17 +++++ docs/updates/README.md | 1 + .../utils/http_client/http_client.py | 72 +++++++++++++++++-- test/unit_test/headless/test_http_stop.py | 67 +++++++++++++++++ 7 files changed, 162 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1ab25d62..ac5f28a7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ webhooks, config sync, signaling): inside a stoppable run or a cancellation scope, nothing is sent once the run is stopped, and a stop, `ac_stop_execution` or `notifications/cancelled` while the request is out shuts its sockets within about 0.1 s and ends the call (`ExecutionStopped`, `CancelledError`, or - `-32800` for an MCP client cancel), instead of waiting for the reply or the timeout. A TCP connect or - name lookup already in progress still runs to its timeout, and its result is discarded. Outside a run - the request is unchanged. + `-32800` for an MCP client cancel), instead of waiting for the reply or the timeout. The TCP handshake + is waited for in the same 0.1 s slices; only a name lookup already in progress still runs on, and its + result is discarded. Outside a run the request is unchanged. - GUI (`start_autocontrol_gui()`): while the window is open, automatic cyclic garbage collection is switched off and a GUI-thread timer collects instead (`gui/_gui_thread_gc.py`), at the interpreter's diff --git a/Progress.md b/Progress.md index c583e95b3..c9ec565af 100644 --- a/Progress.md +++ b/Progress.md @@ -108,7 +108,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR;擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求已可停止,U-20261116-08,但正在進行的 TCP 連線/DNS 查詢仍只能等到逾時)、單一手勢內的節奏 sleep; +- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR;擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求已可停止,U-20261116-08/-10,連 TCP 交握也可中斷,只剩正在進行的 DNS 查詢不行)、單一手勢內的節奏 sleep; 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/architecture_explore.md b/architecture_explore.md index 2b4dc83d1..794a6ead3 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,547 | -| 程式碼總行數 | 238,822 | +| 程式碼總行數 | 238,886 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -562,7 +562,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,722 行。 +> 24 個套件、約 7,786 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -572,7 +572,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/email_send/` | 118 | SMTP 寄信(email 觸發器的發送端搭檔) | | `utils/events/` | 106 | 對外 CloudEvents 發送(執行生命週期事件) | | `utils/http_cassette/` | 200 | 錄製/重播 HTTP 互動,做離線決定性 API 測試 | -| `utils/http_client/` | 405 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | +| `utils/http_client/` | 469 | 零依賴 HTTP(S) 用戶端,供 action 步驟呼叫 API | | `utils/http_conditional/` | 148 | 條件式 HTTP 請求與快取驗證器 | | `utils/http_content/` | 158 | HTTP 內容協商與回應解壓縮 | | `utils/http_problem/` | 122 | RFC 9457 problem+json 解析 | @@ -1571,8 +1571,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,323 | -| **總計** | **1,535** | **238,077** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,387 | +| **總計** | **1,535** | **238,141** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 4056e6334..24da7fc3e 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1019,3 +1019,20 @@ - **Why.** Over HTTP any caller that can reach the server can report roots, so a client's own description of its workspace is not trusted by default. With the variable on, the check is enabled by itself, and until the client answers, every file argument is refused rather than let through. - **Change:** none in code. The rule is already documented under `JE_AUTOCONTROL_MCP_PATH_ROOTS_FROM_CLIENT` in `docs/source/{Eng,Zh}/doc/mcp_server/mcp_server_doc.rst`. The confirmation request is removed from `Progress.md`; the rest of that MCP path-root entry, which is about coverage gaps, stays. - **Files:** `Progress.md`. + +## U-20261116-10 · 2026-11-16 · A stop also ends an HTTP request that is still connecting · #done #http #executor + +- **What.** U-20261116-08 left the TCP handshake uninterruptible: a stop while a request was still connecting waited out the call's timeout. The maintainer chose to close that gap (2026-11-16). +- **Change** (`utils/http_client/http_client.py`). + - For a stoppable request, each recorded connection's `_create_connection`, the hook `http.client` opens its socket through, proxies included, is replaced by `_connect_in_slices`. + - `_connect_in_slices` resolves the address and starts a non-blocking `connect_ex` for each address in turn. It then waits for writability in 0.1 s slices (`_await_connect`), checking the request's stop flag every slice, up to the call's timeout. + - The connected socket goes back to blocking, with the call's timeout as its per-operation timeout. A connect error is raised as `OSError`, and the deadline as `TimeoutError`. + - `_wait_writable` (normally `select.select`) is a seam so a test can hold a handshake open without a black-holed address. +- **Still not interruptible:** a name lookup (`getaddrinfo`) already in progress. +- **Tests:** `test_http_stop.py` gains 3 cases, 10 in all: + - a stop ends the sliced connect of a socket that never finishes connecting within 2 s, and the socket is closed; + - such a connect still times out at its deadline; + - a real request held in the connect phase ends on a stop within 3 s and is never sent (it skips if a loopback connect completes at once; it did not here). + - The 26 HTTP-dependent modules, `test_mcp_call_run.py` and the complexity, broad-except and file-length gates: 435 passed, 17 skipped. + - `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean on the package. +- **Files:** `je_auto_control/utils/http_client/http_client.py`, `test/unit_test/headless/test_http_stop.py`, `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). diff --git a/docs/updates/README.md b/docs/updates/README.md index 522c46a74..765f1f1c0 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-10 | 2026-11-16 | A stop also ends an HTTP request that is still connecting | #done #http #executor | [2026-11-b](2026-11-b.md) | | U-20261116-09 | 2026-11-16 | MCP roots from roots/list stay opt-in | #done #mcp #security #decision | [2026-11-b](2026-11-b.md) | | U-20261116-08 | 2026-11-16 | A stop or cancel ends an HTTP request that is already out | #done #executor #mcp #http | [2026-11-b](2026-11-b.md) | | U-20261116-07 | 2026-11-16 | The GUI collects cyclic garbage on its own thread only | #gui #pyside6 #done | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/http_client/http_client.py b/je_auto_control/utils/http_client/http_client.py index 86470a46b..49b595b3d 100644 --- a/je_auto_control/utils/http_client/http_client.py +++ b/je_auto_control/utils/http_client/http_client.py @@ -9,10 +9,15 @@ """ import base64 import contextvars +import errno +import functools import http.client import json +import os +import select import socket import threading +import time import urllib.error import urllib.parse import urllib.request @@ -201,10 +206,12 @@ def _origin(url: str) -> "tuple[str, str]": class _Connections: """The connections one stoppable request opened, so a stop can shut their sockets. - Shutting the socket ends a ``recv`` that is waiting for the reply at once; - a connection that finishes connecting after the stop is shut before it - sends anything. A connect (or name lookup) already in progress cannot be - interrupted: it ends at the call's timeout and its result is discarded. + Shutting the socket ends a ``recv`` that is waiting for the reply at once, + and the TCP handshake is waited for in slices that look at the stop + (:func:`_connect_in_slices`); a connection that finishes connecting after + the stop is shut before it sends anything. A name lookup already in + progress cannot be interrupted: it ends on its own and its result is + discarded. """ def __init__(self) -> None: @@ -225,6 +232,8 @@ def checked_connect() -> None: raise urllib.error.URLError("request stopped") connection.connect = checked_connect + # http.client opens its socket through this attribute (proxies included). + connection._create_connection = functools.partial(_connect_in_slices, aborted=self._is_aborted) with self._lock: if self._aborted: raise urllib.error.URLError("request stopped") @@ -245,6 +254,61 @@ def abort(self) -> None: _shut(connection) +# A non-blocking connect that has not finished yet reports one of these. +_CONNECTING = frozenset({0, errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY, 10035}) # 10035: WSAEWOULDBLOCK +# The readiness wait; a seam so a test can hold a connect open without a black-holed address. +_wait_writable = select.select + + +def _connect_in_slices(address: Any, timeout: Any = None, source_address: Any = None, *, + aborted: Any, make_socket: Any = socket.socket) -> socket.socket: + """``socket.create_connection`` whose wait for the handshake looks at ``aborted`` every slice. + + The name lookup (``getaddrinfo``) still blocks. Each address is tried in + turn, as ``create_connection`` does; the connected socket is handed back + blocking, with ``timeout`` as its per-operation timeout again. + """ + host, port = address[0], address[1] + limit = timeout if isinstance(timeout, (int, float)) else socket.getdefaulttimeout() + deadline = None if limit is None else time.monotonic() + limit + failure: Optional[OSError] = None + for family, kind, proto, _name, target in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): + sock = make_socket(family, kind, proto) + try: + if source_address: + sock.bind(source_address) + sock.setblocking(False) + code = sock.connect_ex(target) + if code not in _CONNECTING: + raise OSError(code, os.strerror(code)) + if code != 0: + _await_connect(sock, deadline, aborted) + sock.settimeout(limit) + return sock + except urllib.error.URLError: + sock.close() + raise + except OSError as error: + sock.close() + failure = error + raise failure if failure is not None else OSError(f"no address for {host!r}") + + +def _await_connect(sock: Any, deadline: Optional[float], aborted: Any) -> None: + while True: + if aborted(): + raise urllib.error.URLError("request stopped") + remaining = _STOP_POLL_SECONDS if deadline is None else min(_STOP_POLL_SECONDS, deadline - time.monotonic()) + if remaining <= 0: + raise TimeoutError("timed out") + _readable, writable, failed = _wait_writable([], [sock], [sock], remaining) + if writable or failed: + code = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) + if code: + raise OSError(code, os.strerror(code)) + return + + def _shut(connection: Any) -> None: sock = getattr(connection, "sock", None) if sock is None: diff --git a/test/unit_test/headless/test_http_stop.py b/test/unit_test/headless/test_http_stop.py index 234005799..a354f085e 100644 --- a/test/unit_test/headless/test_http_stop.py +++ b/test/unit_test/headless/test_http_stop.py @@ -3,9 +3,12 @@ Real sockets on 127.0.0.1: one server reads the request and never answers (and notes when the client hangs up), one answers at once. """ +import errno import socket +import sys import threading import time +import urllib.error from concurrent.futures import CancelledError import pytest @@ -155,3 +158,67 @@ def test_a_stopped_ac_http_request_ends_the_script_promptly(silent): ["AC_set_var", {"name": "after", "value": 1}]]) assert time.monotonic() - started < 10 assert executor.variables.get("after") is None + + +class _PendingSocket: + """A socket whose non-blocking connect never completes.""" + + closed = False + + def __init__(self, *args) -> None: + self.timeout = "unset" + + def setblocking(self, flag) -> None: + return None + + def connect_ex(self, target) -> int: + return 10035 if sys.platform == "win32" else errno.EINPROGRESS + + def settimeout(self, value) -> None: + self.timeout = value + + def close(self) -> None: + _PendingSocket.closed = True + + +def _never_ready(read, write, error, timeout): + time.sleep(timeout) + return [], [], [] + + +def test_a_stop_ends_a_connect_that_has_not_finished(monkeypatch): + monkeypatch.setattr(http_client, "_wait_writable", _never_ready) + stop = threading.Event() + _later(stop.set) + started = time.monotonic() + with pytest.raises(urllib.error.URLError, match="request stopped"): + http_client._connect_in_slices(("127.0.0.1", 9), 30, aborted=stop.is_set, make_socket=_PendingSocket) + assert time.monotonic() - started < 2 + assert _PendingSocket.closed + + +def test_a_connect_that_never_finishes_still_times_out(monkeypatch): + monkeypatch.setattr(http_client, "_wait_writable", _never_ready) + started = time.monotonic() + with pytest.raises(TimeoutError): + http_client._connect_in_slices(("127.0.0.1", 9), 0.4, aborted=lambda: False, make_socket=_PendingSocket) + assert 0.3 < time.monotonic() - started < 2 + + +def test_a_stop_ends_a_request_still_connecting_and_sends_nothing(silent, monkeypatch): + waits = [] + + def held(read, write, error, timeout): + waits.append(timeout) + return _never_ready(read, write, error, timeout) + + monkeypatch.setattr(http_client, "_wait_writable", held) + token = StopToken("http-connecting") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + _call(silent.url) + if not waits: + pytest.skip("this loopback connect completed at once, so there was no handshake to wait on") + assert time.monotonic() - started < 3 + assert not silent.requested.is_set(), "the request was sent after the stop" From c89f3ae19eb05fcf1cbb14a6af0f0307091f22c5 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 18:31:28 +0800 Subject: [PATCH 154/161] Stop waiting for an image search or OCR pass when a run is stopped One matchTemplate or OCR pass is a single native call a stop could not reach. Inside a stoppable run or cancellation scope it now runs on a helper thread through run_control.stoppable_call, so a stop ends the call within 0.1 s; the pass itself finishes in the background and is discarded. --- CHANGELOG.md | 6 + Progress.md | 2 +- README.md | 2 +- README/README_zh-CN.md | 2 +- README/README_zh-TW.md | 2 +- architecture_explore.md | 22 +-- docs/updates/2026-11-b.md | 22 +++ docs/updates/README.md | 1 + .../utils/cv2_utils/template_detection.py | 4 +- je_auto_control/utils/executor/run_control.py | 43 +++++- je_auto_control/utils/ocr/ocr_engine.py | 6 +- .../unit_test/headless/test_stoppable_call.py | 133 ++++++++++++++++++ 12 files changed, 225 insertions(+), 20 deletions(-) create mode 100644 test/unit_test/headless/test_stoppable_call.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ac5f28a7b..aded17e75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +- Image search and OCR (`find_image` and everything on `cv2_utils.template_detection`, `find_text_matches`, + `read_text_in_region` and the OCR commands built on them): inside a stoppable run or a cancellation scope + the single native pass runs on a helper thread (`run_control.stoppable_call`), and a stop or cancel ends + the call within about 0.1 s instead of waiting for the pass. The pass itself cannot be interrupted: it + finishes in the background and its result is discarded. Outside a run nothing changes. + - HTTP requests through the shared client (`AC_http_request`, MCP `ac_http_request`, assertions, webhooks, config sync, signaling): inside a stoppable run or a cancellation scope, nothing is sent once the run is stopped, and a stop, `ac_stop_execution` or `notifications/cancelled` while the request is out diff --git a/Progress.md b/Progress.md index c9ec565af..3b10a6a96 100644 --- a/Progress.md +++ b/Progress.md @@ -108,7 +108,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令(一次影像搜尋、OCR;擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求已可停止,U-20261116-08/-10,連 TCP 交握也可中斷,只剩正在進行的 DNS 查詢不行)、單一手勢內的節奏 sleep; +- **stop 還叫不醒的**:已經進到後端的單一指令只剩其他未接合的原生呼叫(擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求連 TCP 交握都可中斷,只剩正在進行的 DNS 查詢不行,U-20261116-08/-10;`template_detection` 與 OCR 引擎的單次原生運算改由 `stoppable_call` 不再等待,但運算本身在背景跑完,U-20261116-11;`visual_match`、`color_match`、`edge_match`、`rotated_match`、自愈的 `frame_locators` 等其他比對路徑尚未接合)、單一手勢內的節奏 sleep; 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/README.md b/README.md index 8d3f34c58..ba4e7f7c3 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Host-requested file sends remain owned until their sender worker exits, includin MCP read-only hints do not grant viewer access. Reviewed live-screen and caller-data tools use `read_screen`; stored files, device data and unknown tools require `read_data`. Aliases share canonical policy and stronger overrides take precedence. Optional image sources, environment-backed config fields and file open plans require `read_data`. Anchor locators permit live accessibility/OCR; image templates require `read_data` and VLM requests require `drive_input`. Read-only invocation rejects capture artifacts and VLM branches, and its catalogue excludes caller-selected ADB executables. MCP CI annotations return formatted lines without writing to stdout. Unreviewed plugin and WebRunner initialization tools are omitted from read-only catalogues and require dependency-specific review. -An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first, except a captured shell command (`ac_shell`, `AC_shell_to_var`), whose process tree is killed, and an HTTP request (`AC_http_request`, `ac_http_request`, and the other clients built on the shared HTTP client), whose sockets are shut; either way the call ends. +An MCP `tools/call` runs as a stoppable run listed as `mcp-…`. `notifications/cancelled` stops it: an action list from `ac_execute_actions` halts before its next action, and `ac_wait_for_image` / `ac_wait_for_pixel` wake mid-poll; the call is answered with `-32800`. `ac_stop_execution` and other stop requests end it the same way, reported as a tool error. A command already inside a backend still finishes first, except a captured shell command (`ac_shell`, `AC_shell_to_var`), whose process tree is killed, an HTTP request (`AC_http_request`, `ac_http_request`, and the other clients built on the shared HTTP client), whose sockets are shut, and a template-match or OCR pass, which the call stops waiting for (the native pass finishes in the background and its result is discarded); in each case the call ends. REST host-data reads now follow the matching MCP authority: jobs, remote sessions, USB passthrough status and loopback/remote inventories, and diagnostics require `read_data`. The corresponding registered status commands, `AC_probe_capabilities` and `AC_diagnose` enforce it before providers run. A read-only hint is not viewer access; operator/admin callers retain access. USB enumeration/events, retained inspector statistics and process metrics also require `read_data`, as do `AC_list_usb_devices`, `AC_usb_recent_events`, `AC_inspector_recent` and `AC_inspector_summary`. Dashboard panels report missing capabilities independently and clear stale rows. A successful session refresh also clears its previous error status. Unlisted executor-command authorization remains a separate audit scope. diff --git a/README/README_zh-CN.md b/README/README_zh-CN.md index 4f837f7d3..3b4b96679 100644 --- a/README/README_zh-CN.md +++ b/README/README_zh-CN.md @@ -81,7 +81,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成软件清理。`PeerStop MCP 只读标记不授予 viewer 访问权限。已审查的实时画面与调用者数据运算使用 `read_screen`;文件、设备数据及未知工具需要 `read_data`。别名共用标准名称的权限,较强的明确设置优先。提供图像来源、从环境变量读取配置字段或规划打开本地文件时需要 `read_data`。Anchor locator 的 accessibility/OCR 允许观察实时画面,图像模板需要 `read_data`,VLM 请求需要 `drive_input`。只读调用拒绝捕获产物及 VLM 分支,目录排除可自选 ADB 可执行文件的工具。MCP CI annotations 只返回格式化文本,不写入 stdout。未经审查的 plugin 与 WebRunner 初始化工具不列入只读目录,等待依赖版本的单独审查。 -MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完;例外的是捕获输出的 shell 指令(`ac_shell`、`AC_shell_to_var`),它的进程树会被结束;以及 HTTP 请求(`AC_http_request`、`ac_http_request` 与其他走共用 HTTP client 的调用),它的 socket 会被关闭;两者的调用都随即结束。 +MCP 的 `tools/call` 以可停止的执行进行,列为 `mcp-…`。`notifications/cancelled` 会停掉它:`ac_execute_actions` 的动作列表在下一个动作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在轮询中途醒来;该次调用以 `-32800` 回复。`ac_stop_execution` 与其他停止请求以同样方式结束它,报告为工具错误。已经进入后端的单个指令仍会先执行完;例外的是捕获输出的 shell 指令(`ac_shell`、`AC_shell_to_var`),它的进程树会被结束;HTTP 请求(`AC_http_request`、`ac_http_request` 与其他走共用 HTTP client 的调用),它的 socket 会被关闭;以及一次模板匹配或 OCR,调用不再等它(原生运算在后台跑完、结果丢弃);这些调用都随即结束。 REST 主机数据读取与对应 MCP 权限一致:调度、远程 session、USB passthrough 状态、loopback/remote 设备列表及诊断需要 `read_data`。对应已注册的状态命令、`AC_probe_capabilities` 与 `AC_diagnose` 会在运行提供者之前检查权限。只读标记不授予 viewer 访问权;operator/admin 仍可使用。USB 枚举/事件、保留的 inspector 统计与进程 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同样检查此权限。Dashboard 各面板分别显示缺少的权限并清除旧数据;session 刷新成功后也会清除先前的错误状态。未列入权限表的 executor 命令仍属于另一项审查范围。 diff --git a/README/README_zh-TW.md b/README/README_zh-TW.md index 3ee1ffec4..6930c3856 100644 --- a/README/README_zh-TW.md +++ b/README/README_zh-TW.md @@ -81,7 +81,7 @@ WebRTC host/viewer 的 `stop()` 最多等待三秒完成軟體清理。`PeerStop MCP 唯讀標記不授予 viewer 存取權。已審查的即時畫面與呼叫者資料運算使用 `read_screen`;檔案、裝置資料及未知工具需要 `read_data`。別名共用標準名稱的權限,較強的明確設定優先。提供影像來源、從環境變數讀取設定欄位或規劃開啟本機檔案時需要 `read_data`。Anchor locator 的 accessibility/OCR 允許觀測即時畫面,影像範本需要 `read_data`,VLM 請求需要 `drive_input`。唯讀呼叫拒絕擷取產物及 VLM 分支,目錄排除可自選 ADB 執行檔的工具。MCP CI annotations 只回傳格式化文字,不寫入 stdout。未審查的 plugin 與 WebRunner 初始化工具不列入唯讀目錄,等待相依版本的個別審查。 -MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完;例外的是擷取輸出的 shell 指令(`ac_shell`、`AC_shell_to_var`),它的行程樹會被結束;以及 HTTP 請求(`AC_http_request`、`ac_http_request` 與其他走共用 HTTP client 的呼叫),它的 socket 會被關閉;兩者的呼叫都隨即結束。 +MCP 的 `tools/call` 以可停止的執行進行,列為 `mcp-…`。`notifications/cancelled` 會停掉它:`ac_execute_actions` 的動作清單在下一個動作前停下,`ac_wait_for_image`/`ac_wait_for_pixel` 在輪詢中途醒來;該次呼叫以 `-32800` 回覆。`ac_stop_execution` 與其他停止請求以同樣方式結束它,回報為工具錯誤。已經進到後端的單一指令仍會先跑完;例外的是擷取輸出的 shell 指令(`ac_shell`、`AC_shell_to_var`),它的行程樹會被結束;HTTP 請求(`AC_http_request`、`ac_http_request` 與其他走共用 HTTP client 的呼叫),它的 socket 會被關閉;以及一次範本比對或 OCR,呼叫不再等它(原生運算在背景跑完、結果丟棄);這些呼叫都隨即結束。 REST 主機資料讀取與對應 MCP 權限一致:排程、遠端 session、USB passthrough 狀態、loopback/remote 裝置清單及診斷需要 `read_data`。對應已註冊的狀態指令、`AC_probe_capabilities` 與 `AC_diagnose` 會在執行提供者之前檢查權限。唯讀標記不授予 viewer 存取權;operator/admin 仍可使用。USB 列舉/事件、保留的 inspector 統計與程序 metrics 也需要 `read_data`;`AC_list_usb_devices`、`AC_usb_recent_events`、`AC_inspector_recent`、`AC_inspector_summary` 同樣檢查此權限。Dashboard 各面板分別顯示缺少的權限並清除舊資料;session 重新整理成功後也會清除先前的錯誤狀態。未列入權限表格的 executor 指令仍屬另一項審查範圍。 diff --git a/architecture_explore.md b/architecture_explore.md index 794a6ead3..bdb6c4f93 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,547 | -| 程式碼總行數 | 238,886 | +| 程式碼總行數 | 238,929 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -292,7 +292,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.1 執行引擎與腳本資產 -> 25 個套件、約 19,571 行。 +> 25 個套件、約 19,612 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -304,7 +304,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/decision_table/` | 112 | DMN 風格決策表:規則 + 命中策略,把分支外部化 | | `utils/deterministic/` | 116 | 決定性執行控制:固定亂數種子 + 凍結時鐘 | | `utils/action_journal/` | 856 | 結構化動作日誌:schema v1、寫入前遮罩、跨行程排序/尾端復原、executor 明確 scope 擷取與本機 parallel/DAG parent 傳遞;門面、AC/MCP、Script Builder 與 CLI 擷取/有界查閱;observer/路徑政策隨巢狀根與 workers 保留,Run History 查閱與手動 history 關聯共用相同來源。 | -| `utils/executor/` | 10,765 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | +| `utils/executor/` | 10,806 | **核心**。`Executor` 指令分派表(774 個 `AC_*`)、參數插值、乾跑、逐步 callback;`flow_control` 提供 34 個區塊指令(迴圈/分支/try/巨集/變數) | | `utils/flow_debugger/` | 166 | action list 的單步除錯器與追蹤器 | | `utils/input_macro/` | 481 | 定時輸入事件:錄製結果的整形(`timeline`/`InputRecorder`,Windows 與 macOS 共用)、重播與宣告式輸入序列 DSL | | `utils/json/` | 99 | action JSON 檔讀寫與正規化格式化(`fmt --check` 的後端) | @@ -393,7 +393,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,579 行。 +> 37 個套件、約 6,581 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -403,7 +403,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/color_region/` | 106 | 以顏色定位畫面區域(遮罩 + 連通元件) | | `utils/color_stats/` | 103 | 區域顏色統計:平均色與主色 | | `utils/coordinate_space/` | 93 | 模型網格座標與實體像素之間的座標空間對映 | -| `utils/cv2_utils/` | 1,091 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | +| `utils/cv2_utils/` | 1,093 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | | `utils/edge_lines/` | 131 | 以 Hough 轉換偵測線條/格線/分隔線 | | `utils/edge_match/` | 116 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | | `utils/feature_match/` | 146 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | @@ -745,7 +745,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `windows_launch.py` | 225 | Attest a process this host launched itself, from an image file pinned by SHA-256. | | `windows_native.py` | 113 | Typed Win32 query/read bindings and caller-sized memory information layouts. | -#### `utils/executor/`(10,765 行)— 執行核心 +#### `utils/executor/`(10,806 行)— 執行核心 | 檔案 | 行數 | 職責 | | --- | ---: | --- | @@ -919,7 +919,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `rest_registry.py` | 91 | 保存執行中 REST 伺服器的行程級單例,狀態包含 RBAC 模式並隱去停用的共用 token。 | | `__main__.py` | 66 | `python -m je_auto_control.utils.rest_api` 進入點。 | -#### `utils/cv2_utils/`(1,091 行)— 擷取、影像與共用定位 frame +#### `utils/cv2_utils/`(1,093 行)— 擷取、影像與共用定位 frame | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -933,7 +933,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/cv2_utils/screen_grabber.py` | 229 | One place that decides how this platform's pixels are read. | | `utils/cv2_utils/screen_record.py` | 125 | Internal image/capture utilities. | | `utils/cv2_utils/screenshot.py` | 95 | Internal image/capture utilities. | -| `utils/cv2_utils/template_detection.py` | 182 | Locate a template image on screen, in the coordinates the mouse takes. | +| `utils/cv2_utils/template_detection.py` | 184 | Locate a template image on screen, in the coordinates the mouse takes. | | `utils/cv2_utils/video_recording.py` | 76 | Internal image/capture utilities. | #### `utils/config_sync/`(8,577 行)— 持久化、因果模型與本機重送 @@ -1554,7 +1554,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `gui/` | 167 | 44,024 | | `utils/mcp_server/` | 63 | 22,322 | | `utils/remote_desktop/` | 77 | 16,970 | -| `utils/executor/` | 11 | 10,765 | +| `utils/executor/` | 11 | 10,806 | | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | | `utils/accessibility/` | 16 | 3,384 | @@ -1571,8 +1571,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,387 | -| **總計** | **1,535** | **238,141** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,389 | +| **總計** | **1,535** | **238,184** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 24da7fc3e..22d0854b3 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1036,3 +1036,25 @@ - The 26 HTTP-dependent modules, `test_mcp_call_run.py` and the complexity, broad-except and file-length gates: 435 passed, 17 skipped. - `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean on the package. - **Files:** `je_auto_control/utils/http_client/http_client.py`, `test/unit_test/headless/test_http_stop.py`, `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). + +## U-20261116-11 · 2026-11-16 · A stop no longer waits for an image search or OCR pass · #done #executor #ocr #image + +- **What.** This is part of the `Progress.md` item "stop 還叫不醒的". One template match (`cv2.matchTemplate`) or one OCR pass (`image_to_matches` of the Tesseract, EasyOCR or Paddle backend) is a single native call that cannot look at a stop. A stop waited for it to finish. The maintainer chose (2026-11-16) to stop waiting for it, accepting that the native work runs on in the background. +- **Change.** + - New `run_control.stoppable_call(function, *args, **kwargs)`. Outside a stoppable run and a cancellation scope it is a plain call. + - Inside either, it checks both, then runs the call on a daemon helper thread under the caller's copied context. The caller waits in 0.1 s slices, checking both, so a stop or cancel raises at once (`ExecutionStopped` / `CancelledError`). + - The call's late result or error is discarded. The work itself is not interrupted, and the CPU it uses is not freed until it ends. + - It is used for the `matchTemplate` call in `cv2_utils/template_detection._prepare`, which covers `find_image`, `find_image_multi` and everything built on them. It is also used for both `engine.image_to_matches` calls in `ocr/ocr_engine.py` (`find_text_matches`, `read_text_in_region` and what calls them). + - OpenCV, pytesseract's subprocess wait and EasyOCR all release the GIL while they work. Both OCR backends keep their shared state under a lock. +- **Not covered:** the other match paths (`visual_match`, `color_match`, `edge_match`, `rotated_match`, self-healing `frame_locators`). They stay in `Progress.md`. +- **Tests:** new `test_stoppable_call.py`, 7 cases: + - a plain call outside a run; + - inside a run, the value and errors still arrive; + - a stop, and separately a cancellation, returns within 2 s while the call is still running; + - a stopped run never starts the call; + - `find_image` with a blocked `matchTemplate` ends on a stop within 2 s; + - `find_text_matches` with a blocked engine ends on a stop within 2 s. + - The last two fail against the unwrapped call sites. + - The 56 test modules that touch template detection, OCR, image or text waits or `run_control`, plus the complexity, broad-except and file-length gates: 1,516 passed, 8 skipped. + - `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean on the package. +- **Files:** `je_auto_control/utils/executor/run_control.py`, `je_auto_control/utils/cv2_utils/template_detection.py`, `je_auto_control/utils/ocr/ocr_engine.py`, `test/unit_test/headless/test_stoppable_call.py`, `README.md` with both translations (line 84), `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). diff --git a/docs/updates/README.md b/docs/updates/README.md index 765f1f1c0..2388b9440 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-11 | 2026-11-16 | A stop no longer waits for an image search or OCR pass | #done #executor #ocr #image | [2026-11-b](2026-11-b.md) | | U-20261116-10 | 2026-11-16 | A stop also ends an HTTP request that is still connecting | #done #http #executor | [2026-11-b](2026-11-b.md) | | U-20261116-09 | 2026-11-16 | MCP roots from roots/list stay opt-in | #done #mcp #security #decision | [2026-11-b](2026-11-b.md) | | U-20261116-08 | 2026-11-16 | A stop or cancel ends an HTTP request that is already out | #done #executor #mcp #http | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/cv2_utils/template_detection.py b/je_auto_control/utils/cv2_utils/template_detection.py index 3d6b1d335..1bf9d440e 100644 --- a/je_auto_control/utils/cv2_utils/template_detection.py +++ b/je_auto_control/utils/cv2_utils/template_detection.py @@ -13,6 +13,7 @@ from je_auto_control.utils.cv2_utils.optional import require_cv2, require_je_open_cv from je_auto_control.utils.cv2_utils.locator_frame import current_locator_frame from je_auto_control.utils.exception.exceptions import ImageNotFoundException +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.monitor_layout.logical_frame import grab_logical @@ -56,7 +57,8 @@ def _prepare(image: Any, detect_threshold: float, frame = _to_gray(cv2, grab_image) if template.shape[0] > frame.shape[0] or template.shape[1] > frame.shape[1]: raise ImageNotFoundException("template is larger than the searched area") - scores = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED) + # One native pass; a stop does not wait for it (see ``stoppable_call``). + scores = stoppable_call(cv2.matchTemplate, frame, template, cv2.TM_CCOEFF_NORMED) except cv2.error as error: # An input OpenCV cannot match (an empty frame, a pixel type it does # not take) is a search that found nothing, in the type callers catch. diff --git a/je_auto_control/utils/executor/run_control.py b/je_auto_control/utils/executor/run_control.py index 140cb530d..31f3bc80a 100644 --- a/je_auto_control/utils/executor/run_control.py +++ b/je_auto_control/utils/executor/run_control.py @@ -35,6 +35,7 @@ thread inherits its creator's context variables -- unless it is handed the token and binds it with :func:`bound_stop_token`, as ``AC_parallel`` does. """ +import contextvars import threading import time import uuid @@ -155,6 +156,46 @@ def checkpoint() -> None: raise ExecutionStopped(token.run_id, token.reason) +# How often a caller waiting on :func:`stoppable_call` looks at its stop. +_CALL_POLL_SECONDS = 0.1 + + +def stoppable_call(function: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """Run one call that cannot look at a stop itself, so a stop does not wait for it. + + Inside a stoppable run or a cancellation scope the call runs on a helper + thread under the caller's context, and the caller waits in 0.1 s slices + that look at both: a stop or cancel raises at once (``ExecutionStopped`` / + ``CancelledError``). The call itself cannot be interrupted -- a native + image search or OCR pass runs to its end in the background and its result + is discarded. Outside both it is a plain call on the caller's thread. + """ + from je_auto_control.utils.exception.cancellation import cancellation_checkpoint, current_cancellation_token + if _CURRENT.get() is None and current_cancellation_token() is None: + return function(*args, **kwargs) + cancellation_checkpoint() + checkpoint() + outcome: Dict[str, Any] = {} + done = threading.Event() + context = contextvars.copy_context() + + def run() -> None: + try: + outcome["value"] = context.run(function, *args, **kwargs) + except BaseException as error: # reason: handed to the waiting caller, which raises it + outcome["error"] = error + finally: + done.set() + + threading.Thread(target=run, name="stoppable-call", daemon=True).start() + while not done.wait(_CALL_POLL_SECONDS): + cancellation_checkpoint() + checkpoint() + if "error" in outcome: + raise outcome["error"] + return outcome["value"] + + def pause(seconds: float, sleep: Optional[Callable[[float], Any]] = None) -> None: """Sleep ``seconds``; inside a stoppable run, wake and raise on a stop. @@ -302,5 +343,5 @@ def release_held_inputs(token: StopToken) -> int: __all__ = [ "ExecutionStopped", "StopToken", "active_executions", "bound_stop_token", "checkpoint", "current_stop_token", "note_command", "pause", - "release_held_inputs", "shielded", "stop_execution", "stoppable_run", + "release_held_inputs", "shielded", "stop_execution", "stoppable_call", "stoppable_run", ] diff --git a/je_auto_control/utils/ocr/ocr_engine.py b/je_auto_control/utils/ocr/ocr_engine.py index 51754e5a4..d52bb3c27 100644 --- a/je_auto_control/utils/ocr/ocr_engine.py +++ b/je_auto_control/utils/ocr/ocr_engine.py @@ -15,7 +15,7 @@ from typing import Any, List, Optional, Pattern, Sequence, Tuple from je_auto_control.utils.exception.exceptions import AutoControlActionException -from je_auto_control.utils.executor.run_control import pause +from je_auto_control.utils.executor.run_control import pause, stoppable_call from je_auto_control.utils.logging.logging_instance import autocontrol_logger from je_auto_control.utils.monitor_layout.logical_frame import grab_logical from je_auto_control.utils.ocr.backends import ( @@ -109,7 +109,7 @@ def find_text_matches(target: str, """ engine = _resolve(backend) frame, offset_x, offset_y = _grab(region) - matches = engine.image_to_matches(frame, lang, min_confidence) + matches = stoppable_call(engine.image_to_matches, frame, lang, min_confidence) # image_to_matches returns image-local coords; translate to absolute. shifted = [TextMatch( text=m.text, x=m.x + offset_x, y=m.y + offset_y, @@ -146,7 +146,7 @@ def read_text_in_region(region: Optional[Sequence[int]] = None, """Return every OCR hit in ``region`` (or whole screen) as TextMatch records.""" engine = _resolve(backend) frame, offset_x, offset_y = _grab(region) - matches = engine.image_to_matches(frame, lang, min_confidence) + matches = stoppable_call(engine.image_to_matches, frame, lang, min_confidence) return [TextMatch( text=m.text, x=m.x + offset_x, y=m.y + offset_y, width=m.width, height=m.height, confidence=m.confidence, diff --git a/test/unit_test/headless/test_stoppable_call.py b/test/unit_test/headless/test_stoppable_call.py new file mode 100644 index 000000000..718b442c1 --- /dev/null +++ b/test/unit_test/headless/test_stoppable_call.py @@ -0,0 +1,133 @@ +"""A stop does not wait for one native call it cannot interrupt: an image search pass or an OCR pass. + +``stoppable_call`` runs such a call on a helper thread inside a stoppable run +or a cancellation scope, and the caller returns as soon as either stops; the +call's late result is discarded. Every slow call here is a fake that waits on +an event, so nothing reads the real screen. +""" +import threading +import time +from concurrent.futures import CancelledError + +import pytest + +from je_auto_control.utils.exception.cancellation import CancellationToken, cancellation_scope +from je_auto_control.utils.executor.run_control import ExecutionStopped, StopToken, stoppable_call, stoppable_run + + +def _later(action, delay: float = 0.3) -> None: + timer = threading.Timer(delay, action) + timer.daemon = True + timer.start() + + +class _Slow: + """A call that blocks until released (or 10 s), noting the thread it ran on.""" + + def __init__(self, value=7) -> None: + self.value = value + self.release = threading.Event() + self.threads = [] + self.finished = threading.Event() + + def __call__(self, *args, **kwargs): + self.threads.append(threading.current_thread()) + self.release.wait(10) + self.finished.set() + return self.value + + +def test_outside_any_run_it_is_a_plain_call(): + slow = _Slow() + slow.release.set() + assert stoppable_call(slow) == 7 + assert slow.threads == [threading.current_thread()] + + +def test_inside_a_run_the_result_and_errors_still_arrive(): + slow = _Slow(value={"ok": True}) + slow.release.set() + with stoppable_run(token=StopToken("call-value")): + assert stoppable_call(slow) == {"ok": True} + + def broken(): + raise ValueError("bad input") + + with pytest.raises(ValueError, match="bad input"): + stoppable_call(broken) + assert slow.threads != [threading.current_thread()] + + +def test_a_stop_returns_without_waiting_for_the_call(): + slow = _Slow() + token = StopToken("call-stop") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + stoppable_call(slow) + assert time.monotonic() - started < 2 + assert not slow.finished.is_set() # still running; its result is discarded + slow.release.set() + + +def test_a_cancellation_returns_without_waiting_for_the_call(): + slow = _Slow() + token = CancellationToken(task_id=51) + _later(token.cancel) + started = time.monotonic() + with cancellation_scope(token), pytest.raises(CancelledError): + stoppable_call(slow) + assert time.monotonic() - started < 2 + slow.release.set() + + +def test_a_stopped_run_never_starts_the_call(): + slow = _Slow() + token = StopToken("call-stopped") + token.stop("before") + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + stoppable_call(slow) + assert slow.threads == [] + + +def test_a_stop_ends_an_image_search_stuck_in_its_match(monkeypatch): + np = pytest.importorskip("numpy") + cv2 = pytest.importorskip("cv2") + pytest.importorskip("je_open_cv") + from PIL import Image + + from je_auto_control.utils.cv2_utils import template_detection + frame = Image.fromarray(np.zeros((60, 80, 3), dtype=np.uint8)) + monkeypatch.setattr(template_detection, "grab_logical", lambda region, all_screens=True: (frame.copy(), 0, 0)) + slow = _Slow(value=np.zeros((51, 71), dtype=np.float32)) + monkeypatch.setattr(cv2, "matchTemplate", slow) + token = StopToken("image-stop") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + template_detection.find_image(np.zeros((10, 10), dtype=np.uint8), detect_threshold=0.9) + assert time.monotonic() - started < 2 + assert slow.threads, "the search never reached the match" + slow.release.set() + + +def test_a_stop_ends_an_ocr_pass(monkeypatch): + from je_auto_control.utils.ocr import ocr_engine + + class _Engine: + def __init__(self) -> None: + self.slow = _Slow(value=[]) + + def image_to_matches(self, frame, lang, min_confidence): + return self.slow(frame, lang, min_confidence) + + engine = _Engine() + monkeypatch.setattr(ocr_engine, "_grab", lambda region: (object(), 0, 0)) + token = StopToken("ocr-stop") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + ocr_engine.find_text_matches("Save", backend=engine) + assert time.monotonic() - started < 2 + assert engine.slow.threads, "OCR never started" + engine.slow.release.set() From 75319dcf98e801187adc63f1b672564fa98ba0f5 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 18:36:40 +0800 Subject: [PATCH 155/161] Add the M0 routing profile that never falls back to desktop input M0 asked for the profile, its result types and a routing rule forbidding desktop input as reviewable data. Routes name a closed set of background channels, a pending or unknown operation is unsupported, and the Windows profile is the contract's capability matrix, kept in step by a test. --- Progress.md | 4 +- architecture_explore.md | 15 +-- docs/process_memory_contract.md | 9 ++ docs/updates/2026-11-b.md | 22 ++++ docs/updates/README.md | 1 + .../process_memory/background_profile.py | 119 ++++++++++++++++++ .../test_process_memory_background_profile.py | 71 +++++++++++ 7 files changed, 232 insertions(+), 9 deletions(-) create mode 100644 je_auto_control/utils/process_memory/background_profile.py create mode 100644 test/unit_test/headless/test_process_memory_background_profile.py diff --git a/Progress.md b/Progress.md index 3b10a6a96..b587110d2 100644 --- a/Progress.md +++ b/Progress.md @@ -644,7 +644,7 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 `WIP` — 內部 `utils/process_memory/` 已有不可變身分/probe、區段與位元組預算、 序號一致性檢查、語意欄位白名單及失敗 handle 保留重試。契約與 fixture 協定見 -[process_memory_contract.md](docs/process_memory_contract.md)。M0/M1 尚未完成, +[process_memory_contract.md](docs/process_memory_contract.md)。M0 的 profile、結果型別與禁用桌面輸入的路由規則已完成(U-20261116-12,`utils/process_memory/background_profile.py`);M1 尚未完成, 已有自有 fixture 的固定緩衝區與有界管線控制協定,測試僅驗證本機資料配置及背景子程序通訊。 bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報資訊,不能充當 OS 出生身分或可信 resolver。 typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 handle 的注入測試; @@ -655,7 +655,7 @@ resolver 已能透過保留 handle 取得主映像基址與大小並做有預算 fixture 的原生身分核對(標頭挑戰已有,U-20261115-18,只在本行程內驗過)與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 -1. **M0:能力盤點與範圍契約。** 先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 +1. **M0:能力盤點與範圍契約。**(profile/路由規則已完成,U-20261116-12;之後選定提供正式背景介面的應用仍待決定)先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 讀取來源、執行介面、權限、是否全背景、支援版本、驗證方式與不支援原因。 第一個目標採自有 fixture 程序,之後選一個提供正式背景介面的應用;不能先承諾任意軟體。 完成條件:profile、上述結果型別及禁用桌面輸入的路由規則具體可審閱,既有桌面路徑不被暗中改寫。 diff --git a/architecture_explore.md b/architecture_explore.md index bdb6c4f93..01405ec5a 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -27,8 +27,8 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | -| Python 模組總數(含周邊子專案) | 1,547 | -| 程式碼總行數 | 238,929 | +| Python 模組總數(含周邊子專案) | 1,548 | +| 程式碼總行數 | 239,048 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -324,7 +324,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.2 框架基礎設施 -> 15 個套件、約 5,314 行。 +> 15 個套件、約 5,433 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -340,7 +340,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/package_manager/` | 198 | 動態載入套件並把 executor 注入其中;載入前先過套件閘門(允許清單加上只能從 Python 呼叫的開關,工作區 X-12) | | `utils/path_guard/` | 267 | 命令列及伺服器的路徑邊界、客戶端根目錄隔離與受管任務來源政策紀錄 | | `utils/platform_id/` | 62 | 作業系統家族的單一判定點。`sys.platform` 原本在一百多處跟字面清單比對,而那些清單都沒有 BSD;`is_x11_unix()` 問的是「這是不是 X11 unix」,這才是守衛一直想問的問題 | -| `utils/process_memory/` | 1,471 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測、自有啟動加釘選雜湊的 attestor 與失敗 handle 回收;檔案證據不等於載入程式碼身分,原生驗收及 runtime 整合待完成 | +| `utils/process_memory/` | 1,590 | 內部受審 probe 的有界語意觀察、typed Windows provider、獨立映像檔觀測、自有啟動加釘選雜湊的 attestor 與失敗 handle 回收;檔案證據不等於載入程式碼身分,原生驗收及 runtime 整合待完成 | | `utils/shell_process/` | 312 | `ShellManager`:以 argv list 執行外部命令(禁用 `shell=True`) | | `utils/start_exe/` | 36 | 啟動另一個執行檔行程 | @@ -731,11 +731,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 上表以子套件為單位;以下把行數最大的幾個子系統展開到檔案層。 -#### `utils/process_memory/`(1,471 行/9 檔) +#### `utils/process_memory/`(1,590 行/10 檔) | 檔案 | 行數 | 職責 | | --- | ---: | --- | | `__init__.py` | 1 | Internal reviewed process observations; no native provider or public command registration. | +| `background_profile.py` | 119 | Reviewable M0 routing profile: which background channel serves an operation, never desktop input. | | `models.py` | 203 | Closed identities, reviewed probes and safe semantic observation results. | | `reader.py` | 310 | Adapter-owned semantic observations with bounded reads and retained cleanup ownership. | | `windows.py` | 194 | Owned Windows read handles with measured native facts and reviewed application attestation. | @@ -1571,8 +1572,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,009 | 104,389 | -| **總計** | **1,535** | **238,184** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,010 | 104,508 | +| **總計** | **1,536** | **238,303** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/process_memory_contract.md b/docs/process_memory_contract.md index 0d10f06af..944d7a2b3 100644 --- a/docs/process_memory_contract.md +++ b/docs/process_memory_contract.md @@ -37,6 +37,15 @@ process. Existing desktop foreground and input-presence gates are unchanged. | OS service operation | Specific approved service's management interface | Explicit service scope and independent status readback | Adapter and policy integration pending | | Completed background task | Fresh state or artifact verification under current runtime authority | Observation does not grant execution rights or replace a completion receipt | End-to-end M4/M5 integration pending | +The same matrix is data in `utils/process_memory/background_profile.py` +(`WINDOWS_PROFILE`), and a test keeps the two row for row. A route names one +of a closed set of `Channel`s; desktop keyboard, mouse, focus and foreground +switching are not channels, and a route naming one is refused when it is +built. `route(profile, operation)` returns a route only when its state is +`existing` or `injected_tests`; an unknown operation or a pending adapter is +`unsupported`, never a fallback to desktop input. The module reads and opens +nothing and imports no input, wrapper or native code. + ## Retained identity and private reads `ProcessIdentity` includes host/session identifiers, PID, process birth, executable diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 22d0854b3..8cfd47587 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1058,3 +1058,25 @@ - The 56 test modules that touch template detection, OCR, image or text waits or `run_control`, plus the complexity, broad-except and file-length gates: 1,516 passed, 8 skipped. - `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean on the package. - **Files:** `je_auto_control/utils/executor/run_control.py`, `je_auto_control/utils/cv2_utils/template_detection.py`, `je_auto_control/utils/ocr/ocr_engine.py`, `test/unit_test/headless/test_stoppable_call.py`, `README.md` with both translations (line 84), `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). + +## U-20261116-12 · 2026-11-16 · M0 routing profile: background channels only, never desktop input · #done #process-memory #policy + +- **What.** M0 of the background-operation plan (`Progress.md` › 下一步擴充…). Its completion condition: the profile, its result types and a routing rule that forbids desktop input must be concrete and reviewable, and the existing desktop path must not be rewritten. The maintainer resumed only this policy part of the paused process-memory work (2026-11-16). No reading capability was added. +- **Change.** New `je_auto_control/utils/process_memory/background_profile.py`, which reads nothing, opens nothing and imports only `dataclasses`, `enum` and the package's `models`. + - **`Channel`** is a closed set: `os_query`, `uia_read`, `managed_dom`, `memory_read`, `application_api`, `os_service`, `state_readback`. Desktop keyboard, mouse, focus and foreground switching are deliberately absent (`DESKTOP_INPUT`), and a `BackgroundRoute` naming one, or naming anything that is not a `Channel`, is refused when it is built. + - **`RouteState`** is `existing`, `injected_tests` or `pending`. + - **`BackgroundProfile`** holds unique routes. + - **`route(profile, operation)`** returns a route only in the first two states. An unknown operation or a pending adapter raises `MemoryObservationError(UNSUPPORTED)`, never a fallback. + - **`WINDOWS_PROFILE`** is the contract's Windows capability matrix as data, with 7 routes. +- **Docs:** `docs/process_memory_contract.md` describes the profile under the matrix. `Progress.md` marks M0's profile and routing rule done; choosing an application with an official background interface is still open, and M1 onward is unchanged. `architecture_explore.md` has a row for the module (re-measured: 1,590 lines in 10 files). +- **Tests:** new `test_process_memory_background_profile.py`, 15 cases: + - the profile equals the contract table row for row; + - no channel is desktop input; + - routable states are handed back, while pending or unknown operations are unsupported; + - only closed channels are accepted; + - routes are unique; + - only command channels declare writes; + - the module imports no input, wrapper or native code. + - All `test_process_memory_*` modules plus the docs, line-count, file-length, complexity and broad-except gates: 303 passed. `typing_contract_verify.py` was OK with and without `--extras`, and bandit was clean. +- **Files:** `je_auto_control/utils/process_memory/background_profile.py`, `test/unit_test/headless/test_process_memory_background_profile.py`, `docs/process_memory_contract.md`, `Progress.md`, `architecture_explore.md`. +- **Open items:** in `Progress.md`, choosing the first application with an official background interface, and M1 onward (native acceptance stays paused). diff --git a/docs/updates/README.md b/docs/updates/README.md index 2388b9440..e75b54964 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-12 | 2026-11-16 | M0 routing profile: background channels only, never desktop input | #done #process-memory #policy | [2026-11-b](2026-11-b.md) | | U-20261116-11 | 2026-11-16 | A stop no longer waits for an image search or OCR pass | #done #executor #ocr #image | [2026-11-b](2026-11-b.md) | | U-20261116-10 | 2026-11-16 | A stop also ends an HTTP request that is still connecting | #done #http #executor | [2026-11-b](2026-11-b.md) | | U-20261116-09 | 2026-11-16 | MCP roots from roots/list stay opt-in | #done #mcp #security #decision | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/process_memory/background_profile.py b/je_auto_control/utils/process_memory/background_profile.py new file mode 100644 index 000000000..8b8561669 --- /dev/null +++ b/je_auto_control/utils/process_memory/background_profile.py @@ -0,0 +1,119 @@ +"""Reviewable M0 routing profile: which background channel serves an operation, never desktop input. + +This is the M0 deliverable of the background-operation plan in ``Progress.md`` +and ``docs/process_memory_contract.md``: the profile, its result types and the +routing rule, as data that can be reviewed and tested. It reads nothing, opens +nothing and imports no input, wrapper or native code, so the existing desktop +foreground and input paths are not touched by it. + +The routing rule is closed. :class:`Channel` lists the only interfaces a +background operation may use; desktop keyboard, mouse, focus and foreground +switching are deliberately not among them, and a route naming one is refused +when it is built. :func:`route` hands back a route only when its state says it +can be used; an unknown operation, or one whose adapter is still pending, +fails as ``UNSUPPORTED`` instead of falling back to anything else. +""" +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + +from .models import FailureReason, MemoryObservationError, _identifier + + +class Channel(str, Enum): + """The interfaces a background operation may use. Desktop input is not one of them.""" + + OS_QUERY = "os_query" # retained OS handle and its documented queries + UIA_READ = "uia_read" # UI Automation properties only: no Invoke, SetValue or focus + MANAGED_DOM = "managed_dom" # the existing WebRunner managed browser session + MEMORY_READ = "memory_read" # reviewed probe over the bounded read provider; never writes + APPLICATION_API = "application_api" # an application's official API, CLI or IPC + OS_SERVICE = "os_service" # one approved service's management interface + STATE_READBACK = "state_readback" # fresh state or artifact verification under runtime authority + + +class RouteState(str, Enum): + """How far an operation's adapter has got; only the first two may be routed to.""" + + EXISTING = "existing" # an implementation already in the package serves it + INJECTED_TESTS = "injected_tests" # typed calls exist and are tested through injected functions only + PENDING = "pending" # not implemented; routing to it is unsupported + + +#: Names that must never appear as a route's channel: they are the desktop input path. +DESKTOP_INPUT = frozenset({"desktop_input", "keyboard", "mouse", "focus", "foreground"}) + +_ROUTABLE = frozenset({RouteState.EXISTING, RouteState.INJECTED_TESTS}) + + +@dataclass(frozen=True) +class BackgroundRoute: + """One row of the capability matrix: an operation, the channel that serves it, and its state.""" + + operation: str + label: str + channel: Channel + read_only: bool + requirement: str + state: RouteState + + def __post_init__(self) -> None: + _identifier(self.operation) + if str(getattr(self.channel, "value", self.channel)) in DESKTOP_INPUT or not isinstance(self.channel, Channel): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + if not isinstance(self.state, RouteState) or not self.label or not self.requirement: + raise MemoryObservationError(FailureReason.UNSUPPORTED) + + +@dataclass(frozen=True) +class BackgroundProfile: + """The routes one platform offers; operations are unique.""" + + platform: str + routes: tuple[BackgroundRoute, ...] + + def __post_init__(self) -> None: + _identifier(self.platform) + names = [item.operation for item in self.routes] + if not names or len(set(names)) != len(names): + raise MemoryObservationError(FailureReason.UNSUPPORTED) + + def get(self, operation: str) -> BackgroundRoute | None: + """The route for ``operation`` whatever its state, or ``None`` if the profile has none.""" + return next((item for item in self.routes if item.operation == operation), None) + + +def route(profile: BackgroundProfile, operation: str) -> BackgroundRoute: + """The route that serves ``operation``; ``UNSUPPORTED`` when there is none or it is still pending. + + Never a fallback: an operation this profile cannot serve in the background + is reported as unsupported, not handed to desktop input. + """ + found = profile.get(operation) + if found is None or found.state not in _ROUTABLE: + raise MemoryObservationError(FailureReason.UNSUPPORTED) + return found + + +#: The Windows capability matrix of ``docs/process_memory_contract.md``, as data. +WINDOWS_PROFILE = BackgroundProfile("windows", ( + BackgroundRoute("process.identity", "Process/session identity", Channel.OS_QUERY, True, + "Read/query/synchronize rights only; no privilege escalation", RouteState.INJECTED_TESTS), + BackgroundRoute("ui.state", "UI state", Channel.UIA_READ, True, + "No Invoke, SetValue or focus change", RouteState.PENDING), + BackgroundRoute("browser.state", "Browser state", Channel.MANAGED_DOM, True, + "Dedicated managed browser; no desktop input fallback", RouteState.EXISTING), + BackgroundRoute("fixture.state", "Fixture semantic state", Channel.MEMORY_READ, True, + "Bounded query/read provider; no writes", RouteState.INJECTED_TESTS), + BackgroundRoute("application.command", "Application command", Channel.APPLICATION_API, False, + "Must independently prove no foreground/focus/mouse/input interference", RouteState.PENDING), + BackgroundRoute("os.service", "OS service operation", Channel.OS_SERVICE, False, + "Explicit service scope and independent status readback", RouteState.PENDING), + BackgroundRoute("task.completion", "Completed background task", Channel.STATE_READBACK, True, + "Observation does not grant execution rights or replace a completion receipt", RouteState.PENDING), +)) + + +__all__ = ["BackgroundProfile", "BackgroundRoute", "Channel", "DESKTOP_INPUT", "RouteState", + "WINDOWS_PROFILE", "route"] diff --git a/test/unit_test/headless/test_process_memory_background_profile.py b/test/unit_test/headless/test_process_memory_background_profile.py new file mode 100644 index 000000000..6bebcd55e --- /dev/null +++ b/test/unit_test/headless/test_process_memory_background_profile.py @@ -0,0 +1,71 @@ +"""The M0 routing profile: closed channels, no desktop-input route, no fallback, and the doc's matrix as data.""" +import ast +from pathlib import Path +import re + +import pytest + +from je_auto_control.utils.process_memory import background_profile +from je_auto_control.utils.process_memory.background_profile import ( + DESKTOP_INPUT, WINDOWS_PROFILE, BackgroundProfile, BackgroundRoute, Channel, RouteState, route, +) +from je_auto_control.utils.process_memory.models import MemoryObservationError + +_ROOT = Path(__file__).resolve().parents[3] +_CONTRACT = _ROOT / "docs" / "process_memory_contract.md" + + +def _matrix_labels() -> list: + text = _CONTRACT.read_text(encoding="utf-8") + section = text.split("## Windows capability matrix", 1)[1].split("\n## ", 1)[0] + rows = [line for line in section.splitlines() if line.startswith("| ") and not line.startswith("| Operation")] + return [row.split("|")[1].strip() for row in rows if not set(row) <= set("|- ")] + + +def test_the_profile_is_the_contract_matrix_row_for_row(): + assert [item.label for item in WINDOWS_PROFILE.routes] == _matrix_labels() + + +def test_no_channel_is_desktop_input(): + assert not {channel.value for channel in Channel} & DESKTOP_INPUT + + +@pytest.mark.parametrize("state", [RouteState.EXISTING, RouteState.INJECTED_TESTS]) +def test_a_route_that_can_serve_is_handed_back(state): + profile = BackgroundProfile("windows", ( + BackgroundRoute("x.read", "X", Channel.OS_QUERY, True, "read only", state),)) + assert route(profile, "x.read").channel is Channel.OS_QUERY + + +def test_a_pending_or_unknown_operation_is_unsupported_not_a_fallback(): + for operation in ("application.command", "os.service", "ui.state", "click.button", "desktop_input"): + with pytest.raises(MemoryObservationError, match="unsupported"): + route(WINDOWS_PROFILE, operation) + assert route(WINDOWS_PROFILE, "browser.state").channel is Channel.MANAGED_DOM + + +@pytest.mark.parametrize("channel", ["desktop_input", "mouse", "keyboard", "focus", "foreground", "uia_read"]) +def test_a_route_can_only_name_a_closed_channel(channel): + with pytest.raises(MemoryObservationError, match="unsupported"): + BackgroundRoute("x.op", "X", channel, True, "requirement", RouteState.EXISTING) + + +@pytest.mark.parametrize("routes", [(), "duplicate"]) +def test_a_profile_needs_unique_routes(routes): + item = BackgroundRoute("x.op", "X", Channel.OS_QUERY, True, "requirement", RouteState.PENDING) + with pytest.raises(MemoryObservationError, match="unsupported"): + BackgroundProfile("windows", (item, item) if routes == "duplicate" else routes) + + +def test_writes_are_only_declared_by_command_channels(): + writing = {item.channel for item in WINDOWS_PROFILE.routes if not item.read_only} + assert writing <= {Channel.APPLICATION_API, Channel.OS_SERVICE} + assert all(item.read_only for item in WINDOWS_PROFILE.routes if item.channel is Channel.MEMORY_READ) + + +def test_the_profile_touches_no_desktop_input_or_native_code(): + tree = ast.parse(Path(background_profile.__file__).read_text(encoding="utf-8")) + imported = {node.module or "" for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)} + imported |= {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names} + assert imported <= {"__future__", "dataclasses", "enum", "models"}, imported + assert not re.search(r"ctypes|wrapper|keyboard|mouse|windows_native", " ".join(imported)) From 754d101a0a9a26b0828bc22a013761797bcd9d36 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 20:53:41 +0800 Subject: [PATCH 156/161] Keep the lease watch out of a DAG revocation test's refusal The service's maintain() loop cancels a task once its owner loses the role, which raced act()'s own authority check and failed Windows 3.13 with CancelledError. The test holds the loop off so act()'s refusal is the one under test. --- docs/updates/2026-11-b.md | 8 ++++++++ docs/updates/README.md | 1 + test/unit_test/headless/test_agent_dag_local_tasks.py | 8 ++++++++ 3 files changed, 17 insertions(+) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 8cfd47587..c641de71c 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1080,3 +1080,11 @@ - All `test_process_memory_*` modules plus the docs, line-count, file-length, complexity and broad-except gates: 303 passed. `typing_contract_verify.py` was OK with and without `--extras`, and bandit was clean. - **Files:** `je_auto_control/utils/process_memory/background_profile.py`, `test/unit_test/headless/test_process_memory_background_profile.py`, `docs/process_memory_contract.md`, `Progress.md`, `architecture_explore.md`. - **Open items:** in `Progress.md`, choosing the first application with an official background interface, and M1 onward (native acceptance stays paused). + +## U-20261116-13 · 2026-11-16 · A DAG revocation test no longer races the lease watch · #incident #ci #test #agent + +- **Run.** Quality run 43850427243 on `75319dcf` (PR #552). Windows 2022 / Python 3.13 failed one test, `test_agent_dag_local_tasks.py::test_revocation_during_grounding_is_refused_before_the_target_input_call`. It raised `CancelledError` where `AuthorizationError` was expected. Every other square passed. +- **Cause.** The test revokes the owner's role inside the target's `observe()`, during `act()`'s grounding, and expects `act()`'s authority check to refuse the action. Meanwhile `AgentRuntimeService`'s lease watch calls `runtime.maintain()` every 0.25 s. Once the role is gone, `maintain()` stops the task through `_stop_owned`, which cancels the task's token. When that pass landed between the revocation and `act()`'s `checkpoint()`, the token raised first. Either outcome refuses the input; the race was in the test, not in a changed code path. The failing action is local and touches no HTTP. +- **Change.** The test replaces `instance.runtime.maintain` with an event setter and waits for the watch to call it once, so no real pass begun before the swap is still running. `act()`'s own refusal is then the only one that can fire. Product code is unchanged. +- **Tests:** `test_agent_dag_local_tasks.py`, 15 passed in each of 3 runs. The single test passed 5 of 5 locally before the change too. +- **Files:** `test/unit_test/headless/test_agent_dag_local_tasks.py`. diff --git a/docs/updates/README.md b/docs/updates/README.md index e75b54964..ef7ade91d 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-13 | 2026-11-16 | A DAG revocation test no longer races the lease watch | #incident #ci #test #agent | [2026-11-b](2026-11-b.md) | | U-20261116-12 | 2026-11-16 | M0 routing profile: background channels only, never desktop input | #done #process-memory #policy | [2026-11-b](2026-11-b.md) | | U-20261116-11 | 2026-11-16 | A stop no longer waits for an image search or OCR pass | #done #executor #ocr #image | [2026-11-b](2026-11-b.md) | | U-20261116-10 | 2026-11-16 | A stop also ends an HTTP request that is still connecting | #done #http #executor | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/test_agent_dag_local_tasks.py b/test/unit_test/headless/test_agent_dag_local_tasks.py index eedec3ead..19f786b9a 100644 --- a/test/unit_test/headless/test_agent_dag_local_tasks.py +++ b/test/unit_test/headless/test_agent_dag_local_tasks.py @@ -1,5 +1,6 @@ """Cross-owner local DAG work uses original ownership and independently revocable admitting authority.""" import json +import threading from copy import deepcopy from unittest.mock import Mock @@ -186,6 +187,13 @@ def test_maintenance_retires_lease_when_admin_loses_cross_owner_authority(owned, def test_revocation_during_grounding_is_refused_before_the_target_input_call(owned, monkeypatch): _client, instance, target, users, owner, _actor, _batch = owned + # The service's lease watch calls maintain() every 0.25 s. Once the role is revoked below it cancels + # the task's token, which raced act()'s own refusal: a slow Windows runner raised CancelledError at + # act()'s checkpoint instead of AuthorizationError (run 43850427243). Hold the watch off for this + # test, and wait until it has run the stand-in once, so no pass that began before the swap is live. + ticked = threading.Event() + monkeypatch.setattr(instance.runtime, "maintain", ticked.set) + assert ticked.wait(5) started, node = begin(owned) monkeypatch.setattr(instance.runtime.background, "start", Mock()) task = local(owned, started, "submit", submission(node)) From 776c80a06b8679e8e9bd146b90db89dc3f4944aa Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Mon, 16 Nov 2026 22:04:35 +0800 Subject: [PATCH 157/161] Route every template match through stoppable_call The other match paths (visual, colour, edge, rotated, self-healing frame and device-frame matching) still made a stop wait for a native matchTemplate pass. A structural test now fails on any direct call, so a new matcher cannot bring the wait back. --- CHANGELOG.md | 5 +-- Progress.md | 2 +- architecture_explore.md | 26 +++++++-------- docs/updates/2026-11-b.md | 19 +++++++++++ docs/updates/README.md | 1 + .../utils/color_match/color_match.py | 7 ++-- .../utils/edge_match/edge_match.py | 3 +- .../utils/rotated_match/rotated_match.py | 3 +- .../utils/self_healing/frame_locators.py | 3 +- .../utils/visual_match/visual_match.py | 9 ++--- je_auto_control/wrapper/device_frame.py | 3 +- .../unit_test/headless/test_stoppable_call.py | 33 +++++++++++++++++++ 12 files changed, 87 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aded17e75..fcfc3da99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,9 @@ ## [Unreleased] -- Image search and OCR (`find_image` and everything on `cv2_utils.template_detection`, `find_text_matches`, - `read_text_in_region` and the OCR commands built on them): inside a stoppable run or a cancellation scope +- Image search and OCR (`find_image` and everything on `cv2_utils.template_detection`, `visual_match`, + `color_match`, `edge_match`, `rotated_match`, self-healing frame locators, device-frame matching, + `find_text_matches`, `read_text_in_region` and the commands built on them): inside a stoppable run or a cancellation scope the single native pass runs on a helper thread (`run_control.stoppable_call`), and a stop or cancel ends the call within about 0.1 s instead of waiting for the pass. The pass itself cannot be interrupted: it finishes in the background and its result is discarded. Outside a run nothing changes. diff --git a/Progress.md b/Progress.md index b587110d2..a3b0580af 100644 --- a/Progress.md +++ b/Progress.md @@ -108,7 +108,7 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令只剩其他未接合的原生呼叫(擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求連 TCP 交握都可中斷,只剩正在進行的 DNS 查詢不行,U-20261116-08/-10;`template_detection` 與 OCR 引擎的單次原生運算改由 `stoppable_call` 不再等待,但運算本身在背景跑完,U-20261116-11;`visual_match`、`color_match`、`edge_match`、`rotated_match`、自愈的 `frame_locators` 等其他比對路徑尚未接合)、單一手勢內的節奏 sleep; +- **stop 還叫不醒的**:已經進到後端的單一指令只剩其他未接合的原生呼叫(擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求連 TCP 交握都可中斷,只剩正在進行的 DNS 查詢不行,U-20261116-08/-10;套件內每個 `cv2.matchTemplate` 與 OCR 引擎的單次原生運算都改由 `stoppable_call` 不再等待,但運算本身在背景跑完,U-20261116-11/-14)、單一手勢內的節奏 sleep; 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 diff --git a/architecture_explore.md b/architecture_explore.md index 01405ec5a..a669ab7a4 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,548 | -| 程式碼總行數 | 239,048 | +| 程式碼總行數 | 239,054 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -393,19 +393,19 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.5 影像辨識與畫面分析 -> 37 個套件、約 6,581 行。 +> 37 個套件、約 6,585 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/annotate/` | 123 | 截圖標註:畫框、highlight、箭頭、標籤 | | `utils/barcode/` | 59 | 一維條碼(EAN/UPC)解碼,解碼器可注入 | -| `utils/color_match/` | 151 | 在 HSV 通道上做顏色感知的樣板比對 | +| `utils/color_match/` | 152 | 在 HSV 通道上做顏色感知的樣板比對 | | `utils/color_region/` | 106 | 以顏色定位畫面區域(遮罩 + 連通元件) | | `utils/color_stats/` | 103 | 區域顏色統計:平均色與主色 | | `utils/coordinate_space/` | 93 | 模型網格座標與實體像素之間的座標空間對映 | | `utils/cv2_utils/` | 1,093 | OpenCV 基礎層:擷取後端選擇(`screen_grabber`,Pillow/mss 或平台後端)、截圖、`[left, top, right, bottom]` 區域擷取(`region_capture`,Windows 經 `grab_logical` 涵蓋所有螢幕)、樣板比對(走 `grab_logical`,涵蓋所有螢幕)、螢幕錄影、影片錄製(兩者都經 `frame_clock` 依 fps 配速)、連通元件、影像堆疊的取用口(`optional`,Windows arm64 沒有 wheel 時語意報錯)、非 ASCII 路徑也讀寫得到的影像檔存取(`image_file`) | | `utils/edge_lines/` | 131 | 以 Hough 轉換偵測線條/格線/分隔線 | -| `utils/edge_match/` | 116 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | +| `utils/edge_match/` | 117 | 邊緣形狀(Chamfer/距離轉換)樣板比對 | | `utils/feature_match/` | 146 | ORB 特徵比對:在旋轉/縮放/主題變更下定位樣板 | | `utils/hsv_segment/` | 103 | HSV 色彩空間分割(抗光照的顏色遮罩 + blob 框) | | `utils/icon_classify/` | 151 | 從像素形狀判斷一個框是哪一類元件 | @@ -422,7 +422,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/perceptual_diff/` | 203 | 感知式(YIQ)影像差異,抑制反鋸齒邊緣誤報 | | `utils/preprocess/` | 276 | OCR/比對前的影像前處理(灰階、二值化、去傾斜…) | | `utils/qr/` | 59 | 從影像或螢幕區域解碼 QR code(OpenCV) | -| `utils/rotated_match/` | 202 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | +| `utils/rotated_match/` | 203 | 容忍旋轉與縮放的樣板比對(尺度空間 × 角度掃描) | | `utils/saliency/` | 113 | 頻譜殘差視覺顯著性:顯著圖與排序後的顯著區域 | | `utils/scale_detect/` | 105 | 偵測樣板實際渲染的顯示縮放/視覺 DPI | | `utils/screen_grid/` | 146 | 供 VLM 接地用的粗粒度標號網格(點 ↔ 格對映) | @@ -432,7 +432,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/subpixel_match/` | 108 | 以二次曲面擬合做次像素級比對精修 | | `utils/theme_normalize/` | 94 | 主題無關的影像正規化,讓亮色樣板能配對深色模式 | | `utils/video_report/` | 171 | 影片步驟疊圖報告:把截圖加字幕串成操作導覽影片 | -| `utils/visual_match/` | 534 | 會回傳信心值的樣板比對(分數、多尺度、find-all + NMS);擷取走 `grab_logical`,命中座標已加回虛擬桌面原點,單色樣板直接拒收;`image_source.py` 是比對與影像分析模組共用的 `ImageSource` 別名(型別契約允許的 numpy 陣列 `Any` 邊界,列在 `SDK_ANY_ADAPTERS`) | +| `utils/visual_match/` | 535 | 會回傳信心值的樣板比對(分數、多尺度、find-all + NMS);擷取走 `grab_logical`,命中座標已加回虛擬桌面原點,單色樣板直接拒收;`image_source.py` 是比對與影像分析模組共用的 `ImageSource` 別名(型別契約允許的 numpy 陣列 `Any` 邊界,列在 `SDK_ANY_ADAPTERS`) | | `utils/visual_regression/` | 251 | 桌面 GUI 的視覺回歸測試(黃金圖比對) | ### 5.4.6 OCR 與文字理解 @@ -486,7 +486,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.8 元素定位、自我修復與智慧等待 -> 23 個套件、約 6,344 行。 +> 23 個套件、約 6,345 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -509,7 +509,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/observation_delta/` | 122 | token 預算內的觀察差異:兩個 UI 影格之間變了什麼 | | `utils/screen_state/` | 191 | 語義畫面狀態:快照/差異與結構化畫面描述 | | `utils/scroll_find/` | 103 | 捲動直到目標影像/文字可見 | -| `utils/self_healing/` | 2,236 | 執行時自癒定位與固定 PNG 版本比較、明確母體/延遲/來源報告 | +| `utils/self_healing/` | 2,237 | 執行時自癒定位與固定 PNG 版本比較、明確母體/延遲/來源報告 | | `utils/semantic_recording/` | 502 | 為錄製內容加上語義錨點,支援換機重播與自癒重播 | | `utils/settle_detector/` | 79 | 以純函式介面判定 UI 是否已靜止 | | `utils/smart_waits/` | 663 | 智慧等待:以影格差異取代 `time.sleep` | @@ -1025,7 +1025,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/codegen/journal_commands.py` | 13 | 日誌候選的 JSON executor 轉接與明確匯出。 | | `utils/codegen/journal_cli.py` | 26 | CLI --from-log 模式、JSON 審閱輸出與可選 ZIP。 | -#### `utils/self_healing/`(2,236 行)— 執行時定位與固定影像比較 +#### `utils/self_healing/`(2,237 行)— 執行時定位與固定影像比較 | 模組 | 行數 | 職責 | | --- | ---: | --- | @@ -1044,7 +1044,7 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 | `utils/self_healing/heal_log.py` | 141 | 相容既有格式的 JSONL 記錄與執行中秘密遮蔽。 | | `utils/self_healing/evaluation_models.py` | 236 | 不可變影像樣本、候選、母體與來源模型。 | | `utils/self_healing/evaluation.py` | 175 | 固定 frame 比較;標註、驗證、誤判、成本及延遲分開統計。 | -| `utils/self_healing/frame_locators.py` | 141 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | +| `utils/self_healing/frame_locators.py` | 142 | 純影像比對與明確 VLM backend;共用區域、原點與縮放換算。 | | `utils/self_healing/evaluation_io.py` | 188 | 有界且受路徑政策限制的本機資料集、原子 JSON/HTML 報告。 | #### `utils/agent_runtime/`(26,101 行/182 檔) @@ -1559,7 +1559,7 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `utils/usb/` | 20 | 5,069 | | `je_auto_control/`(頂層 3 檔) | 5 | 5,168 | | `utils/accessibility/` | 16 | 3,384 | -| `wrapper/` | 25 | 6,065 | +| `wrapper/` | 25 | 6,066 | | `windows/` | 24 | 2,363 | | `utils/rest_api/` | 8 | 2,236 | | `utils/agent/` | 13 | 2,254 | @@ -1572,8 +1572,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,010 | 104,508 | -| **總計** | **1,536** | **238,303** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,010 | 104,513 | +| **總計** | **1,536** | **238,309** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index c641de71c..1e53f3fe5 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1088,3 +1088,22 @@ - **Change.** The test replaces `instance.runtime.maintain` with an event setter and waits for the watch to call it once, so no real pass begun before the swap is still running. `act()`'s own refusal is then the only one that can fire. Product code is unchanged. - **Tests:** `test_agent_dag_local_tasks.py`, 15 passed in each of 3 runs. The single test passed 5 of 5 locally before the change too. - **Files:** `test/unit_test/headless/test_agent_dag_local_tasks.py`. + +## U-20261116-14 · 2026-11-16 · Every template match in the package is stoppable · #done #executor #image + +- **What.** U-20261116-11 wrapped only `cv2_utils/template_detection` and the OCR engine in `run_control.stoppable_call`. The other match paths still made a stop wait for a native `cv2.matchTemplate` pass. This is the same change, with the trade-off the maintainer accepted for U-20261116-11: the pass finishes in the background and its result is discarded. +- **Change.** Every remaining `cv2.matchTemplate(...)` call now goes through `stoppable_call(cv2.matchTemplate, ...)`, with its arguments unchanged: 11 calls in 6 modules. + - `utils/visual_match/visual_match.py` (4). This also covers `match_autothresh`, `match_trust`, `scale_detect` and `subpixel_match`, which reuse its score map. + - `utils/color_match/color_match.py` (3) + - `utils/edge_match/edge_match.py` (1) + - `utils/rotated_match/rotated_match.py` (1) + - `utils/self_healing/frame_locators.py` (1) + - `wrapper/device_frame.py` (1) + + Outside a stoppable run or a cancellation scope each one is still a plain call. +- **Tests.** `test_stoppable_call.py` gains 2 cases, 9 in all: + - `visual_match.match_template` with a blocked `matchTemplate` ends on a stop within 2 s; + - a structural guard fails on any `cv2.matchTemplate(` call in `je_auto_control/` that does not go through `stoppable_call`, so a new match path cannot bring the waiting stop back. + + The 47 test modules that touch these matchers or self-healing, plus the complexity, broad-except and file-length gates, gave 666 passed. `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean on the package. +- **Files:** the six modules above, `test/unit_test/headless/test_stoppable_call.py`, `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). diff --git a/docs/updates/README.md b/docs/updates/README.md index ef7ade91d..494d48356 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-14 | 2026-11-16 | Every template match in the package is stoppable | #done #executor #image | [2026-11-b](2026-11-b.md) | | U-20261116-13 | 2026-11-16 | A DAG revocation test no longer races the lease watch | #incident #ci #test #agent | [2026-11-b](2026-11-b.md) | | U-20261116-12 | 2026-11-16 | M0 routing profile: background channels only, never desktop input | #done #process-memory #policy | [2026-11-b](2026-11-b.md) | | U-20261116-11 | 2026-11-16 | A stop no longer waits for an image search or OCR pass | #done #executor #ocr #image | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/color_match/color_match.py b/je_auto_control/utils/color_match/color_match.py index 670f2c82e..b03479b00 100644 --- a/je_auto_control/utils/color_match/color_match.py +++ b/je_auto_control/utils/color_match/color_match.py @@ -17,6 +17,7 @@ """ from typing import Any, List, Optional, Sequence +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.color_region.color_region import _grab_rgb, _origin, _to_rgb from je_auto_control.utils.visual_match.visual_match import ( Match, _contain_cv2_error, _nms, _resize, _select_candidates, @@ -68,9 +69,9 @@ def _channel_distance(template: Any, haystack: Any, channel: str, mask: Any = No pixels = float(mask.sum()) if mask is not None else float(t_plane.size) masked = {"mask": mask} if mask is not None else {} if channel != "h": - return cv2.matchTemplate(h_plane, t_plane, cv2.TM_SQDIFF, **masked) / (pixels * 255.0 ** 2) - direct = cv2.matchTemplate(h_plane, t_plane, cv2.TM_SQDIFF, **masked) - shifted = cv2.matchTemplate(np.mod(h_plane + 90.0, 180.0), + return stoppable_call(cv2.matchTemplate, h_plane, t_plane, cv2.TM_SQDIFF, **masked) / (pixels * 255.0 ** 2) + direct = stoppable_call(cv2.matchTemplate, h_plane, t_plane, cv2.TM_SQDIFF, **masked) + shifted = stoppable_call(cv2.matchTemplate, np.mod(h_plane + 90.0, 180.0), np.mod(t_plane + 90.0, 180.0), cv2.TM_SQDIFF, **masked) return np.minimum(direct, shifted) / (pixels * 90.0 ** 2) diff --git a/je_auto_control/utils/edge_match/edge_match.py b/je_auto_control/utils/edge_match/edge_match.py index 40d7e165f..ad807c42b 100644 --- a/je_auto_control/utils/edge_match/edge_match.py +++ b/je_auto_control/utils/edge_match/edge_match.py @@ -16,6 +16,7 @@ """ from typing import Any, List, Optional, Sequence, Tuple +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.visual_match.visual_match import ( Match, _contain_cv2_error, _haystack_gray, _haystack_gray_with_origin, _nms, _resize, _to_gray, _to_screen, @@ -44,7 +45,7 @@ def _chamfer_score_map(template_gray: Any, scene_gray: Any, distance = cv2.distanceTransform(cv2.bitwise_not(scene_edges), cv2.DIST_L2, 3).astype(np.float32) mask = (template_edges > 0).astype(np.float32) - total = cv2.matchTemplate(distance, mask, cv2.TM_CCORR) + total = stoppable_call(cv2.matchTemplate, distance, mask, cv2.TM_CCORR) score_map = 1.0 / (1.0 + total / edge_count) return score_map, (template_edges.shape[1], template_edges.shape[0]) diff --git a/je_auto_control/utils/rotated_match/rotated_match.py b/je_auto_control/utils/rotated_match/rotated_match.py index 899d15197..ad56a3353 100644 --- a/je_auto_control/utils/rotated_match/rotated_match.py +++ b/je_auto_control/utils/rotated_match/rotated_match.py @@ -18,6 +18,7 @@ from dataclasses import asdict, dataclass from typing import Any, Dict, List, Optional, Sequence, Tuple +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.visual_match.visual_match import ( _NMS_CANDIDATE_FACTOR, _NMS_CANDIDATE_MIN, _contain_cv2_error, _haystack_gray_with_origin, _method, _nms, _reject_flat_template, _resize, @@ -94,7 +95,7 @@ def _scores_at(hay: Any, tmpl: Any, scale: float, angle: float, warped, mask = _rotate_with_mask(_resize(tmpl, float(scale)), float(angle)) if warped.shape[0] > hay.shape[0] or warped.shape[1] > hay.shape[1]: return None - scores = cv2.matchTemplate(hay, warped, metric, mask=mask) + scores = stoppable_call(cv2.matchTemplate, hay, warped, metric, mask=mask) if metric == cv2.TM_SQDIFF_NORMED: scores = 1.0 - scores # lower is better for sqdiff; the maximum was the worst spot # Masked correlation over a flat window divides by zero. diff --git a/je_auto_control/utils/self_healing/frame_locators.py b/je_auto_control/utils/self_healing/frame_locators.py index 252daa82b..f50e8eb90 100644 --- a/je_auto_control/utils/self_healing/frame_locators.py +++ b/je_auto_control/utils/self_healing/frame_locators.py @@ -7,6 +7,7 @@ from time import perf_counter from typing import Any, Optional +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.cv2_utils.optional import require_cv2 from je_auto_control.utils.cv2_utils.template_detection import _to_gray from je_auto_control.utils.self_healing.evaluation_models import ( @@ -99,7 +100,7 @@ def _match(self, view: _FrameView) -> Optional[Point]: if height > frame.shape[0] or width > frame.shape[1]: return None # pylint: disable-next=no-member # reason: optional OpenCV exports these C extension symbols at runtime - scores = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED) + scores = stoppable_call(cv2.matchTemplate, frame, template, cv2.TM_CCOEFF_NORMED) # pylint: disable-next=no-member # reason: optional OpenCV exports this C extension symbol at runtime _low, score, _low_at, (x, y) = cv2.minMaxLoc(scores) if score < min(self.threshold, 1.0 - 1e-5): diff --git a/je_auto_control/utils/visual_match/visual_match.py b/je_auto_control/utils/visual_match/visual_match.py index c58956855..1e69ccefb 100644 --- a/je_auto_control/utils/visual_match/visual_match.py +++ b/je_auto_control/utils/visual_match/visual_match.py @@ -17,6 +17,7 @@ from dataclasses import asdict, dataclass from typing import Any, Callable, Dict, List, Optional, ParamSpec, Protocol, Sequence, Tuple, TypeVar +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.exception.exceptions import ( AutoControlFlatTemplateException, AutoControlScreenException, ) @@ -267,7 +268,7 @@ def _score_map_with_origin(template: ImageSource, haystack: Optional[ImageSource hay, origin_x, origin_y = _haystack_gray_with_origin(haystack, region) if tmpl.shape[0] > hay.shape[0] or tmpl.shape[1] > hay.shape[1]: return None, tmpl, origin_x, origin_y - result = cv2.matchTemplate(hay, tmpl, _method(method)) + result = stoppable_call(cv2.matchTemplate, hay, tmpl, _method(method)) if method == "sqdiff_normed": result = 1.0 - result return result, tmpl, origin_x, origin_y @@ -294,7 +295,7 @@ def match_template(template: ImageSource, *, haystack: Optional[ImageSource] = N scaled = _resize(tmpl, float(scale)) if scaled.shape[0] > hay.shape[0] or scaled.shape[1] > hay.shape[1]: continue - _, max_val, _, max_loc = cv2.minMaxLoc(cv2.matchTemplate(hay, scaled, + _, max_val, _, max_loc = cv2.minMaxLoc(stoppable_call(cv2.matchTemplate, hay, scaled, metric)) if max_val >= min_score and (best is None or max_val > best.score): best = Match(int(max_loc[0]) + origin_x, int(max_loc[1]) + origin_y, @@ -397,7 +398,7 @@ def match_template_all(template: ImageSource, *, height, width = tmpl.shape[:2] if height > hay.shape[0] or width > hay.shape[1]: return [] - result = cv2.matchTemplate(hay, tmpl, cv2.TM_CCOEFF_NORMED) + result = stoppable_call(cv2.matchTemplate, hay, tmpl, cv2.TM_CCOEFF_NORMED) candidates = _select_candidates(result, min_score, width, height, max_results, (origin_x, origin_y)) return _nms(candidates, float(nms_iou))[:int(max_results)] @@ -466,7 +467,7 @@ def _masked_scores(template: ImageSource, mask: Optional[ImageSource], hay, origin_x, origin_y = _haystack_gray_with_origin(haystack, region) if tmpl.shape[0] > hay.shape[0] or tmpl.shape[1] > hay.shape[1]: return None, tmpl, origin_x, origin_y - result = cv2.matchTemplate(hay, tmpl, cv2.TM_CCORR_NORMED, mask=msk) + result = stoppable_call(cv2.matchTemplate, hay, tmpl, cv2.TM_CCORR_NORMED, mask=msk) return np.nan_to_num(result, nan=0.0, posinf=0.0, neginf=0.0), tmpl, origin_x, origin_y diff --git a/je_auto_control/wrapper/device_frame.py b/je_auto_control/wrapper/device_frame.py index 48aaee6cd..43e479406 100644 --- a/je_auto_control/wrapper/device_frame.py +++ b/je_auto_control/wrapper/device_frame.py @@ -19,6 +19,7 @@ from pathlib import Path from typing import Any, Dict, Optional, Tuple +from je_auto_control.utils.executor.run_control import stoppable_call from je_auto_control.utils.exception.exceptions import ImageNotFoundException from je_auto_control.wrapper.device_context import DeviceError @@ -153,7 +154,7 @@ def locate_image(self, template: Any, detect_threshold: float = 0.9) -> Point: if needle.shape[0] > haystack.shape[0] or needle.shape[1] > haystack.shape[1]: raise ImageNotFoundException("template is larger than the device frame") try: - scores = cv2.matchTemplate(haystack, needle, cv2.TM_CCOEFF_NORMED) + scores = stoppable_call(cv2.matchTemplate, haystack, needle, cv2.TM_CCOEFF_NORMED) except cv2.error as error: raise ImageNotFoundException(f"cannot match template image: {error}") from error _low, best, _low_at, (left, top) = cv2.minMaxLoc(scores) diff --git a/test/unit_test/headless/test_stoppable_call.py b/test/unit_test/headless/test_stoppable_call.py index 718b442c1..4256005ae 100644 --- a/test/unit_test/headless/test_stoppable_call.py +++ b/test/unit_test/headless/test_stoppable_call.py @@ -131,3 +131,36 @@ def image_to_matches(self, frame, lang, min_confidence): assert time.monotonic() - started < 2 assert engine.slow.threads, "OCR never started" engine.slow.release.set() + + +def test_a_stop_ends_a_visual_match_stuck_in_its_match(monkeypatch): + np = pytest.importorskip("numpy") + cv2 = pytest.importorskip("cv2") + from je_auto_control.utils.visual_match import visual_match + noise = np.random.default_rng(7) + haystack = noise.integers(0, 255, (60, 80), dtype=np.uint8) + template = haystack[10:30, 20:45].copy() + slow = _Slow(value=np.zeros((41, 56), dtype=np.float32)) + monkeypatch.setattr(cv2, "matchTemplate", slow) + token = StopToken("visual-stop") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + visual_match.match_template(template, haystack=haystack) + assert time.monotonic() - started < 2 + assert slow.threads, "the match never started" + slow.release.set() + + +def test_every_template_match_in_the_package_goes_through_stoppable_call(): + """A new match path that calls ``cv2.matchTemplate`` directly would bring the waiting stop back.""" + import re + from pathlib import Path + package = Path(__file__).resolve().parents[3] / "je_auto_control" + bare = [] + for path in package.rglob("*.py"): + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + code = line.split("#", 1)[0] + if re.search(r"(? Date: Mon, 16 Nov 2026 23:57:51 +0800 Subject: [PATCH 158/161] Return at once from a Slack handler's stop, and pin the DNS-lookup stop stop() and wait_idle() called from a command handler waited out their timeout: the handler holds the turn the worker needs for its reply. They now ask and return False at once. A test also shows a stop does not wait for a blocked name lookup and nothing is sent after it, so Progress.md no longer lists that as a gap. --- Progress.md | 4 +-- architecture_explore.md | 10 +++---- docs/updates/2026-11-b.md | 15 ++++++++++ docs/updates/README.md | 1 + je_auto_control/utils/chatops/slack_bot.py | 29 +++++++++++++++---- .../test_chatops_slack_background_run.py | 28 ++++++++++++++++++ test/unit_test/headless/test_http_stop.py | 23 +++++++++++++++ 7 files changed, 97 insertions(+), 13 deletions(-) diff --git a/Progress.md b/Progress.md index a3b0580af..d3220c9d1 100644 --- a/Progress.md +++ b/Progress.md @@ -108,9 +108,9 @@ U-20261009-18 的每一個裝置面呼叫都只對假的 ADB/uiautomator2/WD 結果裡內嵌的動作清單以「參數」規則遮蔽,那些欄位不提供一次性顯示。 對話框從未在真的螢幕上顯示過,真的系統剪貼簿(`QClipboard.clear()`/`text()`)在測試裡是假物件。 `AC_approval_request` 的 `token`(請求編號)在結果畫面保持可見,但在 log 裡仍被遮蔽。 -- **stop 還叫不醒的**:已經進到後端的單一指令只剩其他未接合的原生呼叫(擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求連 TCP 交握都可中斷,只剩正在進行的 DNS 查詢不行,U-20261116-08/-10;套件內每個 `cv2.matchTemplate` 與 OCR 引擎的單次原生運算都改由 `stoppable_call` 不再等待,但運算本身在背景跑完,U-20261116-11/-14)、單一手勢內的節奏 sleep; +- **stop 還叫不醒的**:已經進到後端的單一指令只剩其他未接合的原生呼叫(擷取輸出的 shell 指令已可停止,U-20261115-23;共用 HTTP client 的請求連 TCP 交握都可中斷,正在進行的 DNS 查詢也不必等(查詢在背景跑完、之後不會送出請求),U-20261116-08/-10/-15;套件內每個 `cv2.matchTemplate` 與 OCR 引擎的單次原生運算都改由 `stoppable_call` 不再等待,但運算本身在背景跑完,U-20261116-11/-14)、單一手勢內的節奏 sleep; 非腳本分頁已傳遞協作取消;尚未檢查 token 的後端呼叫仍只能丟棄晚到結果,須逐一接合。 - ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在輪詢執行緒上的指令 handler 裡呼叫 `stop()` 也會等到逾時。沒對真的 Slack workspace 跑過。 + ChatOps 的 Slack bot:`/run` 現在在工作執行緒上跑,`/stop` 的反應受輪詢間隔限制(預設 5 秒);卡在不可中斷的後端呼叫裡的執行仍停不掉,`stop()` 逾時後回 `False`;在指令 handler 裡呼叫 `stop()`/`wait_idle()` 會立刻回 `False`、不再等到逾時(U-20261116-15)。沒對真的 Slack workspace 跑過。 新轉成可停止的等待裡,`AC_handle_file_dialog`、`AC_wait_until_app_idle`、`AC_wait_for_composition_commit`、`AC_wait_for_unlock` 與行動裝置的 `wait_for_app` 只對假探針測過。 - **WebRTC**:LAN 廣播的註冊與取消已移出 GUI 執行緒,但真的 zeroconf 的時間與名稱衝突行為只對假物件測過。 - **切換主題後那幾個事件迴圈回合內**,以被暫存的頁面為 parent 的 `QMessageBox` 會相對於隱藏的暫存 widget 定位(只影響位置)。 diff --git a/architecture_explore.md b/architecture_explore.md index a669ab7a4..c9fcdaad6 100644 --- a/architecture_explore.md +++ b/architecture_explore.md @@ -28,7 +28,7 @@ iOS(WebDriverAgent)。核心能力是滑鼠/鍵盤控制、影像辨識、 | 指標 | 數值 | | --- | ---: | | Python 模組總數(含周邊子專案) | 1,548 | -| 程式碼總行數 | 239,054 | +| 程式碼總行數 | 239,071 | | `je_auto_control/utils/` 子套件數 | 313 | | `AC_*` 動作指令數(`known_commands()` 實測) | 911 | | 套件門面 `__all__` 公開名稱數 | 1504 | @@ -562,12 +562,12 @@ socket server 有 8 MiB 讀取上限與 30 秒 handler timeout。 ### 5.4.11 伺服器、網路協定與外部整合 -> 24 個套件、約 7,786 行。 +> 24 個套件、約 7,803 行。 | 模組 | 行數 | 職責 | | --- | ---: | --- | | `utils/acme_v2/` | 617 | 完整 ACME v2 用戶端(RFC 8555),不依賴 certbot | -| `utils/chatops/` | 928 | Chat-ops bot:接收 Slack/Discord/webhook 的 slash 指令並路由到動作 | +| `utils/chatops/` | 945 | Chat-ops bot:接收 Slack/Discord/webhook 的 slash 指令並路由到動作 | | `utils/cookie_jar/` | 192 | RFC 6265 cookie jar | | `utils/email_send/` | 118 | SMTP 寄信(email 觸發器的發送端搭檔) | | `utils/events/` | 106 | 對外 CloudEvents 發送(執行生命週期事件) | @@ -1572,8 +1572,8 @@ socket 預設綁 `127.0.0.1`;資源一律用 `with`。 | `osx/` | 17 | 988 | | `autocontrol-lsp/` | 8 | 744 | | `utils/hotkey/` | 7 | 867 | -| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,010 | 104,513 | -| **總計** | **1,536** | **238,309** | +| 其餘模組(約 286 個 `utils/` 子套件 + `android/`/`ios/`/周邊小工具) | 1,010 | 104,530 | +| **總計** | **1,536** | **238,326** | `gui/agent_observation_view.py` provides the bounded read-only agent element table and DPR-1 image selection preview. `gui/agent_tasks_tab.py` owns only request editing and Actions-menu translation; business validation remains in the headless runtime. diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 1e53f3fe5..9c4b3ee2b 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1107,3 +1107,18 @@ The 47 test modules that touch these matchers or self-healing, plus the complexity, broad-except and file-length gates, gave 666 passed. `typing_contract_verify.py` was OK with and without `--extras`. Ruff and bandit were clean on the package. - **Files:** the six modules above, `test/unit_test/headless/test_stoppable_call.py`, `CHANGELOG.md`, `Progress.md`, `architecture_explore.md` (re-measured). + +## U-20261116-15 · 2026-11-16 · Two stop gaps in Progress.md, measured and closed · #done #http #chatops + +- **A name lookup.** `Progress.md` said a DNS lookup already in progress could not be stopped. That turned out to be stricter than the behaviour. + - The request runs on its helper thread, so the caller already returns on a stop: it waits at most 1 s for the thread and then raises. + - The connection the lookup leads to is refused by the stopped recorder, so nothing is sent once the lookup ends. + - New `test_http_stop.py::test_a_stop_does_not_wait_for_a_name_lookup_and_nothing_is_sent_after_it` blocks `getaddrinfo`. It shows the stop returning within 3 s, and, once the lookup is released, no request reaching the server. + - Only the lookup's own background thread runs on, the same trade-off as an image or OCR pass. `Progress.md` now says so. +- **Slack `stop()` from a handler.** Called from a command handler, `SlackBot.stop()` or `wait_idle()` waited out its whole timeout. + - The handler holds `_turn`, a plain lock, while the worker needs that same turn to post its reply, so the join could never succeed. + - The bot now records the thread holding the turn (`_turn_owner`, set and cleared inside `_handle`). From that thread, `stop()` still asks the run to stop but returns `False` at once, and `wait_idle()` returns `False` at once. The worker posts its reply when the handler gives the turn back. + - The docstring already promised `False` in this case. + - New `test_chatops_slack_background_run.py::test_stop_called_from_a_command_handler_returns_at_once`: both calls return in under 2 s, and the replies arrive in order (`halting`, then `run stopped. (the bot was stopped)`). It fails against the previous bot, where the poll blocked past its 10 s guard. +- **Tests:** all `test_chatops_*` modules, `test_r3_net_chatops.py`, `test_http_stop.py` and the complexity and broad-except gates: 88 passed. `typing_contract_verify.py` was OK and bandit was clean. +- **Files:** `je_auto_control/utils/chatops/slack_bot.py`, `test/unit_test/headless/test_chatops_slack_background_run.py`, `test/unit_test/headless/test_http_stop.py`, `Progress.md`, `architecture_explore.md` (re-measured). diff --git a/docs/updates/README.md b/docs/updates/README.md index 494d48356..236479f37 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261116-15 | 2026-11-16 | Two stop gaps in Progress.md, measured and closed | #done #http #chatops | [2026-11-b](2026-11-b.md) | | U-20261116-14 | 2026-11-16 | Every template match in the package is stoppable | #done #executor #image | [2026-11-b](2026-11-b.md) | | U-20261116-13 | 2026-11-16 | A DAG revocation test no longer races the lease watch | #incident #ci #test #agent | [2026-11-b](2026-11-b.md) | | U-20261116-12 | 2026-11-16 | M0 routing profile: background channels only, never desktop input | #done #process-memory #policy | [2026-11-b](2026-11-b.md) | diff --git a/je_auto_control/utils/chatops/slack_bot.py b/je_auto_control/utils/chatops/slack_bot.py index 7cce6910f..22d646e05 100644 --- a/je_auto_control/utils/chatops/slack_bot.py +++ b/je_auto_control/utils/chatops/slack_bot.py @@ -89,6 +89,9 @@ class SlackBot: # while it posts its reply: the answer to a /stop is posted before the # "stopped" reply of the run it ended. _turn: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) + # The thread holding ``_turn`` for a message, so stop() / wait_idle() called from a + # command handler know not to wait for a worker that needs that same turn. + _turn_owner: Optional[int] = field(default=None, init=False, repr=False) def __post_init__(self) -> None: if not self.token or not self.token.startswith("xox"): @@ -163,7 +166,9 @@ def stop(self, timeout: float = _JOIN_TIMEOUT) -> bool: whether no worker is left. ``False`` means the command is inside a call that cannot be interrupted (the worker is a daemon thread and ends with the process), or that this was called from a command - handler, which holds the turn the worker needs to post its reply. + handler, which holds the turn the worker needs to post its reply: then + the stop is requested and ``False`` comes back at once, without + waiting out ``timeout``. Until :meth:`run_forever` is called again a background command is refused rather than started. """ @@ -174,6 +179,8 @@ def stop(self, timeout: float = _JOIN_TIMEOUT) -> bool: return True if token is not None: token.stop("the bot was stopped") + if self._in_handler(): + return False # the worker posts its reply once this handler gives the turn back return self._join(worker, timeout) def wait_idle(self, timeout: float = _JOIN_TIMEOUT) -> bool: @@ -185,8 +192,14 @@ def wait_idle(self, timeout: float = _JOIN_TIMEOUT) -> bool: worker = self._worker if worker is None or not worker.is_alive(): return True + if self._in_handler(): + return False # waiting here would hold the turn the worker needs to finish return self._join(worker, timeout) + def _in_handler(self) -> bool: + """Whether this thread is dispatching a message, and so holds the turn a worker's reply needs.""" + return self._turn_owner == threading.get_ident() + @property def running_run_id(self) -> Optional[str]: """The run id of the background command in progress, or ``None``.""" @@ -212,11 +225,15 @@ def _join(worker: threading.Thread, timeout: float) -> bool: def _handle(self, text: str, message: Dict[str, Any]) -> bool: """Dispatch one message; whether it was a command.""" with self._turn: - argv = self._background_argv(text) - if argv is None: - return self._route_one(text, message) is not None - self._start_background(argv, text, message) - return True + self._turn_owner = threading.get_ident() + try: + argv = self._background_argv(text) + if argv is None: + return self._route_one(text, message) is not None + self._start_background(argv, text, message) + return True + finally: + self._turn_owner = None def _context(self, message: Dict[str, Any]) -> Dict[str, Any]: return {"slack_user": message.get("user"), "slack_ts": message.get("ts"), diff --git a/test/unit_test/headless/test_chatops_slack_background_run.py b/test/unit_test/headless/test_chatops_slack_background_run.py index bdb48b6ca..7a50e87bf 100644 --- a/test/unit_test/headless/test_chatops_slack_background_run.py +++ b/test/unit_test/headless/test_chatops_slack_background_run.py @@ -11,6 +11,7 @@ """ import json import threading +import time import pytest @@ -385,3 +386,30 @@ def test_a_failed_reply_from_the_worker_does_not_rerun_or_end_the_bot(bot, slack assert _Poll(bot).count == 1 assert bot.last_seen_ts == "2" assert script.after == ["ran"] + + +def test_stop_called_from_a_command_handler_returns_at_once(slack, script, root, monkeypatch): + """The handler holds the turn the worker needs for its reply, so stop() asks and does not wait.""" + router = register_chatops_default_commands(CommandRouter()) + outcome, holder = {}, [] + + def halt(_argv, _context): + started = time.monotonic() + outcome["stopped"] = holder[0].stop(timeout=_WAIT) + outcome["idle"] = holder[0].wait_idle(timeout=_WAIT) + outcome["elapsed"] = time.monotonic() - started + return CommandResult(text="halting") + + router.register("halt", halt) + made = _make_bot(slack, monkeypatch, router) + holder.append(made) + try: + _start_long_run(made, slack, script) + slack.say(2, "/halt") + _Poll(made) + assert outcome["stopped"] is False and outcome["idle"] is False + assert outcome["elapsed"] < 2, "stop() from a handler waited out its timeout" + assert slack.wait_for_posts(2) + assert slack.texts() == ["halting", "run stopped. (the bot was stopped)"] + finally: + assert made.stop(timeout=_WAIT) is True diff --git a/test/unit_test/headless/test_http_stop.py b/test/unit_test/headless/test_http_stop.py index a354f085e..1142f1564 100644 --- a/test/unit_test/headless/test_http_stop.py +++ b/test/unit_test/headless/test_http_stop.py @@ -222,3 +222,26 @@ def held(read, write, error, timeout): pytest.skip("this loopback connect completed at once, so there was no handshake to wait on") assert time.monotonic() - started < 3 assert not silent.requested.is_set(), "the request was sent after the stop" + + +def test_a_stop_does_not_wait_for_a_name_lookup_and_nothing_is_sent_after_it(silent, monkeypatch): + """A lookup cannot be interrupted, but the call does not wait for it and sends nothing once it ends.""" + looked_up, release = threading.Event(), threading.Event() + real = socket.getaddrinfo + + def slow_lookup(*args, **kwargs): + looked_up.set() + release.wait(10) + return real(*args, **kwargs) + + monkeypatch.setattr(http_client.socket, "getaddrinfo", slow_lookup) + token = StopToken("http-lookup") + _later(lambda: token.stop("test")) + started = time.monotonic() + with stoppable_run(token=token), pytest.raises(ExecutionStopped): + _call(silent.url) + assert time.monotonic() - started < 3, "the stop waited for the lookup" + assert looked_up.is_set() + release.set() # the lookup finishes after the stop ... + time.sleep(0.5) + assert not silent.requested.is_set(), "... and nothing is sent once it has" From a8596ec25ea317a9009f6d322c8558b31d9a99a6 Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 17 Nov 2026 08:50:07 +0800 Subject: [PATCH 159/161] Close M0: the first background target is the owned fixture The maintainer chose to keep the repository's own fixture as the first target and pick a real application only after M1's native acceptance runs. --- Progress.md | 4 ++-- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Progress.md b/Progress.md index d3220c9d1..f88850f3d 100644 --- a/Progress.md +++ b/Progress.md @@ -644,7 +644,7 @@ browser adapter 從受管頁面取得欄位、透過 DOM 提交,再驗證新 `WIP` — 內部 `utils/process_memory/` 已有不可變身分/probe、區段與位元組預算、 序號一致性檢查、語意欄位白名單及失敗 handle 保留重試。契約與 fixture 協定見 -[process_memory_contract.md](docs/process_memory_contract.md)。M0 的 profile、結果型別與禁用桌面輸入的路由規則已完成(U-20261116-12,`utils/process_memory/background_profile.py`);M1 尚未完成, +[process_memory_contract.md](docs/process_memory_contract.md)。M0 已完成(profile、結果型別與禁用桌面輸入的路由規則 U-20261116-12,`utils/process_memory/background_profile.py`;第一個目標為自有 fixture,U-20261117-01);M1 尚未完成, 已有自有 fixture 的固定緩衝區與有界管線控制協定,測試僅驗證本機資料配置及背景子程序通訊。 bootstrap 的 PID、位址、來源雜湊與 launch nonce 都是未驗證自報資訊,不能充當 OS 出生身分或可信 resolver。 typed Windows provider 已有有界查詢/讀取、原生身分事實與保留 handle 的注入測試; @@ -655,7 +655,7 @@ resolver 已能透過保留 handle 取得主映像基址與大小並做有預算 fixture 的原生身分核對(標頭挑戰已有,U-20261115-18,只在本行程內驗過)與頁面故障注入、runtime grant/helper 生命週期及公開入口;M2 也仍缺實際應用版本 adapter。原生驗收固定列於本檔上方。 -1. **M0:能力盤點與範圍契約。**(profile/路由規則已完成,U-20261116-12;之後選定提供正式背景介面的應用仍待決定)先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 +1. **M0:能力盤點與範圍契約。**(已完成:profile/路由規則 U-20261116-12;維護者 2026-11-17 決定第一個目標只用自有 fixture,真實應用待 M1 原生驗收跑通後再選,U-20261117-01)先列 Windows 的 UI/OS/應用操作矩陣,每項記錄 讀取來源、執行介面、權限、是否全背景、支援版本、驗證方式與不支援原因。 第一個目標採自有 fixture 程序,之後選一個提供正式背景介面的應用;不能先承諾任意軟體。 完成條件:profile、上述結果型別及禁用桌面輸入的路由規則具體可審閱,既有桌面路徑不被暗中改寫。 diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 9c4b3ee2b..1eb74cf0a 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1122,3 +1122,10 @@ - New `test_chatops_slack_background_run.py::test_stop_called_from_a_command_handler_returns_at_once`: both calls return in under 2 s, and the replies arrive in order (`halting`, then `run stopped. (the bot was stopped)`). It fails against the previous bot, where the poll blocked past its 10 s guard. - **Tests:** all `test_chatops_*` modules, `test_r3_net_chatops.py`, `test_http_stop.py` and the complexity and broad-except gates: 88 passed. `typing_contract_verify.py` was OK and bandit was clean. - **Files:** `je_auto_control/utils/chatops/slack_bot.py`, `test/unit_test/headless/test_chatops_slack_background_run.py`, `test/unit_test/headless/test_http_stop.py`, `Progress.md`, `architecture_explore.md` (re-measured). + +## U-20261117-01 · 2026-11-17 · M0 closed: the first target is the owned fixture · #done #process-memory #decision + +- **Decision (maintainer, 2026-11-17).** M0's remaining step was to choose the first target with an official background interface. The first target stays the repository's own fixture process. A real application is chosen after M1's native acceptance is unpaused and the full flow has run end to end. No third-party software is committed to now. +- **Options not taken:** LibreOffice through UNO in headless mode, Excel through COM with `Visible=False`, and a Windows service through the Service Control Manager. +- **Change:** `Progress.md` marks M0 complete: the routing profile of U-20261116-12 plus this choice. M1 onward and the native-acceptance pause are unchanged. No code changed. +- **Files:** `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index 236479f37..b03195327 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261117-01 | 2026-11-17 | M0 closed: the first target is the owned fixture | #done #process-memory #decision | [2026-11-b](2026-11-b.md) | | U-20261116-15 | 2026-11-16 | Two stop gaps in Progress.md, measured and closed | #done #http #chatops | [2026-11-b](2026-11-b.md) | | U-20261116-14 | 2026-11-16 | Every template match in the package is stoppable | #done #executor #image | [2026-11-b](2026-11-b.md) | | U-20261116-13 | 2026-11-16 | A DAG revocation test no longer races the lease watch | #incident #ci #test #agent | [2026-11-b](2026-11-b.md) | From d97f09c75ea8e635b772117f3627624f522c4fcf Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 17 Nov 2026 08:52:42 +0800 Subject: [PATCH 160/161] Decide the deployment plan's rollback: a branch at P, not a reset The maintainer chose a rollback branch at the pre-deployment commit so dev keeps its history; the helper, Chromium, profile and multi-host items still need the production machine's details. --- Progress.md | 2 +- docs/superpowers/plans/2026-11-01-deployment-rollback.md | 5 +++-- docs/updates/2026-11-b.md | 7 +++++++ docs/updates/README.md | 1 + 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Progress.md b/Progress.md index f88850f3d..4542f235a 100644 --- a/Progress.md +++ b/Progress.md @@ -255,7 +255,7 @@ Jeffrey_RPA 的 test_je_facade → 推送 `dev`(會觸發 je_auto_control_dev - 核對既有瀏覽器呼叫者各自的環境是否已安裝相容 `je_web_runner`。舊 bridge 依賴呼叫環境的 SDK,不會自動使用受管 helper;缺套件時應保留明確失敗,不能退回其他瀏覽器引擎。 - `DECIDE`:部署/回復計畫已寫成 `docs/superpowers/plans/2026-11-01-deployment-rollback.md`(未執行); - 其中標「待決定」的回復方式、helper 直譯器、套件鎖、Chromium 與主機 profile 待維護者批准。 + 回復方式已決定(建回復分支再切換,U-20261117-02);其餘標「待決定」的 helper 直譯器、套件鎖、Chromium、主機 profile 與多主機名冊待維護者提供並批准。 正式變更前仍須依該計畫安排主工作樹、既有 Jeffrey_RPA 批次與服務的部署/回復;不能直接將 功能工作樹當作已部署版本,也不能替換共用 `.venv` 或自動重啟正式服務。 舊版回復須先取得輸入退場確證,審閱相符的升級前狀態及原位置,並從全部舊版任務根目錄 diff --git a/docs/superpowers/plans/2026-11-01-deployment-rollback.md b/docs/superpowers/plans/2026-11-01-deployment-rollback.md index 89eabfd0e..010d3ef95 100644 --- a/docs/superpowers/plans/2026-11-01-deployment-rollback.md +++ b/docs/superpowers/plans/2026-11-01-deployment-rollback.md @@ -55,8 +55,9 @@ 3. 新版建立、舊版不認識的私有檔案(例如新版私有根下的快取)必須從舊版會掃描的任務根目錄中排除; 舊版不能沿用新版的資料庫或快取。若無法證明舊版不會讀到它們,停止並交維護者審閱,不直接回復。 4. 主工作樹回到 `P`。這一步會改寫工作樹檔案,所以先確認沒有他人的未提交修改(同第 2 節第 4 點)。 - **待決定**:回復方式由維護者選定,例如把本機 `dev` 重設到 `P`,或建立指向 `P` 的回復分支並切換過去; - 兩者都不能遺失未提交的工作。 + **已決定**(維護者,2026-11-17):建立指向 `P` 的回復分支(`rollback/<日期>-

`)並切換過去, + 本機 `dev` 留在 `T` 不動、不改寫歷史;要再前進時切回 `dev` 即可。切換前照第 2 節第 4 點確認沒有他人的 + 未提交修改,不能遺失未提交的工作。不採用把本機 `dev` 重設到 `P` 的做法。 5. 重跑第 3 節第 4 點的驗證,並比對來源/成品雜湊與 `P` 一致。 ## 5. 瀏覽器 helper 與受管 Chromium(P4) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 1eb74cf0a..18dbcf4ad 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1129,3 +1129,10 @@ - **Options not taken:** LibreOffice through UNO in headless mode, Excel through COM with `Visible=False`, and a Windows service through the Service Control Manager. - **Change:** `Progress.md` marks M0 complete: the routing profile of U-20261116-12 plus this choice. M1 onward and the native-acceptance pause are unchanged. No code changed. - **Files:** `Progress.md`. + +## U-20261117-02 · 2026-11-17 · The deployment plan's rollback method is decided · #decision #deployment + +- **Decision (maintainer, 2026-11-17).** This settles §4 of `docs/superpowers/plans/2026-11-01-deployment-rollback.md`, the rollback of the production main worktree to the pre-deployment commit `P`. The rollback creates a branch pointing at `P` (`rollback/-`) and switches to it. Local `dev` stays at `T` and no history is rewritten; moving forward again is a switch back to `dev`. The check that no other session has uncommitted changes still comes first, and resetting local `dev` to `P` is not used. +- **Not decided:** §5, the browser helper interpreter, package lock, managed Chromium version and location, and host profile; and §6, the participating hosts, endpoints, and host-credential issuance and revocation. These need facts about the production machine and stay with the maintainer. +- **Change:** the plan's §4 says "已決定" with the chosen method, and the `DECIDE` line in `Progress.md` lists only the remaining items. Nothing was deployed or rolled back; the plan is still not executed. +- **Files:** `docs/superpowers/plans/2026-11-01-deployment-rollback.md`, `Progress.md`. diff --git a/docs/updates/README.md b/docs/updates/README.md index b03195327..ef3be490a 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261117-02 | 2026-11-17 | The deployment plan's rollback method is decided | #decision #deployment | [2026-11-b](2026-11-b.md) | | U-20261117-01 | 2026-11-17 | M0 closed: the first target is the owned fixture | #done #process-memory #decision | [2026-11-b](2026-11-b.md) | | U-20261116-15 | 2026-11-16 | Two stop gaps in Progress.md, measured and closed | #done #http #chatops | [2026-11-b](2026-11-b.md) | | U-20261116-14 | 2026-11-16 | Every template match in the package is stoppable | #done #executor #image | [2026-11-b](2026-11-b.md) | From 229bb33d8862ed147dc0a62224f13c6bfdadf06f Mon Sep 17 00:00:00 2001 From: JeffreyChen Date: Tue, 17 Nov 2026 10:33:05 +0800 Subject: [PATCH 161/161] Retry a presence-source drain inspect that missed its 0.25 s cap Windows 3.12 failed a presence test at an inspect that only waits for the observer to drain; like check, it shares the request cap and changes nothing, so a missed deadline is retried. --- docs/updates/2026-11-b.md | 8 +++++++ docs/updates/README.md | 1 + .../headless/test_agent_presence_windows.py | 21 +++++++++++++++++-- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/updates/2026-11-b.md b/docs/updates/2026-11-b.md index 18dbcf4ad..2ad4f1eec 100644 --- a/docs/updates/2026-11-b.md +++ b/docs/updates/2026-11-b.md @@ -1136,3 +1136,11 @@ - **Not decided:** §5, the browser helper interpreter, package lock, managed Chromium version and location, and host profile; and §6, the participating hosts, endpoints, and host-credential issuance and revocation. These need facts about the production machine and stay with the maintainer. - **Change:** the plan's §4 says "已決定" with the chosen method, and the `DECIDE` line in `Progress.md` lists only the remaining items. Nothing was deployed or rolled back; the plan is still not executed. - **Files:** `docs/superpowers/plans/2026-11-01-deployment-rollback.md`, `Progress.md`. + +## U-20261117-03 · 2026-11-17 · Two presence-source drain inspects retry a missed deadline · #incident #ci #test #agent + +- **Run.** Quality run 43991182772 on `d97f09c7` (PR #552): Windows 2022 / Python 3.12 failed `test_agent_presence_windows.py::test_timeout_during_fresh_native_poll_cannot_create_even_a_temporary_late_lease`, at `source.request('inspect', {})` with `physical presence request deadline exhausted`. The merge waiting on that head was not done. +- **Cause.** After unblocking the fake native poll, the test sends an `inspect` only to wait until the observer has drained what was blocked. Like `check` (U-20261116-01), that request shares the source's 0.25 s cap, so a slow runner can miss it. `inspect` reads passive state and changes nothing. +- **Change.** A new `settled(source)` helper retries an `inspect` that missed its deadline, or that found the source busy, for up to 5 s, as `check` does. It replaces the two drain calls (lines 175 and 223). The inspects that test the deadline, the capacity limit or the not-started path are unchanged. +- **Tests:** `test_agent_presence_windows.py`, 26 passed in each of 3 runs. +- **Files:** `test/unit_test/headless/test_agent_presence_windows.py`. diff --git a/docs/updates/README.md b/docs/updates/README.md index ef3be490a..ebdd37e5b 100644 --- a/docs/updates/README.md +++ b/docs/updates/README.md @@ -58,6 +58,7 @@ In the same commit: delete the item from `Progress.md`, add a `#done` entry here | ID | Date | Title | Tags | Batch | |---|---|---|---|---| +| U-20261117-03 | 2026-11-17 | Two presence-source drain inspects retry a missed deadline | #incident #ci #test #agent | [2026-11-b](2026-11-b.md) | | U-20261117-02 | 2026-11-17 | The deployment plan's rollback method is decided | #decision #deployment | [2026-11-b](2026-11-b.md) | | U-20261117-01 | 2026-11-17 | M0 closed: the first target is the owned fixture | #done #process-memory #decision | [2026-11-b](2026-11-b.md) | | U-20261116-15 | 2026-11-16 | Two stop gaps in Progress.md, measured and closed | #done #http #chatops | [2026-11-b](2026-11-b.md) | diff --git a/test/unit_test/headless/test_agent_presence_windows.py b/test/unit_test/headless/test_agent_presence_windows.py index 7f0b35647..37b99a4c3 100644 --- a/test/unit_test/headless/test_agent_presence_windows.py +++ b/test/unit_test/headless/test_agent_presence_windows.py @@ -86,6 +86,23 @@ def check(source, token): pytest.fail('synthetic observer never answered a check inside its deadline') +def settled(source): + # An ``inspect`` that only waits for the observer to have drained what was + # blocked. It shares the 0.25 s cap, reads passive state and changes nothing, + # so a deadline miss on a slow runner is retried like ``check`` + # (Windows 3.12, run 43991182772). + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + try: + return source.request('inspect', {}) + except AgentControlBusy: + threading.Event().wait(0.001) + except AgentTaskError as error: + if 'deadline exhausted' not in str(error): + raise + pytest.fail('synthetic observer never answered an inspect inside its deadline') + + def test_inert_inspection_does_not_create_a_native_api_or_thread(): api = FakeAPI() source = actor(api) @@ -172,7 +189,7 @@ def test_timed_out_request_does_not_allocate_a_late_lease(): source.request('acquire', {}, timeout=0.05) api.block.clear() api.allow.set() - source.request('inspect', {}) + settled(source) assert len(source._state._leases) == 1 assert check(source, first)['state'] == 'monitoring' finally: @@ -220,7 +237,7 @@ def test_timeout_during_fresh_native_poll_cannot_create_even_a_temporary_late_le assert api.blocked.is_set() api.block.clear() api.allow.set() - source.request('inspect', {}) + settled(source) assert calls == [] finally: api.allow.set()