← Back to Pull requests

Resolve the TSF InputSite HWND within the owning Terminal window #20913

Open
96-kdh opened this pull request with 197 lines diff across 9 files
View on GitHub
96-kdh 96-kdh commented on Nov 11, 2026 14:48 UTC
Author

Summary of the Pull Request

Resolve the TSF InputSite HWND within the control's owning window instead of caching a HWND obtained from the thread's document-manager enumeration. With multiple Terminal windows sharing a UI thread, the cached handle can belong to another window, leaving Korean input toggles ineffective after window reactivation.

References and Relevant Issues

Closes #20912.

Draft for discussion of the proposed approach. The issue has been filed; maintainer agreement on the approach has not yet been obtained.

Detailed Description of the Pull Request / Additional comments

Search for the InputSite descendant under OwningHwnd(). If it does not exist yet, return the owner and search again on the next call. A null owner returns null. Remove the HWND cache so owner changes and InputSite recreation do not retain stale handles or borrow another window's TSF context.

Five tests use real hidden Win32 windows to cover separate owners, null owners, delayed creation, nested descendants/reparenting, and destruction/recreation. These exercise the helper rather than the complete TSF event sequence.

The cross-window cache mismatch was directly observed in official 1.24.12741.0. The exact initialization ordering that first selects the incorrect handle is not isolated; the visible failure is intermittent. See #20912 for evidence and reproduction details.

AI assistance was used for investigation, implementation, tests and drafting. The submitting contributor personally observed the automated reproduction, checked the results, and read and understood the complete code change.

