Skip to content

fix(WeaselIPC, WeaselServer): 客戶端 IPC 改為有界等待,托盤刷新移至專用執行緒(#1909 後續) - #1914

Open
Wujidadi wants to merge 6 commits into
rime:masterfrom
Wujidadi:fix/ipc-bounded-wait
Open

Wujidadi wants to merge 6 commits into
rime:masterfrom
Wujidadi:fix/ipc-bounded-wait

Conversation

@Wujidadi

@Wujidadi Wujidadi commented Aug 22, 2026 •

Copy link
Copy Markdown

概要

補 #1909 的客戶端那一半,與已合併的 #1912 互補。

#1912 把托盤刷新移到伺服器訊息執行緒,斷開了「explorer 工作列執行緒等管線回應 ↔ WeaselServer 管線工作執行緒等 Shell_NotifyIcon」的死結環,解決了最常見的 7~8 秒凍結。
但 WeaselIPC 客戶端本身仍是無限等待:TSF 模組載入於每個宿主行程,焦點切換與按鍵的 IPC 往返都跑在宿主 UI 執行緒上,只要伺服器因任何原因停頓,宿主視窗就被一起拖死。
本 PR 讓跑在宿主執行緒上的客戶端 IPC 一律有上限,伺服器端呼叫路徑維持原行為。

現況問題(WeaselIPC/PipeChannel.cpp)

  1. _Connect() 以 while (_Invalid(pipe = _TryConnect())) ::WaitNamedPipe(name, 500); 無限重試——伺服器忙到掛不出管線執行個體時,宿主 UI 執行緒永遠等下去。
  2. _Receive()/_WritePipe() 用同步 ReadFile/WriteFile,無逾時;連上之後伺服器不回應即死等(WeaselIPC 客戶端在宿主程式 UI 執行緒上無限等待伺服器,切換視窗時造成卡頓或視窗凍結 7~8 秒 #1909 與 weasel.dll 导致应用进程卡死,附详细堆栈信息 #1878 的傾印都停在這裡的 WaitForSingleObject(hPipe, INFINITE))。
  3. _WritePipe() 內的 FlushFileBuffers 在具名管線上會等到對端讀走才返回,伺服器忙碌時成為額外阻塞點;request/response 模式已有同步點,此呼叫無必要。

#1912 之後仍會觸發上述等待的情境:

  • 部署、SyncUserData、大型 userdb 寫入等使 g_api_mutex 長時間被持有。
  • RimeWithWeaselHandler::FocusIn → _UpdateUI() 仍在管線工作執行緒上呼叫 m_ui->Hide()/m_ui->Update();後者在 ctx/status 改變時會走 WeaselPanel::Refresh() 的 SetWindowPos,而候選視窗屬伺服器訊息執行緒,跨執行緒 SetWindowPos/ShowWindow 是同步送訊息。若訊息執行緒此刻正在 Shell_NotifyIcon(內部 SendMessageTimeout 帶 SMTO_BLOCK,期間不處理送入訊息),原本的環仍可短暫成立。
  • 第三方掛鉤(防毒)包覆管線 I/O 拉長處理時間。

修改內容

提交依主題分為三組,可獨立審閱:

1. WeaselIPC 客戶端有界等待

全部收斂在 WeaselIPC,不動 TSF 端語義:

  • _Connect() 改為 fail-fast:一次連不上即丟 ERROR_PIPE_BUSY,由既有 _Ensure() 接住回傳失敗;移除 WaitNamedPipe 迴圈。
  • 管線以 FILE_FLAG_OVERLAPPED 開啟;新增 _WaitIo() 對讀寫套 WaitForSingleObject 逾時,逾時即 CancelIoEx 視同斷線。ERROR_MORE_DATA 兩段式讀取語義保留。
  • 移除 _WritePipe() 的 FlushFileBuffers。
  • _ConnectServerPipe() 配合改用 OVERLAPPED 的 ConnectNamedPipe(等待仍為 INFINITE),並修掉失敗路徑的控制代碼洩漏。
  • _WritePipe()/_Receive()/Transact() 新增 timeout_ms 參數,預設 INFINITE,伺服器端呼叫不受影響。
  • 客戶端逾時依指令性質分兩級(WeaselClientImpl.cpp 的 _TimeoutForCommand()):
    • 組字/按鍵路徑(真實按鍵的 PROCESS_KEY_EVENT、COMMIT、選字、翻頁等):kClientIoTimeoutMs,確保按鍵不因短暫忙碌被放行。
    • 焦點/通知路徑(ECHO、FOCUS_IN/FOCUS_OUT、START_SESSION/END_SESSION、START_MAINTENANCE/END_MAINTENANCE、UPDATE_INPUT_POS、TRAY_COMMAND,以及 OnSetThreadFocus 送出的 keycode 0 焦點刷新探測):kClientFocusTimeoutMs,漏掉一次下次事件自動補上。

失敗路徑:所有逾時/錯誤以 DWORD 例外丟出,由 ClientImpl::_SendMessage 既有的 catch (DWORD) 接住回 0,輸入法安靜降級(該次按鍵放行、下次自動重連),宿主程式不受影響。

2. _Send() 重連後的重送

上游 c9938e7 已讓 _Send() 的重送改用 _Reconnect() 後的新控制代碼,但 _GetPipeHandle() 回傳 HANDLE*,直接傳給 _WritePipe(HANDLE, ...) 會隱式轉成 void*,寫入的對象是指標本身而非管線,重送仍必定失敗。
本 PR 改傳 *_GetPipeHandle()。

3. 托盤改由專用執行緒擁有(#1912 的後續)

#1912 把 Shell_NotifyIcon 移到伺服器訊息執行緒,但訊息執行緒同時擁有候選視窗:管線工作執行緒在 FocusIn → _UpdateUI() 仍會對候選視窗做跨執行緒 ShowWindow/SetWindowPos,同步送訊息給訊息執行緒;而 Shell_NotifyIcon 內部以 SMTO_BLOCK 等工作列、期間不處理送入訊息。當工作列 UI 執行緒正在等管線回應時,環仍可能成立(只在焦點切換伴隨 UI 狀態改變時,窗口比原本窄)。

  • WeaselTrayIcon 在專用托盤執行緒上建立 CSystemTray 的隱藏視窗並執行該執行緒的訊息迴圈,所有 CSystemTray 操作(刷新、托盤通知、工作列重建、右鍵選單)都在這個執行緒串行處理,訊息執行緒不再呼叫 Shell_NotifyIcon,也不與托盤執行緒共用鎖。
  • RequestRefresh() 只存快照並以 PostMessage 喚醒托盤執行緒,待處理請求合併後套用;DisableRefresh()/解構子送出結束訊息並 join,圖示在托盤執行緒移除。
  • 右鍵選單改以 TPM_RETURNCMD 由托盤視窗擁有,選擇結果以 PostMessage(WM_COMMAND) 轉交伺服器主視窗,選單訊息不再同步送往訊息執行緒。
  • 移除因此無用的 WM_WEASEL_SERVICE_NOTIFY、ServerImpl::OnServiceNotifyMessage、Server::SetTrayRefreshCallback。
  • 移除 _RefreshTrayIcon() 對 explorer.exe 延遲 100 ms 另開執行緒的「Dangerous, don't touch」繞道:回呼已不阻塞,對任何客戶端同步呼叫皆安全。

第一版的托盤狀態鎖 m_tray_mutex 會讓訊息執行緒在托盤通知時等待正卡在 Shell_NotifyIcon 的托盤執行緒(感謝 @selcomad77 的隔離驗證),最後一個提交改為上述執行緒歸屬並移除該鎖。
若維護者希望保留 #1912 的訊息執行緒結構,第 3 組提交可單獨拆出另議。

逾時值

目前提交的值為 kClientIoTimeoutMs = 500、kClientFocusTimeoutMs = 25,是在 #1909 的環境(Windows 11 25H2、0.17.4)實測肉眼無感且輸入正常的值。
這兩個常數開放討論:若偏好保守,可改為焦點 100 ms/按鍵 1000~2000 ms,或改成可由 weasel.yaml 設定;我可依回饋調整。

測試

  • Windows 11 25H2(build 26200)、x64 自建版,連續使用 2026-08-09 至 2026-08-22:多開視窗、快速點擊工作列切換,凍結消失;VS Code、Windows Terminal、檔案總管輸入正常;候選視窗、切換中英、部署通知行為不變。
  • 與 fix(WeaselServer): avoid tray refresh blocking IPC pipe #1912 同時套用(合入 d73f629 後重建)亦正常。
  • 托盤執行緒歸屬:比照 @selcomad77 的方法,直接編譯 WeaselTrayIcon.cpp 與 SystemTraySDK.cpp,保留實際隱藏視窗與訊息迴圈,僅以事件閘門替換 Shell_NotifyIcon、TrackPopupMenu、LoadMenu。
    Shell 阻塞期間投遞托盤通知後,主執行緒仍處理探針訊息(第一版不處理);右鍵選單在托盤執行緒彈出、選擇結果送達主視窗;結束時等待進行中的刷新,圖示在托盤執行緒移除。
  • 托盤執行緒歸屬版本於 2026-11-24 在同一台機器上實測:托盤右鍵選單各項、雙擊、中英切換時的圖示更新皆正常。
  • 未測:ARM64、Win32 宿主(32 位元程式載入 32 位元 weasel.dll)——程式碼路徑相同,但未在實機驗證。(我沒有這種實機😭)

相關

🤖 Generated with Claude Code

The TSF module is loaded into every text-input process, and focus changes make a synchronous round trip to WeaselServer on the host's UI thread.
The unbounded retry loop in `_Connect()` and the blocking reads/writes without timeout in `_Receive()`/`_WritePipe()` freeze the whole window for seconds whenever the server is busy: the window greys out and stops responding, consistently across VS Code, File Explorer and Windows Terminal, while Alt+Tab is unaffected.

All changes stay inside WeaselIPC; server-side calls keep the old behavior because `timeout_ms` defaults to `INFINITE`:
- `_Connect()` fails fast: the `WaitNamedPipe` loop is removed, a single failed attempt throws `ERROR_PIPE_BUSY`, and the existing `_Ensure()` handles it.
- The pipe is opened with `FILE_FLAG_OVERLAPPED`; the new `_WaitIo()` applies a `WaitForSingleObject` timeout to reads and writes, and a timeout calls `CancelIoEx` and is treated as a disconnect. The two-step `ERROR_MORE_DATA` read is preserved.
- `FlushFileBuffers` is removed from `_WritePipe()`.
- `_ConnectServerPipe()` switches to `OVERLAPPED` accordingly and no longer leaks the handle on failure.

Client timeouts are chosen per command by `_TimeoutForCommand()`:
- Compose/keystroke commands keep `kClientIoTimeoutMs = 500` so keys are not passed through by mistake.
- Focus/notification commands, including the keycode 0 focus probe sent by `OnSetThreadFocus`, use `kClientFocusTimeoutMs = 25`; a missed one self-heals on the next event, so window switching stays imperceptible.

Failures go through the existing `catch (DWORD)`, so the IME degrades quietly (that key is passed through and the next call reconnects) and the host application is unaffected.
Copilot AI lite review requested due to automatic review settings August 22, 2026 12:07

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR follows up on #1909/#1912 by (1) making WeaselIPC client-side pipe operations bounded (so host-app UI threads don’t block indefinitely when WeaselServer is busy) and (2) moving tray refresh execution off the server message thread to further reduce deadlock risk involving Explorer/taskbar interactions.

Changes:

  • Add client-side IPC timeouts via overlapped pipe I/O and per-command timeout selection (focus vs keystroke paths).
  • Fix resend-after-reconnect to use the new pipe handle instead of the stale one.
  • Move tray icon refresh to a dedicated thread and remove the prior server-message-thread refresh callback/WM message path and the explorer-specific delayed workaround.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
WeaselServer/WeaselTrayIcon.h Introduces dedicated tray refresh thread plumbing (thread member, API changes).
WeaselServer/WeaselTrayIcon.cpp Implements coalesced refresh processing on a dedicated thread and shutdown/join behavior.
WeaselServer/WeaselServerApp.cpp Removes server refresh callback wiring; uses direct RequestRefresh() + DisableRefresh().
WeaselIPCServer/WeaselServerImpl.h Removes WM_WEASEL_SERVICE_NOTIFY handler and tray refresh callback plumbing.
WeaselIPCServer/WeaselServerImpl.cpp Removes tray refresh message handler and Server::SetTrayRefreshCallback implementation.
WeaselIPC/WeaselClientImpl.cpp Adds _TimeoutForCommand() and applies bounded timeouts to client Transact.
WeaselIPC/PipeChannel.cpp Implements overlapped connect/read/write + bounded wait/cancel behavior and server-side overlapped ConnectNamedPipe.
RimeWithWeasel/RimeWithWeasel.cpp Removes the explorer-specific delayed refresh workaround (now safe to call synchronously).
include/WeaselIPC.h Removes WM_WEASEL_SERVICE_NOTIFY and Server::SetTrayRefreshCallback from the public interface.
include/PipeChannel.h Adds timeout constants and timeout-capable Transact/_Send/_ReceiveResponse API surface.
Suppressed comments (2)

WeaselIPC/PipeChannel.cpp:101

  • _WaitIo can block indefinitely after a timeout/WAIT_FAILED because it unconditionally calls WaitForSingleObject(INFINITE) after CancelIoEx without checking whether CancelIoEx actually succeeded (or why it failed). If CancelIoEx fails unexpectedly, the intended bounded-wait behavior can be lost. Handle CancelIoEx failure explicitly and preserve the original wait error when throwing.
  if (wait != WAIT_OBJECT_0) {
    ::CancelIoEx(pipe, &ov);
    ::WaitForSingleObject(ov.hEvent, INFINITE);
    _ThrowCode(wait == WAIT_TIMEOUT ? static_cast<DWORD>(ERROR_TIMEOUT)
                                    : ::GetLastError());

WeaselIPC/PipeChannel.cpp:177

  • In _ConnectServerPipe, the overlapped ConnectNamedPipe wait ignores the return value of WaitForSingleObject. If the wait fails (e.g., invalid event handle), the code proceeds to GetOverlappedResult and can report a confusing error. Check the wait result and fail/close the pipe handle immediately on WAIT_FAILED.
  if (!ok && err == ERROR_IO_PENDING) {
    ::WaitForSingleObject(op.ov.hEvent, INFINITE);
    DWORD n = 0;

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread WeaselIPC/PipeChannel.cpp
Comment on lines +19 to +26
struct OverlappedOp {
OVERLAPPED ov;
OverlappedOp() : ov() { ov.hEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); }
~OverlappedOp() {
if (ov.hEvent)
::CloseHandle(ov.hEvent);
}
};
Comment thread WeaselServer/WeaselTrayIcon.cpp Outdated
state = m_pending_state;
m_refresh_pending = false;
m_refresh_in_progress = true;
Refresh(state);
- `OverlappedOp` throws immediately when `CreateEvent` fails instead of waiting on a null event later.
- `_WaitIo()` saves the original timeout/failure error code before `CancelIoEx` and the second wait, so later calls no longer overwrite it.
  The second wait is still required: the `OVERLAPPED` lives on the caller's stack and must not go out of scope before the I/O completes, and the only failure of `CancelIoEx` (`ERROR_NOT_FOUND`) means the I/O has already completed and the event is signaled.
- `_ConnectServerPipe()` checks the result of `WaitForSingleObject` and on failure cancels the I/O, closes the pipe and throws.
- `_Receive()` closes the client's pipe connection on failure, including timeout: an abandoned reply would otherwise stay in the pipe and be read as the reply to the next request. The next transaction reconnects automatically, and the server-side worker thread cleans up when its read or write fails.
… message threads

`Refresh()` modifies `CSystemTray` state (`m_tnd`, `m_bHidden`, etc.) on the tray thread, while the message thread still touches the same state on taskbar re-creation (`InstallIconPending()`) and tray notifications (`OnTrayNotification()`).
All three entry points take `m_tray_mutex`; it is recursive because the modal loop of the tray menu may dispatch a taskbar re-creation while the lock is held.
`CSystemTray::InstallIconPending()` becomes virtual so it can be overridden.
Wujidadi added a commit to Wujidadi/weasel that referenced this pull request Aug 22, 2026
- `OverlappedOp` 於 `CreateEvent` 失敗時立即拋出,避免後續以空事件等待。
- `_WaitIo()` 在 `CancelIoEx` 與第二次等待之前先保存逾時/失敗的原始錯誤碼,不再被後續呼叫覆寫;
  第二次等待仍為必要:`OVERLAPPED` 位於呼叫端堆疊,I/O 未完成前不得返回,`CancelIoEx` 唯一的失敗情境(`ERROR_NOT_FOUND`)代表 I/O 已完成、事件已觸發。
- `_ConnectServerPipe()` 檢查 `WaitForSingleObject` 結果,失敗即取消 I/O、關閉管線並拋出。
- `_Receive()` 失敗(含逾時)時關閉客戶端的管線連線:被放棄的回應否則會留在管線中,成為下一筆請求讀到的回應;下一次交易自動重連,伺服器端工作執行緒於讀寫失敗時自行收尾。
@Wujidadi

Copy link
Copy Markdown
Author

已依 Copilot 的審查補了兩個提交(8d429d9、1a853c7):

WeaselIPC/PipeChannel.cpp

  • OverlappedOp:CreateEvent 失敗即拋出。
  • _WaitIo():在 CancelIoEx 之前先保存逾時/失敗的原始錯誤碼,不再被第二次等待覆寫。第二次 WaitForSingleObject(INFINITE) 保留:OVERLAPPED 位於呼叫端堆疊,I/O 未完成前不能返回;CancelIoEx 唯一會失敗的情境是 I/O 已完成(ERROR_NOT_FOUND),此時事件已觸發、等待立即返回,不會無限阻塞。
  • _ConnectServerPipe():檢查 WaitForSingleObject 結果,失敗即取消 I/O、關閉管線並拋出。
  • 另補一個審查未提、但我自查發現的問題:_Receive() 逾時後原本未關閉連線,被放棄的回應會留在管線裡成為下一筆請求的回應。現在 _Receive() 失敗即關閉客戶端連線,下一次交易自動重連;伺服器端 _ProcessPipeThread 本就在讀寫失敗時 _FinalizePipe。

WeaselServer/WeaselTrayIcon.*

  • Refresh()(托盤執行緒)、InstallIconPending()(工作列重建)、OnTrayNotification()(托盤通知)三個進入點一律持同一把 recursive mutex;CSystemTray::InstallIconPending() 改為 virtual 以便覆寫。
    OnTrayNotification() 實際只讀 Create() 之後不再變動的欄位,加鎖主要是讓狀態存取規則單純。

Wujidadi added a commit to Wujidadi/weasel that referenced this pull request Aug 22, 2026
- `OverlappedOp` 於 `CreateEvent` 失敗時立即拋出,避免後續以空事件等待。
- `_WaitIo()` 在 `CancelIoEx` 與第二次等待之前先保存逾時/失敗的原始錯誤碼,不再被後續呼叫覆寫;
  第二次等待仍為必要:`OVERLAPPED` 位於呼叫端堆疊,I/O 未完成前不得返回,`CancelIoEx` 唯一的失敗情境(`ERROR_NOT_FOUND`)代表 I/O 已完成、事件已觸發。
- `_ConnectServerPipe()` 檢查 `WaitForSingleObject` 結果,失敗即取消 I/O、關閉管線並拋出。
- `_Receive()` 失敗(含逾時)時關閉客戶端的管線連線:被放棄的回應否則會留在管線中,成為下一筆請求讀到的回應;下一次交易自動重連,伺服器端工作執行緒於讀寫失敗時自行收尾。

(cherry picked from commit 8d429d9)
Wujidadi added a commit to Wujidadi/weasel that referenced this pull request Aug 22, 2026
- build.bat 的 fork 版號後綴進位 -wujidadi.4
- FORK-CHANGELOG 新增 0.17.4-wujidadi.4 節,記錄自 rime#1914 分支揀回的四筆修正
- appcast 與 testing-appcast 條目更新至 0.17.4-wujidadi.4
fcxxxz added a commit to fcxxxz/weasel that referenced this pull request Sep 1, 2026
按用户指令恢复 GPU 优先/WARP 兜底(WEASEL_WARP=1 可选软渲染):
CPU 满载时渲染不与系统抢 CPU,全屏布局+阴影在 4K 下必须 GPU
(对抗审查 rime#7 实锤该场景软渲染为每键整屏 CPU 光栅化)。

服务器端已接受管道改阻塞读写:worker 线程可弃,无需每请求付
overlapped 事件跳转;客户端完整保留 overlapped+分级超时,rime#1914
防冻语义不变。审查确认无死锁/帧错位回归。

对抗性审查(18 项)落地四项修复:
- Present 改回 (0,0):每帧等 vblank 最高 8ms 打字卡顿,TSF 进程内
  模式下卡的是宿主应用 UI 线程(rime#1)
- _ReceiveSync 删短读分支:防旧版客户端消息被当正文吞掉造成帧
  错位(rime#10)
- Initialize 先销毁旧保活会话:防部署后双初始化泄漏(rime#14)
- Prewarm 应用待定尺寸 + 隐藏期钳位用待定尺寸(rime#2/rime#3)

GPU 模式验证:p50 40µs、会话 3ms、切换 1ms、句柄 30k 键稳定;
单测/parser 门全绿;墨菲压测(90k 键+并发+强杀客户端)全过。
@fxliang

fxliang commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

命名管道变成无名管道?

@Wujidadi

Copy link
Copy Markdown
Author

命名管道变成无名管道?

不是,兩端仍然是具名管道。是指 _Connect(const wchar_t* name) 的 name 被拿掉嗎?

name 參數原本用在 WaitNamedPipe(name, 500) 的無限重試迴圈,
我改成:一次連不上,就拋 ERROR_PIPE_BUSY,由 _Ensure() 回傳失敗,參數已無用,故移除。
管道兩端還是 client 端的 _TryConnect() → CreateFile(pname, ...) 和 server 端的 CreateNamedPipe(pn, ...),
但各自加上 FILE_FLAG_OVERLAPPED 旗標,讓讀寫可帶逾時。

@selcomad77

Copy link
Copy Markdown

补充一个托盘线程方面的隔离验证结果,供完善这个 PR 时参考;没有另开重复 PR。

检查的版本是本 PR head 1a853c796d9c735090a735906f62eface7f473fe,对照为当前 master f96ed24a8a535961b6ffc7160d98851a69cee4f8(包含 #1912)。专用刷新线程确实使普通刷新不再阻塞服务器消息线程。不过,新增的 m_tray_mutex 仍可能将 Shell 等待传回消息线程:

刷新线程:Refresh -> 持有 m_tray_mutex -> Shell_NotifyIcon 等待
主消息线程:托盘隐藏窗口回调 -> OnTrayNotification -> 等待 m_tray_mutex

InstallIconPending 也获取同一把锁,但本次没有对该入口做动态测试。递归锁允许同一线程重入,不能避免不同线程之间的等待。

验证直接编译了上述两个版本的 WeaselTrayIcon.cpp 与 SystemTraySDK.cpp,保留实际隐藏窗口及消息循环,仅以事件闸门替换 Shell_NotifyIcon,并替换菜单/前台激活调用。没有操作真实托盘或 Explorer,也没有链接图标/菜单资源来做外观验收。

复现步骤:

  1. 在代表服务器主消息线程的线程上创建 WeaselTrayIcon 和消息窗口;master 按实际代码由 WM_WEASEL_SERVICE_NOTIFY 调用 ApplyRefresh。
  2. 初始化后,在下一次 Shell 通知处阻塞替身,调用 RequestRefresh。闸门有 5 秒安全上限,测试会在到期前主动释放。
  3. 给主线程投递探针消息,等待 250 ms。
  4. 保持 Shell 阻塞,向托盘隐藏窗口投递 WM_WEASEL_TRAY_NOTIFY,随后再投递探针消息。使用不匹配的图标 ID,使基类回调不显示菜单;本 PR 在进入基类 ID 检查之前就获取 m_tray_mutex。记录消息循环已经开始派发该通知。
  5. 再等待 250 ms,然后释放 Shell 闸门,检查消息循环恢复。
观察项 master(#1912) 本 PR head
RequestRefresh 返回 是 是
Shell 阻塞、未发送托盘通知时,主线程处理探针 否 是
加入托盘通知后,主线程处理探针 否 否
释放 Shell 闸门后恢复 是 是
触及 5 秒安全上限 否 否

因此这不是说本 PR 的专用线程无效,而是仍有一个入口能让主线程重新等待正在调用 Shell 的线程。与 PR 描述中的跨线程候选窗口调用组合时,这可能重新接上等待链;这里只实测了托盘锁向主线程传播等待这一段,没有声称在此 PR 上复现了完整 Explorer 死锁,也没有测试 IPC 超时部分。

建议考虑让专用线程同时拥有托盘隐藏窗口、消息循环及菜单,所有 CSystemTray 操作在同一线程串行处理;菜单由该线程窗口拥有,选择结果用 PostMessage(WM_COMMAND) 转交服务器主窗口,避免再通过共享锁或同步菜单消息把主线程拉入 Shell 等待。状态发布仍只复制快照并唤醒该线程。

我们基于旧版的下游采用这一线程归属方式后,原用户复现的第三方托盘菜单收起卡顿已在安装重启后消失。但那是下游的用户反馈,不能替代本 PR 的官方版本验收。希望这组局部验证有助于现有修复收敛。

Wujidadi added a commit to Wujidadi/weasel that referenced this pull request Nov 24, 2026
`m_tray_mutex` 讓訊息執行緒在托盤通知時等待正持鎖呼叫 `Shell_NotifyIcon` 的托盤執行緒,仍能把 Shell 等待傳回訊息執行緒(selcomad77 於 rime#1914 的隔離驗證)。

- 所有 `CSystemTray` 操作改在托盤執行緒串行處理,訊息執行緒只以 `PostMessage` 送出刷新與結束請求,不再與托盤執行緒共用鎖。
- 托盤選單改以 `TPM_RETURNCMD` 由托盤視窗擁有,選擇結果以 `PostMessage(WM_COMMAND)` 轉交伺服器主視窗,不讓選單訊息同步送往訊息執行緒。
- `CSystemTray::InstallIconPending()` 不再需要覆寫,還原為非 virtual。
…nnect

c9938e7 makes `_Send()` resend on the handle opened by `_Reconnect()`, but `_GetPipeHandle()` returns `HANDLE*`; passing it to `_WritePipe(HANDLE, ...)` converts it implicitly to `void*`, so the write targets the pointer rather than the pipe and the resend always fails.
Pass `*_GetPipeHandle()` instead.
…the deadlock window left by rime#1912

On `FocusIn` → `_UpdateUI()`, pipe worker threads still call `ShowWindow`/`SetWindowPos` on the candidate window across threads, which sends messages synchronously to the server message thread.
`Shell_NotifyIcon` waits for the taskbar with `SMTO_BLOCK` and does not process incoming sent messages meanwhile.
When the taskbar UI thread is itself waiting for a pipe reply, the cycle worker → message thread → taskbar → worker can still form.

- WeaselTrayIcon applies refreshes on a dedicated thread: `RequestRefresh()` only stores a snapshot and wakes the thread, `RefreshThreadProc()` coalesces pending requests before calling `Refresh()`, and `DisableRefresh()` stops and joins the thread.
- Remove `WM_WEASEL_SERVICE_NOTIFY`, `ServerImpl::OnServiceNotifyMessage` and `Server::SetTrayRefreshCallback`, introduced by rime#1912 and now unused.
- Remove the workaround in `_RefreshTrayIcon()` that deferred the refresh for explorer.exe by 100 ms on a separate thread: the callback no longer blocks, so a synchronous call is safe for every client.
…oop and menu

`m_tray_mutex` makes the message thread wait, on tray notifications, for the tray thread that holds the lock while calling `Shell_NotifyIcon`, which still propagates the Shell wait back to the message thread (isolated verification by selcomad77 in rime#1914).

- All `CSystemTray` operations are serialized on the tray thread; other threads only post refresh and quit requests with `PostMessage` and no longer share a lock with the tray thread.
- The tray menu is owned by the tray window and tracked with `TPM_RETURNCMD`; the selected command is forwarded to the server main window with `PostMessage(WM_COMMAND)`, so menu messages are no longer sent synchronously to the message thread.
- `CSystemTray::InstallIconPending()` no longer needs to be overridden and is non-virtual again.
@Wujidadi
Wujidadi force-pushed the fix/ipc-bounded-wait branch from 1a853c7 to 5e940e6 Compare November 24, 2026 06:28
@Wujidadi

Wujidadi commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

@selcomad77 感謝這組隔離驗證,分析正確:m_tray_mutex 確實會讓主訊息執行緒在 OnTrayNotification 等待正卡在 Shell_NotifyIcon 的刷新執行緒。

已依建議改為由托盤執行緒擁有托盤(5e940e6):

  • 托盤執行緒建立 CSystemTray 的隱藏視窗並執行自己的訊息迴圈;刷新、托盤通知、工作列重建、右鍵選單都在該執行緒串行處理,移除 m_tray_mutex。
  • RequestRefresh() 只存快照並 PostMessage 喚醒托盤執行緒;結束時送出結束訊息並 join,圖示在托盤執行緒移除。
  • 右鍵選單改以 TPM_RETURNCMD 由托盤視窗擁有,選擇結果以 PostMessage(WM_COMMAND) 轉交伺服器主視窗。

驗證比照你的作法:直接編譯 WeaselTrayIcon.cpp 與 SystemTraySDK.cpp,保留實際隱藏視窗與訊息迴圈,以事件閘門替換 Shell_NotifyIcon,並替換 TrackPopupMenu/LoadMenu。

觀察項 第一版(m_tray_mutex) 本次修改
Shell 阻塞、未送托盤通知時,主執行緒處理探針 是 是
加入托盤通知後,主執行緒處理探針 否 是
釋放 Shell 閘門後恢復 是 是
右鍵選單由托盤執行緒擁有、結果送達主視窗 否 是
結束時等待進行中的刷新 是 是
結束時圖示於托盤執行緒移除 否(主執行緒移除) 是
觸及 5 秒安全上限 否 否

實機(Windows 11 x64)上托盤右鍵選單各項、雙擊、中英切換時的圖示更新皆正常;同樣沒有聲稱重現或排除完整的 Explorer 死結。

另外,分支已 rebase 到目前的 master(解掉衝突)。
@fxliang rebase 時注意到 c9938e7 的 _WritePipe(_GetPipeHandle(), ...):_GetPipeHandle() 回傳 HANDLE*,傳給 _WritePipe(HANDLE, ...) 會隱式轉成 void*,寫入對象是指標本身而非管線,重連後的重送仍會失敗;本 PR 的 af581b4 改為傳 *_GetPipeHandle()。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants