-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathFreOverlay.cpp
More file actions
1913 lines (1753 loc) · 91.5 KB
/
Copy pathFreOverlay.cpp
File metadata and controls
1913 lines (1753 loc) · 91.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "FreOverlay.h"
#include "FreAgentEntry.g.cpp"
#include "FreOverlay.g.cpp"
#include "../inc/AgentRegistry.h"
#include "../inc/AgentAvailability.h"
#include "../inc/WtaProcess.h"
#include "../inc/ShellIntegration.h"
#include "../inc/RtlHelper.h"
#include "AgentPaneLog.h"
#include "ShellIntegrationSweep.h"
#include "WindowsPackageManagerFactory.h"
#include <winrt/Windows.UI.Xaml.Documents.h>
#include <mutex>
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Controls;
using namespace winrt::Windows::UI::Xaml::Documents;
namespace Automation = winrt::Windows::UI::Xaml::Automation;
namespace Model = winrt::Microsoft::Terminal::Settings::Model;
namespace winrt::TerminalApp::implementation
{
// ── Static prewarm state (single-flight per process) ────────────
// See FreOverlay.h for the design contract. Definitions live here
// because C++ requires out-of-line definitions for non-inline static
// class members.
std::mutex FreOverlay::s_prewarmMutex;
winrt::Windows::Foundation::IAsyncAction FreOverlay::s_prewarmAction{ nullptr };
FreOverlay::FreOverlay()
{
InitializeComponent();
// Seed the overlay's status text from the existing localized
// resource (reused here rather than adding a new .Text key
// across every locale).
SavingStatusText().Text(RS_(L"FreOverlay_SettingUp"));
}
// ── Detection helpers ───────────────────────────────────────────────
bool FreOverlay::_IsAgentInstalled(const wchar_t* name)
{
wchar_t buf[MAX_PATH]{};
if (SearchPathW(nullptr, name, L".exe", MAX_PATH, buf, nullptr) > 0)
{
_agentPaneLog("[FRE] _IsAgentInstalled: " + winrt::to_string(winrt::hstring{ name }) + " found at " + winrt::to_string(winrt::hstring{ buf }));
return true;
}
const auto cmdName = std::wstring(name) + L".cmd";
if (SearchPathW(nullptr, cmdName.c_str(), nullptr, MAX_PATH, buf, nullptr) > 0)
{
_agentPaneLog("[FRE] _IsAgentInstalled: " + winrt::to_string(winrt::hstring{ name }) + " found at " + winrt::to_string(winrt::hstring{ buf }));
return true;
}
_agentPaneLog("[FRE] _IsAgentInstalled: " + winrt::to_string(winrt::hstring{ name }) + " NOT found on PATH");
return false;
}
bool FreOverlay::_IsNodeInstalled()
{
wchar_t buf[MAX_PATH];
if (SearchPathW(nullptr, L"npx", L".cmd", MAX_PATH, buf, nullptr) > 0)
return true;
if (SearchPathW(nullptr, L"npx", L".exe", MAX_PATH, buf, nullptr) > 0)
return true;
return false;
}
// Detect whether winget itself is available on PATH. When winget is
// missing (e.g. App Installer not installed, or stripped on LTSC/Server
// SKUs) the Copilot/Node bootstrap calls would fail with a generic
// "install failed" error that wrongly points at the package; surface a
// dedicated message that links to the winget setup docs instead.
bool FreOverlay::_IsWingetInstalled()
{
wchar_t buf[MAX_PATH];
return SearchPathW(nullptr, L"winget", L".exe", MAX_PATH, buf, nullptr) > 0;
}
// ── Agent ComboBox ──────────────────────────────────────────────────
// (Re)build the agent dropdown from the GPO-filtered registry. Each entry's
// status label reflects the live install state at call time, so calling this
// again after a save refreshes Copilot from "(will install)" to
// "(installed)" once the winget install has actually succeeded. Preserves
// the currently selected agent across rebuilds.
void FreOverlay::_PopulateAgentComboBox()
{
if (!_settings)
return;
namespace Reg = ::Microsoft::Terminal::Settings::Model::AgentRegistry;
const auto& globals = _settings.GlobalSettings();
// Keep the user's current selection across a rebuild: prefer the live
// ComboBox selection, falling back to the effective settings value the
// first time (when nothing is selected yet).
winrt::hstring selectedId;
if (const auto selected = AgentComboBox().SelectedItem())
{
if (const auto entry = selected.try_as<winrt::TerminalApp::FreAgentEntry>())
{
selectedId = entry.Id();
}
}
if (selectedId.empty())
{
selectedId = globals.EffectiveAcpAgent();
}
const auto allowedAgents = Reg::FilteredAcpAgents();
const auto availableAgents = ::Microsoft::Terminal::AgentAvailability::ProbeHostAgentIds();
auto items = AgentComboBox().Items();
items.Clear();
int32_t selectedIndex = 0;
int32_t idx = 0;
for (const auto& a : allowedAgents)
{
const bool installed = availableAgents.contains(std::wstring{ a.id });
const bool isCopilot = (a.id == L"copilot");
// Show Copilot always + detected agents only
if (!isCopilot && !installed)
continue;
auto entry = winrt::make<FreAgentEntry>();
entry.Id(winrt::hstring{ a.id });
if (isCopilot && !installed)
{
entry.DisplayLabel(winrt::hstring{ std::wstring(a.displayName) + std::wstring(RS_(L"FreOverlay_AgentStatusWillInstall")) });
}
else
{
entry.DisplayLabel(winrt::hstring{ std::wstring(a.displayName) + std::wstring(RS_(L"FreOverlay_AgentStatusInstalled")) });
}
items.Append(entry);
if (a.id == selectedId)
{
selectedIndex = idx;
}
idx++;
}
if (items.Size() > 0)
{
AgentComboBox().SelectedIndex(selectedIndex);
}
}
// ── Initialize ──────────────────────────────────────────────────────
void FreOverlay::Initialize(const winrt::Microsoft::Terminal::Settings::Model::CascadiaSettings& settings)
{
_settings = settings;
const auto& globals = _settings.GlobalSettings();
// Honor RTL languages on the FRE root grid. XAML cascades
// FlowDirection down the tree and auto-mirrors HorizontalAlignment,
// so this single line is enough to flip the entire two-page wizard
// for any RTL language the OS knows about (and the qps-plocm
// pseudo-locale used for validation). We honor the explicit
// `Language` override from settings.json first (matches the way
// AppLogic::_ApplyLanguageSettingChange resolves it), then fall
// back to the OS preferred UI language.
{
winrt::hstring language = globals.Language();
if (language.empty())
{
try
{
const auto langs = winrt::Windows::Globalization::ApplicationLanguages::Languages();
if (langs && langs.Size() > 0)
{
language = langs.GetAt(0);
}
}
CATCH_LOG();
}
// Explicit on both branches so that re-initializing the
// same overlay element for a different language correctly
// resets the cascade — Initialize is called every time the
// FRE is shown, and the underlying XAML element is reused.
using winrt::Windows::UI::Xaml::FlowDirection;
RootGrid().FlowDirection(::Microsoft::Terminal::RtlHelper::IsRtlLocale(language)
? FlowDirection::RightToLeft
: FlowDirection::LeftToRight);
}
// Set subtitle Run texts (can't use x:Uid for <Run> inside <Hyperlink>)
WelcomeSubtitlePrefix().Text(RS_(L"FreOverlay_WelcomeSubtitlePrefix"));
WelcomeSubtitleLink().Text(RS_(L"FreOverlay_WelcomeSubtitleLink"));
SettingsSubtitlePrefix().Text(RS_(L"FreOverlay_SettingsSubtitlePrefix"));
SettingsSubtitleLink().Text(RS_(L"FreOverlay_SettingsSubtitleLink"));
AutoErrorHandlingShellIntegrationHintPrefix().Text(RS_(L"FreOverlay_AutoErrorHandlingShellIntegrationHintPrefix"));
AutoErrorHandlingShellIntegrationHintLink().Text(RS_(L"FreOverlay_AutoErrorHandlingShellIntegrationHintLink"));
// Split the description on "ACP" (locked token) so it can be rendered as an inline Hyperlink.
{
const auto descStr = RS_(L"FreOverlay_AgentDescription/Text");
const std::wstring_view desc{ descStr };
constexpr std::wstring_view token{ L"ACP" };
const auto pos = desc.find(token);
if (pos != std::wstring_view::npos)
{
AgentDescriptionBefore().Text(winrt::hstring{ desc.substr(0, pos) });
AgentDescriptionAcpToken().Text(winrt::hstring{ token });
AgentDescriptionAfter().Text(winrt::hstring{ desc.substr(pos + token.size()) });
}
else
{
// Fallback (shouldn't happen — ACP is locked): degrade to plain text.
AgentDescriptionBefore().Text(winrt::hstring{ desc });
}
}
// Set toggle On/Off labels
ShowTokenUsageAndCostToggle().OnContent(winrt::box_value(RS_(L"FreOverlay_ToggleOn")));
ShowTokenUsageAndCostToggle().OffContent(winrt::box_value(RS_(L"FreOverlay_ToggleOff")));
SessionManagementToggle().OnContent(winrt::box_value(RS_(L"FreOverlay_ToggleOn")));
SessionManagementToggle().OffContent(winrt::box_value(RS_(L"FreOverlay_ToggleOff")));
// Populate agent ComboBox using GPO-filtered list — only agents
// permitted by policy are shown. Each entry's status label reflects the
// live install state, so this is re-run after a save to flip Copilot
// from "(will install)" to "(installed)".
_PopulateAgentComboBox();
// Agent dropdown — show policy notice if AllowedAgents GPO is active
if (globals.IsAgentPolicyLocked())
{
const auto policyText = RS_(L"FreOverlay_PolicyLocked");
AgentPolicyNotice().Text(policyText);
AgentPolicyNotice().Visibility(Visibility::Visible);
Automation::AutomationProperties::SetHelpText(AgentComboBox(), policyText);
}
// Populate pane position ComboBox
auto posItems = PanePositionComboBox().Items();
posItems.Clear();
posItems.Append(winrt::box_value(RS_(L"FreOverlay_PanePositionBottom")));
posItems.Append(winrt::box_value(RS_(L"FreOverlay_PanePositionRight")));
posItems.Append(winrt::box_value(RS_(L"FreOverlay_PanePositionLeft")));
posItems.Append(winrt::box_value(RS_(L"FreOverlay_PanePositionTop")));
const auto currentPos = globals.AgentPanePosition();
if (currentPos == L"right") PanePositionComboBox().SelectedIndex(1);
else if (currentPos == L"left") PanePositionComboBox().SelectedIndex(2);
else if (currentPos == L"top") PanePositionComboBox().SelectedIndex(3);
else PanePositionComboBox().SelectedIndex(0); // default: bottom
auto handlingItems = AutoErrorHandlingComboBox().Items();
handlingItems.Clear();
const std::pair<winrt::hstring, Model::AutoErrorHandling> handlingOptions[] = {
{ RS_(L"FreOverlay_AutoErrorHandling_DetectErrorsAutomatically"), Model::AutoErrorHandling::DetectErrorsAutomatically },
{ RS_(L"FreOverlay_AutoErrorHandling_DetectErrorsAndSendToAgentForFixesAutomatically"), Model::AutoErrorHandling::DetectErrorsAndSendToAgentForFixesAutomatically },
{ RS_(L"FreOverlay_AutoErrorHandling_Off"), Model::AutoErrorHandling::Off },
};
for (const auto& [label, value] : handlingOptions)
{
ComboBoxItem item;
item.Content(winrt::box_value(label));
item.Tag(winrt::box_value(value));
if (value == Model::AutoErrorHandling::DetectErrorsAndSendToAgentForFixesAutomatically &&
globals.IsAutoErrorHandlingPolicyRestricted())
{
item.IsEnabled(false);
}
handlingItems.Append(item);
}
_SelectAutoErrorHandling(globals.EffectiveAutoErrorHandling());
_UpdateAutoErrorHandlingHint();
ShowTokenUsageAndCostToggle().IsOn(globals.ShowTokenUsageAndCost());
if (globals.IsAutoErrorHandlingPolicyRestricted())
{
const auto policyText = RS_(L"FreOverlay_PolicyLocked");
AutoErrorHandlingPolicyNotice().Text(policyText);
AutoErrorHandlingPolicyNotice().Visibility(Visibility::Visible);
Automation::AutomationProperties::SetHelpText(AutoErrorHandlingComboBox(), policyText);
}
// Session management toggle — honour AllowAgentSessionHooks GPO
if (globals.IsAgentSessionHooksPolicyLocked())
{
SessionManagementToggle().IsOn(false);
SessionManagementToggle().IsEnabled(false);
const auto policyText = RS_(L"FreOverlay_PolicyLocked");
SessionHooksPolicyNotice().Text(policyText);
SessionHooksPolicyNotice().Visibility(Visibility::Visible);
// Accessibility: explain why the toggle is disabled
Automation::AutomationProperties::SetHelpText(SessionManagementToggle(), policyText);
}
// ── Accessibility: set AutomationProperties.Name so screen readers
// announce controls and pages correctly. Re-uses existing x:Uid
// .Text values from Resources.resw — no extra keys needed.
Automation::AutomationProperties::SetName(
WelcomePage(), RS_(L"FreOverlay_WelcomeTitle/Text"));
Automation::AutomationProperties::SetName(
SettingsPage(), RS_(L"FreOverlay_SettingsTitle/Text"));
Automation::AutomationProperties::SetName(
AutoErrorHandlingComboBox(), RS_(L"FreOverlay_AutoErrorHandlingLabel/Text"));
Automation::AutomationProperties::SetName(
ShowTokenUsageAndCostToggle(), RS_(L"FreOverlay_ShowTokenUsageAndCostLabel/Text"));
Automation::AutomationProperties::SetName(
SessionManagementToggle(), RS_(L"FreOverlay_SessionLabel/Text"));
Automation::AutomationProperties::SetName(
AgentComboBox(), RS_(L"FreOverlay_AgentLabel/Text"));
Automation::AutomationProperties::SetName(
PanePositionComboBox(), RS_(L"FreOverlay_PanePositionLabel/Text"));
// Give the SavingProgressRing a localized accessible Name so
// Narrator announces "Setting up Intelligent Terminal, busy"
// when focus lands on it during a save/install (and the same
// readout on Caps+Tab mid-install). _SetSavingState defers
// the ring.Focus() call via Dispatcher().RunAsync(Low) so it
// fires after IsActive(true) and the visibility change have
// been laid out — the announcement combines this Name with
// the "busy" state from the active spinner in a single
// readout. Without this Name, Narrator would just read
// "ProgressRing".
Automation::AutomationProperties::SetName(
SavingProgressRing(), RS_(L"FreOverlay_SettingUp"));
// ── Pre-warm winget source cache ───────────────────────────────
// While the user reads the Welcome + Settings pages (typically
// 5-30s), pre-warm winget's source manifest cache so the on-Save
// install skips the slow refresh step. Best-effort, no error UI.
// Save will await any in-flight prewarm before its own winget call
// to keep the two operations serialised.
_MaybeStartPrewarm(
/*copilotMissing*/ !_IsAgentInstalled(L"copilot"),
/*nodeMissing*/ !_IsNodeInstalled());
}
// ── Agent selection changed ─────────────────────────────────────────
void FreOverlay::_OnAgentSelectionChanged(const IInspectable& /*sender*/,
const winrt::Windows::UI::Xaml::Controls::SelectionChangedEventArgs& /*args*/)
{
// Show Node.js install hint for Claude/Codex (they use npx adapters)
if (const auto selected = AgentComboBox().SelectedItem())
{
if (const auto entry = selected.try_as<winrt::TerminalApp::FreAgentEntry>())
{
const auto id = entry.Id();
const bool needsNode = (id == L"claude" || id == L"codex");
AgentInstallHintRow().Visibility(needsNode ? Visibility::Visible : Visibility::Collapsed);
}
}
}
void FreOverlay::_OnSessionManagementToggled(const IInspectable& /*sender*/,
const RoutedEventArgs& /*args*/)
{
// Guard: event can fire during InitializeComponent before controls exist
auto toggle = SessionManagementToggle();
// Hide/show the whole hint row (icon + text), not just the text — the
// monochrome FontIcon lives in the same StackPanel and would otherwise
// be left dangling when the toggle is off.
auto row = SessionManagementHintRow();
if (toggle && row)
{
row.Visibility(toggle.IsOn() ? Visibility::Visible : Visibility::Collapsed);
}
}
void FreOverlay::_OnAutoErrorHandlingSelectionChanged(
const IInspectable& /*sender*/,
const SelectionChangedEventArgs& /*args*/)
{
_UpdateAutoErrorHandlingHint();
}
Model::AutoErrorHandling FreOverlay::_SelectedAutoErrorHandling()
{
if (const auto combo = AutoErrorHandlingComboBox())
{
if (const auto item = combo.SelectedItem().try_as<ComboBoxItem>())
{
return winrt::unbox_value<Model::AutoErrorHandling>(item.Tag());
}
}
return Model::AutoErrorHandling::Off;
}
void FreOverlay::_SelectAutoErrorHandling(const Model::AutoErrorHandling value)
{
if (const auto combo = AutoErrorHandlingComboBox())
{
for (uint32_t i = 0; i < combo.Items().Size(); ++i)
{
if (const auto item = combo.Items().GetAt(i).try_as<ComboBoxItem>())
{
if (winrt::unbox_value<Model::AutoErrorHandling>(item.Tag()) == value)
{
combo.SelectedIndex(static_cast<int32_t>(i));
return;
}
}
}
combo.SelectedIndex(0);
}
}
void FreOverlay::_UpdateAutoErrorHandlingHint()
{
if (const auto row = AutoErrorHandlingShellIntegrationHintRow())
{
row.Visibility(_SelectedAutoErrorHandling() == Model::AutoErrorHandling::Off ?
Visibility::Collapsed :
Visibility::Visible);
}
}
// ── Page navigation ─────────────────────────────────────────────────
void FreOverlay::_OnNextButtonClick(const IInspectable& /*sender*/,
const RoutedEventArgs& /*args*/)
{
WelcomePage().Visibility(Visibility::Collapsed);
SettingsPage().Visibility(Visibility::Visible);
// Focus the Save button so Enter triggers it on the Settings page.
Dispatcher().RunAsync(winrt::Windows::UI::Core::CoreDispatcherPriority::Low,
[weak = get_weak()]() {
if (auto self = weak.get())
{
self->SaveButton().Focus(FocusState::Programmatic);
}
});
}
// ── WinGet source pre-warm ──────────────────────────────────────────
//
// Kick off `winget source update --name winget` in the background as
// soon as the FRE overlay is shown, so that the on-Save `winget install`
// sees a warm source manifest cache and skips the 3-20s refresh step.
// Gated on whether the install would actually run (Copilot or Node
// missing) AND winget being available. Single-flight per process —
// reentrant Initialize() calls and multi-window FRE coalesce onto
// one running prewarm. The Save handler awaits s_prewarmAction before
// its own winget call (see _SaveAndInstallAsync); in practice the
// two winget operations never run concurrently. Exception: if
// _RunPrewarmAsync hits its 120s timeout, it returns while the
// underlying `winget source update` may still be running in the
// background. We accept this tradeoff because killing winget
// mid-write risks corrupting its source DB, and 120s timeouts are
// very rare in practice. A future migration of the prewarm to the
// COM `RefreshPackageCatalogAsync` API would eliminate this race
// entirely.
void FreOverlay::_MaybeStartPrewarm(bool copilotMissing, bool nodeMissing)
{
// Gate: nothing to pre-warm if no winget install step will run.
if (!copilotMissing && !nodeMissing)
{
return;
}
if (!_IsWingetInstalled())
{
return;
}
// Single-flight: first caller wins; later callers find the
// existing IAsyncAction in the slot and bail out.
std::lock_guard<std::mutex> lock{ s_prewarmMutex };
if (s_prewarmAction)
{
return;
}
// _RunPrewarmAsync starts on the calling thread, hops to background
// at its first co_await, and returns the IAsyncAction handle here
// for storage and later co_await by Save.
s_prewarmAction = _RunPrewarmAsync();
}
winrt::Windows::Foundation::IAsyncAction FreOverlay::_RunPrewarmAsync()
{
// Hop to background — must never block the UI thread.
co_await winrt::resume_background();
try
{
_agentPaneLog("[FRE] Pre-warm: winget source update --name winget");
STARTUPINFOW si{};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi{};
// CreateProcessW requires a *writable* cmdline buffer (it may
// mutate the string in-place when parsing). `--disable-interactivity`
// prevents any prompt (e.g. source first-run agreement) from
// hanging the hidden child process forever.
wchar_t cmdline[] = L"winget source update --name winget --disable-interactivity";
if (!CreateProcessW(nullptr, cmdline, nullptr, nullptr, FALSE,
CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi))
{
_agentPaneLog("[FRE] Pre-warm: CreateProcess failed err="
+ std::to_string(GetLastError()));
co_return;
}
// Wait up to 120s. Corporate proxies / cold caches can push
// honest cases past 30s, so we err on the side of patience.
// We deliberately do NOT TerminateProcess on timeout: killing
// winget mid-write can corrupt its source DB. The Save handler
// awaits this whole coroutine, which only completes after
// WaitForSingleObject returns, so even a slow prewarm cannot
// collide with the eventual install.
const DWORD wait = WaitForSingleObject(pi.hProcess, 120000);
DWORD exitCode = 0;
GetExitCodeProcess(pi.hProcess, &exitCode);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
_agentPaneLog(wait == WAIT_TIMEOUT
? "[FRE] Pre-warm: still running after 120s (proceeding)"
: "[FRE] Pre-warm: completed exit=" + std::to_string(exitCode));
}
catch (...)
{
// Pre-warm is strictly best-effort; never let an exception
// escape into the IAsyncAction promise. Save's co_await on
// s_prewarmAction also has its own try/catch as belt-and-
// suspenders, but this is the primary guard.
LOG_CAUGHT_EXCEPTION();
}
}
// ── WinGet install helper ───────────────────────────────────────────
//
// Installs a package via the WinGet COM/WinRT API
// (`Microsoft.Management.Deployment.PackageManager`) instead of
// shelling out to `winget.exe`.
//
// Why this matters:
//
// The CLI path doesn't work for us. winget.exe, when launched from
// a packaged GUI parent (which IT is), runs through an App Execution
// Alias activation that breaks stdio inheritance — child writes
// nothing to whatever pipe/file we redirect to. We verified across
// 6 spawn variants (NUL stdin, pipe stdin, GetStdHandle stdin,
// combined vs split pipes, plus `cmd.exe /c "winget … > tempfile 2>&1"`)
// that the captured output is consistently 0 bytes for real failures.
// This is a Microsoft design limitation, not a winget bug:
// packaged-from-packaged stdio inheritance is documented as unsupported
// (see https://github.com/microsoft/winget-cli/issues/504).
//
// The COM API bypasses the alias activation entirely — it calls
// AppInstaller's out-of-proc COM server directly via CoCreateInstance
// (CLSCTX_LOCAL_SERVER, no child process spawn). We get back a
// structured InstallResult with InstallResultStatus, ExtendedErrorCode
// (the same HRESULT that the CLI would have printed), and
// InstallerErrorCode — far better diagnostics than the CLI ever gave
// us, and reliably available from packaged context.
namespace
{
using namespace winrt::Microsoft::Management::Deployment;
// Enum-to-string helpers — log values are human-readable instead
// of bare ints, so anyone reading the log can grep the winmd /
// PackageManager.idl directly without an enum reference table.
constexpr const char* ConnectStatusName(ConnectResultStatus s) noexcept
{
switch (s)
{
case ConnectResultStatus::Ok: return "Ok";
case ConnectResultStatus::CatalogError: return "CatalogError";
case ConnectResultStatus::SourceAgreementsNotAccepted: return "SourceAgreementsNotAccepted";
default: return "Unknown";
}
}
constexpr const char* FindStatusName(FindPackagesResultStatus s) noexcept
{
switch (s)
{
case FindPackagesResultStatus::Ok: return "Ok";
case FindPackagesResultStatus::BlockedByPolicy: return "BlockedByPolicy";
case FindPackagesResultStatus::CatalogError: return "CatalogError";
case FindPackagesResultStatus::InvalidOptions: return "InvalidOptions";
case FindPackagesResultStatus::InternalError: return "InternalError";
default: return "Unknown";
}
}
constexpr const char* InstallStatusName(InstallResultStatus s) noexcept
{
switch (s)
{
case InstallResultStatus::Ok: return "Ok";
case InstallResultStatus::BlockedByPolicy: return "BlockedByPolicy";
case InstallResultStatus::CatalogError: return "CatalogError";
case InstallResultStatus::InternalError: return "InternalError";
case InstallResultStatus::InvalidOptions: return "InvalidOptions";
case InstallResultStatus::DownloadError: return "DownloadError";
case InstallResultStatus::InstallError: return "InstallError";
case InstallResultStatus::ManifestError: return "ManifestError";
case InstallResultStatus::NoApplicableInstallers: return "NoApplicableInstallers";
case InstallResultStatus::NoApplicableUpgrade: return "NoApplicableUpgrade";
case InstallResultStatus::PackageAgreementsNotAccepted: return "PackageAgreementsNotAccepted";
default: return "Unknown";
}
}
// Copy winget's own diagnostic logs from AppInstaller's DiagOutputDir
// into our per-version `winget\` subfolder, so the bug-report zip
// picks them up alongside `terminal-agent-pane.log`.
//
// Why this matters: our [FRE] log only records the final
// InstallResultStatus + HRESULT + InstallerErrorCode. The winget
// COM API internally writes a much more detailed trace (HTTP
// request URLs, retry attempts, hash/signature verification,
// installer-exec arguments, MSI verbose output) to its own log
// files. When `winget install GitHub.Copilot` fails on a user's
// box, that detailed trace is what tells us *why* — without it,
// bug reports come down to "install failed, here's a generic
// HRESULT". Colocating the logs gives us triage-grade diagnostics.
//
// Filtering: anything `.log` modified at or after `since` in the
// DiagOutputDir is copied. We avoid filename-prefix assumptions
// (winget has historically used `WinGet-*.log`, but a future
// release could add `WinGetCOM-*.log` or similar and we'd
// silently miss it).
//
// Defensive size caps: skip any single file larger than
// kPerFileCapBytes and abort the loop once kTotalCapBytes have
// been copied. Without these, a stale clock, an aggressive
// verbose-MSI run, or unrelated concurrent winget activity could
// dump tens of MB into our log folder.
//
// DiagOutputDir path is `Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\`
// hardcoded. This package family name has been stable for 5+
// years; if it ever moves, the helper logs "DiagOutputDir not
// found" and returns — no exception bubbles to the install
// coroutine.
//
// Timeout caveat: when the install path hits our 20-min hard
// cap, winget's underlying installer may still be running when
// we copy its log. The captured file may therefore be
// truncated (missing the very last entries). We do not delay
// copy on timeout because winget can keep writing for an
// arbitrary additional time — a bounded sleep would not
// reliably get the "final" log, just the "slightly less
// truncated" one. Engineers needing the absolutely final
// contents can grab the source files from DiagOutputDir
// directly post-mortem.
//
// noexcept-from-caller: every failure mode (env var missing,
// ACL deny, disk full, file lock race) is swallowed with a log
// line. The install flow never sees an exception from here.
static void _CopyWingetLogsSince(std::filesystem::file_time_type since) noexcept
{
try
{
// Defensive caps. Per-file cap protects against a single
// verbose-MSI log eating our disk; total cap is the
// ceiling across all files in this capture.
constexpr std::uintmax_t kPerFileCapBytes = 25ULL * 1024ULL * 1024ULL; // 25 MB
constexpr std::uintmax_t kTotalCapBytes = 50ULL * 1024ULL * 1024ULL; // 50 MB
wchar_t localAppData[MAX_PATH]{};
const DWORD lenWritten =
GetEnvironmentVariableW(L"LOCALAPPDATA", localAppData, MAX_PATH);
// Treat both "missing" (0) and "would have truncated"
// (>= MAX_PATH) as "give up" — a multi-thousand-char
// %LOCALAPPDATA% is unusual enough that capturing logs
// for that user isn't worth the extra alloc dance.
if (lenWritten == 0 || lenWritten >= MAX_PATH)
{
return;
}
const std::filesystem::path diagDir =
std::filesystem::path{ localAppData } /
L"Packages" /
L"Microsoft.DesktopAppInstaller_8wekyb3d8bbwe" /
L"LocalState" /
L"DiagOutputDir";
std::error_code ec;
if (!std::filesystem::exists(diagDir, ec) || ec)
{
_agentPaneLog("[FRE] winget DiagOutputDir not present, skipping log capture");
return;
}
const auto destDir = ::IntelligentTerminal::LogDirVersioned() / L"winget";
std::filesystem::create_directories(destDir, ec);
if (ec)
{
return;
}
int copied = 0;
int skipped = 0;
std::uintmax_t totalBytes = 0;
// Iterate explicitly with `increment(ec)` instead of
// range-for: the latter's `operator++` can throw on
// filesystem races (file deleted mid-scan, antivirus
// contention), which would unwind out of our noexcept
// contract via the outer catch. Explicit increment lets
// us treat every iteration step as a soft failure that
// skips the entry and continues.
std::filesystem::directory_iterator it{ diagDir, ec };
const std::filesystem::directory_iterator end{};
if (ec)
{
_agentPaneLog(fmt::format(
"[FRE] winget log capture: failed to open DiagOutputDir ({})",
ec.message()));
return;
}
while (it != end)
{
const auto entryPath = it->path();
bool entryHandled = false;
if (it->is_regular_file(ec) && !ec &&
entryPath.extension() == L".log")
{
const auto mtime = std::filesystem::last_write_time(entryPath, ec);
const auto fileSize = !ec ? std::filesystem::file_size(entryPath, ec) : 0;
if (!ec && mtime >= since)
{
if (fileSize > kPerFileCapBytes)
{
_agentPaneLog(fmt::format(
"[FRE] winget log capture: skipping {} (size {} > per-file cap {})",
winrt::to_string(entryPath.filename().wstring()),
fileSize,
kPerFileCapBytes));
++skipped;
entryHandled = true;
}
else if (totalBytes + fileSize > kTotalCapBytes)
{
_agentPaneLog(fmt::format(
"[FRE] winget log capture: total cap {} reached after {} files; stopping",
kTotalCapBytes,
copied));
break;
}
else
{
std::filesystem::copy_file(
entryPath,
destDir / entryPath.filename(),
std::filesystem::copy_options::overwrite_existing,
ec);
if (ec)
{
++skipped;
}
else
{
++copied;
totalBytes += fileSize;
}
entryHandled = true;
}
}
}
(void)entryHandled;
ec.clear();
it.increment(ec);
if (ec)
{
// Soft-stop on iterator failure — better to
// report partial capture than to throw.
_agentPaneLog(fmt::format(
"[FRE] winget log capture: iterator error ({}); stopping early",
ec.message()));
break;
}
}
_agentPaneLog(fmt::format(
"[FRE] winget log capture: copied={} skipped={} bytes={} dest={}",
copied,
skipped,
totalBytes,
winrt::to_string(destDir.wstring())));
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
}
}
IAsyncOperation<int32_t> FreOverlay::_WingetInstallAsync(winrt::hstring packageId)
{
using namespace winrt::Microsoft::Management::Deployment;
using Kind = FreWingetFailureKind;
// Capture a weak reference so writes to _lastWinget* are safe even
// if the overlay is destroyed mid-await (e.g. user dismissed the
// window during a long install).
auto weak = get_weak();
// Snapshot the install start time before any winget work. Used as
// the cutoff for the post-install DiagOutputDir log capture so we
// pick up every log winget produced for this attempt — including
// long-running install logs that started 10+ minutes ago — and not
// logs from unrelated prior winget activity.
const auto installStartTime = std::filesystem::file_time_type::clock::now();
// Helper: persist diagnostic state to the instance (so the caller
// can read it after our co_return), capture any fresh winget logs
// from AppInstaller's DiagOutputDir on failure paths, and return
// the encoded kind. Called from EVERY co_return — the
// success/failure branch lives inside.
//
// Why only-on-failure for the log copy: the bug-report use case
// for the colocated winget logs is "install failed, we need
// triage details". Successful installs don't need the extra
// logs, and copying them anyway would (a) waste a few MB of
// disk per FRE run for no benefit, and (b) silently include any
// unrelated concurrent winget activity captured by the mtime
// window into the bug-report zip (e.g. URLs to private package
// sources the user happened to be browsing in another shell).
auto finish = [&weak, installStartTime](Kind k, int32_t hr, uint32_t installerErr) {
if (auto self = weak.get())
{
self->_lastWingetHr = hr;
self->_lastWingetInstallerErrorCode = installerErr;
}
if (k != Kind::Success)
{
_CopyWingetLogsSince(installStartTime);
}
return static_cast<int32_t>(k);
};
// Copy packageId before switching threads (coroutine parameter safety)
auto id = winrt::hstring{ packageId };
// Local diagnostic state. Written to the instance fields only via
// `finish(...)` immediately before each co_return, so the caller
// always sees consistent (kind, hr, installerErr) tuples and a
// stale value never leaks across calls.
int32_t hr = 0;
uint32_t installerErr = 0;
co_await winrt::resume_background();
try
{
// ── 1. Activate the out-of-proc PackageManager COM server ──
const PackageManager pm = WindowsPackageManagerFactory::CreatePackageManager();
// ── 2. Connect to the winget catalog ──
// Mirror the pattern used by `TerminalPage._FindPackageAsync`:
// up to 3 attempts to absorb transient connection flakes.
// Set AcceptSourceAgreements(true) — equivalent to the CLI's
// --accept-source-agreements; without this, first-time winget
// users (no prior agreement acceptance recorded) would hit
// SourceAgreementsNotAccepted and be unable to install.
auto catalogRef = pm.GetPredefinedPackageCatalog(PredefinedPackageCatalog::OpenWindowsCatalog);
catalogRef.AcceptSourceAgreements(true);
ConnectResult connectResult{ nullptr };
for (int attempt = 0; attempt < 3; ++attempt)
{
connectResult = catalogRef.Connect();
if (connectResult.Status() == ConnectResultStatus::Ok)
{
break;
}
}
if (connectResult.Status() != ConnectResultStatus::Ok)
{
_agentPaneLog(fmt::format(
"[FRE] winget catalog connect failed: {} (status={})",
ConnectStatusName(connectResult.Status()),
static_cast<int>(connectResult.Status())));
// CatalogError during connect almost always means we
// couldn't reach the catalog server (DNS / TLS / proxy /
// firewall). The 1.8 contract doesn't expose
// ConnectResult.ExtendedErrorCode so we can't whitelist
// here — treat the catalog-error case as Network and
// anything else (SourceAgreementsNotAccepted, future
// statuses) as Generic.
co_return finish(connectResult.Status() == ConnectResultStatus::CatalogError
? Kind::Network
: Kind::Generic,
hr, installerErr);
}
// ── 3. Find the package by exact ID ──
auto filter = WindowsPackageManagerFactory::CreatePackageMatchFilter();
filter.Field(PackageMatchField::Id);
filter.Option(PackageFieldMatchOption::Equals);
filter.Value(id);
auto findOpts = WindowsPackageManagerFactory::CreateFindPackagesOptions();
findOpts.Filters().Append(filter);
findOpts.ResultLimit(1);
const auto findResult = co_await connectResult.PackageCatalog().FindPackagesAsync(findOpts);
if (findResult.Status() != FindPackagesResultStatus::Ok)
{
_agentPaneLog(fmt::format(
"[FRE] winget FindPackages failed: {} (status={})",
FindStatusName(findResult.Status()),
static_cast<int>(findResult.Status())));
co_return finish(findResult.Status() == FindPackagesResultStatus::BlockedByPolicy
? Kind::BlockedByPolicy
: Kind::Generic,
hr, installerErr);
}
if (findResult.Matches().Size() == 0)
{
_agentPaneLog("[FRE] winget package not found: " + winrt::to_string(id));
co_return finish(Kind::PackageNotFound, hr, installerErr);
}
const CatalogPackage package = findResult.Matches().GetAt(0).CatalogPackage();
// ── 4. Configure install options and kick off install ──
auto installOpts = WindowsPackageManagerFactory::CreateInstallOptions();
installOpts.AcceptPackageAgreements(true);
installOpts.PackageInstallMode(PackageInstallMode::Silent);
installOpts.PackageInstallScope(PackageInstallScope::Any);
const auto installOp = pm.InstallPackageAsync(package, installOpts);
// ── 5. Bounded wait for install to complete ──
// The COM API has no built-in timeout. Without one, a stuck
// broker / unreachable installer would freeze the FRE Save
// flow indefinitely. We allow up to 20 min (observed cold
// installs are ~5-6 min, so 20 min covers the P99 with a
// ~3x safety margin); at the 5 min mark we log a heads-up
// so anyone tailing the log can tell "still running" apart
// from "deadlocked".
constexpr DWORD kInstallSoftWarnMs = 5 * 60 * 1000; // 5 min
constexpr DWORD kInstallHardCapMs = 20 * 60 * 1000; // 20 min
const auto startTick = GetTickCount64();
bool warnedSoft = false;
while (installOp.Status() == winrt::Windows::Foundation::AsyncStatus::Started)
{
const auto elapsed = GetTickCount64() - startTick;
if (!warnedSoft && elapsed > kInstallSoftWarnMs)
{
_agentPaneLog("[FRE] winget install: still running after 5 min, will hard-cancel at 20 min");
warnedSoft = true;
}
if (elapsed > kInstallHardCapMs)
{
// Cancel is best-effort — if the installer's already
// running, it may keep going in the background. We
// surface that nuance in the user-facing Timeout
// message (see FreOverlay_InstallError_Timeout).
_agentPaneLog("[FRE] winget install: hard timeout after 20 min, cancelling");
installOp.Cancel();
co_return finish(Kind::Timeout, hr, installerErr);
}
co_await winrt::resume_after(std::chrono::milliseconds(500));
}
const auto installResult = installOp.GetResults();
const auto status = installResult.Status();
const auto exHr = installResult.ExtendedErrorCode();
const auto rawInstallerErr = installResult.InstallerErrorCode();
hr = static_cast<int32_t>(exHr);
installerErr = rawInstallerErr;
if (status != InstallResultStatus::Ok)
{
_agentPaneLog(fmt::format(
"[FRE] winget install failed: {} (status={}) hr=0x{:08X} installerErr={}",
InstallStatusName(status),
static_cast<int>(status),
static_cast<uint32_t>(exHr),
rawInstallerErr));
Kind kind = Kind::Generic;
switch (status)
{
case InstallResultStatus::BlockedByPolicy: