Skip to content

Commit f55797b

Browse files
authored
ui: extend console parenting beyond MSAL (#2465)
This follows up on #2464. Visible-console parenting currently lives inside the MSAL adapter, so _other_ in-process authentication dialogs remain unparented unless `GCM_MODAL_PARENTHWND` is supplied. Those prompts can appear disconnected from the terminal that initiated the Git operation. This PR moves console-parent discovery into a shared platform helper and uses it in the authentication and UI-helper parent handle lookups. This extends the fallback beyond MSAL while keeping the two lookup paths consistent. MSAL retains responsibility for creating a progress window when broker authentication requires a parent and no usable handle was resolved. Explicit HWNDs still take precedence and are not visibility-filtered. Automatically discovered owners must be visible, with visibility checked after resolving the console's root owner to accommodate ConPTY compatibility windows. Update the environment variable documentation to describe the fallback to the console-parent window. Tested behaviour on Windows Terminal, conhost.exe (classic terminal host), and Git Bash/MSYS2's terminal.
2 parents 2d60006 + a3f1cea commit f55797b

6 files changed

Lines changed: 62 additions & 127 deletions

File tree

‎docs/environment.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,12 @@ Defaults to enabled.
177177

178178
Specify the parent window handle (`HWND`) for modal dialogs on Windows.
179179

180+
When this variable is unset, GCM tries to parent authentication dialogs to the
181+
console's visible root-owner window. Hidden or invalid windows are ignored.
182+
183+
Explicitly setting a handle using this variable takes precedence and it is not
184+
checked for visibility.
185+
180186
> [!NOTE]
181187
> This is intended for use by application developers who are calling Git and/or
182188
> GCM from their application and wish to correctly parent authentication dialogs

‎src/Core.Tests/Authentication/Entra/MsalParentWindowAdapterTests.cs‎

Lines changed: 6 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -10,60 +10,22 @@ public class MsalParentWindowAdapterTests
1010
[Theory]
1111
[InlineData(42, false)]
1212
[InlineData(42, true)]
13-
[InlineData(-1, false)]
14-
[InlineData(-1, true)]
15-
public void GetWindow_ExplicitParent_TakesPrecedence(int parentValue, bool createIfMissing)
13+
public void GetWindow_ExplicitParent_ReturnsParent(int parentValue, bool createIfMissing)
1614
{
1715
object parentWindow = new IntPtr(parentValue);
1816
using var adapter = new MsalParentWindowAdapter(parentWindow, createIfMissing,
19-
() => throw new InvalidOperationException("Console lookup should not be called."),
20-
_ => throw new InvalidOperationException("Visibility should not be checked."),
2117
_ => throw new InvalidOperationException("A progress window should not be created."));
2218

2319
object result = adapter.GetWindow();
2420
Assert.Same(parentWindow, result);
2521
}
2622

27-
[Theory]
28-
[InlineData(false)]
29-
[InlineData(true)]
30-
public void GetWindow_VisibleConsoleRoot_PrecedesProgressWindow(bool createIfMissing)
31-
{
32-
var consoleRoot = new IntPtr(42);
33-
bool visibilityChecked = false;
34-
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, createIfMissing,
35-
() => consoleRoot,
36-
hwnd =>
37-
{
38-
Assert.Equal(consoleRoot, hwnd);
39-
visibilityChecked = true;
40-
return true;
41-
},
42-
_ => throw new InvalidOperationException("A progress window should not be created."));
43-
44-
IntPtr result = Assert.IsType<IntPtr>(adapter.GetWindow());
45-
46-
Assert.Equal(consoleRoot, result);
47-
Assert.True(visibilityChecked);
48-
}
49-
50-
[Theory]
51-
[InlineData(0)]
52-
[InlineData(42)]
53-
public void GetWindow_NoVisibleConsoleRoot_CreatesProgressWhenRequired(int consoleRootValue)
23+
[Fact]
24+
public void GetWindow_NoParent_Required_CreatesProgressWindow()
5425
{
55-
var consoleRoot = new IntPtr(consoleRootValue);
56-
var progressWindow = new IntPtr(84);
57-
int visibilityChecks = 0;
26+
var progressWindow = new IntPtr(42);
5827
var windowToken = CancellationToken.None;
5928
using (var adapter = new MsalParentWindowAdapter(IntPtr.Zero, true,
60-
() => consoleRoot,
61-
hwnd =>
62-
{
63-
Assert.Equal(consoleRoot, hwnd);
64-
visibilityChecks++;
65-
return false;
66-
},
6729
ct =>
6830
{
6931
windowToken = ct;
@@ -73,66 +35,21 @@ public void GetWindow_NoVisibleConsoleRoot_CreatesProgressWhenRequired(int conso
7335
IntPtr result = Assert.IsType<IntPtr>(adapter.GetWindow());
7436

7537
Assert.Equal(progressWindow, result);
76-
Assert.Equal(consoleRootValue == 0 ? 0 : 1, visibilityChecks);
7738
Assert.True(windowToken.CanBeCanceled);
7839
Assert.False(windowToken.IsCancellationRequested);
7940
}
8041

8142
Assert.True(windowToken.IsCancellationRequested);
8243
}
8344

84-
[Theory]
85-
[InlineData(0)]
86-
[InlineData(42)]
87-
public void GetWindow_NoVisibleConsoleRoot_ReturnsNullWhenParentNotRequired(int consoleRootValue)
88-
{
89-
var consoleRoot = new IntPtr(consoleRootValue);
90-
int visibilityChecks = 0;
91-
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, false,
92-
() => consoleRoot,
93-
hwnd =>
94-
{
95-
Assert.Equal(consoleRoot, hwnd);
96-
visibilityChecks++;
97-
return false;
98-
},
99-
_ => throw new InvalidOperationException("A progress window should not be created."));
100-
101-
object result = adapter.GetWindow();
102-
103-
Assert.Null(result);
104-
Assert.Equal(consoleRootValue == 0 ? 0 : 1, visibilityChecks);
105-
}
106-
10745
[Fact]
108-
public void GetWindow_VisibilityCheckThrows_PropagatesException()
46+
public void GetWindow_NoParent_NotRequired_ReturnsNull()
10947
{
110-
var exception = new InvalidOperationException("Visibility check failed.");
111-
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, true,
112-
() => new IntPtr(42),
113-
_ => throw exception,
48+
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, false,
11449
_ => throw new InvalidOperationException("A progress window should not be created."));
11550

116-
var thrown = Assert.Throws<InvalidOperationException>(adapter.GetWindow);
117-
Assert.Same(exception, thrown);
118-
}
119-
120-
[Fact]
121-
public void Create_ExplicitParent_IsReturned()
122-
{
123-
object parentWindow = new IntPtr(42);
124-
using var adapter = MsalParentWindowAdapter.Create(parentWindow, true);
125-
12651
object result = adapter.GetWindow();
127-
Assert.Same(parentWindow, result);
128-
}
129-
130-
[PosixFact]
131-
public void Create_NoExplicitParent_Posix_ReturnsNull()
132-
{
133-
using var adapter = MsalParentWindowAdapter.Create(IntPtr.Zero);
13452

135-
object result = adapter.GetWindow();
13653
Assert.Null(result);
13754
}
13855
}

