-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVSCodeSidePanelLayout.ps1
More file actions
2749 lines (2302 loc) · 97.7 KB
/
VSCodeSidePanelLayout.ps1
File metadata and controls
2749 lines (2302 loc) · 97.7 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
# VS Code Side Panel Layout Script
# Hotkey: Ctrl+Alt+V (dual monitor), Ctrl+Alt+N (top monitors)
# Snaps VS Code window and resizes auxiliary bar via CDP sash drag (no cursor movement)
# Trusts the live CDP endpoint/targets and keeps current windows open if CDP is not ready yet
# reprompty-mcp: {"toolName":"dual_monitor_layout_bottom","label":"Dual monitor layout (bottom)","description":"Run the Ctrl+Alt+V dual monitor bottom layout","args":["-Once"]}
# reprompty-mcp: {"toolName":"top_monitors_layout_panel_full","label":"Top monitors layout (panel full)","description":"Run the Ctrl+Alt+N top monitors panel-full layout","args":["-SingleOnce"]}
param(
[switch]$Once, # Run Ctrl+Alt+V layout once (dual monitors bottom)
[switch]$SingleOnce, # Run Ctrl+Alt+N layout once (top monitors)
[switch]$Duplicate, # Duplicate window first, then snap
[string]$WindowTitle = "", # Target a specific VS Code window by title
[Int64]$WindowHandle = 0, # Target a specific VS Code window by exact handle
[string]$LogPath = "", # Optional per-run layout transcript path
[switch]$RepairOnly, # Internal: run fast-check-first repair and exit
[string]$RepairTriggerSource = "manual", # Internal repair trigger source
[switch]$StartupRepairOnly, # Re-apply CDP launch hooks and exit
[switch]$InstallStartup, # Install startup repair entry
[switch]$UninstallStartup # Remove startup repair entry
)
# ============================================================
# Ensure VS Code always launches with --remote-debugging-port
# Uses a hybrid wrapper install:
# - swaps install-path Code.exe with a forwarding wrapper for first-launch coverage
# - keeps stable external shims and shell overrides for update repair
# ============================================================
$CDPPort = 9222
$cdpFlag = "--remote-debugging-port=$CDPPort"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ScriptPath = $MyInvocation.MyCommand.Path
$StartupRunKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
$StartupValueName = "VSCodeSidePanelLayoutCDPRepair"
$PowerShellExe = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
$UserEnvironmentKey = "HKCU:\Environment"
$UserPathBackupValueName = "VSCodeSidePanelLayoutPathBackup"
$UserTempPath = Join-Path $env:LOCALAPPDATA "Temp"
$CodeInstallDir = Join-Path $env:LOCALAPPDATA "Programs\Microsoft VS Code"
$ManagedCodePath = Join-Path $CodeInstallDir "Code.exe"
$ManagedRealCodePath = Join-Path $CodeInstallDir "Code.real.exe"
$PendingRealCodePath = Join-Path $CodeInstallDir "Code.real.pending.exe"
$ManagedMarkerPath = Join-Path $CodeInstallDir "Code.cdp-wrapper.marker"
$RepairLogDir = Join-Path $env:LOCALAPPDATA "VSCodeSidePanelLayout"
$RepairLogPath = Join-Path $RepairLogDir "repair.log"
$VSCodeArgvJsonPath = Join-Path $env:USERPROFILE ".vscode\argv.json"
$ShimDir = Join-Path $env:LOCALAPPDATA "CodeCDPShim"
$ShimExePath = Join-Path $ShimDir "code.exe"
$ShimCmdPath = Join-Path $ShimDir "code.cmd"
$WrapperSrcPath = Join-Path $ScriptDir "CodeCDPWrapper.cs"
$WrapperExePath = Join-Path $ScriptDir "CodeCDPWrapper.exe"
$WrapperIconPath = Join-Path $ScriptDir "CodeCDPWrapper.ico"
$IfeoKey = "HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\Code.exe"
$DevToolsActivePortPath = Join-Path $env:APPDATA "Code\DevToolsActivePort"
$IntegrityPollIntervalMs = 2000
$RepairDebounceMs = 5000
$RepairMutexName = "Local\VSCodeSidePanelLayoutCDPRepair"
$script:LastIntegrityPollAt = [DateTime]::MinValue
$script:LastDriftRepairAt = [DateTime]::MinValue
$script:LastDriftSignature = ""
$script:LastRepairLockNoticeAt = [DateTime]::MinValue
function Write-RepairLog {
param(
[string]$Message,
[string]$Level = "INFO"
)
try {
New-Item -ItemType Directory -Path $RepairLogDir -Force -ErrorAction SilentlyContinue | Out-Null
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
Add-Content -LiteralPath $RepairLogPath -Value "[$timestamp] [$Level] $Message" -Encoding UTF8
} catch {
# Logging should never block repair.
}
}
$script:LayoutTranscriptActive = $false
function Start-LayoutRunLogging {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) {
return
}
try {
$parentDir = Split-Path -Parent $Path
if (-not [string]::IsNullOrWhiteSpace($parentDir)) {
New-Item -ItemType Directory -Path $parentDir -Force -ErrorAction SilentlyContinue | Out-Null
}
Start-Transcript -Path $Path -Force | Out-Null
$script:LayoutTranscriptActive = $true
Write-Host " Layout transcript: $Path" -ForegroundColor DarkGray
} catch {
Write-RepairLog "Failed to start layout transcript at '$Path': $($_.Exception.Message)" "WARN"
}
}
function Stop-LayoutRunLogging {
if (-not $script:LayoutTranscriptActive) {
return
}
try {
Stop-Transcript | Out-Null
} catch {
Write-RepairLog "Failed to stop layout transcript: $($_.Exception.Message)" "WARN"
} finally {
$script:LayoutTranscriptActive = $false
}
}
function Get-VSCodeArgvJsonStatus {
$fileExists = Test-Path -LiteralPath $VSCodeArgvJsonPath
$rawValue = ""
$matchesPort = $false
$errorMessage = ""
if ($fileExists) {
try {
$content = Get-Content -LiteralPath $VSCodeArgvJsonPath -Raw -ErrorAction Stop
$match = [regex]::Match($content, '"remote-debugging-port"\s*:\s*"(?<port>[^"]+)"', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($match.Success) {
$rawValue = $match.Groups['port'].Value
}
$matchesPort = $rawValue -eq "$CDPPort"
} catch {
$errorMessage = $_.Exception.Message
}
}
return [pscustomobject]@{
Path = $VSCodeArgvJsonPath
FileExists = $fileExists
RawValue = $rawValue
MatchesPort = $matchesPort
ErrorMessage = $errorMessage
}
}
function Ensure-VSCodeArgvJsonPort {
$parentDir = Split-Path -Parent $VSCodeArgvJsonPath
New-Item -ItemType Directory -Path $parentDir -Force -ErrorAction SilentlyContinue | Out-Null
$fileAlreadyExists = Test-Path -LiteralPath $VSCodeArgvJsonPath
$rawContent =
if ($fileAlreadyExists) {
Get-Content -LiteralPath $VSCodeArgvJsonPath -Raw -ErrorAction Stop
} else {
@"
// This configuration file allows you to pass permanent command line arguments to VS Code.
// Only a subset of arguments is currently supported to reduce the likelihood of breaking
// the installation.
//
// PLEASE DO NOT CHANGE WITHOUT UNDERSTANDING THE IMPACT
//
// NOTE: Changing this file requires a restart of VS Code.
{
"remote-debugging-port": "$CDPPort"
}
"@
}
$updatedContent = $rawContent
$desiredProperty = ('"remote-debugging-port": "{0}"' -f $CDPPort)
$existingPropertyPattern = '"remote-debugging-port"\s*:\s*(?:"[^"]*"|\d+)'
if ([regex]::IsMatch($updatedContent, $existingPropertyPattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) {
$updatedContent = [regex]::Replace(
$updatedContent,
$existingPropertyPattern,
$desiredProperty,
[System.Text.RegularExpressions.RegexOptions]::IgnoreCase
)
} else {
$newline = if ($updatedContent -match "`r`n") { "`r`n" } else { "`n" }
$contentWithoutLineComments = [regex]::Replace($updatedContent, '(?m)^\s*//.*$', '')
$hasAnyProperty = $contentWithoutLineComments -match '"[^"]+"\s*:'
$commaPrefix = if ($hasAnyProperty) { "," } else { "" }
$insertion = "$commaPrefix$newline`t$desiredProperty$newline"
$updatedContent = [regex]::Replace($updatedContent.TrimEnd(), '\}\s*$', "$insertion}", 1)
}
if (($updatedContent -ne $rawContent) -or -not $fileAlreadyExists) {
Set-Content -LiteralPath $VSCodeArgvJsonPath -Value $updatedContent -Encoding Ascii
return $true
}
return $false
}
function Invoke-VSCodeArgvJsonEnsure {
param(
[string]$TriggerSource = "manual",
[switch]$WriteConsoleNotice
)
try {
$updated = Ensure-VSCodeArgvJsonPort
$status = Get-VSCodeArgvJsonStatus
if ($updated) {
Write-RepairLog "Ensured argv.json remote-debugging-port for source '$TriggerSource'."
if ($WriteConsoleNotice) {
Write-Host " Ensured argv.json remote-debugging-port=$CDPPort before evaluating CDP health..." -ForegroundColor DarkGray
}
}
return [pscustomobject]@{
Updated = $updated
Status = $status
ErrorMessage = ""
}
} catch {
$errorMessage = $_.Exception.Message
Write-RepairLog "Failed to ensure argv.json for source '$TriggerSource': $errorMessage" "WARN"
return [pscustomobject]@{
Updated = $false
Status = Get-VSCodeArgvJsonStatus
ErrorMessage = $errorMessage
}
}
}
function Format-RepairElapsed {
param([System.Diagnostics.Stopwatch]$Stopwatch)
if ($null -eq $Stopwatch) {
return "0 ms"
}
return "$($Stopwatch.ElapsedMilliseconds) ms"
}
function Test-CDPRepairInProgress {
$mutex = $null
$lockAcquired = $false
try {
$mutex = New-Object System.Threading.Mutex($false, $RepairMutexName)
try {
$lockAcquired = $mutex.WaitOne(0)
} catch [System.Threading.AbandonedMutexException] {
$lockAcquired = $true
}
if ($lockAcquired) {
$mutex.ReleaseMutex()
return $false
}
return $true
} finally {
if ($null -ne $mutex) {
$mutex.Dispose()
}
}
}
function Invoke-CDPLaunchRepairCore {
param(
[string]$TriggerSource,
[string[]]$DetectionReasons = @()
)
$mutex = $null
$lockAcquired = $false
try {
$mutex = New-Object System.Threading.Mutex($false, $RepairMutexName)
try {
$lockAcquired = $mutex.WaitOne(0)
} catch [System.Threading.AbandonedMutexException] {
$lockAcquired = $true
}
if (-not $lockAcquired) {
Write-RepairLog "Repair already in progress; source=$TriggerSource reused the in-flight repair."
return "locked"
}
Install-CDPLaunchHooks -Quiet -TriggerSource $TriggerSource -DetectionReasons $DetectionReasons
return "completed"
} catch {
Write-RepairLog "Repair execution failed for source '$TriggerSource': $($_.Exception.Message)" "ERROR"
return "failed"
} finally {
if ($lockAcquired -and $null -ne $mutex) {
try {
$mutex.ReleaseMutex()
} catch {
# Ignore release issues during shutdown.
}
}
if ($null -ne $mutex) {
$mutex.Dispose()
}
}
}
function Start-CDPBackgroundRepair {
param([string]$TriggerSource)
try {
$process = Start-Process -FilePath $PowerShellExe -ArgumentList @(
"-NoProfile",
"-WindowStyle", "Hidden",
"-ExecutionPolicy", "Bypass",
"-File", $ScriptPath,
"-RepairOnly",
"-RepairTriggerSource", $TriggerSource
) -WindowStyle Hidden -PassThru
Write-RepairLog "Queued background repair process $($process.Id) for trigger '$TriggerSource'."
return $true
} catch {
Write-RepairLog "Failed to queue background repair for '$TriggerSource': $($_.Exception.Message)" "ERROR"
return $false
}
}
function Write-ManagedInstallMarker {
Set-Content -LiteralPath $ManagedMarkerPath -Value "Managed by VSCodeSidePanelLayout" -Encoding Ascii
}
function Get-ManagedShortcutPaths {
return @(
"$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Visual Studio Code\Visual Studio Code.lnk",
"$env:APPDATA\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Visual Studio Code.lnk",
"$env:USERPROFILE\Desktop\Visual Studio Code.lnk"
)
}
function Get-ExpectedShellCommandDefinitions {
param([string]$WrapperExe)
return @(
[pscustomobject]@{ KeyPath = "HKCU:\Software\Classes\Applications\Code.exe\shell\open\command"; CommandValue = ('"{0}" "%1"' -f $WrapperExe) },
[pscustomobject]@{ KeyPath = "HKCU:\Software\Classes\VSCodeSourceFile\shell\open\command"; CommandValue = ('"{0}" "%1"' -f $WrapperExe) },
[pscustomobject]@{ KeyPath = "HKCU:\Software\Classes\Directory\shell\VSCode\command"; CommandValue = ('"{0}" "%V"' -f $WrapperExe) },
[pscustomobject]@{ KeyPath = "HKCU:\Software\Classes\Directory\Background\shell\VSCode\command"; CommandValue = ('"{0}" "%V"' -f $WrapperExe) }
)
}
function Promote-PendingRealCode {
if (-not (Test-Path -LiteralPath $PendingRealCodePath)) {
return $false
}
if ((Test-Path -LiteralPath $ManagedRealCodePath) -and (Test-FilesMatch -PathA $PendingRealCodePath -PathB $ManagedRealCodePath)) {
Remove-Item -LiteralPath $PendingRealCodePath -Force -ErrorAction SilentlyContinue
Write-RepairLog "Removed redundant staged Code.real pending update because it already matches Code.real.exe."
return $true
}
try {
Copy-Item -LiteralPath $PendingRealCodePath -Destination $ManagedRealCodePath -Force -ErrorAction Stop
Remove-Item -LiteralPath $PendingRealCodePath -Force -ErrorAction SilentlyContinue
Write-RepairLog "Promoted staged Code.real pending update into Code.real.exe."
return $true
} catch {
Write-RepairLog "Deferred staged Code.real pending update: $($_.Exception.Message)"
return $false
}
}
function Test-FilesMatch {
param(
[string]$PathA,
[string]$PathB
)
if (-not (Test-Path -LiteralPath $PathA) -or -not (Test-Path -LiteralPath $PathB)) {
return $false
}
try {
$hashA = (Get-FileHash -LiteralPath $PathA -Algorithm SHA256).Hash
$hashB = (Get-FileHash -LiteralPath $PathB -Algorithm SHA256).Hash
return $hashA -eq $hashB
} catch {
return $false
}
}
function Test-IsVSCodeBinary {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
return $false
}
try {
$info = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($Path)
return (
$info.FileDescription -eq "Visual Studio Code" -or
$info.ProductName -eq "Visual Studio Code" -or
$info.OriginalFilename -eq "electron.exe"
)
} catch {
return $false
}
}
function Ensure-UsableTempEnvironment {
param([switch]$PersistUserVariables)
New-Item -ItemType Directory -Path $UserTempPath -Force -ErrorAction SilentlyContinue | Out-Null
$env:TEMP = $UserTempPath
$env:TMP = $UserTempPath
if ($PersistUserVariables) {
New-Item -Path $UserEnvironmentKey -Force -ErrorAction SilentlyContinue | Out-Null
$existingTemp = [Environment]::GetEnvironmentVariable("TEMP", "User")
$existingTmp = [Environment]::GetEnvironmentVariable("TMP", "User")
if ([string]::IsNullOrWhiteSpace($existingTemp) -or $existingTemp -ieq "C:\Windows\TEMP") {
New-ItemProperty -Path $UserEnvironmentKey -Name TEMP -Value $UserTempPath -PropertyType String -Force | Out-Null
}
if ([string]::IsNullOrWhiteSpace($existingTmp) -or $existingTmp -ieq "C:\Windows\TEMP") {
New-ItemProperty -Path $UserEnvironmentKey -Name TMP -Value $UserTempPath -PropertyType String -Force | Out-Null
}
}
}
function Ensure-CodeWrapperIcon {
$iconSourcePath = $null
if (Test-Path -LiteralPath $ManagedRealCodePath) {
$iconSourcePath = $ManagedRealCodePath
} elseif (Test-IsVSCodeBinary -Path $ManagedCodePath) {
$iconSourcePath = $ManagedCodePath
}
if ([string]::IsNullOrWhiteSpace($iconSourcePath)) {
return $null
}
$needsRefresh =
-not (Test-Path -LiteralPath $WrapperIconPath) -or
(Get-Item -LiteralPath $iconSourcePath).LastWriteTime -gt (Get-Item -LiteralPath $WrapperIconPath).LastWriteTime
if ($needsRefresh) {
Add-Type -AssemblyName System.Drawing
$icon = [System.Drawing.Icon]::ExtractAssociatedIcon($iconSourcePath)
if ($null -ne $icon) {
$stream = [System.IO.File]::Create($WrapperIconPath)
try {
$icon.Save($stream)
} finally {
$stream.Dispose()
$icon.Dispose()
}
}
}
if (Test-Path -LiteralPath $WrapperIconPath) {
return $WrapperIconPath
}
return $null
}
function Ensure-CodeWrapperCompiled {
param([switch]$Quiet)
$cscPath = Join-Path $env:SystemRoot "Microsoft.NET\Framework64\v4.0.30319\csc.exe"
$iconPath = Ensure-CodeWrapperIcon
if (-not (Test-Path -LiteralPath $WrapperSrcPath)) {
throw "Wrapper source not found: $WrapperSrcPath"
}
if (-not (Test-Path -LiteralPath $cscPath)) {
throw "C# compiler not found: $cscPath"
}
$needsCompile =
-not (Test-Path -LiteralPath $WrapperExePath) -or
(Get-Item -LiteralPath $WrapperSrcPath).LastWriteTime -gt (Get-Item -LiteralPath $WrapperExePath).LastWriteTime -or
($iconPath -and (Test-Path -LiteralPath $iconPath) -and ((Get-Item -LiteralPath $iconPath).LastWriteTime -gt (Get-Item -LiteralPath $WrapperExePath).LastWriteTime))
if ($needsCompile) {
$compileArgs = @(
"-nologo",
"-target:winexe",
"-out:$WrapperExePath"
)
if ($iconPath) {
$compileArgs += "-win32icon:$iconPath"
}
$compileArgs += $WrapperSrcPath
& $cscPath @compileArgs 2>$null
}
if (-not (Test-Path -LiteralPath $WrapperExePath)) {
throw "Wrapper executable was not produced: $WrapperExePath"
}
return $WrapperExePath
}
function Get-CodeInstallState {
param([string]$SourceWrapperExe)
$managedCodeExists = Test-Path -LiteralPath $ManagedCodePath
$managedRealExists = Test-Path -LiteralPath $ManagedRealCodePath
$markerExists = Test-Path -LiteralPath $ManagedMarkerPath
$managedCodeIsWrapper = $false
$managedCodeIsVSCode = $false
$managedRealIsVSCode = $false
if ($managedCodeExists) {
$managedCodeIsWrapper = Test-FilesMatch -PathA $ManagedCodePath -PathB $SourceWrapperExe
$managedCodeIsVSCode = Test-IsVSCodeBinary -Path $ManagedCodePath
}
if ($managedRealExists) {
$managedRealIsVSCode = Test-IsVSCodeBinary -Path $ManagedRealCodePath
}
$state = switch ($true) {
{ $managedCodeExists -and $managedCodeIsWrapper -and $managedRealExists -and $managedRealIsVSCode -and $markerExists } { "managed"; break }
{ $managedCodeExists -and $managedCodeIsWrapper -and $managedRealExists -and $managedRealIsVSCode -and -not $markerExists } { "managed-marker-missing"; break }
{ -not $managedCodeExists -and $managedRealExists -and $managedRealIsVSCode } { "managed-code-missing"; break }
{ $managedCodeExists -and $managedCodeIsVSCode -and $managedRealExists -and $managedRealIsVSCode } { "managed-overwritten"; break }
{ $managedCodeExists -and $managedCodeIsVSCode -and -not $managedRealExists -and -not $markerExists } { "unmanaged"; break }
{ $managedCodeExists -and $managedCodeIsWrapper -and -not $managedRealExists } { "wrapper-without-real"; break }
{ -not $managedCodeExists -and -not $managedRealExists } { "missing-install"; break }
default { "unknown" }
}
return [pscustomobject]@{
State = $state
ManagedCodeExists = $managedCodeExists
ManagedRealExists = $managedRealExists
MarkerExists = $markerExists
ManagedCodeIsWrapper = $managedCodeIsWrapper
ManagedCodeIsVSCode = $managedCodeIsVSCode
ManagedRealIsVSCode = $managedRealIsVSCode
}
}
function Install-CodeExeSwap {
param(
[string]$SourceWrapperExe,
[switch]$Quiet
)
Promote-PendingRealCode | Out-Null
$stateBefore = Get-CodeInstallState -SourceWrapperExe $SourceWrapperExe
Write-RepairLog "Install state before repair: $($stateBefore.State)"
switch ($stateBefore.State) {
"managed" {
Write-RepairLog "Managed state already healthy."
}
"managed-marker-missing" {
Write-ManagedInstallMarker
Write-RepairLog "Marker file restored for managed state."
}
"managed-code-missing" {
Copy-Item -LiteralPath $SourceWrapperExe -Destination $ManagedCodePath -Force -ErrorAction Stop
Write-ManagedInstallMarker
Write-RepairLog "Restored missing managed Code.exe wrapper."
}
"managed-overwritten" {
if (Test-FilesMatch -PathA $ManagedCodePath -PathB $ManagedRealCodePath) {
Remove-Item -LiteralPath $PendingRealCodePath -Force -ErrorAction SilentlyContinue
Write-RepairLog "Managed-overwritten payload already matches Code.real.exe; staging skipped."
} else {
Copy-Item -LiteralPath $ManagedCodePath -Destination $PendingRealCodePath -Force -ErrorAction Stop
try {
Copy-Item -LiteralPath $ManagedCodePath -Destination $ManagedRealCodePath -Force -ErrorAction Stop
Remove-Item -LiteralPath $PendingRealCodePath -Force -ErrorAction SilentlyContinue
Write-RepairLog "Promoted overwritten Code.exe payload into Code.real.exe."
} catch {
Write-RepairLog "Code.real.exe is in use; staged updated real binary at $PendingRealCodePath for later promotion."
}
}
Copy-Item -LiteralPath $SourceWrapperExe -Destination $ManagedCodePath -Force -ErrorAction Stop
Write-ManagedInstallMarker
Write-RepairLog "Recovered from update overwrite and restored managed wrapper."
}
"unmanaged" {
Move-Item -LiteralPath $ManagedCodePath -Destination $ManagedRealCodePath -Force -ErrorAction Stop
Copy-Item -LiteralPath $SourceWrapperExe -Destination $ManagedCodePath -Force -ErrorAction Stop
Write-ManagedInstallMarker
Write-RepairLog "Promoted unmanaged install into managed wrapper state."
}
"wrapper-without-real" {
Write-RepairLog "Wrapper exists without Code.real.exe; repair cannot continue safely." "ERROR"
throw "Managed wrapper exists without Code.real.exe. Manual recovery is required."
}
"missing-install" {
Write-RepairLog "VS Code install missing from expected root." "ERROR"
throw "VS Code install not found at $CodeInstallDir"
}
default {
Write-RepairLog "Unknown install state; refusing blind repair." "ERROR"
throw "Unrecognized VS Code install state. Manual recovery is required."
}
}
$stateAfter = Get-CodeInstallState -SourceWrapperExe $SourceWrapperExe
Write-RepairLog "Install state after repair: $($stateAfter.State)"
if ($stateAfter.State -ne "managed") {
throw "Managed install state was not restored. Current state: $($stateAfter.State)"
}
return $stateAfter
}
function Install-CodeShims {
param(
[string]$SourceWrapperExe,
[switch]$Quiet
)
$realCliCmd = Join-Path $CodeInstallDir "bin\code.cmd"
if (-not (Test-Path -LiteralPath $realCliCmd)) {
throw "VS Code CLI not found at $realCliCmd"
}
New-Item -ItemType Directory -Path $ShimDir -Force -ErrorAction Stop | Out-Null
Copy-Item -LiteralPath $SourceWrapperExe -Destination $ShimExePath -Force -ErrorAction Stop
$shimContent = @(
"@echo off",
"setlocal",
"call `"$realCliCmd`" --remote-debugging-port=9222 %*",
"set EXITCODE=%ERRORLEVEL%",
"endlocal & exit /b %EXITCODE%"
) -join "`r`n"
Set-Content -LiteralPath $ShimCmdPath -Value $shimContent -Encoding Ascii
}
function Broadcast-EnvironmentChange {
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class EnvironmentBroadcast {
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
UIntPtr wParam,
string lParam,
uint fuFlags,
uint uTimeout,
out UIntPtr lpdwResult
);
}
"@ -ErrorAction SilentlyContinue
$result = [UIntPtr]::Zero
[void][EnvironmentBroadcast]::SendMessageTimeout(
[IntPtr]0xffff,
0x001A,
[UIntPtr]::Zero,
"Environment",
0x0002,
5000,
[ref]$result
)
}
function Get-DerivedUserPathSegments {
param([string]$PrefixPath)
$machineSegments = @(
[Environment]::GetEnvironmentVariable("Path", "Machine") -split ';' |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
)
$machineSet = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($segment in $machineSegments) {
[void]$machineSet.Add($segment.TrimEnd('\'))
}
$derivedSegments = @()
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($segment in ($env:Path -split ';')) {
if ([string]::IsNullOrWhiteSpace($segment)) {
continue
}
$normalizedSegment = $segment.TrimEnd('\')
if (
$normalizedSegment -ieq $PrefixPath.TrimEnd('\') -or
$normalizedSegment -ieq $CodeInstallDir.TrimEnd('\') -or
$normalizedSegment -like "$($env:USERPROFILE)\.codex\tmp\*"
) {
continue
}
if ($machineSet.Contains($normalizedSegment) -or $seen.Contains($normalizedSegment)) {
continue
}
[void]$seen.Add($normalizedSegment)
$derivedSegments += $segment
}
return $derivedSegments
}
function Ensure-UserPathPrefix {
param(
[string]$PrefixPath,
[switch]$Quiet
)
New-Item -Path $UserEnvironmentKey -Force -ErrorAction SilentlyContinue | Out-Null
$environmentValues = Get-ItemProperty -Path $UserEnvironmentKey -ErrorAction SilentlyContinue
$existingUserPath = $environmentValues.Path
$backupUserPath = $environmentValues.$UserPathBackupValueName
if (
-not [string]::IsNullOrWhiteSpace($existingUserPath) -and
$existingUserPath.TrimEnd('\') -ine $PrefixPath.TrimEnd('\') -and
$existingUserPath -ne $backupUserPath
) {
Set-ItemProperty -Path $UserEnvironmentKey -Name $UserPathBackupValueName -Value $existingUserPath
$backupUserPath = $existingUserPath
}
$baseUserPath = $existingUserPath
if ([string]::IsNullOrWhiteSpace($baseUserPath) -or $baseUserPath.TrimEnd('\') -ieq $PrefixPath.TrimEnd('\')) {
if (-not [string]::IsNullOrWhiteSpace($backupUserPath)) {
$baseUserPath = $backupUserPath
} else {
$baseUserPath = (Get-DerivedUserPathSegments -PrefixPath $PrefixPath) -join ';'
if (-not [string]::IsNullOrWhiteSpace($baseUserPath)) {
Set-ItemProperty -Path $UserEnvironmentKey -Name $UserPathBackupValueName -Value $baseUserPath
}
}
}
$segments = @()
foreach ($segment in ($baseUserPath -split ';')) {
if ([string]::IsNullOrWhiteSpace($segment)) {
continue
}
if ($segment.TrimEnd('\') -ieq $PrefixPath.TrimEnd('\')) {
continue
}
$segments += $segment
}
$updatedUserPath = ((@($PrefixPath) + $segments) -join ';')
Set-ItemProperty -Path $UserEnvironmentKey -Name Path -Value $updatedUserPath
$processSegments = @()
foreach ($segment in ($env:Path -split ';')) {
if ([string]::IsNullOrWhiteSpace($segment)) {
continue
}
if ($segment.TrimEnd('\') -ieq $PrefixPath.TrimEnd('\')) {
continue
}
$processSegments += $segment
}
$env:Path = ((@($PrefixPath) + $processSegments) -join ';')
Broadcast-EnvironmentChange
}
function Set-ShortcutTarget {
param(
[Parameter(Mandatory = $true)]
$WshShell,
[string]$ShortcutPath,
[string]$TargetPath,
[string]$Arguments,
[string]$IconTargetPath
)
if (-not (Test-Path -LiteralPath $ShortcutPath)) {
return
}
$shortcut = $WshShell.CreateShortcut($ShortcutPath)
$existingWorkingDirectory = $shortcut.WorkingDirectory
$shortcut.TargetPath = $TargetPath
$shortcut.Arguments = $Arguments
$shortcut.WorkingDirectory =
if ([string]::IsNullOrWhiteSpace($existingWorkingDirectory)) {
Split-Path -Parent $IconTargetPath
} else {
$existingWorkingDirectory
}
$shortcut.IconLocation = "$IconTargetPath,0"
$shortcut.Save()
}
function Set-RegistryCommand {
param(
[string]$KeyPath,
[string]$CommandValue
)
$item = New-Item -Path $KeyPath -Force -ErrorAction Stop
$item.SetValue("", $CommandValue)
}
function Get-CDPLaunchSurfaceStatus {
param([string]$SourceWrapperExe = $WrapperExePath)
$reasons = New-Object 'System.Collections.Generic.List[string]'
$shortcutIssues = New-Object 'System.Collections.Generic.List[string]'
$shellIssues = New-Object 'System.Collections.Generic.List[string]'
$shimIssues = New-Object 'System.Collections.Generic.List[string]'
$argvIssues = New-Object 'System.Collections.Generic.List[string]'
$wrapperExists = Test-Path -LiteralPath $SourceWrapperExe
if (-not $wrapperExists) {
$reasons.Add("wrapper-missing")
}
$installState =
if ($wrapperExists) {
Get-CodeInstallState -SourceWrapperExe $SourceWrapperExe
} else {
[pscustomobject]@{
State = "wrapper-missing"
ManagedCodeExists = Test-Path -LiteralPath $ManagedCodePath
ManagedRealExists = Test-Path -LiteralPath $ManagedRealCodePath
MarkerExists = Test-Path -LiteralPath $ManagedMarkerPath
ManagedCodeIsWrapper = $false
ManagedCodeIsVSCode = $false
ManagedRealIsVSCode = $false
}
}
if ($installState.State -ne "managed") {
$reasons.Add($installState.State)
}
if (-not (Test-Path -LiteralPath $ShimExePath)) {
$shimIssues.Add("shim-exe-missing")
$reasons.Add("shim-exe-missing")
} elseif ($wrapperExists -and -not (Test-FilesMatch -PathA $ShimExePath -PathB $SourceWrapperExe)) {
$shimIssues.Add("shim-exe-mismatch")
$reasons.Add("shim-exe-mismatch")
}
$realCliCmd = Join-Path $CodeInstallDir "bin\code.cmd"
if (-not (Test-Path -LiteralPath $ShimCmdPath)) {
$shimIssues.Add("shim-cmd-missing")
$reasons.Add("shim-cmd-missing")
} else {
$shimCmdContent = Get-Content -LiteralPath $ShimCmdPath -Raw -ErrorAction SilentlyContinue
$expectedShimCall = ('call "{0}" --remote-debugging-port=9222 %*' -f $realCliCmd)
if ([string]::IsNullOrWhiteSpace($shimCmdContent) -or $shimCmdContent -notlike "*$expectedShimCall*") {
$shimIssues.Add("shim-cmd-mismatch")
$reasons.Add("shim-cmd-mismatch")
}
}
$codeSource = ""
try {
$codeCmdInfo = Get-Command code -ErrorAction SilentlyContinue
if ($codeCmdInfo) {
$codeSource = $codeCmdInfo.Source
if ($codeSource -notlike "$ShimDir*") {
$reasons.Add("code-path-drift")
}
} else {
$reasons.Add("code-command-missing")
}
} catch {
$reasons.Add("code-command-unresolved")
}
$argvStatus = Get-VSCodeArgvJsonStatus
if (-not $argvStatus.FileExists) {
$argvIssues.Add("argv-json-missing")
$reasons.Add("argv-json-missing")
} elseif ($argvStatus.MatchesPort) {
# Healthy argv.json state.
} elseif (-not [string]::IsNullOrWhiteSpace($argvStatus.RawValue)) {
$argvIssues.Add("argv-cdp-mismatch:$($argvStatus.RawValue)")
$reasons.Add("argv-cdp-mismatch")
} elseif (-not [string]::IsNullOrWhiteSpace($argvStatus.ErrorMessage)) {
$argvIssues.Add("argv-read-failed:$($argvStatus.ErrorMessage)")
$reasons.Add("argv-read-failed")
} else {
$argvIssues.Add("argv-cdp-missing")
$reasons.Add("argv-cdp-missing")
}
$expectedShortcutTarget =
if ($installState.State -eq "managed") {
$ManagedCodePath
} else {
$SourceWrapperExe
}
try {
$wshShell = New-Object -ComObject WScript.Shell
foreach ($shortcutPath in (Get-ManagedShortcutPaths)) {
if (-not (Test-Path -LiteralPath $shortcutPath)) {
continue
}
$shortcut = $wshShell.CreateShortcut($shortcutPath)
$targetPath = $shortcut.TargetPath
$arguments = $shortcut.Arguments
if (
$targetPath -ne $expectedShortcutTarget -or
(-not [string]::IsNullOrWhiteSpace($arguments))
) {
$shortcutIssues.Add("$shortcutPath => target='$targetPath' args='$arguments'")
}
}
} catch {
$shortcutIssues.Add("shortcut-check-failed: $($_.Exception.Message)")
}
if ($shortcutIssues.Count -gt 0) {
$reasons.Add("shortcut-drift")
}
foreach ($definition in (Get-ExpectedShellCommandDefinitions -WrapperExe $SourceWrapperExe)) {
try {
$currentValue = (Get-ItemProperty -Path $definition.KeyPath -ErrorAction Stop).'(default)'
if ($currentValue -ne $definition.CommandValue) {
$shellIssues.Add("{0} => '{1}'" -f $definition.KeyPath, $currentValue)
}
} catch {
$shellIssues.Add("{0} => missing" -f $definition.KeyPath)
}
}
if ($shellIssues.Count -gt 0) {
$reasons.Add("shell-command-drift")
}
$reasonArray = @($reasons.ToArray() | Select-Object -Unique)
return [pscustomobject]@{
IsHealthy = $reasonArray.Count -eq 0
InstallState = $installState.State
Reasons = $reasonArray
CodeSource = $codeSource
ShortcutIssues = $shortcutIssues.ToArray()
ShellIssues = $shellIssues.ToArray()
ShimIssues = $shimIssues.ToArray()
ArgvIssues = $argvIssues.ToArray()
ArgvStatus = $argvStatus
}
}
function Install-CDPLaunchHooks {
param(
[switch]$Quiet,
[string]$TriggerSource = "startup",
[string[]]$DetectionReasons = @()
)
Ensure-UsableTempEnvironment -PersistUserVariables
$wrapperExe = Ensure-CodeWrapperCompiled -Quiet:$Quiet
$repairTimer = [System.Diagnostics.Stopwatch]::StartNew()
Write-RepairLog "Starting CDP launch hook repair."
Write-RepairLog "Repair trigger source: $TriggerSource"
if ($DetectionReasons.Count -gt 0) {
Write-RepairLog "Repair detection reasons: $($DetectionReasons -join '; ')"
}
try {
Remove-Item -LiteralPath $IfeoKey -Recurse -Force -ErrorAction SilentlyContinue
Write-RepairLog "Removed stale IFEO key."
} catch {}
$installState = $null
try {
$stageTimer = [System.Diagnostics.Stopwatch]::StartNew()
$installState = Install-CodeExeSwap -SourceWrapperExe $wrapperExe -Quiet:$Quiet
Write-RepairLog "Repair stage install swap completed in $(Format-RepairElapsed -Stopwatch $stageTimer)."
} catch {
Write-RepairLog "Code.exe swap repair failed: $($_.Exception.Message)" "ERROR"