Validation Steps Performed

  • Built the x64 Release application and Control tests using VS 2026, MSVC 14.51.36231 and Windows SDK 10.0.26100.0. XAML/resource fallback warnings were emitted; builds were not warning-free.

  • TAEF Control.Unit.Tests.dll /name:InputSiteWindowTests: 5 passed, 0 failed.

  • Complete Control.Unit.Tests.dll: 34 passed, 0 failed, 0 blocked/skipped/not run.

  • Same-source application comparison on base commit 5f7dc283013152f89bfb76950515c33f45157ad7: original implementation failed in 7/20 tabs; proposed implementation failed in 0/20. All 40 cases had complete received-text records and owned focus at every observation. Each variant retained windows in one process, so these counts are not population failure-rate estimates.

  • Compared 31 executable/resource files across the layouts: only Microsoft.Terminal.Control.dll differed. Actual loaded DLL paths were independently recorded. Both layouts successfully launched PowerShell child processes.

  • Limits: injected keys on one PC/OS/Korean IME; actual UI tab dragging, split panes and other IMEs were not tested. Owner changes/recreation were tested at helper level only. Zero observed failures does not establish universal correctness.
  • PR Checklist


  • Closes #20912

  • Tests added/passed

  • Documentation updated — no user-facing documentation change required.

  • Schema updated (if necessary) — not applicable.
  • Diff: 197 lines (+140 / -57) across 9 files Reviewer: lhecker Review duration: 19411m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.46) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.46 · 197 lines diff across 9 files
    0.46
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.316
    Real PR Conversation Timeline
    11 items
    azure-pipelines[bot] azure-pipelines[bot] commented on Nov 11, 2026 14:48 UTC
    Bot

    <!-- AzurePipelinesStatusComment -->
    <samp>
    Azure Pipelines:<br>
    There may be pipelines that require an authorized user to comment /azp run to run.<br>

    </samp>

    96-kdh 96-kdh commented on Nov 11, 2026 14:51 UTC
    Author

    @microsoft-github-policy-service agree

    96-kdh 96-kdh commented on Nov 11, 2026 15:06 UTC
    Author

    The spelling check failed during dependency installation due to a DNS resolution error for azure.archive.ubuntu.com, before spelling validation ran. Could a maintainer please rerun the failed job?

    Failed job: https://github.com/microsoft/terminal/actions/runs/43042027734/job/130596059108

    lhecker lhecker requested changes on Nov 11, 2026 18:06 UTC
    Changes Requested Reviewer

    Thank you for making this PR. But it's incomplete:
    It states that FindWindowOfActiveTSF is wrong and yet it still exists
    It also states that it may not be cached but not why it should not be cached. _tsfDataProvider is per pane and the only bug I see is that we don't reset _tsfDataProvider._hwnd when the tab gets dragged.

    96-kdh 96-kdh commented on Nov 13, 2026 08:10 UTC
    Author

    Thanks for the review. My earlier explanation was too broad: the issue is which window's HWND gets cached, rather than caching itself. I've revised the change to address both points:

  • Removed FindWindowOfActiveTSF, including its declarations and the Handle wrapper. This also removes the recursion guard from #18248, which is no longer needed since GetHwnd() no longer calls into TSF.

  • Restored the per-control HWND cache, with the lookup restricted to descendants of the control's owning window. Moving a tab to another window creates a new TermControl through NewControlByAttachingContent, rather than moving the existing control. A control's owning window therefore never changes, so tab moves cannot leave its cached HWND stale. When no InputSite window is found, the lookup returns the owner HWND without caching it, allowing a later call to retry.
  • The underlying problem is that all Terminal windows share one UI thread and ITfThreadMgr. EnumDocumentMgrs enumerates document managers in creation order rather than focus order, so the previous implementation could select and cache another window's InputSite HWND. This reproduces with multiple windows open, without any tab dragging.

    For validation, I used automated UI tests (AutoHotkey) with eight windows open simultaneously, checking whether the Hangul/English toggle took effect:

  • Official 1.24, two runs: the toggle took effect in 18/20 and 16/20 per-tab checks, and 25/30 and 26/30 randomized focus-switch checks (click, window activation, tab switch).

  • Local PR build based on main: the toggle took effect in 20/20 per-tab checks and 30/30 randomized focus-switch checks.

  • The same change applied on top of 1.24 also passed both runs: the toggle took effect in 20/20 per-tab checks and 30/30 randomized focus-switch checks in each run.

  • Control unit tests: 34/34 passed.
  • These results are limited to the tested environment and automated input sequence.

    lhecker lhecker commented on Nov 16, 2026 16:20 UTC
    Contributor

    @96-kdh We do not permit LLM-authored comments in our repository, and I'll not read what you wrote out of principle. We're basically down to ~1 maintainer for this project and have little time to read large amounts of text, as typically produced by LLMs. You may use LLMs for translating your comments, however.

    lhecker lhecker commented on code on Nov 16, 2026 16:22 UTC
    Code Review
    src/cascadia/TerminalControl/TermControl.cpp:1
    @@ -182,12 +183,17 @@ namespace winrt::Microsoft::Terminal::Control::implementation
             {
                 // WinUI's WinRT based TSF runs in its own window "Windows.UI.Input.InputSite.WindowClass" (..."great")
                 // and in order for us to snatch the focus away from that one we need to find its HWND.
    -            // The way we do it here is by finding the existing, active TSF context and getting the HWND from it.
    -            _hwnd = GetTSFHandle().FindWindowOfActiveTSF();
    -            if (!_hwnd)
    +            // All windows share the same UI thread and ITfThreadMgr, so we must look for the one underneath
    +            // our own window. Asking TSF instead (e.g. via EnumDocumentMgrs) yields an arbitrary window's.
    +            const auto owner = reinterpret_cast<HWND>(_termControl->OwningHwnd());
    +            const auto hwnd = FindInputSiteWindow(owner);
    +            // Only cache a successful lookup. A TermControl never changes windows
    +            // (moving a tab creates a new one), so the result never goes stale.
    +            if (hwnd != owner)
    

    Seems like you may want to return nullptr instead. The comparison against owner is not obvious without reading FindInputSiteWindow's implementation.

    lhecker lhecker commented on code on Nov 16, 2026 16:23 UTC
    Code Review
    src/cascadia/TerminalControl/TermControl.cpp:1
    @@ -182,12 +183,17 @@ namespace winrt::Microsoft::Terminal::Control::implementation
             {
                 // WinUI's WinRT based TSF runs in its own window "Windows.UI.Input.InputSite.WindowClass" (..."great")
                 // and in order for us to snatch the focus away from that one we need to find its HWND.
    -            // The way we do it here is by finding the existing, active TSF context and getting the HWND from it.
    -            _hwnd = GetTSFHandle().FindWindowOfActiveTSF();
    -            if (!_hwnd)
    +            // All windows share the same UI thread and ITfThreadMgr, so we must look for the one underneath
    +            // our own window. Asking TSF instead (e.g. via EnumDocumentMgrs) yields an arbitrary window's.
    

    Ah I see now, your theory is that EnumDocumentMgrs may return any windows' input site.

    My assumption was that focusing a window enables the current windows' input site _first_ and only then raises the XAML focus event, and only _then_ we enter this function after all - by this time, FindWindowOfActiveTSF would thus return the input site HWND.

    96-kdh 96-kdh commented on code on Nov 17, 2026 01:21 UTC
    Code Review
    src/cascadia/TerminalControl/TermControl.cpp:1
    @@ -182,12 +183,17 @@ namespace winrt::Microsoft::Terminal::Control::implementation
             {
                 // WinUI's WinRT based TSF runs in its own window "Windows.UI.Input.InputSite.WindowClass" (..."great")
                 // and in order for us to snatch the focus away from that one we need to find its HWND.
    -            // The way we do it here is by finding the existing, active TSF context and getting the HWND from it.
    -            _hwnd = GetTSFHandle().FindWindowOfActiveTSF();
    -            if (!_hwnd)
    +            // All windows share the same UI thread and ITfThreadMgr, so we must look for the one underneath
    +            // our own window. Asking TSF instead (e.g. via EnumDocumentMgrs) yields an arbitrary window's.
    +            const auto owner = reinterpret_cast<HWND>(_termControl->OwningHwnd());
    +            const auto hwnd = FindInputSiteWindow(owner);
    +            // Only cache a successful lookup. A TermControl never changes windows
    +            // (moving a tab creates a new one), so the result never goes stale.
    +            if (hwnd != owner)
    

    Done in 0cb4382cf.

    96-kdh 96-kdh commented on code on Nov 17, 2026 01:25 UTC
    Code Review
    src/cascadia/TerminalControl/TermControl.cpp:1
    @@ -182,12 +183,17 @@ namespace winrt::Microsoft::Terminal::Control::implementation
             {
                 // WinUI's WinRT based TSF runs in its own window "Windows.UI.Input.InputSite.WindowClass" (..."great")
                 // and in order for us to snatch the focus away from that one we need to find its HWND.
    -            // The way we do it here is by finding the existing, active TSF context and getting the HWND from it.
    -            _hwnd = GetTSFHandle().FindWindowOfActiveTSF();
    -            if (!_hwnd)
    +            // All windows share the same UI thread and ITfThreadMgr, so we must look for the one underneath
    +            // our own window. Asking TSF instead (e.g. via EnumDocumentMgrs) yields an arbitrary window's.
    

    FindWindowOfActiveTSF takes only the first entry from EnumDocumentMgrs via Next(1, …), without checking whether it belongs to the focused window. Even with the focus sequence you described, that first entry is not necessarily associated with the current window.

    If the first lookup selects another window's InputSite, that HWND remains cached for subsequent calls.

    In the tests, failures clustered on the same tabs across clicks, window activation, and tab switches, though those tabs sometimes succeeded.

    Reviewers
    Assignees
    96-kdh 96-kdh
    Labels
    risk: low confidence: 90.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 46.4% (MEDIUM) · Higher = larger blast radius
    46.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.6% · Lower = rushed or shallow review
    90.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.4% · Safe to merge
    4.4%