‎src/Core/Authentication/AuthenticationBase.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
using System.Linq;
66
using System.Threading;
77
using System.Threading.Tasks;
8-
using GitCredentialManager.Tty;
98
using GitCredentialManager.UI.ViewModels;
109

1110
namespace GitCredentialManager.Authentication
@@ -125,11 +124,19 @@ protected void ThrowIfWindowCancelled(WindowViewModel viewModel)
125124

126125
protected IntPtr GetParentWindowHandle()
127126
{
127+
// Check if the user has specified a parent window ID
128128
if (int.TryParse(Context.Settings.ParentWindowId, out int id))
129129
{
130130
return new IntPtr(id);
131131
}
132132

133+
// Check if we can use the console window as a parent
134+
IntPtr consoleParent = PlatformUtils.GetConsoleParentWindow();
135+
if (consoleParent != IntPtr.Zero)
136+
{
137+
return consoleParent;
138+
}
139+
133140
return IntPtr.Zero;
134141
}
135142

‎src/Core/Authentication/Entra/MsalAdaptors.cs‎

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using System.Net.Http;
33
using System.Threading;
4-
using GitCredentialManager.Interop.Windows.Native;
54
using GitCredentialManager.UI.Controls;
65
using Microsoft.Identity.Client;
76

@@ -31,48 +30,32 @@ internal class MsalParentWindowAdapter : IDisposable
3130
private readonly bool _createIfMissing;
3231
private readonly CancellationTokenSource _cts = new();
3332

34-
private readonly Func<IntPtr> _getConsoleParentWindow;
35-
private readonly Func<IntPtr, bool> _isWindowVisible;
3633
private readonly Func<CancellationToken, IntPtr> _createWindow;
3734

3835
public static MsalParentWindowAdapter Create(object parentWindow, bool createIfMissing = false)
3936
{
40-
return new MsalParentWindowAdapter(parentWindow, createIfMissing,
41-
GetConsoleParentWindow, User32.IsWindowVisible, ProgressWindow.ShowAndGetHandle);
37+
return new MsalParentWindowAdapter(parentWindow, createIfMissing, ProgressWindow.ShowAndGetHandle);
4238
}
4339

4440
internal MsalParentWindowAdapter(object parentWindow, bool createIfMissing,
45-
Func<IntPtr> getConsoleParentWindow, Func<IntPtr, bool> isWindowVisible,
4641
Func<CancellationToken, IntPtr> createWindow)
4742
{
48-
EnsureArgument.NotNull(getConsoleParentWindow, nameof(getConsoleParentWindow));
49-
EnsureArgument.NotNull(isWindowVisible, nameof(isWindowVisible));
5043
EnsureArgument.NotNull(createWindow, nameof(createWindow));
5144

5245
_parentWindow = parentWindow;
5346
_createIfMissing = createIfMissing;
54-
55-
_getConsoleParentWindow = getConsoleParentWindow;
56-
_isWindowVisible = isWindowVisible;
5747
_createWindow = createWindow;
5848
}
5949

6050
public object GetWindow()
6151
{
52+
// Try to use the parent window we were given (if any)
6253
if (_parentWindow is IntPtr p && p != IntPtr.Zero)
6354
{
6455
return _parentWindow;
6556
}
6657

67-
// See if we can use the console window as a parent.
68-
// We only consider the window if it is valid and visible.
69-
IntPtr consoleParent = _getConsoleParentWindow();
70-
if (consoleParent != IntPtr.Zero && _isWindowVisible(consoleParent))
71-
{
72-
return consoleParent;
73-
}
74-
75-
// Create a stub window to use as a parent
58+
// Create a stub window to use as a parent instead (if the caller requires it)
7659
if (_createIfMissing)
7760
{
7861
return _createWindow(_cts.Token);
@@ -81,23 +64,6 @@ public object GetWindow()
8164
return null;
8265
}
8366

84-
private static IntPtr GetConsoleParentWindow()
85-
{
86-
// On Windows we can try and get the console window parent handle if that exists
87-
if (!PlatformUtils.IsWindows())
88-
{
89-
return IntPtr.Zero;
90-
}
91-
92-
IntPtr consoleHandle = Kernel32.GetConsoleWindow();
93-
94-
// When the parent is using ConPTY (pseudo-terminals) the console
95-
// window may be a fake/stub (as is the case with Windows Terminal).
96-
// This means we need to walk up the ancestor chain to get the actual
97-
// root owner (typically the terminal emulator's window).
98-
return User32.GetAncestor(consoleHandle, GetAncestorFlags.GetRootOwner);
99-
}
100-
10167
public void Dispose()
10268
{
10369
// Close and clean up any stub window we may have created

‎src/Core/PlatformUtils.cs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Runtime.InteropServices;
66
using System.Runtime.Versioning;
77
using GitCredentialManager.Interop.Posix.Native;
8+
using GitCredentialManager.Interop.Windows.Native;
89

910
namespace GitCredentialManager
1011
{
@@ -211,6 +212,36 @@ public static bool IsElevatedUser()
211212
return false;
212213
}
213214

215+
public static IntPtr GetConsoleParentWindow()
216+
{
217+
// On Windows we can try and get the console window parent handle if that exists
218+
if (!IsWindows())
219+
{
220+
return IntPtr.Zero;
221+
}
222+
223+
IntPtr consoleHandle = Kernel32.GetConsoleWindow();
224+
225+
// When the parent is using ConPTY (pseudo-terminals) the console
226+
// window may be a fake/stub (as is the case with Windows Terminal).
227+
// This means we need to walk up the ancestor chain to get the actual
228+
// root owner (typically the terminal emulator's window).
229+
IntPtr parent = User32.GetAncestor(consoleHandle, GetAncestorFlags.GetRootOwner);
230+
231+
// On Windows the parent window may be hidden (not visible) if the console is
232+
// running in a background process (like a service).
233+
// We do not consider a hidden window as a valid parent. We do however consider
234+
// a minimised window as a valid parent (and the user is able to restore it and
235+
// see our child window too).
236+
if (User32.IsWindowVisible(parent))
237+
{
238+
return parent;
239+
}
240+
241+
// No visible console window available!
242+
return IntPtr.Zero;
243+
}
244+
214245
#region Platform Entry Path Utils
215246

216247
/// <summary>

‎src/Core/UI/HelperCommand.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,19 @@ public HelperCommand(ICommandContext context, string name, string description)
1616

1717
protected IntPtr GetParentHandle()
1818
{
19+
// Check if the user has specified a parent window ID
1920
if (int.TryParse(Context.Settings.ParentWindowId, out int id))
2021
{
2122
return new IntPtr(id);
2223
}
2324

25+
// Check if we can use the console window as a parent
26+
IntPtr consoleParent = PlatformUtils.GetConsoleParentWindow();
27+
if (consoleParent != IntPtr.Zero)
28+
{
29+
return consoleParent;
30+
}
31+
2432
return IntPtr.Zero;
2533
}
2634

0 commit comments

Comments
 (0)