From 34e9c525930518e962e9bbfdbb3b1a1f63d5907b Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:11:17 +0000 Subject: [PATCH 1/9] feat: offer selective voice-model removal when uninstalling Companion Worked on by: - @DonnieFi Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> OpenClaw-Publication: 73d4d23a-1d56-4b8d-91f3-1b381396c797 --- docs/SETUP.md | 4 + installer.iss | 236 +++++++++++++++ scripts/Uninstall-DownloadedModels.ps1 | 92 ++++++ .../Audio/KokoroDownloadCatalog.cs | 38 +++ .../Audio/KokoroModelManager.cs | 17 +- .../Audio/KokoroUninstallFiles.cs | 249 ++++++++++++++++ .../InstallerModelCleanupContractTests.cs | 56 ++++ .../KokoroUninstallFilesTests.cs | 276 ++++++++++++++++++ 8 files changed, 958 insertions(+), 10 deletions(-) create mode 100644 scripts/Uninstall-DownloadedModels.ps1 create mode 100644 src/OpenClaw.Shared/Audio/KokoroDownloadCatalog.cs create mode 100644 src/OpenClaw.Shared/Audio/KokoroUninstallFiles.cs create mode 100644 tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs create mode 100644 tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs diff --git a/docs/SETUP.md b/docs/SETUP.md index b8cc649822..414ce8603f 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -194,6 +194,10 @@ OpenClaw Companion checks for updates automatically and shows a notification whe Go to **Settings → Apps → Installed apps**, find **OpenClaw Companion**, and click **Uninstall**. Alternatively, use **Add or Remove Programs** in the Control Panel. You'll be asked whether to also remove the local WSL gateway; choose **Yes** to unregister its WSL distro and generated state, or **No** to leave the gateway and that state in place. +For the **Inno installer**, interactive uninstall offers an unchecked Kokoro download-removal choice, independent of Gateway removal. Continue immediately to keep models, or choose **Check downloaded models** to see exact file paths and measured byte counts before enabling removal. The dialog remains visible during the read-only check; Cancel requests that the model-check worker stop and aborts uninstall without starting model removal. Keeping models is the default, including silent uninstall. Only the catalog model and voices files whose current contents match their pinned hashes are eligible; other models, partial downloads, unknown files, shared caches, and directories are kept. Redirected paths, hard links, locked files, and unverified contents are not removed. Store migration or uncertain ownership suppresses removal, as does a custom `OPENCLAW_TRAY_DATA_DIR`. + +The model summary distinguishes removed bytes, measured retained catalog files, and files that could not be checked. Other app-data sizes are not scanned, so these numbers are not a total of all retained data. Cancelling the model choice stops uninstall before model removal; cleanup failures leave an incomplete summary rather than a claim that everything was removed. This option does not change MSIX uninstall or the separate Gateway cleanup scope. + Your settings file at `%APPDATA%\OpenClawTray\settings.json` is not removed automatically, and device identity files for gateways unrelated to the one you removed (including per-gateway keys at `%APPDATA%\OpenClawTray\gateways\\device-key-ed25519.json`) are preserved. Choosing **Yes** also removes the removed gateway's own identity directory. Root operator and node tokens are preserved only while an external gateway record remains; otherwise they are cleared, even if another local or loopback gateway record remains. Delete `%APPDATA%\OpenClawTray\` manually if you want a fully clean uninstall. For the **Companion MSIX**, managed Gateway cleanup uses a current-user interactive scheduled task that survives Companion removal. Its worker, registration script and versioned `cleanup-host-.exe` are copied to `%USERPROFILE%\.openclaw-companion\cleanup\\`. The task runs at logon and every minute through a GUI-subsystem helper that starts Windows PowerShell with `CreateNoWindow`, preventing a desktop console from being created. The helper targets the Windows-provided .NET Framework 4.8 and forwards the worker's exit code, recording failures in `cleanup-host-error.txt` beside the worker. It does not depend on VBScript, the Companion's .NET 10 runtime, or an executable inside the removed package. Versioned helper paths allow an updated Companion to refresh the task without overwriting a running helper. diff --git a/installer.iss b/installer.iss index da9e9b6d25..10e9ebf511 100644 --- a/installer.iss +++ b/installer.iss @@ -114,6 +114,11 @@ Source: "{#publish}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs Source: "scripts\Uninstall-LocalGateway.ps1"; DestDir: "{app}"; Flags: ignoreversion Source: "scripts\Test-InnoMigration.ps1"; DestDir: "{app}"; Flags: ignoreversion Source: "src\OpenClaw.Connection\Migration\MigrationRecordCodec.cs"; DestDir: "{app}"; Flags: ignoreversion +; The model helper compiles the same pinned catalog and file operation as Shared. +; It does not load Companion or keep its installed binaries locked. +Source: "scripts\Uninstall-DownloadedModels.ps1"; DestDir: "{app}"; Flags: ignoreversion +Source: "src\OpenClaw.Shared\Audio\KokoroDownloadCatalog.cs"; DestDir: "{app}"; Flags: ignoreversion +Source: "src\OpenClaw.Shared\Audio\KokoroUninstallFiles.cs"; DestDir: "{app}"; Flags: ignoreversion #if vcRedist != "" Source: "{#vcRedist}"; DestDir: "{tmp}"; DestName: "vc_redist.exe"; Flags: deleteafterinstall; AfterInstall: InstallVCRuntime #endif @@ -156,6 +161,16 @@ var MigrationOperationHandle: THandle; MigrationOperationLocked: Boolean; MigrationOperationUnavailable: Boolean; + ModelCleanupSelection: Integer; + ModelSummary: String; + ModelScanRunning, ModelScanCancelled, ModelScanAllowed: Boolean; + ModelPreviewEligible: Integer; + ModelDialog: TSetupForm; + ModelDetails: TNewMemo; + ModelRemoveCheck: TNewCheckBox; + ModelScanButton, ModelContinueButton: TNewButton; + +function ChooseModelCleanup: Boolean; forward; function OpenMigrationOperationFile( FileName: String; DesiredAccess, ShareMode: LongWord; SecurityAttributes: Integer; @@ -273,6 +288,8 @@ begin if Result and MigrationOperationUnavailable then Log('Migration state could not be locked. Uninstall continues and preserves the local gateway.'); #endif + if Result then + Result := ChooseModelCleanup; end; procedure DeinitializeUninstall; @@ -521,6 +538,218 @@ begin MigrateLegacyBackgroundLaunch; end; +function ReadModelText(Path: String; var Value: String): Boolean; +var + Lines: TArrayOfString; + I: Integer; +begin + Value := ''; + Result := LoadStringsFromFile(Path, Lines); + if not Result then Exit; + for I := 0 to GetArrayLength(Lines) - 1 do + begin + if I > 0 then Value := Value + #13#10; + Value := Value + Lines[I]; + end; +end; + +function StageModelHelper: Boolean; +begin + Result := CopyFile(ExpandConstant('{app}\Uninstall-DownloadedModels.ps1'), + ExpandConstant('{tmp}\Uninstall-DownloadedModels.ps1'), False); + if not Result then Exit; + Result := CopyFile(ExpandConstant('{app}\KokoroDownloadCatalog.cs'), + ExpandConstant('{tmp}\KokoroDownloadCatalog.cs'), False); + if not Result then Exit; + Result := CopyFile(ExpandConstant('{app}\KokoroUninstallFiles.cs'), + ExpandConstant('{tmp}\KokoroUninstallFiles.cs'), False); +end; + +function RunModelHelper(Selection: Integer; var Eligible: Integer): Boolean; +var + Params, Mask, ReportText: String; + Code: Integer; +begin + Result := False; + Eligible := 0; + DeleteFile(ExpandConstant('{tmp}\model-report.txt')); + DeleteFile(ExpandConstant('{tmp}\model-selection.txt')); + Params := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + + AddQuotes(ExpandConstant('{tmp}\Uninstall-DownloadedModels.ps1')) + + ' -DataDirectory ' + AddQuotes(ExpandConstant('{userappdata}\{#MyInstallDir}')) + + ' -ReportPath ' + AddQuotes(ExpandConstant('{tmp}\model-report.txt')) + + ' -SelectionPath ' + AddQuotes(ExpandConstant('{tmp}\model-selection.txt')) + + ' -CancellationPath ' + AddQuotes(ExpandConstant('{tmp}\model-cancel.txt')) + + ' -SelectionMask ' + IntToStr(Selection); + if Selection <> 0 then Params := Params + ' -ConfirmDestructive'; + if not Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), + Params, '', SW_HIDE, ewWaitUntilTerminated, Code) then Exit; + if not ReadModelText(ExpandConstant('{tmp}\model-report.txt'), ReportText) then Exit; + ModelSummary := ReportText; + if (Code <> 0) and (Code <> 1) then Exit; + if not ReadModelText(ExpandConstant('{tmp}\model-selection.txt'), Mask) then Exit; + Eligible := StrToIntDef(Trim(Mask), 0); + if (Eligible < 0) or (Eligible > 15) then Eligible := 0; + Result := True; +end; + +procedure CancelModelPreview(Sender: TObject); +begin + if ModelScanRunning then + begin + ModelScanCancelled := True; + SaveStringToFile(ExpandConstant('{tmp}\model-cancel.txt'), 'cancel', False); + ModelDetails.Text := 'Cancelling the model check. No model removal has started.'; + end + else + ModelDialog.ModalResult := mrCancel; +end; + +procedure ModelPreviewCloseQuery(Sender: TObject; var CanClose: Boolean); +begin + CanClose := not ModelScanRunning; + if not CanClose then CancelModelPreview(Sender); +end; + +procedure CheckModelPreview(Sender: TObject); +begin + ModelScanRunning := True; + ModelScanCancelled := False; + ModelPreviewEligible := 0; + ModelRemoveCheck.Checked := False; + ModelRemoveCheck.Enabled := False; + ModelScanButton.Enabled := False; + ModelContinueButton.Enabled := False; + DeleteFile(ExpandConstant('{tmp}\model-cancel.txt')); + ModelDetails.Text := 'Checking ownership and downloaded model files. Cancel stops this read-only check.'; + try + // Exec pumps window messages while waiting, so Cancel remains available. + if CheckCompletedStoreMigration <> 0 then + ModelSummary := 'Store migration or uncertain ownership requires preservation. Models are kept; sizes were not scanned.' + else if not ModelScanCancelled then + begin + if StageModelHelper then + begin + if not RunModelHelper(0, ModelPreviewEligible) then + begin + ModelPreviewEligible := 0; + ModelSummary := 'Model inventory is unavailable. No model removal will be attempted.' + #13#10 + ModelSummary; + end; + end + else + ModelSummary := 'The model helper is unavailable. Models are kept.' + #13#10 + ModelSummary; + end; + finally + ModelScanRunning := False; + ModelDetails.Text := ModelSummary; + ModelRemoveCheck.Enabled := ModelPreviewEligible <> 0; + ModelScanButton.Enabled := ModelScanAllowed; + ModelContinueButton.Enabled := True; + if ModelScanCancelled then ModelDialog.ModalResult := mrCancel; + end; +end; + +function ShowModelReport(Choosing: Boolean): Boolean; +var + CancelButton: TNewButton; +begin + ModelDialog := CreateCustomForm; + try + ModelDialog.Caption := 'Downloaded voice models'; + ModelDialog.ClientWidth := ScaleX(640); + ModelDialog.ClientHeight := ScaleY(440); + ModelDialog.OnCloseQuery := @ModelPreviewCloseQuery; + ModelRemoveCheck := TNewCheckBox.Create(ModelDialog); + ModelRemoveCheck.Parent := ModelDialog; + ModelRemoveCheck.SetBounds(ScaleX(16), ScaleY(16), ScaleX(608), ScaleY(32)); + ModelRemoveCheck.Caption := 'Remove the verified Kokoro downloads listed below'; + ModelRemoveCheck.Checked := False; + ModelRemoveCheck.Enabled := False; + ModelRemoveCheck.Visible := Choosing; + ModelDetails := TNewMemo.Create(ModelDialog); + ModelDetails.Parent := ModelDialog; + ModelDetails.SetBounds(ScaleX(16), ScaleY(56), ScaleX(608), ScaleY(320)); + ModelDetails.ReadOnly := True; + ModelDetails.ScrollBars := ssVertical; + ModelDetails.WordWrap := True; + ModelDetails.Text := ModelSummary; + ModelScanButton := TNewButton.Create(ModelDialog); + ModelScanButton.Parent := ModelDialog; + ModelScanButton.SetBounds(ScaleX(16), ScaleY(392), ScaleX(240), ScaleY(32)); + ModelScanButton.Caption := 'Check downloaded models'; + ModelScanButton.Enabled := ModelScanAllowed; + ModelScanButton.Visible := Choosing; + ModelScanButton.OnClick := @CheckModelPreview; + ModelContinueButton := TNewButton.Create(ModelDialog); + ModelContinueButton.Parent := ModelDialog; + ModelContinueButton.SetBounds(ScaleX(352), ScaleY(392), ScaleX(152), ScaleY(32)); + ModelContinueButton.ModalResult := mrOk; + ModelContinueButton.Default := True; + if Choosing then ModelContinueButton.Caption := 'Continue uninstall' + else ModelContinueButton.Caption := 'Close'; + CancelButton := TNewButton.Create(ModelDialog); + CancelButton.Parent := ModelDialog; + CancelButton.SetBounds(ScaleX(512), ScaleY(392), ScaleX(112), ScaleY(32)); + CancelButton.Caption := 'Cancel'; + CancelButton.OnClick := @CancelModelPreview; + CancelButton.Cancel := True; + CancelButton.Visible := Choosing; + Result := ModelDialog.ShowModal = mrOk; + if Choosing and Result and ModelRemoveCheck.Checked then + ModelCleanupSelection := ModelPreviewEligible; + finally + ModelDialog.Free; + end; +end; + +function ChooseModelCleanup: Boolean; +begin + Result := True; + ModelCleanupSelection := 0; + ModelPreviewEligible := 0; + ModelScanRunning := False; + ModelScanAllowed := False; + ModelSummary := 'Downloaded models and other app data will be kept at ' + + ExpandConstant('{userappdata}\{#MyInstallDir}') + '.' + #13#10 + + 'Sizes have not been measured. Gateway removal is a separate choice.'; + if UninstallSilent() then Exit; + if GetEnv('OPENCLAW_TRAY_DATA_DIR') <> '' then + ModelSummary := 'A custom app-data directory is configured. Models are kept; sizes were not scanned.' + + #13#10 + 'Configured path: ' + GetEnv('OPENCLAW_TRAY_DATA_DIR') + #13#10 + ModelSummary + else if MigrationOperationUnavailable then + ModelSummary := 'Migration ownership could not be checked. Models are kept.' + #13#10 + ModelSummary + else + begin + ModelScanAllowed := True; + ModelSummary := ModelSummary + #13#10#13#10 + + 'Continue to keep models, or check downloaded models to preview files eligible for optional removal.'; + end; + // Keeping models needs no scan. The visible dialog owns the optional check. + Result := ShowModelReport(True); +end; + +procedure RunSelectedModelCleanup; +var + Ignored: Integer; +begin + if ModelCleanupSelection = 0 then Exit; + // Preserve on changed Store ownership, independently of the Gateway choice. + if MigrationOperationUnavailable then + begin + ModelSummary := 'Models were kept: migration ownership is unavailable.' + #13#10 + ModelSummary; + Exit; + end; + if CheckCompletedStoreMigration <> 0 then + begin + ModelSummary := 'Models were kept: Store migration or ownership changed.' + #13#10 + ModelSummary; + Exit; + end; + UninstallProgressForm.StatusLabel.Caption := 'Checking and removing selected voice models...'; + if not RunModelHelper(ModelCleanupSelection, Ignored) then + ModelSummary := 'Model cleanup could not be completed or verified. Some selected files may remain.' + + #13#10 + ModelSummary; +end; + procedure EnsureLocalGatewayCleanupChoice; var MigrationResult: Integer; @@ -736,6 +965,7 @@ procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); begin if CurUninstallStep = usUninstall then begin + RunSelectedModelCleanup; RemoveAppAutoStart; EnsureLocalGatewayCleanupChoice; RunLocalGatewayCleanup; @@ -743,5 +973,11 @@ begin else if CurUninstallStep = usPostUninstall then begin DeleteGeneratedAppState; + if not UninstallSilent() then + begin + if ModelCleanupSelection = 0 then + ModelSummary := 'No model removal was requested. Measurements below are from the preview.' + #13#10 + ModelSummary; + ShowModelReport(False); + end; end; end; diff --git a/scripts/Uninstall-DownloadedModels.ps1 b/scripts/Uninstall-DownloadedModels.ps1 new file mode 100644 index 0000000000..6640d3d4f2 --- /dev/null +++ b/scripts/Uninstall-DownloadedModels.ps1 @@ -0,0 +1,92 @@ +<# +.SYNOPSIS + Preview or explicitly remove only verified Kokoro downloads for Inno uninstall. +.DESCRIPTION + No recursive removal, app startup, Gateway cleanup, or shared-cache access. + The installer keeps its migration lease and rechecks preservation before removal. + A nonzero selection requires -ConfirmDestructive. The C# owner re-verifies every + selected file, pins its ancestors, and deletes using its verified file handle. + Reports are local to this uninstall, never telemetry or an ownership receipt. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$DataDirectory, + [Parameter(Mandatory = $true)][string]$ReportPath, + [Parameter(Mandatory = $true)][string]$SelectionPath, + [ValidateRange(0, 15)][int]$SelectionMask = 0, + [string]$CancellationPath = '', + [switch]$ConfirmDestructive, + [switch]$Worker +) + +$ErrorActionPreference = 'Stop' +$encoding = New-Object System.Text.UTF8Encoding $true +try { + if ($SelectionMask -ne 0 -and -not $ConfirmDestructive) { + throw 'Model removal requires explicit confirmation.' + } + if (-not $Worker) { + # Bound compiler startup as well as scanning. On timeout, do not retry a + # possibly partial deletion or claim the selected files were all removed. + $seconds = 180 + $configured = 0 + if ([int]::TryParse($env:OPENCLAW_MODEL_UNINSTALL_PROCESS_TIMEOUT_SECONDS, [ref]$configured) -and + $configured -ge 30 -and $configured -le 900) { $seconds = $configured } + $cancellationPollMilliseconds = 100 + $terminationWaitMilliseconds = 10000 + if ($CancellationPath -and [IO.File]::Exists($CancellationPath)) { + throw 'Model check was cancelled before starting. No model removal was started.' + } + $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', + (Join-Path $PSScriptRoot 'Uninstall-DownloadedModels.ps1'), + '-DataDirectory', $DataDirectory, '-ReportPath', $ReportPath, + '-SelectionPath', $SelectionPath, '-SelectionMask', [string]$SelectionMask, '-Worker') + if ($ConfirmDestructive) { $arguments += '-ConfirmDestructive' } + # Every value is quoted using Windows argv backslash rules. + $quoted = foreach ($argument in $arguments) { + if ($argument.Contains('"')) { throw 'Unexpected quote in uninstall path.' } + '"' + ($argument -replace '(\\+)$', '$1$1') + '"' + } + $start = New-Object System.Diagnostics.ProcessStartInfo + $start.FileName = Join-Path $PSHOME 'powershell.exe' + $start.Arguments = $quoted -join ' ' + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $child = [Diagnostics.Process]::Start($start) + try { + $clock = [Diagnostics.Stopwatch]::StartNew() + while (-not $child.WaitForExit($cancellationPollMilliseconds)) { + $cancelled = $CancellationPath -and [IO.File]::Exists($CancellationPath) + if ($cancelled -or $clock.Elapsed.TotalSeconds -ge $seconds) { + $child.Kill() + if (-not $child.WaitForExit($terminationWaitMilliseconds)) { + throw 'The model helper has not confirmed exit. Its result is unknown; do not retry cleanup.' + } + if ($cancelled -and $SelectionMask -eq 0) { + throw 'Model check cancelled. No model removal was started.' + } + throw 'Model cleanup interrupted. Removal may be partial; inspect the model paths before retrying.' + } + } + exit $child.ExitCode + } finally { $child.Dispose() } + } + + Add-Type -Path @((Join-Path $PSScriptRoot 'KokoroDownloadCatalog.cs'), + (Join-Path $PSScriptRoot 'KokoroUninstallFiles.cs')) -ErrorAction Stop + $result = [OpenClaw.Shared.Audio.KokoroUninstallFiles]::Run($DataDirectory, $SelectionMask) + [IO.File]::WriteAllText($ReportPath, $result.Text, $encoding) + [IO.File]::WriteAllText($SelectionPath, [string]$result.EligibleMask, $encoding) + if (-not $result.Complete) { exit 1 } + exit 0 +} catch { + [IO.File]::WriteAllText($SelectionPath, '0', $encoding) + $message = @( + 'Model cleanup could not be completed or verified. Files may remain; no complete-cleanup claim is made.', + "Model path: $DataDirectory\models\kokoro", + 'Other app data and shared caches are outside this choice. Sizes are unknown.', + $_.Exception.Message + ) -join [Environment]::NewLine + [IO.File]::WriteAllText($ReportPath, $message, $encoding) + exit 2 +} diff --git a/src/OpenClaw.Shared/Audio/KokoroDownloadCatalog.cs b/src/OpenClaw.Shared/Audio/KokoroDownloadCatalog.cs new file mode 100644 index 0000000000..1878926a7d --- /dev/null +++ b/src/OpenClaw.Shared/Audio/KokoroDownloadCatalog.cs @@ -0,0 +1,38 @@ +// Pinned Kokoro downloads shared by the app and the Inno uninstall helper. +// Keep this file compatible with Windows PowerShell 5.1 Add-Type (.NET Framework). +// Example: KokoroDownloadCatalog.EnglishModel describes one verified download. +namespace OpenClaw.Shared.Audio +{ + internal sealed class KokoroDownloadAsset + { + internal readonly string PackId, FileName, Url, Sha256; + internal readonly long SizeBytes; + + internal KokoroDownloadAsset(string packId, string fileName, string url, string sha256, long sizeBytes) + { + PackId = packId; FileName = fileName; Url = url; Sha256 = sha256; SizeBytes = sizeBytes; + } + } + + internal static class KokoroDownloadCatalog + { + private const string Release = "https://github.com/larroy/kokoro.cpp/releases/download/voices_model_files/"; + internal static readonly KokoroDownloadAsset EnglishModel = new KokoroDownloadAsset( + "v1.1-en-zh", "kokoro-v1.1-zh.onnx", Release + "kokoro-v1.1-zh.onnx", + "eefec708cbc7aba8e8129b5c2f7cb92e1fe7d281af1e1dd451592d9ff0714a0d", 343605188); + internal static readonly KokoroDownloadAsset EnglishVoices = new KokoroDownloadAsset( + "v1.1-en-zh", "voices-v1.1-zh.bin", Release + "voices-v1.1-zh.bin", + "e678019845e6cfe3b7c34531779396b28f509451b91e6535d5dc09bbf11a4be5", 53792177); + internal static readonly KokoroDownloadAsset SpanishModel = new KokoroDownloadAsset( + "v1.0-es", "kokoro-v1.0.onnx", + "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/kokoro-v1.0.onnx", + "7d5df8ecf7d4b1878015a32686053fd0eebe2bc377234608764cc0ef3636a6c5", 325532387); + internal static readonly KokoroDownloadAsset SpanishVoices = new KokoroDownloadAsset( + "v1.0-es", "voices-v1.0-es.bin", Release + "voices-v1.0-es.bin", + "cdaf0ecca101f3738763f6e3a13b63d46137909b8ebcf9de2be4ef2a73014c52", 1566778); + + // Stable bit positions identify exactly the files shown in the uninstall preview. + internal static readonly KokoroDownloadAsset[] All = + { EnglishModel, EnglishVoices, SpanishModel, SpanishVoices }; + } +} diff --git a/src/OpenClaw.Shared/Audio/KokoroModelManager.cs b/src/OpenClaw.Shared/Audio/KokoroModelManager.cs index 55a284fb60..cb2bfec29a 100644 --- a/src/OpenClaw.Shared/Audio/KokoroModelManager.cs +++ b/src/OpenClaw.Shared/Audio/KokoroModelManager.cs @@ -34,7 +34,6 @@ public sealed class KokoroModelManager public const string DefaultVoiceId = "af_maple"; private const string InstallMarkerSuffix = ".installing"; - private const string LarroyReleaseBase = "https://github.com/larroy/kokoro.cpp/releases/download/voices_model_files/"; // Static so two managers over the same data directory coalesce against the // same in-flight download. Ordinal: pack ids are fixed catalog keys. @@ -68,10 +67,8 @@ public sealed class KokoroModelManager public static readonly KokoroModelPackInfo[] AvailablePacks = [ new("v1.1-en-zh", "English and Chinese (Kokoro v1.1)", - new KokoroAssetInfo("kokoro-v1.1-zh.onnx", LarroyReleaseBase + "kokoro-v1.1-zh.onnx", - "eefec708cbc7aba8e8129b5c2f7cb92e1fe7d281af1e1dd451592d9ff0714a0d", 343_605_188), - new KokoroAssetInfo("voices-v1.1-zh.bin", LarroyReleaseBase + "voices-v1.1-zh.bin", - "e678019845e6cfe3b7c34531779396b28f509451b91e6535d5dc09bbf11a4be5", 53_792_177), + ModelAsset(KokoroDownloadCatalog.EnglishModel), + ModelAsset(KokoroDownloadCatalog.EnglishVoices), [ new("af_maple", "English (US): Maple", "en-US"), new("af_sol", "English (US): Sol", "en-US"), @@ -79,11 +76,8 @@ public sealed class KokoroModelManager .. ChineseVoiceIds.Select(id => new KokoroVoiceInfo(id, $"中文 (CN): {id}", "zh-CN")), ]), new("v1.0-es", "Español (Kokoro v1.0)", - new KokoroAssetInfo("kokoro-v1.0.onnx", - "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/kokoro-v1.0.onnx", - "7d5df8ecf7d4b1878015a32686053fd0eebe2bc377234608764cc0ef3636a6c5", 325_532_387), - new KokoroAssetInfo("voices-v1.0-es.bin", LarroyReleaseBase + "voices-v1.0-es.bin", - "cdaf0ecca101f3738763f6e3a13b63d46137909b8ebcf9de2be4ef2a73014c52", 1_566_778), + ModelAsset(KokoroDownloadCatalog.SpanishModel), + ModelAsset(KokoroDownloadCatalog.SpanishVoices), [ new("ef_dora", "Español (ES): Dora", "es-ES"), new("em_alex", "Español (ES): Alex", "es-ES"), @@ -91,6 +85,9 @@ public sealed class KokoroModelManager ]), ]; + private static KokoroAssetInfo ModelAsset(KokoroDownloadAsset asset) => + new(asset.FileName, asset.Url, asset.Sha256, asset.SizeBytes); + private readonly string _packsDirectory; private readonly IOpenClawLogger _logger; diff --git a/src/OpenClaw.Shared/Audio/KokoroUninstallFiles.cs b/src/OpenClaw.Shared/Audio/KokoroUninstallFiles.cs new file mode 100644 index 0000000000..6f687ab9ac --- /dev/null +++ b/src/OpenClaw.Shared/Audio/KokoroUninstallFiles.cs @@ -0,0 +1,249 @@ +// Narrow file operation for the Inno model choice, also compiled by PowerShell 5.1. +// Example: Run(dataDirectory, 0) previews; Run(dataDirectory, preview.EligibleMask) +// removes only that selection after the installer has obtained explicit consent. +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.Win32.SafeHandles; + +namespace OpenClaw.Shared.Audio +{ + /// Measured catalog files, not a recursive app-data or shared-cache inventory. + public sealed class KokoroUninstallReport + { + public int EligibleMask { get; internal set; } + public long VerifiedBytes { get; internal set; } + public long RetainedBytes { get; internal set; } + public long RemovedBytes { get; internal set; } + public bool Complete { get; internal set; } + public string Text { get; internal set; } + + internal KokoroUninstallReport() { Complete = true; Text = string.Empty; } + } + + /// Verifies catalog contents and deletes by the same locked handle, never recursively. + public static class KokoroUninstallFiles + { + private const int DefaultScanTimeoutSeconds = 120; + private const uint GenericRead = 0x80000000, DeleteAccess = 0x10000; + private const uint ShareRead = 1, OpenExisting = 3; + private const uint OpenReparsePoint = 0x00200000, BackupSemantics = 0x02000000; + private const uint DirectoryAttribute = 0x10, ReparseAttribute = 0x400; + + /// Zero selection is read-only. Bits select only the fixed, shipped catalog. + public static KokoroUninstallReport Run(string dataDirectory, int selectionMask) + { + int seconds; + if (!int.TryParse(Environment.GetEnvironmentVariable("OPENCLAW_MODEL_UNINSTALL_TIMEOUT_SECONDS"), out seconds) + || seconds < 10 || seconds > 600) seconds = DefaultScanTimeoutSeconds; + return Inspect(dataDirectory, KokoroDownloadCatalog.All, selectionMask, + CancellationToken.None, TimeSpan.FromSeconds(seconds)); + } + + internal static KokoroUninstallReport Inspect(string dataDirectory, KokoroDownloadAsset[] assets, + int selectionMask, CancellationToken cancellationToken, TimeSpan timeout) + { + if (assets.Length > 30 || selectionMask < 0 || (selectionMask >> assets.Length) != 0) + throw new ArgumentOutOfRangeException("selectionMask"); + var root = Path.GetFullPath(dataDirectory); + var drive = Path.GetPathRoot(root); + if (root.StartsWith(@"\\", StringComparison.Ordinal) || drive == null || drive.Length != 3) + throw new ArgumentException("Only an ordinary local app-data path can be checked."); + + var report = new KokoroUninstallReport(); + var lines = new StringBuilder(); + var clock = Stopwatch.StartNew(); + for (int i = 0; i < assets.Length; i++) + { + var asset = assets[i]; + // Catalog entries, not caller-provided paths, define the deletion boundary. + if (Path.GetFileName(asset.PackId) != asset.PackId || asset.PackId == ".." + || Path.GetFileName(asset.FileName) != asset.FileName || asset.FileName == "..") + throw new InvalidDataException("Invalid Kokoro catalog path."); + var path = Path.Combine(root, "models", "kokoro", asset.PackId, asset.FileName); + var selected = (selectionMask & (1 << i)) != 0; + long measured = 0; + bool hasMeasurement = false; + var ancestors = new List(); + try + { + CheckBudget(clock, timeout, cancellationToken); + var directory = Path.GetDirectoryName(path); + if (directory == null) throw new IOException("Model directory is unavailable."); + LockAncestors(directory, ancestors); + using (var handle = Open(path, GenericRead | (selected ? DeleteAccess : 0), ShareRead, OpenReparsePoint)) + { + var info = Information(handle); + if ((info.Attributes & (DirectoryAttribute | ReparseAttribute)) != 0 || info.Links != 1) + throw new IOException("Not an ordinary, single-link model file."); + using (var stream = new FileStream(handle, FileAccess.Read)) + { + measured = stream.Length; + hasMeasurement = true; + var digest = Hash(stream, clock, timeout, cancellationToken); + if (!string.Equals(digest, asset.Sha256, StringComparison.OrdinalIgnoreCase)) + { + report.RetainedBytes += measured; + lines.AppendLine("Retained (content not verified): " + path + " (" + Bytes(measured) + ")"); + if (selected) report.Complete = false; + continue; + } + if (selected) + { + CheckBudget(clock, timeout, cancellationToken); + // The handle denies writes/renames; all ancestors deny replacement. + // Hash verification and deletion therefore refer to the same file. + var disposition = new FileDisposition { DeleteFile = true }; + if (!SetFileInformationByHandle(handle, 4, ref disposition, 1)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + else + { + report.EligibleMask |= 1 << i; + report.VerifiedBytes += measured; + } + } + } + if (selected) + { + report.RemovedBytes += measured; + lines.AppendLine("Removed: " + path + " (" + Bytes(measured) + ")"); + } + else + { + report.RetainedBytes += measured; + lines.AppendLine("Verified download, kept unless selected: " + path + " (" + Bytes(measured) + ")"); + } + } + catch (Win32Exception ex) + { + if (ex.NativeErrorCode == 2 || ex.NativeErrorCode == 3) + lines.AppendLine("Absent: " + path); + else + RetainFailure(report, lines, path, measured, hasMeasurement, "Windows error " + ex.NativeErrorCode); + } + catch (Exception ex) + { + if (!(ex is IOException) && !(ex is UnauthorizedAccessException) + && !(ex is OperationCanceledException) && !(ex is TimeoutException)) throw; + RetainFailure(report, lines, path, measured, hasMeasurement, + ex is OperationCanceledException ? "cancelled" : + ex is TimeoutException ? "scan deadline reached" : "could not safely verify or remove"); + } + finally + { + for (int j = ancestors.Count - 1; j >= 0; j--) ancestors[j].Dispose(); + } + } + + report.Text = "Verified downloads available for selection: " + Bytes(report.VerifiedBytes) + Environment.NewLine + + "Removed model file bytes: " + Bytes(report.RemovedBytes) + Environment.NewLine + + "Measured retained catalog files: " + Bytes(report.RetainedBytes) + + (report.Complete ? "." : " (incomplete; some files could not be checked or removed).") + + Environment.NewLine + Environment.NewLine + lines + + Environment.NewLine + "Other files and directories are retained; their sizes were not scanned." + + Environment.NewLine + "Retained data root: " + root + + Environment.NewLine + "This choice does not remove settings.json, mcp-token.txt, gateways.json, gateways, other models, partial downloads, or shared caches." + + Environment.NewLine + "Gateway removal is a separate choice and may remove its own credentials and state."; + return report; + } + + private static string Bytes(long value) { return value.ToString("N0", CultureInfo.CurrentCulture) + " bytes"; } + + private static void RetainFailure(KokoroUninstallReport report, StringBuilder lines, string path, + long measured, bool hasMeasurement, string reason) + { + report.Complete = false; + if (hasMeasurement) report.RetainedBytes += measured; + lines.AppendLine("Retained / not verified: " + path + " (" + + (hasMeasurement ? Bytes(measured) + "; " : "size unknown; ") + reason + ")"); + } + + private static void CheckBudget(Stopwatch clock, TimeSpan timeout, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (clock.Elapsed >= timeout) throw new TimeoutException(); + } + + private static string Hash(Stream stream, Stopwatch clock, TimeSpan timeout, CancellationToken token) + { + using (var sha = SHA256.Create()) + { + var buffer = new byte[81920]; + int count; + while ((count = stream.Read(buffer, 0, buffer.Length)) != 0) + { + CheckBudget(clock, timeout, token); + sha.TransformBlock(buffer, 0, count, buffer, 0); + } + sha.TransformFinalBlock(new byte[0], 0, 0); + var digest = sha.Hash; + if (digest == null) throw new IOException("Model hash is unavailable."); + return BitConverter.ToString(digest).Replace("-", ""); + } + } + + private static void LockAncestors(string directory, List handles) + { + var paths = new Stack(); + for (var path = directory; !string.IsNullOrEmpty(path); path = Path.GetDirectoryName(path) ?? string.Empty) paths.Push(path); + // Deny write as well as delete sharing: an otherwise pinned directory + // must not become a reparse point before its next descendant is opened. + // Request read access so Windows participates in data-access sharing checks; + // an attribute-only/zero-access handle does not establish this fence. + while (paths.Count != 0) + { + var handle = Open(paths.Pop(), GenericRead, ShareRead, OpenReparsePoint | BackupSemantics); + handles.Add(handle); + var info = Information(handle); + if ((info.Attributes & ReparseAttribute) != 0 || (info.Attributes & DirectoryAttribute) == 0) + throw new IOException("An ancestor is redirected or is not a directory."); + } + } + + private static SafeFileHandle Open(string path, uint access, uint share, uint flags) + { + var handle = CreateFile(path, access, share, IntPtr.Zero, OpenExisting, flags, IntPtr.Zero); + if (!handle.IsInvalid) return handle; + int error = Marshal.GetLastWin32Error(); + handle.Dispose(); + throw new Win32Exception(error); + } + + private static FileInformation Information(SafeFileHandle handle) + { + FileInformation info; + if (!GetFileInformationByHandle(handle, out info)) throw new Win32Exception(Marshal.GetLastWin32Error()); + return info; + } + + [StructLayout(LayoutKind.Sequential)] + private struct FileInformation + { + internal uint Attributes; + internal System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Write; + internal uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow; + } + + [StructLayout(LayoutKind.Sequential)] + private struct FileDisposition { [MarshalAs(UnmanagedType.U1)] internal bool DeleteFile; } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security, + uint creation, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandle(SafeFileHandle file, out FileInformation info); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetFileInformationByHandle(SafeFileHandle file, int informationClass, + ref FileDisposition info, uint size); + } +} diff --git a/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs b/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs new file mode 100644 index 0000000000..6c698e23a2 --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs @@ -0,0 +1,56 @@ +namespace OpenClaw.Tray.Tests; + +// Inno admission and packaging are distinct from the native file-operation tests. +public sealed class InstallerModelCleanupContractTests +{ + private static string Installer => File.ReadAllText( + Path.Combine(TestRepositoryPaths.GetRepositoryRoot(), "installer.iss")).Replace("\r\n", "\n"); + + [Fact] + public void ModelChoice_DefaultsToKeep_AndSilentUninstallCannotOptIn() + { + var source = Installer; + var choice = source[source.IndexOf("function ChooseModelCleanup: Boolean;\nbegin", StringComparison.Ordinal)..]; + choice = choice[..choice.IndexOf("procedure RunSelectedModelCleanup;", StringComparison.Ordinal)]; + Assert.Contains("ModelCleanupSelection := 0;", choice); + Assert.True(choice.IndexOf("ModelCleanupSelection := 0;", StringComparison.Ordinal) + < choice.IndexOf("if UninstallSilent() then Exit;", StringComparison.Ordinal)); + Assert.DoesNotContain("RunModelHelper", choice); + Assert.DoesNotContain("CheckCompletedStoreMigration", choice); + Assert.Contains("Result := ShowModelReport(True);", choice); + Assert.Contains("ModelRemoveCheck.Checked := False;", source); + Assert.Contains("if Choosing and Result and ModelRemoveCheck.Checked then", source); + Assert.Contains("ModelScanButton.OnClick := @CheckModelPreview;", source); + Assert.Contains("CancelButton.OnClick := @CancelModelPreview;", source); + Assert.Contains("CanClose := not ModelScanRunning;", source); + Assert.Contains("if ModelScanCancelled then ModelDialog.ModalResult := mrCancel;", source); + Assert.Contains("Result := ChooseModelCleanup;", source); // Cancel aborts admission. + } + + [Fact] + public void ModelRemoval_RechecksPreservation_AndDoesNotDependOnGatewayRemoval() + { + var source = Installer; + var cleanup = source[source.IndexOf("procedure RunSelectedModelCleanup;", StringComparison.Ordinal)..]; + cleanup = cleanup[..cleanup.IndexOf("procedure EnsureLocalGatewayCleanupChoice;", StringComparison.Ordinal)]; + Assert.Contains("if ModelCleanupSelection = 0 then Exit;", cleanup); + Assert.Contains("if MigrationOperationUnavailable then", cleanup); + Assert.True(cleanup.IndexOf("CheckCompletedStoreMigration <> 0", StringComparison.Ordinal) + < cleanup.IndexOf("RunModelHelper(ModelCleanupSelection", StringComparison.Ordinal)); + Assert.DoesNotContain("LocalGatewayCleanupRequested", cleanup); + Assert.DoesNotContain("LocalGatewayCleanupSucceeded", cleanup); + Assert.DoesNotContain("DelTree", cleanup); + Assert.Contains("ShowModelReport(False);", source); + } + + [Theory] + [InlineData("scripts\\Uninstall-DownloadedModels.ps1", "Uninstall-DownloadedModels.ps1")] + [InlineData("src\\OpenClaw.Shared\\Audio\\KokoroDownloadCatalog.cs", "KokoroDownloadCatalog.cs")] + [InlineData("src\\OpenClaw.Shared\\Audio\\KokoroUninstallFiles.cs", "KokoroUninstallFiles.cs")] + public void ModelHelper_ShipsAuthoritativeSources_AndStagesBeforePayloadRemoval(string sourcePath, string name) + { + var source = Installer; + Assert.Contains($"Source: \"{sourcePath}\"; DestDir: \"{{app}}\"; Flags: ignoreversion", source); + Assert.Contains($"ExpandConstant('{{tmp}}\\{name}')", source); + } +} diff --git a/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs b/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs new file mode 100644 index 0000000000..227ce8130b --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs @@ -0,0 +1,276 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using OpenClaw.Shared.Audio; +using OpenClaw.TestSupport; + +namespace OpenClaw.Tray.Tests; + +public sealed class KokoroUninstallFilesTests +{ + // SHA-256 of the independent three-byte fixture "abc". Catalog size deliberately differs. + private const string FixtureHash = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + private static readonly KokoroDownloadAsset[] Assets = + [ + new("fixture", "model.onnx", "https://example.invalid/model", FixtureHash, 999), + new("fixture", "voices.bin", "https://example.invalid/voices", FixtureHash, 999), + ]; + private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds( + int.TryParse(Environment.GetEnvironmentVariable("OPENCLAW_MODEL_UNINSTALL_TEST_TIMEOUT_SECONDS"), out var seconds) + && seconds > 0 ? seconds : 120); + + [Fact] + public void Preview_MeasuresFilesRatherThanCatalog_AndPreservesEverything() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var path = Seed(temp, 0); + var unknown = Path.Combine(Path.GetDirectoryName(path)!, "personal.onnx"); + File.WriteAllText(unknown, "unrelated"); + File.WriteAllText(temp.Combine("settings.json"), "settings"); + + var result = Inspect(temp, 0); + + Assert.True(result.Complete); + Assert.Equal(1, result.EligibleMask); + Assert.Equal(3, result.VerifiedBytes); + Assert.Equal(3, result.RetainedBytes); + Assert.Equal(0, result.RemovedBytes); + Assert.Equal("abc", File.ReadAllText(path)); + Assert.Equal("unrelated", File.ReadAllText(unknown)); + Assert.Equal("settings", File.ReadAllText(temp.Combine("settings.json"))); + Assert.Contains(path, result.Text); + Assert.Contains("sizes were not scanned", result.Text); + } + + [Fact] + public void Remove_OnlyPreviewSelection_PreservesUnselectedAndUnrelatedFiles() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var first = Seed(temp, 0); + var selection = Inspect(temp, 0).EligibleMask; + var later = Seed(temp, 1); // Downloaded after the preview. Not consented. + var unknown = Path.Combine(Path.GetDirectoryName(first)!, "notes.txt"); + File.WriteAllText(unknown, "keep"); + File.WriteAllText(temp.Combine("mcp-token.txt"), "fixture-token"); + + var result = Inspect(temp, selection); + + Assert.True(result.Complete); + Assert.Equal(3, result.RemovedBytes); + Assert.Equal(3, result.RetainedBytes); + Assert.False(File.Exists(first)); + Assert.Equal("abc", File.ReadAllText(later)); + Assert.Equal("keep", File.ReadAllText(unknown)); + Assert.Equal("fixture-token", File.ReadAllText(temp.Combine("mcp-token.txt"))); + Assert.True(Directory.Exists(Path.GetDirectoryName(first))); + } + + [Fact] + public void Remove_RechecksContentAfterPreview_AndReportsChangedFileRetained() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var path = Seed(temp, 0); + var selection = Inspect(temp, 0).EligibleMask; + File.WriteAllText(path, "user model"); + + var result = Inspect(temp, selection); + + Assert.False(result.Complete); + Assert.Equal(0, result.RemovedBytes); + Assert.Equal(10, result.RetainedBytes); + Assert.Equal("user model", File.ReadAllText(path)); + Assert.Contains("content not verified", result.Text); + } + + [Fact] + public void Remove_MissingSelectedFile_IsNotCountedAsRemoved() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var path = Seed(temp, 0); + File.Delete(path); + var result = Inspect(temp, 1); + Assert.True(result.Complete); + Assert.Equal(0, result.RemovedBytes); + Assert.Contains("Absent: " + path, result.Text); + } + + [Fact] + public void LockedFile_DoesNotHidePartialScanOrPreventOtherSelectedCleanup() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var first = Seed(temp, 0); + var second = Seed(temp, 1); + using (var locked = new FileStream(first, FileMode.Open, FileAccess.Read, FileShare.None)) + { + var result = Inspect(temp, 3); + Assert.False(result.Complete); + Assert.Equal(3, result.RemovedBytes); + Assert.Contains("size unknown", result.Text); + Assert.Contains(first, result.Text); + } + Assert.Equal("abc", File.ReadAllText(first)); + Assert.False(File.Exists(second)); + } + + [Fact] + public void ReadOnlyFile_ReportsRemovalFailureWithoutClaimingRemovedBytes() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var path = Seed(temp, 0); + File.SetAttributes(path, FileAttributes.ReadOnly); + try + { + var result = Inspect(temp, 1); + Assert.False(result.Complete); + Assert.Equal(0, result.RemovedBytes); + Assert.True(File.Exists(path)); + } + finally { File.SetAttributes(path, FileAttributes.Normal); } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void CancellationOrExpiredBudget_PreservesFilesAndMarksIncomplete(bool cancel) + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var path = Seed(temp, 0); + var result = KokoroUninstallFiles.Inspect(temp.Path, Assets, 1, + new CancellationToken(cancel), cancel ? TestTimeout : TimeSpan.Zero); + Assert.False(result.Complete); + Assert.Equal(0, result.RemovedBytes); + Assert.Equal("abc", File.ReadAllText(path)); + Assert.Contains(cancel ? "cancelled" : "deadline", result.Text); + } + + [Fact] + public void HardLinkedCatalogFile_IsRetainedEvenWhenItsContentsMatch() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + var path = Seed(temp, 0); + var other = temp.Combine("personal-copy.onnx"); + Assert.True(CreateHardLink(other, path, IntPtr.Zero), $"Windows error {Marshal.GetLastWin32Error()}"); + var result = Inspect(temp, 1); + Assert.False(result.Complete); + Assert.Equal(0, result.RemovedBytes); + Assert.Equal("abc", File.ReadAllText(path)); + Assert.Equal("abc", File.ReadAllText(other)); + } + + [Fact] + public async Task RedirectedModelAncestor_IsNotTraversedOrDeleted() + { + using var temp = new TempDirectory("kokoro-uninstall-"); + using var external = new TempDirectory("kokoro-unrelated-"); + var path = Seed(external, 0); + var link = temp.Combine("models"); + using var process = Process.Start(new ProcessStartInfo("cmd.exe") + { + Arguments = $"/d /c mklink /J \"{link}\" \"{external.Combine("models")}\"", + UseShellExecute = false, + CreateNoWindow = true, + }); + Assert.NotNull(process); + try { await process.WaitForExitAsync().WaitAsync(TestTimeout); } + finally { if (!process.HasExited) process.Kill(entireProcessTree: true); } + Assert.Equal(0, process.ExitCode); + try + { + var result = Inspect(temp, 1); + Assert.False(result.Complete); + Assert.Equal(0, result.RemovedBytes); + Assert.Equal(0, result.VerifiedBytes); + Assert.Equal("abc", File.ReadAllText(path)); + } + finally { Directory.Delete(link); } + } + + [Fact] + public void PinnedAncestor_DeniesReparseWriterBeforeDescendantIsOpened() + { + using var temp = new TempDirectory("kokoro-ancestor-pin-"); + var ancestor = temp.Combine("models"); + Directory.CreateDirectory(ancestor); + var handles = new List(); + // Exercise the actual native pin boundary without timing a racing thread or + // adding a production callback. The directory is empty, so a reparse writer + // would otherwise be able to redirect the next descendant lookup. + var pin = typeof(KokoroUninstallFiles).GetMethod("LockAncestors", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); + Assert.NotNull(pin); + try + { + pin.Invoke(null, [ancestor, handles]); + using var writer = OpenDirectoryWriter(ancestor, 0x40000000, 7, IntPtr.Zero, + 3, 0x02200000, IntPtr.Zero); + var error = Marshal.GetLastWin32Error(); + Assert.True(writer.IsInvalid); + Assert.Equal(32, error); // ERROR_SHARING_VIOLATION, before FSCTL_SET_REPARSE_POINT. + } + finally { foreach (var handle in handles) handle.Dispose(); } + using var afterRelease = OpenDirectoryWriter(ancestor, 0x40000000, 7, IntPtr.Zero, + 3, 0x02200000, IntPtr.Zero); + Assert.False(afterRelease.IsInvalid); // Fixture permits the operation without pins. + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern Microsoft.Win32.SafeHandles.SafeFileHandle OpenDirectoryWriter( + string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template); + + [Fact] + public void InstallerCatalog_CoversExactlyTheDownloadConsumers() + { + var downloads = KokoroModelManager.AvailablePacks.SelectMany(pack => + new[] { pack.Model, pack.VoicesFile }.Select(asset => + (pack.PackId, asset.FileName, asset.DownloadUrl, asset.Sha256, asset.SizeBytes))).ToArray(); + var cleanup = KokoroDownloadCatalog.All.Select(asset => + (asset.PackId, asset.FileName, asset.Url, asset.Sha256, asset.SizeBytes)).ToArray(); + Assert.Equal(downloads, cleanup); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PowerShell51_RunsPreviewOrHonorsCancellationBeforeStarting(bool cancel) + { + using var temp = new TempDirectory("kokoro-uninstall-host-"); + var root = TestRepositoryPaths.GetRepositoryRoot(); + foreach (var name in new[] { "KokoroDownloadCatalog.cs", "KokoroUninstallFiles.cs" }) + File.Copy(Path.Combine(root, "src", "OpenClaw.Shared", "Audio", name), temp.Combine(name)); + File.Copy(Path.Combine(root, "scripts", "Uninstall-DownloadedModels.ps1"), + temp.Combine("Uninstall-DownloadedModels.ps1")); + var data = temp.Combine("data with spaces"); + Directory.CreateDirectory(data); + var output = await UninstallScriptHost.RunAsync(temp, ["ConvertTo-CleanProcessOutput"], """ + $cancelPath = Join-Path $AppRoot 'cancel.txt' + $expected = 0 + if ($env:OPENCLAW_TEST_CANCEL_MODELS -eq 'True') { + [IO.File]::WriteAllText($cancelPath, 'cancel') + $expected = 2 + } + & (Join-Path $AppRoot 'Uninstall-DownloadedModels.ps1') -DataDirectory (Join-Path $AppRoot 'data with spaces') -ReportPath (Join-Path $AppRoot 'report.txt') -SelectionPath (Join-Path $AppRoot 'selection.txt') -CancellationPath $cancelPath + if ($LASTEXITCODE -ne $expected) { throw "Unexpected model helper result: $LASTEXITCODE" } + Write-Output ([IO.File]::ReadAllText((Join-Path $AppRoot 'selection.txt'))) + Write-Output ([IO.File]::ReadAllText((Join-Path $AppRoot 'report.txt'))) + """, new Dictionary { ["OPENCLAW_TEST_CANCEL_MODELS"] = cancel.ToString() }); + Assert.StartsWith("0", output.Trim()); + Assert.Contains(cancel ? "cancelled before starting" : "Absent:", output); + Assert.Contains(data, output); + if (!cancel) Assert.Contains("sizes were not scanned", output); + } + + private static KokoroUninstallReport Inspect(TempDirectory temp, int selection) => + KokoroUninstallFiles.Inspect(temp.Path, Assets, selection, CancellationToken.None, TestTimeout); + + private static string Seed(TempDirectory temp, int index) + { + var directory = temp.Combine("models", "kokoro", "fixture"); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, Assets[index].FileName); + File.WriteAllText(path, "abc"); + return path; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateHardLinkW")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CreateHardLink(string link, string existing, IntPtr security); +} From 3775dc2912718cb8dbba1e2e4636ef9253e0f2fd Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:22:37 +0000 Subject: [PATCH 2/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> OpenClaw-Publication: 2ec673e9-a7a4-4a0d-898c-50cd68c59447 --- docs/SETUP.md | 2 +- installer.iss | 28 ++++++++----------- scripts/Uninstall-DownloadedModels.ps1 | 15 +++++----- .../InstallerModelCleanupContractTests.cs | 5 ++++ .../KokoroUninstallFilesTests.cs | 12 ++++---- 5 files changed, 32 insertions(+), 30 deletions(-) diff --git a/docs/SETUP.md b/docs/SETUP.md index 414ce8603f..7832218fb3 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -194,7 +194,7 @@ OpenClaw Companion checks for updates automatically and shows a notification whe Go to **Settings → Apps → Installed apps**, find **OpenClaw Companion**, and click **Uninstall**. Alternatively, use **Add or Remove Programs** in the Control Panel. You'll be asked whether to also remove the local WSL gateway; choose **Yes** to unregister its WSL distro and generated state, or **No** to leave the gateway and that state in place. -For the **Inno installer**, interactive uninstall offers an unchecked Kokoro download-removal choice, independent of Gateway removal. Continue immediately to keep models, or choose **Check downloaded models** to see exact file paths and measured byte counts before enabling removal. The dialog remains visible during the read-only check; Cancel requests that the model-check worker stop and aborts uninstall without starting model removal. Keeping models is the default, including silent uninstall. Only the catalog model and voices files whose current contents match their pinned hashes are eligible; other models, partial downloads, unknown files, shared caches, and directories are kept. Redirected paths, hard links, locked files, and unverified contents are not removed. Store migration or uncertain ownership suppresses removal, as does a custom `OPENCLAW_TRAY_DATA_DIR`. +For the **Inno installer**, interactive uninstall offers an unchecked Kokoro download-removal choice, independent of Gateway removal. Continue immediately to keep models, or choose **Check downloaded models** to see exact file paths and measured byte counts before enabling removal. Cancel before or after the read-only check aborts uninstall without starting model removal. The current synchronous helper wait disables the dialog during the check; in-progress cancellation is not yet available. Keeping models is the default, including silent uninstall. Only the catalog model and voices files whose current contents match their pinned hashes are eligible; other models, partial downloads, unknown files, shared caches, and directories are kept. Redirected paths, hard links, locked files, and unverified contents are not removed. Store migration or uncertain ownership suppresses removal, as does a custom `OPENCLAW_TRAY_DATA_DIR`. The model summary distinguishes removed bytes, measured retained catalog files, and files that could not be checked. Other app-data sizes are not scanned, so these numbers are not a total of all retained data. Cancelling the model choice stops uninstall before model removal; cleanup failures leave an incomplete summary rather than a claim that everything was removed. This option does not change MSIX uninstall or the separate Gateway cleanup scope. diff --git a/installer.iss b/installer.iss index 10e9ebf511..615fd8fc23 100644 --- a/installer.iss +++ b/installer.iss @@ -567,18 +567,16 @@ end; function RunModelHelper(Selection: Integer; var Eligible: Integer): Boolean; var - Params, Mask, ReportText: String; + Params, ReportText: String; Code: Integer; begin Result := False; Eligible := 0; DeleteFile(ExpandConstant('{tmp}\model-report.txt')); - DeleteFile(ExpandConstant('{tmp}\model-selection.txt')); Params := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + AddQuotes(ExpandConstant('{tmp}\Uninstall-DownloadedModels.ps1')) + ' -DataDirectory ' + AddQuotes(ExpandConstant('{userappdata}\{#MyInstallDir}')) + ' -ReportPath ' + AddQuotes(ExpandConstant('{tmp}\model-report.txt')) + - ' -SelectionPath ' + AddQuotes(ExpandConstant('{tmp}\model-selection.txt')) + ' -CancellationPath ' + AddQuotes(ExpandConstant('{tmp}\model-cancel.txt')) + ' -SelectionMask ' + IntToStr(Selection); if Selection <> 0 then Params := Params + ' -ConfirmDestructive'; @@ -586,10 +584,10 @@ begin Params, '', SW_HIDE, ewWaitUntilTerminated, Code) then Exit; if not ReadModelText(ExpandConstant('{tmp}\model-report.txt'), ReportText) then Exit; ModelSummary := ReportText; - if (Code <> 0) and (Code <> 1) then Exit; - if not ReadModelText(ExpandConstant('{tmp}\model-selection.txt'), Mask) then Exit; - Eligible := StrToIntDef(Trim(Mask), 0); - if (Eligible < 0) or (Eligible > 15) then Eligible := 0; + // The supervisor returns this reserved success range only after its worker exits. + // Ordinary PowerShell errors never become an eligible selection. + if (Code < 32) or (Code > 47) then Exit; + Eligible := Code - 32; Result := True; end; @@ -621,9 +619,9 @@ begin ModelScanButton.Enabled := False; ModelContinueButton.Enabled := False; DeleteFile(ExpandConstant('{tmp}\model-cancel.txt')); - ModelDetails.Text := 'Checking ownership and downloaded model files. Cancel stops this read-only check.'; + ModelDetails.Text := 'Checking ownership and downloaded model files. Please wait.'; try - // Exec pumps window messages while waiting, so Cancel remains available. + // Synchronous Exec disables this form until the helper exits. if CheckCompletedStoreMigration <> 0 then ModelSummary := 'Store migration or uncertain ownership requires preservation. Models are kept; sizes were not scanned.' else if not ModelScanCancelled then @@ -653,11 +651,9 @@ function ShowModelReport(Choosing: Boolean): Boolean; var CancelButton: TNewButton; begin - ModelDialog := CreateCustomForm; + ModelDialog := CreateCustomForm(ScaleX(640), ScaleY(440), True, True); try ModelDialog.Caption := 'Downloaded voice models'; - ModelDialog.ClientWidth := ScaleX(640); - ModelDialog.ClientHeight := ScaleY(440); ModelDialog.OnCloseQuery := @ModelPreviewCloseQuery; ModelRemoveCheck := TNewCheckBox.Create(ModelDialog); ModelRemoveCheck.Parent := ModelDialog; @@ -714,8 +710,8 @@ begin 'Sizes have not been measured. Gateway removal is a separate choice.'; if UninstallSilent() then Exit; if GetEnv('OPENCLAW_TRAY_DATA_DIR') <> '' then - ModelSummary := 'A custom app-data directory is configured. Models are kept; sizes were not scanned.' + - #13#10 + 'Configured path: ' + GetEnv('OPENCLAW_TRAY_DATA_DIR') + #13#10 + ModelSummary + ModelSummary := 'A custom app-data directory is configured. Models are kept; sizes were not scanned.' + #13#10 + + 'Configured path: ' + GetEnv('OPENCLAW_TRAY_DATA_DIR') + #13#10 + ModelSummary else if MigrationOperationUnavailable then ModelSummary := 'Migration ownership could not be checked. Models are kept.' + #13#10 + ModelSummary else @@ -746,8 +742,8 @@ begin end; UninstallProgressForm.StatusLabel.Caption := 'Checking and removing selected voice models...'; if not RunModelHelper(ModelCleanupSelection, Ignored) then - ModelSummary := 'Model cleanup could not be completed or verified. Some selected files may remain.' + - #13#10 + ModelSummary; + ModelSummary := 'Model cleanup could not be completed or verified. Some selected files may remain.' + #13#10 + + ModelSummary; end; procedure EnsureLocalGatewayCleanupChoice; diff --git a/scripts/Uninstall-DownloadedModels.ps1 b/scripts/Uninstall-DownloadedModels.ps1 index 6640d3d4f2..3e5bcf6cc0 100644 --- a/scripts/Uninstall-DownloadedModels.ps1 +++ b/scripts/Uninstall-DownloadedModels.ps1 @@ -7,12 +7,14 @@ A nonzero selection requires -ConfirmDestructive. The C# owner re-verifies every selected file, pins its ancestors, and deletes using its verified file handle. Reports are local to this uninstall, never telemetry or an ownership receipt. + Exit 32..47 is a completed preview with a four-bit eligible-file mask (code - 32). + Removal returns 32 on completion, 48 when incomplete; 49 means unavailable/unknown. + Keeping success codes separate from ordinary PowerShell errors fails closed. #> [CmdletBinding()] param( [Parameter(Mandatory = $true)][string]$DataDirectory, [Parameter(Mandatory = $true)][string]$ReportPath, - [Parameter(Mandatory = $true)][string]$SelectionPath, [ValidateRange(0, 15)][int]$SelectionMask = 0, [string]$CancellationPath = '', [switch]$ConfirmDestructive, @@ -40,7 +42,7 @@ try { $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $PSScriptRoot 'Uninstall-DownloadedModels.ps1'), '-DataDirectory', $DataDirectory, '-ReportPath', $ReportPath, - '-SelectionPath', $SelectionPath, '-SelectionMask', [string]$SelectionMask, '-Worker') + '-SelectionMask', [string]$SelectionMask, '-Worker') if ($ConfirmDestructive) { $arguments += '-ConfirmDestructive' } # Every value is quoted using Windows argv backslash rules. $quoted = foreach ($argument in $arguments) { @@ -76,11 +78,10 @@ try { (Join-Path $PSScriptRoot 'KokoroUninstallFiles.cs')) -ErrorAction Stop $result = [OpenClaw.Shared.Audio.KokoroUninstallFiles]::Run($DataDirectory, $SelectionMask) [IO.File]::WriteAllText($ReportPath, $result.Text, $encoding) - [IO.File]::WriteAllText($SelectionPath, [string]$result.EligibleMask, $encoding) - if (-not $result.Complete) { exit 1 } - exit 0 + if ($SelectionMask -eq 0) { exit (32 + $result.EligibleMask) } + if (-not $result.Complete) { exit 48 } + exit 32 } catch { - [IO.File]::WriteAllText($SelectionPath, '0', $encoding) $message = @( 'Model cleanup could not be completed or verified. Files may remain; no complete-cleanup claim is made.', "Model path: $DataDirectory\models\kokoro", @@ -88,5 +89,5 @@ try { $_.Exception.Message ) -join [Environment]::NewLine [IO.File]::WriteAllText($ReportPath, $message, $encoding) - exit 2 + exit 49 } diff --git a/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs b/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs index 6c698e23a2..7915dd47cd 100644 --- a/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs +++ b/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs @@ -41,6 +41,11 @@ public void ModelRemoval_RechecksPreservation_AndDoesNotDependOnGatewayRemoval() Assert.DoesNotContain("LocalGatewayCleanupSucceeded", cleanup); Assert.DoesNotContain("DelTree", cleanup); Assert.Contains("ShowModelReport(False);", source); + // Reserved completion codes, not an independent selection file, carry the preview. + Assert.Contains("if (Code < 32) or (Code > 47) then Exit;", source); + Assert.Contains("Eligible := Code - 32;", source); + Assert.DoesNotContain("model-selection.txt", source); + Assert.DoesNotContain("-SelectionPath", source); } [Theory] diff --git a/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs b/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs index 227ce8130b..434fdb2f4e 100644 --- a/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs +++ b/tests/OpenClaw.Tray.Tests/KokoroUninstallFilesTests.cs @@ -223,7 +223,7 @@ public void InstallerCatalog_CoversExactlyTheDownloadConsumers() new[] { pack.Model, pack.VoicesFile }.Select(asset => (pack.PackId, asset.FileName, asset.DownloadUrl, asset.Sha256, asset.SizeBytes))).ToArray(); var cleanup = KokoroDownloadCatalog.All.Select(asset => - (asset.PackId, asset.FileName, asset.Url, asset.Sha256, asset.SizeBytes)).ToArray(); + (asset.PackId, asset.FileName, asset.Url, (string?)asset.Sha256, asset.SizeBytes)).ToArray(); Assert.Equal(downloads, cleanup); } @@ -242,17 +242,17 @@ public async Task PowerShell51_RunsPreviewOrHonorsCancellationBeforeStarting(boo Directory.CreateDirectory(data); var output = await UninstallScriptHost.RunAsync(temp, ["ConvertTo-CleanProcessOutput"], """ $cancelPath = Join-Path $AppRoot 'cancel.txt' - $expected = 0 + $expected = 32 if ($env:OPENCLAW_TEST_CANCEL_MODELS -eq 'True') { [IO.File]::WriteAllText($cancelPath, 'cancel') - $expected = 2 + $expected = 49 } - & (Join-Path $AppRoot 'Uninstall-DownloadedModels.ps1') -DataDirectory (Join-Path $AppRoot 'data with spaces') -ReportPath (Join-Path $AppRoot 'report.txt') -SelectionPath (Join-Path $AppRoot 'selection.txt') -CancellationPath $cancelPath + & (Join-Path $AppRoot 'Uninstall-DownloadedModels.ps1') -DataDirectory (Join-Path $AppRoot 'data with spaces') -ReportPath (Join-Path $AppRoot 'report.txt') -CancellationPath $cancelPath if ($LASTEXITCODE -ne $expected) { throw "Unexpected model helper result: $LASTEXITCODE" } - Write-Output ([IO.File]::ReadAllText((Join-Path $AppRoot 'selection.txt'))) + Write-Output $LASTEXITCODE Write-Output ([IO.File]::ReadAllText((Join-Path $AppRoot 'report.txt'))) """, new Dictionary { ["OPENCLAW_TEST_CANCEL_MODELS"] = cancel.ToString() }); - Assert.StartsWith("0", output.Trim()); + Assert.StartsWith(cancel ? "49" : "32", output.Trim()); Assert.Contains(cancel ? "cancelled before starting" : "Absent:", output); Assert.Contains(data, output); if (!cancel) Assert.Contains("sizes were not scanned", output); From eb9e7fa6ba32db3759a89df92260571812062f64 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:48:42 +0000 Subject: [PATCH 3/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> OpenClaw-Publication: 49448427-c9c4-471b-884d-52cf8d17167b --- docs/SETUP.md | 2 +- installer.iss | 184 ++++++++++++------ scripts/Uninstall-DownloadedModels.ps1 | 148 +++++++------- .../InstallerModelCleanupContractTests.cs | 29 ++- .../KokoroUninstallProcessTests.cs | 160 +++++++++++++++ 5 files changed, 387 insertions(+), 136 deletions(-) create mode 100644 tests/OpenClaw.Tray.Tests/KokoroUninstallProcessTests.cs diff --git a/docs/SETUP.md b/docs/SETUP.md index 7832218fb3..47058c5392 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -194,7 +194,7 @@ OpenClaw Companion checks for updates automatically and shows a notification whe Go to **Settings → Apps → Installed apps**, find **OpenClaw Companion**, and click **Uninstall**. Alternatively, use **Add or Remove Programs** in the Control Panel. You'll be asked whether to also remove the local WSL gateway; choose **Yes** to unregister its WSL distro and generated state, or **No** to leave the gateway and that state in place. -For the **Inno installer**, interactive uninstall offers an unchecked Kokoro download-removal choice, independent of Gateway removal. Continue immediately to keep models, or choose **Check downloaded models** to see exact file paths and measured byte counts before enabling removal. Cancel before or after the read-only check aborts uninstall without starting model removal. The current synchronous helper wait disables the dialog during the check; in-progress cancellation is not yet available. Keeping models is the default, including silent uninstall. Only the catalog model and voices files whose current contents match their pinned hashes are eligible; other models, partial downloads, unknown files, shared caches, and directories are kept. Redirected paths, hard links, locked files, and unverified contents are not removed. Store migration or uncertain ownership suppresses removal, as does a custom `OPENCLAW_TRAY_DATA_DIR`. +For the **Inno installer**, interactive uninstall offers an unchecked Kokoro download-removal choice, independent of Gateway removal. Continue immediately to keep models, or choose **Check downloaded models** to see exact file paths and measured byte counts before enabling removal. The read-only check runs asynchronously, leaving Cancel available. Cancellation waits for the worker result before closing; an unconfirmed result aborts uninstall rather than enabling removal. Keeping models is the default, including silent uninstall. Only the catalog model and voices files whose current contents match their pinned hashes are eligible; other models, partial downloads, unknown files, shared caches, and directories are kept. Redirected paths, hard links, locked files, and unverified contents are not removed. Store migration or uncertain ownership suppresses removal at its final admission check. A custom `OPENCLAW_TRAY_DATA_DIR` disables this cleanup option. The model summary distinguishes removed bytes, measured retained catalog files, and files that could not be checked. Other app-data sizes are not scanned, so these numbers are not a total of all retained data. Cancelling the model choice stops uninstall before model removal; cleanup failures leave an incomplete summary rather than a claim that everything was removed. This option does not change MSIX uninstall or the separate Gateway cleanup scope. diff --git a/installer.iss b/installer.iss index 615fd8fc23..43be39d17f 100644 --- a/installer.iss +++ b/installer.iss @@ -153,6 +153,10 @@ Name: "{userstartup}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Parameter Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent; Check: ShouldLaunchTray [Code] +const + ModelPreviewPollMilliseconds = 100; + ModelStartupGraceSeconds = 30; + ModelStopGraceSeconds = 10; var VCRuntimeInstallSucceeded: Boolean; LocalGatewayCleanupChoiceInitialized: Boolean; @@ -169,6 +173,17 @@ var ModelDetails: TNewMemo; ModelRemoveCheck: TNewCheckBox; ModelScanButton, ModelContinueButton: TNewButton; + ModelPreviewTimer: THandle; + ModelPreviewDeadline: Int64; + ModelInvocation: Integer; + ModelReportPath, ModelCancelPath: String; + +function SetModelTimer(Window: THandle; Id: THandle; Interval: LongWord; Callback: THandle): THandle; + external 'SetTimer@user32.dll stdcall'; +function KillModelTimer(Window: THandle; Id: THandle): Boolean; + external 'KillTimer@user32.dll stdcall'; +function ModelTickCount: Int64; + external 'GetTickCount64@kernel32.dll stdcall'; function ChooseModelCleanup: Boolean; forward; @@ -538,19 +553,24 @@ begin MigrateLegacyBackgroundLaunch; end; -function ReadModelText(Path: String; var Value: String): Boolean; +function ReadModelCompletion(var Code: Integer): Boolean; var Lines: TArrayOfString; I: Integer; begin - Value := ''; - Result := LoadStringsFromFile(Path, Lines); - if not Result then Exit; - for I := 0 to GetArrayLength(Lines) - 1 do + Result := False; + Code := -1; + if not LoadStringsFromFile(ModelReportPath, Lines) then Exit; + if GetArrayLength(Lines) < 2 then Exit; + Code := StrToIntDef(Lines[0], -1); + if (Code < 32) or (Code > 50) then Exit; + ModelSummary := ''; + for I := 1 to GetArrayLength(Lines) - 1 do begin - if I > 0 then Value := Value + #13#10; - Value := Value + Lines[I]; + if I > 1 then ModelSummary := ModelSummary + #13#10; + ModelSummary := ModelSummary + Lines[I]; end; + Result := True; end; function StageModelHelper: Boolean; @@ -565,30 +585,42 @@ begin ExpandConstant('{tmp}\KokoroUninstallFiles.cs'), False); end; -function RunModelHelper(Selection: Integer; var Eligible: Integer): Boolean; +function StartModelHelper(Selection: Integer; Wait: TExecWait; var Code: Integer): Boolean; var - Params, ReportText: String; - Code: Integer; + Params: String; begin - Result := False; - Eligible := 0; - DeleteFile(ExpandConstant('{tmp}\model-report.txt')); + Inc(ModelInvocation); + ModelReportPath := ExpandConstant('{tmp}\model-result-') + IntToStr(ModelInvocation) + '.txt'; + ModelCancelPath := ExpandConstant('{tmp}\model-cancel-') + IntToStr(ModelInvocation) + '.txt'; Params := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + AddQuotes(ExpandConstant('{tmp}\Uninstall-DownloadedModels.ps1')) + ' -DataDirectory ' + AddQuotes(ExpandConstant('{userappdata}\{#MyInstallDir}')) + - ' -ReportPath ' + AddQuotes(ExpandConstant('{tmp}\model-report.txt')) + - ' -CancellationPath ' + AddQuotes(ExpandConstant('{tmp}\model-cancel.txt')) + + ' -ReportPath ' + AddQuotes(ModelReportPath) + + ' -CancellationPath ' + AddQuotes(ModelCancelPath) + ' -SelectionMask ' + IntToStr(Selection); if Selection <> 0 then Params := Params + ' -ConfirmDestructive'; - if not Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), - Params, '', SW_HIDE, ewWaitUntilTerminated, Code) then Exit; - if not ReadModelText(ExpandConstant('{tmp}\model-report.txt'), ReportText) then Exit; - ModelSummary := ReportText; - // The supervisor returns this reserved success range only after its worker exits. - // Ordinary PowerShell errors never become an eligible selection. - if (Code < 32) or (Code > 47) then Exit; - Eligible := Code - 32; - Result := True; + Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), + Params, '', SW_HIDE, Wait, Code); +end; + +procedure StopModelPreviewTimer; +begin + if ModelPreviewTimer <> 0 then + begin + KillModelTimer(0, ModelPreviewTimer); + ModelPreviewTimer := 0; + end; +end; + +procedure FinishModelPreview; +begin + StopModelPreviewTimer; + ModelScanRunning := False; + ModelDetails.Text := ModelSummary; + ModelRemoveCheck.Enabled := ModelPreviewEligible <> 0; + ModelScanButton.Enabled := ModelScanAllowed; + ModelContinueButton.Enabled := True; + if ModelScanCancelled then ModelDialog.Close; end; procedure CancelModelPreview(Sender: TObject); @@ -596,11 +628,11 @@ begin if ModelScanRunning then begin ModelScanCancelled := True; - SaveStringToFile(ExpandConstant('{tmp}\model-cancel.txt'), 'cancel', False); - ModelDetails.Text := 'Cancelling the model check. No model removal has started.'; + SaveStringToFile(ModelCancelPath, 'cancel', False); + ModelDetails.Text := 'Cancelling the model check. Waiting for the worker to stop; no model removal has started.'; end else - ModelDialog.ModalResult := mrCancel; + ModelDialog.Close; end; procedure ModelPreviewCloseQuery(Sender: TObject; var CanClose: Boolean); @@ -609,41 +641,70 @@ begin if not CanClose then CancelModelPreview(Sender); end; +procedure ModelPreviewTick(Window: THandle; Message: LongWord; Timer: THandle; Time: LongWord); +var + Code: Integer; +begin + if (Timer <> ModelPreviewTimer) or not ModelScanRunning then Exit; + if FileExists(ModelReportPath) then + begin + // This file is atomically published by the supervisor, never by the worker. + // A late receipt from another invocation has a different filename. + if not ReadModelCompletion(Code) then Code := 50; + if Code = 50 then + begin + StopModelPreviewTimer; + SaveStringToFile(ModelCancelPath, 'cancel', False); + ModelScanCancelled := True; + MsgBox('The model check could not confirm completion. Uninstall will stop without starting model removal.', mbError, MB_OK); + end + else if (Code >= 32) and (Code <= 47) then + ModelPreviewEligible := Code - 32; + FinishModelPreview; + end + else if ModelTickCount >= ModelPreviewDeadline then + begin + StopModelPreviewTimer; + SaveStringToFile(ModelCancelPath, 'cancel', False); + ModelScanCancelled := True; + MsgBox('The model check did not report completion within its time limit. Uninstall will stop; worker exit is unconfirmed.', mbError, MB_OK); + FinishModelPreview; + end; +end; + procedure CheckModelPreview(Sender: TObject); +var + Code, Seconds: Integer; begin - ModelScanRunning := True; - ModelScanCancelled := False; ModelPreviewEligible := 0; ModelRemoveCheck.Checked := False; ModelRemoveCheck.Enabled := False; + if not StageModelHelper then + begin + ModelDetails.Text := 'The model helper is unavailable. Models are kept.'; + Exit; + end; + ModelScanRunning := True; + ModelScanCancelled := False; ModelScanButton.Enabled := False; ModelContinueButton.Enabled := False; - DeleteFile(ExpandConstant('{tmp}\model-cancel.txt')); - ModelDetails.Text := 'Checking ownership and downloaded model files. Please wait.'; - try - // Synchronous Exec disables this form until the helper exits. - if CheckCompletedStoreMigration <> 0 then - ModelSummary := 'Store migration or uncertain ownership requires preservation. Models are kept; sizes were not scanned.' - else if not ModelScanCancelled then - begin - if StageModelHelper then - begin - if not RunModelHelper(0, ModelPreviewEligible) then - begin - ModelPreviewEligible := 0; - ModelSummary := 'Model inventory is unavailable. No model removal will be attempted.' + #13#10 + ModelSummary; - end; - end - else - ModelSummary := 'The model helper is unavailable. Models are kept.' + #13#10 + ModelSummary; - end; - finally - ModelScanRunning := False; - ModelDetails.Text := ModelSummary; - ModelRemoveCheck.Enabled := ModelPreviewEligible <> 0; - ModelScanButton.Enabled := ModelScanAllowed; - ModelContinueButton.Enabled := True; - if ModelScanCancelled then ModelDialog.ModalResult := mrCancel; + ModelDetails.Text := 'Checking downloaded model files. Cancel stops this read-only check.'; + Seconds := StrToIntDef(GetEnv('OPENCLAW_MODEL_UNINSTALL_PROCESS_TIMEOUT_SECONDS'), 180); + if (Seconds < 30) or (Seconds > 900) then Seconds := 180; + ModelPreviewDeadline := ModelTickCount + (Seconds + ModelStartupGraceSeconds + ModelStopGraceSeconds) * 1000; + ModelPreviewTimer := SetModelTimer(0, 0, ModelPreviewPollMilliseconds, CreateCallback(@ModelPreviewTick)); + if ModelPreviewTimer = 0 then + begin + ModelSummary := 'The model check could not start. Models are kept.'; + FinishModelPreview; + Exit; + end; + // No synchronous wait: Inno must not disable the custom form while scanning. + // Preview is read-only. Store ownership is rechecked at the deletion boundary. + if not StartModelHelper(0, ewNoWait, Code) then + begin + ModelSummary := 'The model helper could not start. Models are kept.'; + FinishModelPreview; end; end; @@ -694,6 +755,7 @@ begin if Choosing and Result and ModelRemoveCheck.Checked then ModelCleanupSelection := ModelPreviewEligible; finally + StopModelPreviewTimer; ModelDialog.Free; end; end; @@ -726,7 +788,7 @@ end; procedure RunSelectedModelCleanup; var - Ignored: Integer; + Code, ReportCode: Integer; begin if ModelCleanupSelection = 0 then Exit; // Preserve on changed Store ownership, independently of the Gateway choice. @@ -741,9 +803,13 @@ begin Exit; end; UninstallProgressForm.StatusLabel.Caption := 'Checking and removing selected voice models...'; - if not RunModelHelper(ModelCleanupSelection, Ignored) then - ModelSummary := 'Model cleanup could not be completed or verified. Some selected files may remain.' + #13#10 + - ModelSummary; + if StartModelHelper(ModelCleanupSelection, ewWaitUntilTerminated, Code) then + begin + if ReadModelCompletion(ReportCode) then + if (Code = 32) and (ReportCode = Code) then Exit; + end; + ModelSummary := 'Model cleanup could not be completed or verified. Some selected files may remain.' + #13#10 + + ModelSummary; end; procedure EnsureLocalGatewayCleanupChoice; diff --git a/scripts/Uninstall-DownloadedModels.ps1 b/scripts/Uninstall-DownloadedModels.ps1 index 3e5bcf6cc0..bf222e8649 100644 --- a/scripts/Uninstall-DownloadedModels.ps1 +++ b/scripts/Uninstall-DownloadedModels.ps1 @@ -2,14 +2,12 @@ .SYNOPSIS Preview or explicitly remove only verified Kokoro downloads for Inno uninstall. .DESCRIPTION - No recursive removal, app startup, Gateway cleanup, or shared-cache access. - The installer keeps its migration lease and rechecks preservation before removal. - A nonzero selection requires -ConfirmDestructive. The C# owner re-verifies every - selected file, pins its ancestors, and deletes using its verified file handle. - Reports are local to this uninstall, never telemetry or an ownership receipt. - Exit 32..47 is a completed preview with a four-bit eligible-file mask (code - 32). - Removal returns 32 on completion, 48 when incomplete; 49 means unavailable/unknown. - Keeping success codes separate from ordinary PowerShell errors fails closed. + The installer owns consent and the migration lease. The worker re-verifies + selected files and deletes through their pinned handles. No recursive cleanup. + The supervisor atomically publishes one completion report AFTER worker exit: + first line is 32..47 (preview mask = code - 32), 32 (removal complete), + 48 (partial removal), 49 (stopped, failed/cancelled), or 50 (exit unconfirmed). + Remaining lines are the human-readable report. Launch alone is not completion. #> [CmdletBinding()] param( @@ -23,71 +21,81 @@ param( $ErrorActionPreference = 'Stop' $encoding = New-Object System.Text.UTF8Encoding $true +$failureText = "Model operation could not be completed. Sizes or removal may be incomplete.$([Environment]::NewLine)Model path: $DataDirectory\models\kokoro" + +if ($Worker) { + try { + if ($SelectionMask -ne 0 -and -not $ConfirmDestructive) { throw 'Explicit removal confirmation is missing.' } + Add-Type -Path @((Join-Path $PSScriptRoot 'KokoroDownloadCatalog.cs'), + (Join-Path $PSScriptRoot 'KokoroUninstallFiles.cs')) -ErrorAction Stop + $result = [OpenClaw.Shared.Audio.KokoroUninstallFiles]::Run($DataDirectory, $SelectionMask) + [IO.File]::WriteAllText($ReportPath, $result.Text, $encoding) + if ($SelectionMask -eq 0) { exit (32 + $result.EligibleMask) } + if (-not $result.Complete) { exit 48 } + exit 32 + } catch { + [IO.File]::WriteAllText($ReportPath, $failureText + [Environment]::NewLine + $_.Exception.Message, $encoding) + exit 49 + } +} + +$child = $null +$stopped = $true +$code = 49 +$report = $failureText try { - if ($SelectionMask -ne 0 -and -not $ConfirmDestructive) { - throw 'Model removal requires explicit confirmation.' + if ($SelectionMask -ne 0 -and -not $ConfirmDestructive) { throw 'Explicit removal confirmation is missing.' } + $seconds = 180 + $configured = 0 + if ([int]::TryParse($env:OPENCLAW_MODEL_UNINSTALL_PROCESS_TIMEOUT_SECONDS, [ref]$configured) -and + $configured -ge 30 -and $configured -le 900) { $seconds = $configured } + $cancellationPollMilliseconds = 100 + $terminationWaitMilliseconds = 10000 + if ($CancellationPath -and [IO.File]::Exists($CancellationPath)) { + throw 'Model check cancelled before starting. No model removal was started.' } - if (-not $Worker) { - # Bound compiler startup as well as scanning. On timeout, do not retry a - # possibly partial deletion or claim the selected files were all removed. - $seconds = 180 - $configured = 0 - if ([int]::TryParse($env:OPENCLAW_MODEL_UNINSTALL_PROCESS_TIMEOUT_SECONDS, [ref]$configured) -and - $configured -ge 30 -and $configured -le 900) { $seconds = $configured } - $cancellationPollMilliseconds = 100 - $terminationWaitMilliseconds = 10000 - if ($CancellationPath -and [IO.File]::Exists($CancellationPath)) { - throw 'Model check was cancelled before starting. No model removal was started.' - } - $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', - (Join-Path $PSScriptRoot 'Uninstall-DownloadedModels.ps1'), - '-DataDirectory', $DataDirectory, '-ReportPath', $ReportPath, - '-SelectionMask', [string]$SelectionMask, '-Worker') - if ($ConfirmDestructive) { $arguments += '-ConfirmDestructive' } - # Every value is quoted using Windows argv backslash rules. - $quoted = foreach ($argument in $arguments) { - if ($argument.Contains('"')) { throw 'Unexpected quote in uninstall path.' } - '"' + ($argument -replace '(\\+)$', '$1$1') + '"' + $workerReport = $ReportPath + '.worker' + $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', + $PSCommandPath, '-DataDirectory', $DataDirectory, '-ReportPath', $workerReport, + '-SelectionMask', [string]$SelectionMask, '-Worker') + if ($ConfirmDestructive) { $arguments += '-ConfirmDestructive' } + $quoted = foreach ($argument in $arguments) { + if ($argument.Contains('"')) { throw 'Unexpected quote in uninstall path.' } + '"' + ($argument -replace '(\\+)$', '$1$1') + '"' + } + $start = New-Object System.Diagnostics.ProcessStartInfo + $start.FileName = Join-Path $PSHOME 'powershell.exe' + $start.Arguments = $quoted -join ' ' + $start.UseShellExecute = $false + $start.CreateNoWindow = $true + $child = [Diagnostics.Process]::Start($start) + $stopped = $false + $clock = [Diagnostics.Stopwatch]::StartNew() + while (-not $child.WaitForExit($cancellationPollMilliseconds)) { + $cancelled = $CancellationPath -and [IO.File]::Exists($CancellationPath) + if ($cancelled -or $clock.Elapsed.TotalSeconds -ge $seconds) { + $child.Kill() + $stopped = $child.WaitForExit($terminationWaitMilliseconds) + if (-not $stopped) { throw 'Worker exit is unconfirmed. Uninstall must stop; do not retry cleanup.' } + if ($cancelled -and $SelectionMask -eq 0) { throw 'Model check cancelled. No model removal was started.' } + throw 'Model operation interrupted. Removal may be partial; inspect the model paths before retrying.' } - $start = New-Object System.Diagnostics.ProcessStartInfo - $start.FileName = Join-Path $PSHOME 'powershell.exe' - $start.Arguments = $quoted -join ' ' - $start.UseShellExecute = $false - $start.CreateNoWindow = $true - $child = [Diagnostics.Process]::Start($start) - try { - $clock = [Diagnostics.Stopwatch]::StartNew() - while (-not $child.WaitForExit($cancellationPollMilliseconds)) { - $cancelled = $CancellationPath -and [IO.File]::Exists($CancellationPath) - if ($cancelled -or $clock.Elapsed.TotalSeconds -ge $seconds) { - $child.Kill() - if (-not $child.WaitForExit($terminationWaitMilliseconds)) { - throw 'The model helper has not confirmed exit. Its result is unknown; do not retry cleanup.' - } - if ($cancelled -and $SelectionMask -eq 0) { - throw 'Model check cancelled. No model removal was started.' - } - throw 'Model cleanup interrupted. Removal may be partial; inspect the model paths before retrying.' - } - } - exit $child.ExitCode - } finally { $child.Dispose() } } - - Add-Type -Path @((Join-Path $PSScriptRoot 'KokoroDownloadCatalog.cs'), - (Join-Path $PSScriptRoot 'KokoroUninstallFiles.cs')) -ErrorAction Stop - $result = [OpenClaw.Shared.Audio.KokoroUninstallFiles]::Run($DataDirectory, $SelectionMask) - [IO.File]::WriteAllText($ReportPath, $result.Text, $encoding) - if ($SelectionMask -eq 0) { exit (32 + $result.EligibleMask) } - if (-not $result.Complete) { exit 48 } - exit 32 + $stopped = $true + $code = $child.ExitCode + if ($code -lt 32 -or $code -gt 49) { throw "Unexpected model worker exit code: $code" } + $report = [IO.File]::ReadAllText($workerReport) } catch { - $message = @( - 'Model cleanup could not be completed or verified. Files may remain; no complete-cleanup claim is made.', - "Model path: $DataDirectory\models\kokoro", - 'Other app data and shared caches are outside this choice. Sizes are unknown.', - $_.Exception.Message - ) -join [Environment]::NewLine - [IO.File]::WriteAllText($ReportPath, $message, $encoding) - exit 49 + if (-not $stopped -and $null -ne $child) { + try { $stopped = $child.HasExited } catch { } + } + $code = if ($stopped) { 49 } else { 50 } + $report = $failureText + [Environment]::NewLine + $_.Exception.Message +} finally { + if ($null -ne $child) { $child.Dispose() } } + +# A unique per-invocation path is supplied by Inno. A partial write is never a receipt. +[IO.File]::WriteAllText($ReportPath + '.pending', [string]$code + [Environment]::NewLine + $report, $encoding) +[IO.File]::Move($ReportPath + '.pending', $ReportPath) +exit $code diff --git a/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs b/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs index 7915dd47cd..0aa3bbbf26 100644 --- a/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs +++ b/tests/OpenClaw.Tray.Tests/InstallerModelCleanupContractTests.cs @@ -15,7 +15,7 @@ public void ModelChoice_DefaultsToKeep_AndSilentUninstallCannotOptIn() Assert.Contains("ModelCleanupSelection := 0;", choice); Assert.True(choice.IndexOf("ModelCleanupSelection := 0;", StringComparison.Ordinal) < choice.IndexOf("if UninstallSilent() then Exit;", StringComparison.Ordinal)); - Assert.DoesNotContain("RunModelHelper", choice); + Assert.DoesNotContain("StartModelHelper", choice); Assert.DoesNotContain("CheckCompletedStoreMigration", choice); Assert.Contains("Result := ShowModelReport(True);", choice); Assert.Contains("ModelRemoveCheck.Checked := False;", source); @@ -23,7 +23,8 @@ public void ModelChoice_DefaultsToKeep_AndSilentUninstallCannotOptIn() Assert.Contains("ModelScanButton.OnClick := @CheckModelPreview;", source); Assert.Contains("CancelButton.OnClick := @CancelModelPreview;", source); Assert.Contains("CanClose := not ModelScanRunning;", source); - Assert.Contains("if ModelScanCancelled then ModelDialog.ModalResult := mrCancel;", source); + Assert.Contains("if ModelScanCancelled then ModelDialog.Close;", source); + Assert.DoesNotContain("ModelDialog.ModalResult", source); Assert.Contains("Result := ChooseModelCleanup;", source); // Cancel aborts admission. } @@ -36,18 +37,34 @@ public void ModelRemoval_RechecksPreservation_AndDoesNotDependOnGatewayRemoval() Assert.Contains("if ModelCleanupSelection = 0 then Exit;", cleanup); Assert.Contains("if MigrationOperationUnavailable then", cleanup); Assert.True(cleanup.IndexOf("CheckCompletedStoreMigration <> 0", StringComparison.Ordinal) - < cleanup.IndexOf("RunModelHelper(ModelCleanupSelection", StringComparison.Ordinal)); + < cleanup.IndexOf("StartModelHelper(ModelCleanupSelection, ewWaitUntilTerminated", StringComparison.Ordinal)); Assert.DoesNotContain("LocalGatewayCleanupRequested", cleanup); Assert.DoesNotContain("LocalGatewayCleanupSucceeded", cleanup); Assert.DoesNotContain("DelTree", cleanup); Assert.Contains("ShowModelReport(False);", source); - // Reserved completion codes, not an independent selection file, carry the preview. - Assert.Contains("if (Code < 32) or (Code > 47) then Exit;", source); - Assert.Contains("Eligible := Code - 32;", source); + // Only an atomic completion receipt can authorize the preview mask. + Assert.Contains("if not ReadModelCompletion(Code) then Code := 50;", source); + Assert.Contains("else if (Code >= 32) and (Code <= 47) then", source); + Assert.Contains("ModelPreviewEligible := Code - 32;", source); Assert.DoesNotContain("model-selection.txt", source); Assert.DoesNotContain("-SelectionPath", source); } + [Fact] + public void Preview_ObservesCompletionWithoutDisablingItsCancelControls() + { + var source = Installer; + var preview = source[source.IndexOf("procedure CheckModelPreview", StringComparison.Ordinal)..]; + preview = preview[..preview.IndexOf("function ShowModelReport", StringComparison.Ordinal)]; + Assert.Contains("StartModelHelper(0, ewNoWait, Code)", preview); + Assert.DoesNotContain("ewWaitUntilTerminated", preview); + Assert.DoesNotContain("CheckCompletedStoreMigration", preview); + Assert.Contains("CreateCallback(@ModelPreviewTick)", preview); + Assert.Contains("Inc(ModelInvocation);", source); + Assert.Contains("if (Timer <> ModelPreviewTimer) or not ModelScanRunning then Exit;", source); + Assert.Contains("finally\n StopModelPreviewTimer;\n ModelDialog.Free;", source); + } + [Theory] [InlineData("scripts\\Uninstall-DownloadedModels.ps1", "Uninstall-DownloadedModels.ps1")] [InlineData("src\\OpenClaw.Shared\\Audio\\KokoroDownloadCatalog.cs", "KokoroDownloadCatalog.cs")] diff --git a/tests/OpenClaw.Tray.Tests/KokoroUninstallProcessTests.cs b/tests/OpenClaw.Tray.Tests/KokoroUninstallProcessTests.cs new file mode 100644 index 0000000000..f5f8c767f1 --- /dev/null +++ b/tests/OpenClaw.Tray.Tests/KokoroUninstallProcessTests.cs @@ -0,0 +1,160 @@ +using System.Diagnostics; +using OpenClaw.Shared.Audio; +using OpenClaw.TestSupport; + +namespace OpenClaw.Tray.Tests; + +// Exercises the shipped supervisor/worker protocol on Windows, not an Inno UI mock. +public sealed class KokoroUninstallProcessTests +{ + private const string FixtureHash = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds( + int.TryParse(Environment.GetEnvironmentVariable("OPENCLAW_MODEL_UNINSTALL_TEST_TIMEOUT_SECONDS"), out var seconds) + && seconds > 0 ? seconds : 120); + + [Theory] + [InlineData(0, false, false, 33, true)] + [InlineData(1, true, false, 32, false)] + [InlineData(1, true, true, 48, true)] + [InlineData(1, false, false, 49, true)] + public async Task Completion_PreservesEncodedSelectionAndPartialOutcomes( + int selection, bool confirm, bool readOnly, int expectedCode, bool retained) + { + using var temp = new TempDirectory("kokoro-process-"); + Stage(temp); + // Only catalog input hashes change. Shipped operation and supervisor source + // execute unchanged against real files, without downloading hundreds of MB. + var catalogPath = temp.Combine("KokoroDownloadCatalog.cs"); + var catalog = File.ReadAllText(catalogPath); + foreach (var asset in KokoroDownloadCatalog.All) catalog = catalog.Replace(asset.Sha256, FixtureHash); + File.WriteAllText(catalogPath, catalog); + var model = temp.Combine("data", "models", "kokoro", + KokoroDownloadCatalog.All[0].PackId, KokoroDownloadCatalog.All[0].FileName); + Directory.CreateDirectory(Path.GetDirectoryName(model)!); + File.WriteAllText(model, "abc"); + File.WriteAllText(temp.Combine("data", "settings.json"), "keep"); + if (readOnly) File.SetAttributes(model, FileAttributes.ReadOnly); + try + { + using var process = Start(temp, selection, confirm); + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + try { await process.WaitForExitAsync().WaitAsync(Timeout); } + finally { await StopIfRunning(process); } + Assert.True(process.ExitCode == expectedCode, await stdout + await stderr); + var report = File.ReadAllLines(temp.Combine("report.txt")); + Assert.Equal(expectedCode.ToString(), report[0]); + Assert.True(report.Length > 1); + Assert.False(File.Exists(temp.Combine("report.txt.pending"))); + Assert.Equal(retained, File.Exists(model)); + Assert.Equal("keep", File.ReadAllText(temp.Combine("data", "settings.json"))); + Assert.Contains(confirm || selection == 0 ? model : temp.Combine("data", "models", "kokoro"), string.Join('\n', report)); + if (selection == 0) Assert.Contains("3 bytes", string.Join('\n', report)); + if (readOnly) Assert.Contains("incomplete", string.Join('\n', report)); + } + finally { if (File.Exists(model)) File.SetAttributes(model, FileAttributes.Normal); } + } + + [Fact] + public async Task Cancellation_PublishesOnlyAfterTheRunningWorkerReleasesItsFile() + { + using var temp = new TempDirectory("kokoro-cancel-"); + Stage(temp); + Directory.CreateDirectory(temp.Combine("data")); + // Controlled external worker for the supervisor's cancellation boundary. + // This is not file-cleanup or real-installer proof: the real-worker cases above + // cover file operations. No test-only switches enter production code. + File.WriteAllText(temp.Combine("KokoroUninstallFiles.cs"), """ + using System; + using System.IO; + using System.Threading; + namespace OpenClaw.Shared.Audio { + public static class KokoroUninstallFiles { + public static object Run(string root, int selection) { + using (var held = new FileStream(Path.Combine(root, "held"), FileMode.CreateNew, FileAccess.Write, FileShare.None)) { + File.WriteAllText(Path.Combine(root, "ready"), "ready"); + // Self-bounded even if the supervisor regresses or its test crashes. + using (var release = new ManualResetEvent(false)) + release.WaitOne(int.Parse(Environment.GetEnvironmentVariable("OPENCLAW_TEST_STALLED_WORKER_TIMEOUT_MS"))); + } + return null; + } + } + } + """); + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var watcher = new FileSystemWatcher(temp.Combine("data"), "ready"); + watcher.Created += (_, _) => ready.TrySetResult(true); + watcher.EnableRaisingEvents = true; + var receipt = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var reports = new FileSystemWatcher(temp.Path, "report.txt"); + void ObserveReceipt() + { + try + { + using var released = new FileStream(temp.Combine("data", "held"), FileMode.Open, FileAccess.ReadWrite, FileShare.None); + receipt.TrySetResult(null); + } + catch (Exception error) { receipt.TrySetResult(error); } + } + reports.Created += (_, _) => ObserveReceipt(); + reports.Renamed += (_, _) => ObserveReceipt(); + reports.EnableRaisingEvents = true; + using var process = Start(temp, 0, false); + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + try + { + var exit = process.WaitForExitAsync(); + var first = await Task.WhenAny(ready.Task, exit).WaitAsync(Timeout); + Assert.True(first == ready.Task, first == exit ? await stdout + await stderr : "Worker did not become ready."); + Assert.False(File.Exists(temp.Combine("report.txt"))); // No premature completion. + File.WriteAllText(temp.Combine("cancel.txt"), "cancel"); + // Check the lock when completion becomes observable, before awaiting + // supervisor exit. An early published receipt must fail this assertion. + Assert.Null(await receipt.Task.WaitAsync(Timeout)); + await exit.WaitAsync(Timeout); + Assert.True(process.ExitCode == 49, await stdout + await stderr); + var report = File.ReadAllLines(temp.Combine("report.txt")); + Assert.Equal("49", report[0]); + Assert.Contains("cancelled", string.Join('\n', report)); + } + finally { await StopIfRunning(process); } + } + + private static void Stage(TempDirectory temp) + { + var root = TestRepositoryPaths.GetRepositoryRoot(); + File.Copy(Path.Combine(root, "scripts", "Uninstall-DownloadedModels.ps1"), temp.Combine("Uninstall-DownloadedModels.ps1")); + foreach (var name in new[] { "KokoroDownloadCatalog.cs", "KokoroUninstallFiles.cs" }) + File.Copy(Path.Combine(root, "src", "OpenClaw.Shared", "Audio", name), temp.Combine(name)); + } + + private static Process Start(TempDirectory temp, int selection, bool confirm) + { + var powershell = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), + "System32", "WindowsPowerShell", "v1.0", "powershell.exe"); + var start = new ProcessStartInfo(powershell) + { + UseShellExecute = false, CreateNoWindow = true, + RedirectStandardOutput = true, RedirectStandardError = true, + WorkingDirectory = temp.Path, + }; + foreach (var argument in new[] { + "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", temp.Combine("Uninstall-DownloadedModels.ps1"), + "-DataDirectory", temp.Combine("data"), "-ReportPath", temp.Combine("report.txt"), + "-CancellationPath", temp.Combine("cancel.txt"), "-SelectionMask", selection.ToString(), + }) start.ArgumentList.Add(argument); + start.Environment["OPENCLAW_TEST_STALLED_WORKER_TIMEOUT_MS"] = + checked((int)Timeout.TotalMilliseconds).ToString(System.Globalization.CultureInfo.InvariantCulture); + if (confirm) start.ArgumentList.Add("-ConfirmDestructive"); + return Process.Start(start) ?? throw new InvalidOperationException("Could not start the model supervisor."); + } + + private static async Task StopIfRunning(Process process) + { + if (process.HasExited) return; + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync().WaitAsync(Timeout); + } +} From ee5b3961addb8aeac3c45c4a202674b77a60af6e Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:17:53 +0000 Subject: [PATCH 4/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi - @jalehman Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> Co-authored-by: jalehman <550978+jalehman@users.noreply.github.com> OpenClaw-Publication: 66d9096b-d3fe-4c66-b2dd-9fde3bfa10f1 --- .github/workflows/inno-uninstall-media.yml | 110 +++ scripts/capture-inno-model-uninstall.ps1 | 858 +++++++++++++++++++++ 2 files changed, 968 insertions(+) create mode 100644 .github/workflows/inno-uninstall-media.yml create mode 100644 scripts/capture-inno-model-uninstall.ps1 diff --git a/.github/workflows/inno-uninstall-media.yml b/.github/workflows/inno-uninstall-media.yml new file mode 100644 index 0000000000..29455c1fe0 --- /dev/null +++ b/.github/workflows/inno-uninstall-media.yml @@ -0,0 +1,110 @@ +name: Inno uninstall media proof + +on: + pull_request: + branches: [main, master] + paths: + - installer.iss + - scripts/Uninstall-DownloadedModels.ps1 + - scripts/capture-inno-model-uninstall.ps1 + - src/OpenClaw.Shared/Audio/Kokoro*.cs + - .github/workflows/inno-uninstall-media.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: inno-media-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + capture: + name: Real Inno uninstall screenshots and video + runs-on: windows-latest + timeout-minutes: 40 + env: + RequireSignedCleanupHost: 'false' + RequireSignedFileWorker: 'false' + OPENCLAW_REPO_ROOT: ${{ github.workspace }} + PROOF_PR_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: 10.0.x + + - uses: actions/cache/restore@v6 + with: + path: ~/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/Directory.Packages.props') }} + restore-keys: nuget-${{ runner.os }}- + + - name: Prepare installer and recording tools + shell: pwsh + run: | + choco install innosetup ffmpeg -y --no-progress + if ($LASTEXITCODE -ne 0) { throw 'Capture prerequisites could not be installed.' } + ffmpeg -version + ./scripts/Set-CiDesktopResolution.ps1 + + - name: Build complete candidate Dev installer + shell: pwsh + run: | + ./scripts/Initialize-ReactorPackages.ps1 + ./scripts/build-inno-local.ps1 -Arch x64 -Dev -Fast + if ($LASTEXITCODE -ne 0) { throw 'Candidate installer build failed.' } + + - name: Fetch verified released baseline + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $ErrorActionPreference = 'Stop' + $baseline = git rev-parse 'v2026.11.3^{commit}' + if ($LASTEXITCODE -ne 0 -or $baseline -ne '66b9b5a559a0651da3aa6ce7ae3d183fbd87cb1c') { + throw 'The baseline release tag moved or is unavailable.' + } + $release = gh api "repos/$env:GITHUB_REPOSITORY/releases/tags/v2026.11.3" | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { throw 'Baseline release lookup failed.' } + $assets = @($release.assets | Where-Object name -eq 'OpenClawCompanion-Setup-x64.exe') + if ($assets.Count -ne 1 -or $assets[0].digest -notmatch '^sha256:[0-9a-fA-F]{64}$') { + throw 'Baseline requires one installer with a published SHA256 digest.' + } + $path = Join-Path $env:RUNNER_TEMP 'OpenClawCompanion-2026.11.3-baseline.exe' + Invoke-WebRequest -Uri $assets[0].browser_download_url -OutFile $path -TimeoutSec 180 + if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -ne $assets[0].digest.Substring(7)) { + throw 'Baseline installer digest mismatch.' + } + $signature = Get-AuthenticodeSignature -LiteralPath $path + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'CN=OpenClaw Foundation(?:,|$)') { + throw 'Baseline installer signature is not the expected valid publisher.' + } + "INNO_BEFORE_INSTALLER=$path" >> $env:GITHUB_ENV + + - name: Capture real uninstall choices and outcomes + shell: powershell -NoProfile -STA -ExecutionPolicy Bypass -File {0} + run: | + $parameters = @{ + BeforeInstaller = $env:INNO_BEFORE_INSTALLER + AfterInstaller = (Resolve-Path 'Output/OpenClawCompanion-Dev-Setup-x64.exe').Path + BeforeRevision = '66b9b5a559a0651da3aa6ce7ae3d183fbd87cb1c' + AfterRevision = (git rev-parse HEAD) + OutputDirectory = (Join-Path $env:GITHUB_WORKSPACE 'TestResults/InnoUninstallMedia') + BeforeReleaseUrl = 'https://github.com/openclaw/openclaw-windows-node/releases/tag/v2026.11.3' + ConfirmDisposableHost = $true + } + ./scripts/capture-inno-model-uninstall.ps1 @parameters + + - name: Retain sanitized media and provenance + if: always() + uses: actions/upload-artifact@v7 + with: + name: inno-uninstall-media + path: TestResults/InnoUninstallMedia/ + if-no-files-found: error + retention-days: 14 diff --git a/scripts/capture-inno-model-uninstall.ps1 b/scripts/capture-inno-model-uninstall.ps1 new file mode 100644 index 0000000000..0c4a5b4f45 --- /dev/null +++ b/scripts/capture-inno-model-uninstall.ps1 @@ -0,0 +1,858 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Capture real installed Inno uninstall UI on an exclusive disposable CI desktop. +.DESCRIPTION + Uses full production/Dev installers, official hash-pinned Kokoro v1.1 assets, + process-bound UIA, cropped window PNGs and live ffmpeg desktop recordings. + Before: ordinary uninstall, keep Gateway/models. After: cancel, keep, reinstall + the same owned payload, select/remove models. Never silently uninstall, launch + Companion, remove Gateway/WSL, or sweep profiles. CI host disposal owns cleanup. + Run with Windows PowerShell 5.1 -STA for the in-box UIAutomation/Drawing assemblies. + ConfirmDisposableHost asserts an authorized exclusive unlocked Windows desktop + and disposable account with synthetic data only. Not for developer workstations. + Source/build attribution is supplied by the caller; actual installer/payload + hashes are recorded. This is unsigned Dev behavior, not signed acceptance. +.EXAMPLE + .\scripts\capture-inno-model-uninstall.ps1 -BeforeInstaller C:\inputs\released.exe ` + -AfterInstaller C:\inputs\candidate-Dev.exe -BeforeSourceRevision <40-hex-sha> ` + -AfterSourceRevision <40-hex-sha> -BeforeBuildIdentity 'release v2026.11.3' ` + -AfterBuildIdentity 'CI run 123, full Dev publish' -OutputDirectory C:\proof\uninstall ` + -ConfirmDisposableHost +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$BeforeInstaller, + [Parameter(Mandatory)][string]$AfterInstaller, + [Parameter(Mandatory)][Alias('BeforeRevision')][ValidatePattern('^[0-9a-fA-F]{40}$')][string]$BeforeSourceRevision, + [Parameter(Mandatory)][Alias('AfterRevision')][ValidatePattern('^[0-9a-fA-F]{40}$')][string]$AfterSourceRevision, + [ValidateNotNullOrEmpty()][string]$BeforeBuildIdentity = 'Official production release (caller-verified asset)', + [ValidateNotNullOrEmpty()][string]$AfterBuildIdentity = 'Full locally built unsigned Dev installer', + [Parameter(Mandatory)][string]$OutputDirectory, + [string]$BeforeReleaseUrl, + [switch]$ConfirmDisposableHost +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +if (-not $ConfirmDisposableHost) { throw 'Pass -ConfirmDisposableHost only for an authorized exclusive disposable CI desktop.' } +if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_ENVIRONMENT -ne 'github-hosted') { + throw 'This capture is restricted to a fresh GitHub-hosted disposable runner.' +} +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Native Windows is required. No proof was captured.' } +if ($PSVersionTable.PSEdition -ne 'Desktop' -or [Threading.Thread]::CurrentThread.GetApartmentState() -ne 'STA') { + throw 'Use powershell.exe -NoProfile -STA -ExecutionPolicy Bypass -File for the in-box native UI assemblies.' +} +if (-not [Environment]::UserInteractive -or (Get-Process -Id $PID).SessionId -eq 0) { + throw 'Refusing a noninteractive/session-0 desktop.' +} + +# Named configurable hang guards, never readiness delays or blind retries. +function Get-Limit([string]$Name, [int]$Default, [int]$Maximum) { + $value = [Environment]::GetEnvironmentVariable("OPENCLAW_INNO_CAPTURE_$Name") + if ([string]::IsNullOrWhiteSpace($value)) { return $Default } + $number = 0 + if (-not [int]::TryParse($value, [ref]$number) -or $number -lt 1 -or $number -gt $Maximum) { + throw "Invalid capture limit $Name (1..$Maximum)." + } + return $number +} +$script:StepSeconds = Get-Limit STEP_SECONDS 300 900 +$script:InstallSeconds = Get-Limit INSTALL_SECONDS 600 1800 +$script:DownloadSeconds = Get-Limit DOWNLOAD_SECONDS 900 1800 +$script:VideoSeconds = Get-Limit VIDEO_SECONDS 480 900 +$script:StopSeconds = Get-Limit STOP_SECONDS 30 120 +$script:PollMilliseconds = Get-Limit POLL_MILLISECONDS 200 2000 +$script:CimSeconds = Get-Limit CIM_SECONDS 15 60 +$script:Runs = [Collections.Generic.List[object]]::new() +$script:Actions = [Collections.Generic.List[object]]::new() +$script:Recording = $null +$script:Proof = [ordered]@{ + schemaVersion = 1; status = 'running'; startedUtc = [DateTime]::UtcNow.ToString('o') + scope = 'Real installed Inno UI on exclusive disposable Windows CI desktop' + limits = 'Unsigned Dev behavior, not signed acceptance; no real Gateway installed or removed.' + authority = 'ConfirmDisposableHost on github-hosted runner'; prHead = $env:PROOF_PR_HEAD; scenarios = [Collections.Generic.List[object]]::new() + tools = [ordered]@{}; artifacts = @(); cleanup = @() +} +function Assert-OrdinaryPath([string]$Path) { + if ($Path -notmatch '^[A-Za-z]:\\') { + throw "Only fully qualified local drive paths are accepted: $Path" + } + $current = [IO.Path]::GetFullPath($Path) + while ($current) { + if (Test-Path -LiteralPath $current) { + $item = Get-Item -LiteralPath $current -Force + if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Redirected path refused: $current" } + } + $current = [IO.Path]::GetDirectoryName($current) + } +} +function Get-Digest([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } +function Write-Json([string]$Name, $Value) { + $Value | ConvertTo-Json -Depth 14 | Set-Content -LiteralPath (Join-Path $OutputDirectory $Name) -Encoding utf8 +} +function Save-Proof { Write-Json 'proof.json' $script:Proof } +function Wait-Condition([string]$Description, [scriptblock]$Condition, [int]$Seconds = $script:StepSeconds) { + $clock = [Diagnostics.Stopwatch]::StartNew() + do { + foreach ($action in $script:Actions) { if ($action.Error) { throw "Owned UI action failed: $($action.Error)" } } + $value = & $Condition + if ($value) { return $value } + if ($clock.Elapsed.TotalSeconds -ge $Seconds) { throw "Timed out waiting for $Description; outcome unconfirmed." } + Start-Sleep -Milliseconds $script:PollMilliseconds + } while ($true) +} + +# Process objects retain lifetimes after launcher exit. Inno's _unins.tmp must be +# an observed descendant, created during its parent's lifetime, with identical +# bytes. Missing intermediate ancestry fails closed rather than guessing by name. +function Start-OwnedProcess([string]$Path, [string[]]$Arguments, [string]$Purpose, [switch]$Uninstaller) { + $info = [Diagnostics.ProcessStartInfo]::new($Path) + $info.UseShellExecute = $false + $info.CreateNoWindow = -not $Uninstaller + $info.RedirectStandardOutput = -not $Uninstaller + $info.RedirectStandardError = -not $Uninstaller + $info.RedirectStandardInput = -not $Uninstaller + # Same Windows quoting policy as Uninstall-DownloadedModels.ps1: reject embedded + # quotes, surround every argument, and double trailing backslashes before closing. + $quoted = foreach ($argument in $Arguments) { + if ($argument.Contains('"')) { throw 'Embedded quote in process argument refused.' } + '"' + ($argument -replace '(\\+)$', '$1$1') + '"' + } + $info.Arguments = $quoted -join ' ' + $process = [Diagnostics.Process]::new() + $process.StartInfo = $info + if (-not $process.Start()) { throw "Could not start $Purpose." } + $node = [pscustomobject]@{ + Process = $process; Id = $process.Id; StartUtc = $process.StartTime.ToUniversalTime() + Path = $Path; UiAllowed = [bool]$Uninstaller; ParentId = $PID + } + $run = [pscustomobject]@{ + Purpose = $Purpose; Root = $node; Nodes = @{}; Uninstaller = [bool]$Uninstaller + ImageHash = $(if ($Uninstaller) { Get-Digest $Path } else { $null }) + Stdout = $null; Stderr = $null + } + $run.Nodes[$node.Id] = $node + if (-not $Uninstaller) { + $run.Stdout = $process.StandardOutput.ReadToEndAsync() + $run.Stderr = $process.StandardError.ReadToEndAsync() + } + $script:Runs.Add($run) + return $run +} +function Update-OwnedTree($Run) { + $snapshot = @(Get-CimInstance Win32_Process -OperationTimeoutSec $script:CimSeconds) + do { + $added = $false + foreach ($item in $snapshot) { + $id = [int]$item.ProcessId + if ($Run.Nodes.ContainsKey($id) -or -not $Run.Nodes.ContainsKey([int]$item.ParentProcessId)) { continue } + $parent = $Run.Nodes[[int]$item.ParentProcessId] + $created = $item.CreationDate.ToUniversalTime() + if ($created -lt $parent.StartUtc) { continue } + if ($parent.Process.HasExited -and $created -gt $parent.Process.ExitTime.ToUniversalTime()) { continue } + $process = Get-Process -Id $id -ErrorAction SilentlyContinue + if (-not $process -or $process.HasExited) { continue } + # CIM and Process report the same kernel creation timestamp at different precision. + if ([Math]::Abs(($process.StartTime.ToUniversalTime() - $created).TotalMilliseconds) -gt 1) { continue } + if (-not $item.ExecutablePath) { throw "Cannot verify descendant path for PID $id." } + $path = [string]$item.ExecutablePath + $uiAllowed = $false + if ($Run.Uninstaller -and [IO.Path]::GetFileName($path) -ieq '_unins.tmp') { + Assert-OrdinaryPath $path + if (-not $path.StartsWith([IO.Path]::GetTempPath(), [StringComparison]::OrdinalIgnoreCase) -or + (Get-Digest $path) -ne $Run.ImageHash) { throw 'Inno self-copy does not match the owned uninstaller.' } + $uiAllowed = $true + } + $Run.Nodes[$id] = [pscustomobject]@{ + Process = $process; Id = $id; StartUtc = $process.StartTime.ToUniversalTime() + Path = $path; UiAllowed = $uiAllowed; ParentId = [int]$item.ParentProcessId + } + $added = $true + } + } while ($added) +} +function Wait-ProcessExit($Run, [int]$Seconds) { + $null = Wait-Condition "$($Run.Purpose) process-tree exit" { + Update-OwnedTree $Run + return @($Run.Nodes.Values | Where-Object { -not $_.Process.HasExited }).Count -eq 0 + } $Seconds + return $Run.Root.Process.ExitCode +} +function Read-ProcessOutput($Task) { + $null = Wait-Condition 'owned process output pipe closure' { $Task.IsCompleted } $script:StopSeconds + return $Task.GetAwaiter().GetResult() +} +function Invoke-Native([string]$Path, [string[]]$Arguments, [string]$Purpose, [int]$Seconds = $script:StepSeconds) { + $run = Start-OwnedProcess $Path $Arguments $Purpose + $code = Wait-ProcessExit $run $Seconds + $stdout = Read-ProcessOutput $run.Stdout + $stderr = Read-ProcessOutput $run.Stderr + if ($code -ne 0) { throw "$Purpose exited $code. $stderr" } + return $stdout +} +function Get-RelatedRegistrations { + foreach ($hive in @('HKCU:', 'HKLM:')) { + foreach ($view in @('Software', 'Software\WOW6432Node')) { + $root = "$hive\$view\Microsoft\Windows\CurrentVersion\Uninstall" + if (-not (Test-Path -LiteralPath $root)) { continue } + foreach ($key in Get-ChildItem -LiteralPath $root) { + $entry = Get-ItemProperty -LiteralPath $key.PSPath + if ($key.PSChildName -match 'M0LTB0T' -or + ($entry.PSObject.Properties['DisplayName'] -and $entry.DisplayName -match 'OpenClaw|Moltbot')) { + [pscustomobject]@{ Key = $key.PSPath; Values = $entry } + } + } + } + } +} +function Get-GatewayInventory { + # Read the distro registry without starting WSL or provisioning it. + $distros = @() + $lxss = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss' + if (Test-Path -LiteralPath $lxss) { + $distros = @(Get-ChildItem -LiteralPath $lxss | ForEach-Object { + $p = Get-ItemProperty -LiteralPath $_.PSPath + [pscustomobject]@{ Id = $_.PSChildName; Name = $p.DistributionName; BasePath = $p.BasePath } + } | Sort-Object Id) + } + # CIM avoids loading the Appx module in pwsh. Failure is not proof of absence. + $packages = @(Get-CimInstance -Namespace root/cimv2 -ClassName Win32_InstalledStoreProgram ` + -OperationTimeoutSec $script:CimSeconds | Where-Object { $_.Name -match 'OpenClaw|Moltbot' } | + Select-Object Name, PackageFullName | Sort-Object Name) + $packageKeys = @() + $packageRoot = 'HKCU:\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages' + if (Test-Path -LiteralPath $packageRoot) { + $packageKeys = @(Get-ChildItem -LiteralPath $packageRoot | Where-Object { + $_.PSChildName -match 'OpenClaw|Moltbot' + } | Select-Object -ExpandProperty PSChildName | Sort-Object) + } + return [pscustomobject]@{ Distros = $distros; RelatedPackages = $packages; RelatedPackageKeys = $packageKeys } +} +function Assert-FreshHost { + if ($env:APPDATA -ine [Environment]::GetFolderPath('ApplicationData') -or + $env:LOCALAPPDATA -ine [Environment]::GetFolderPath('LocalApplicationData') -or + $env:USERPROFILE -ine [Environment]::GetFolderPath('UserProfile')) { + throw 'Profile environment differs from Windows known folders used by Inno.' + } + foreach ($name in @('OPENCLAW_TRAY_DATA_DIR', 'OPENCLAW_TRAY_APPDATA_DIR', 'OPENCLAW_TRAY_LOCALAPPDATA_DIR', + 'OPENCLAW_TRAY_LOCAL_DATA_DIR', 'OPENCLAW_STATE_DIR', 'OPENCLAW_WSL_DISTRO_NAME', 'OPENCLAW_NATIVE_GATEWAY_DEV_PATCH')) { + if ([Environment]::GetEnvironmentVariable($name)) { throw "Path/runtime override refused: $name" } + } + $protected = @() + foreach ($root in @($env:APPDATA, $env:LOCALAPPDATA)) { + foreach ($name in @('OpenClawTray', 'OpenClawTray-Dev', 'OpenClawGatewayMSIX')) { $protected += Join-Path $root $name } + } + $protected += Join-Path $env:USERPROFILE '.openclaw' + $protected += Join-Path $env:USERPROFILE '.openclaw-dev' + $packageData = Join-Path $env:LOCALAPPDATA 'Packages' + if (Test-Path -LiteralPath $packageData) { + $protected += @(Get-ChildItem -LiteralPath $packageData -Directory -Force | Where-Object { + $_.Name -match 'OpenClaw|Moltbot' + } | Select-Object -ExpandProperty FullName) + } + foreach ($path in $protected) { + Assert-OrdinaryPath $path + if (Test-Path -LiteralPath $path) { throw "Existing installation/profile refused, including empty directories: $path" } + if ($OutputDirectory.StartsWith($path.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -or $OutputDirectory -ieq $path) { + throw 'Output directory overlaps a protected profile.' + } + } + if (@(Get-RelatedRegistrations).Count) { throw 'Existing OpenClaw uninstall registration refused.' } + foreach ($name in @('openclaw', 'openclaw-dev')) { + if (Test-Path -LiteralPath "HKCU:\Software\Classes\$name") { throw 'Existing OpenClaw protocol registration refused.' } + } + $runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' + if (Test-Path -LiteralPath $runKey) { + $autoruns = Get-ItemProperty -LiteralPath $runKey + if (@($autoruns.PSObject.Properties | Where-Object { $_.Name -match 'OpenClaw|Moltbot' }).Count) { + throw 'Existing OpenClaw autostart registration refused.' + } + } + if (@(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match 'OpenClaw|Moltbot' }).Count) { + throw 'Existing OpenClaw scheduled task refused.' + } + $processes = @(Get-CimInstance Win32_Process -OperationTimeoutSec $script:CimSeconds | Where-Object { + $_.Name -match '^(OpenClaw|Moltbot|llama-server)' -or + ($_.Name -match '^(node|wsl|wslhost)\.exe$' -and $_.CommandLine -match 'openclaw|moltbot') + }) + if ($processes.Count) { throw 'Existing related processes refused. This helper will not stop them.' } + $inventory = Get-GatewayInventory + if ($inventory.RelatedPackages.Count -or $inventory.RelatedPackageKeys.Count -or + @($inventory.Distros | Where-Object { $_.Name -match 'OpenClaw|Moltbot' }).Count) { + throw 'Existing related Store/native package or WSL distro refused.' + } + return $inventory +} + +# Real pixels and asynchronous UIA patterns, not reconstructed dialogs. Dispatch +# patterns only after binding their containing HWND to the installed uninstaller. +function Initialize-Desktop { + Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes, System.Drawing, System.Windows.Forms + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +using System.Threading; +public sealed class InnoCaptureAction { + public volatile bool Done; + public Exception Error; + public static InnoCaptureAction Start(object pattern, string method) { + var result = new InnoCaptureAction(); + var thread = new Thread(() => { + try { pattern.GetType().GetMethod(method).Invoke(pattern, null); } + catch (Exception ex) { result.Error = ex; } + finally { result.Done = true; } + }); + thread.IsBackground = true; thread.SetApartmentState(ApartmentState.MTA); thread.Start(); + return result; + } +} +public static class InnoCaptureWindow { + [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out Rect r); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); +} +'@ + $null = [InnoCaptureWindow]::SetProcessDPIAware() +} +function Test-OwnedWindow($Run, $Window) { + $id = $Window.Current.ProcessId + if (-not $Run.Nodes.ContainsKey($id)) { return $false } + $node = $Run.Nodes[$id] + if (-not $node.UiAllowed -or $node.Process.HasExited) { return $false } + $live = Get-Process -Id $id -ErrorAction SilentlyContinue + return $live -and $live.StartTime.ToUniversalTime() -eq $node.StartUtc -and $live.Path -ieq $node.Path +} +function Get-OwnedWindows($Run) { + Update-OwnedTree $Run + $children = [Windows.Automation.AutomationElement]::RootElement.FindAll( + [Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition) + foreach ($window in $children) { + try { + if (-not $window.Current.IsOffscreen -and (Test-OwnedWindow $Run $window)) { $window } + } catch [Windows.Automation.ElementNotAvailableException] { continue } + } +} +function Get-WindowText($Window) { + $text = [Collections.Generic.List[string]]::new() + $text.Add($Window.Current.Name) + foreach ($child in $Window.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition)) { + $text.Add($child.Current.Name) + $pattern = $null + if ($child.TryGetCurrentPattern([Windows.Automation.ValuePattern]::Pattern, [ref]$pattern)) { $text.Add($pattern.Current.Value) } + } + return $text -join "`n" +} +function Find-Control($Window, [string]$Name, $Type) { + $matches = @($Window.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition) | + Where-Object { $_.Current.ControlType -eq $Type -and ($_.Current.Name -replace '&', '') -eq $Name -and -not $_.Current.IsOffscreen }) + if ($matches.Count -gt 1) { throw "Ambiguous owned control: $Name" } + if ($matches.Count -eq 1) { return $matches[0] } + return $null +} +function Invoke-Control($Run, $Window, [string]$Name, [switch]$Toggle) { + if (-not (Test-OwnedWindow $Run $Window)) { throw 'UI ownership changed before invocation.' } + $type = if ($Toggle) { [Windows.Automation.ControlType]::CheckBox } else { [Windows.Automation.ControlType]::Button } + $control = Find-Control $Window $Name $type + if (-not $control -or -not $control.Current.IsEnabled) { throw "Owned control is not ready: $Name" } + $patternType = if ($Toggle) { [Windows.Automation.TogglePattern]::Pattern } else { [Windows.Automation.InvokePattern]::Pattern } + $pattern = $control.GetCurrentPattern($patternType) + $action = [InnoCaptureAction]::Start($pattern, $(if ($Toggle) { 'Toggle' } else { 'Invoke' })) + $script:Actions.Add($action) +} +function Wait-Window($Run, [scriptblock]$Predicate, [string]$Description) { + return Wait-Condition $Description { + foreach ($window in @(Get-OwnedWindows $Run)) { + try { if (& $Predicate $window) { return $window } } + catch [Windows.Automation.ElementNotAvailableException] { continue } + } + return $null + } +} +function Save-Window($Run, $Window, [string]$Name) { + if (-not (Test-OwnedWindow $Run $Window)) { throw 'Cannot capture a foreign window.' } + $handle = [IntPtr]$Window.Current.NativeWindowHandle + $null = [InnoCaptureWindow]::SetForegroundWindow($handle) + $state = @{ Last = ''; Count = 0; Rect = $null } + $null = Wait-Condition 'stable owned foreground window bounds' { + if ([InnoCaptureWindow]::GetForegroundWindow() -ne $handle -or -not (Test-OwnedWindow $Run $Window)) { return $false } + $rect = [InnoCaptureWindow+Rect]::new() + if (-not [InnoCaptureWindow]::GetWindowRect($handle, [ref]$rect)) { return $false } + $key = "$($rect.Left),$($rect.Top),$($rect.Right),$($rect.Bottom)" + if ($state.Last -eq $key) { $state.Count++ } else { $state.Count = 0; $state.Last = $key } + $state.Rect = $rect + return $state.Count -ge 2 -and $rect.Right -gt $rect.Left -and $rect.Bottom -gt $rect.Top + } + $r = $state.Rect + $bounds = [Windows.Forms.SystemInformation]::VirtualScreen + if ($r.Left -lt $bounds.Left -or $r.Top -lt $bounds.Top -or $r.Right -gt $bounds.Right -or $r.Bottom -gt $bounds.Bottom) { + throw 'Owned window is clipped by the desktop. Increase the CI desktop resolution.' + } + $bitmap = [Drawing.Bitmap]::new(($r.Right - $r.Left), ($r.Bottom - $r.Top)) + $graphics = [Drawing.Graphics]::FromImage($bitmap) + try { + $graphics.CopyFromScreen($r.Left, $r.Top, 0, 0, $bitmap.Size) + if ([InnoCaptureWindow]::GetForegroundWindow() -ne $handle) { throw 'Foreground changed during capture.' } + $bitmap.Save((Join-Path $OutputDirectory "$Name.png"), [Drawing.Imaging.ImageFormat]::Png) + } finally { $graphics.Dispose(); $bitmap.Dispose() } + Write-Json "$Name.window.json" @{ + processId = $Window.Current.ProcessId; hwnd = $handle.ToInt64(); text = Get-WindowText $Window + bounds = @{ left = $r.Left; top = $r.Top; width = $r.Right - $r.Left; height = $r.Bottom - $r.Top } + } +} +function Get-VideoFrames { + if (-not $script:Recording -or -not (Test-Path -LiteralPath $script:Recording.Progress)) { return 0 } + $frames = @(Get-Content -LiteralPath $script:Recording.Progress | Where-Object { $_ -match '^frame=\d+$' }) + if (-not $frames.Count) { return 0 } + return [int]($frames[-1] -replace '^frame=', '') +} +function Start-Recording([string]$Name) { + if ($script:Recording) { throw 'A capture is already active.' } + $path = Join-Path $OutputDirectory "$Name.mp4" + $progress = Join-Path $script:WorkDirectory "$Name.ffmpeg-progress.txt" + $run = Start-OwnedProcess $script:Ffmpeg @( + '-hide_banner', '-loglevel', 'warning', '-f', 'gdigrab', '-framerate', '12', '-draw_mouse', '0', + '-i', 'desktop', '-t', "$script:VideoSeconds", '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2', '-c:v', 'libx264', + '-preset', 'veryfast', '-crf', '28', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-progress', $progress, $path + ) "record-$Name" + $script:Recording = [pscustomobject]@{ Run = $run; Path = $path; Progress = $progress; Name = $Name } + $null = Wait-Condition 'first live desktop video frames' { + if ($run.Root.Process.HasExited) { throw "ffmpeg exited early: $(Read-ProcessOutput $run.Stderr)" } + return (Get-VideoFrames) -gt 0 + } +} +function Hold-RecordedState($Run, $Window) { + # Deliberate presentation dwell measured in live encoded frames, not a sleep + # that substitutes for readiness. Verify ownership/foreground throughout. + $startFrame = Get-VideoFrames + $handle = [IntPtr]$Window.Current.NativeWindowHandle + $null = [InnoCaptureWindow]::SetForegroundWindow($handle) + $null = Wait-Condition '24 live frames of the verified UI state' { + if ($script:Recording.Run.Root.Process.HasExited) { throw 'Video ended before the scenario completed.' } + if (-not (Test-OwnedWindow $Run $Window) -or [InnoCaptureWindow]::GetForegroundWindow() -ne $handle) { + throw 'Owned UI lost foreground during its recording segment.' + } + return (Get-VideoFrames) -ge ($startFrame + 24) + } +} +function Stop-Recording { + if (-not $script:Recording) { return } + $recording = $script:Recording + $script:Recording = $null + $run = $recording.Run + $endedEarly = $run.Root.Process.HasExited + if (-not $endedEarly) { $run.Root.Process.StandardInput.WriteLine('q'); $run.Root.Process.StandardInput.Flush() } + $code = Wait-ProcessExit $run $script:StopSeconds + Read-ProcessOutput $run.Stderr | Set-Content -LiteralPath (Join-Path $script:WorkDirectory "$($recording.Name).ffmpeg.log") + if ($endedEarly -or $code -ne 0) { throw 'Recording incomplete or ended before the scenario.' } + $probe = Invoke-Native $script:Ffprobe @('-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=codec_name,width,height,nb_read_frames:format=duration,size', '-of', 'json', $recording.Path) 'validate-video' + $parsed = $probe | ConvertFrom-Json + if ([double]$parsed.format.duration -le 0 -or [int]$parsed.streams[0].nb_read_frames -lt 24) { throw 'MP4 has no meaningful decoded live frames.' } + $probe | Set-Content -LiteralPath (Join-Path $OutputDirectory "$($recording.Name).video.json") + if ((Get-Item -LiteralPath $recording.Path).Length -gt 10000000) { + throw 'Recording exceeds 10 MB. Preserve native-resolution text readability when preparing delivery.' + } + if ($recording.Name -eq 'after-remove') { + # Six genuine decoded frames from the live video, not frames used to make + # the video. The sheet is an inspection aid, not a substitute recording. + $duration = [double]$parsed.format.duration + $frameFiles = @() + $samples = @() + for ($index = 0; $index -lt 6; $index++) { + $timestamp = (($index + 0.5) * $duration / 6).ToString('F3', [Globalization.CultureInfo]::InvariantCulture) + $frame = Join-Path $OutputDirectory ("after-remove-frame-{0:D2}.png" -f ($index + 1)) + $null = Invoke-Native $script:Ffmpeg @('-hide_banner', '-loglevel', 'error', '-ss', $timestamp, + '-i', $recording.Path, '-frames:v', '1', '-update', '1', $frame) 'extract-live-video-frame' + $frameFiles += $frame + $samples += @{ file = [IO.Path]::GetFileName($frame); seconds = $timestamp } + } + $first = [Drawing.Image]::FromFile($frameFiles[0]) + $width = $first.Width; $height = $first.Height; $first.Dispose() + $sheet = [Drawing.Bitmap]::new(($width * 3), ($height * 2)) + $graphics = [Drawing.Graphics]::FromImage($sheet) + try { + for ($index = 0; $index -lt 6; $index++) { + $image = [Drawing.Image]::FromFile($frameFiles[$index]) + try { $graphics.DrawImage($image, (($index % 3) * $width), ([int][Math]::Floor($index / 3) * $height), $width, $height) } + finally { $image.Dispose() } + } + $sheet.Save((Join-Path $OutputDirectory 'after-remove-contact-sheet.png'), [Drawing.Imaging.ImageFormat]::Png) + } finally { $graphics.Dispose(); $sheet.Dispose() } + Write-Json 'after-remove-frame-samples.json' $samples + } +} + +# Independent scenario pins must match the production catalog. No synthetic model, +# extracted Pascal function, helper replacement or UI-only stub is admissible. +$script:Assets = @( + @{ FileName = 'kokoro-v1.1-zh.onnx'; Size = 343605188L; Sha256 = 'eefec708cbc7aba8e8129b5c2f7cb92e1fe7d281af1e1dd451592d9ff0714a0d' }, + @{ FileName = 'voices-v1.1-zh.bin'; Size = 53792177L; Sha256 = 'e678019845e6cfe3b7c34531779396b28f509451b91e6535d5dc09bbf11a4be5' } +) +$script:ExpectedBytes = 397397365L +function Get-OfficialAssets { + $catalogPath = Join-Path $PSScriptRoot '..\src\OpenClaw.Shared\Audio\KokoroDownloadCatalog.cs' + $catalog = Get-Content -LiteralPath $catalogPath -Raw + $baseUrl = 'https://github.com/larroy/kokoro.cpp/releases/download/voices_model_files/' + if (-not $catalog.Contains($baseUrl)) { throw 'Source catalog no longer has the pinned official release URL.' } + $cache = Join-Path $script:WorkDirectory 'input-assets' + $null = New-Item -ItemType Directory -Path $cache + foreach ($asset in $script:Assets) { + if (-not $catalog.Contains($asset.FileName) -or -not $catalog.Contains($asset.Sha256) -or -not $catalog.Contains([string]$asset.Size)) { + throw 'Pinned media scenario does not match the production download catalog.' + } + $asset.Url = $baseUrl + $asset.FileName + $asset.Path = Join-Path $cache $asset.FileName + Invoke-WebRequest -UseBasicParsing -Uri $asset.Url -OutFile $asset.Path -TimeoutSec $script:DownloadSeconds + if ((Get-Item -LiteralPath $asset.Path).Length -ne $asset.Size -or (Get-Digest $asset.Path) -ne $asset.Sha256) { + throw "Official asset size/hash mismatch: $($asset.FileName)" + } + } + $script:Proof.assets = @($script:Assets | ForEach-Object { @{ file = $_.FileName; url = $_.Url; sha256 = $_.Sha256; bytes = $_.Size } }) +} +function Get-Inventory([string]$Root) { + if (-not (Test-Path -LiteralPath $Root)) { return @() } + Assert-OrdinaryPath $Root + $prefix = [IO.Path]::GetFullPath($Root).TrimEnd('\') + '\' + return @(Get-ChildItem -LiteralPath $Root -File -Recurse -Force | Sort-Object FullName | ForEach-Object { + Assert-OrdinaryPath $_.FullName + [pscustomobject]@{ path = $_.FullName.Substring($prefix.Length); bytes = $_.Length; sha256 = Get-Digest $_.FullName } + }) +} +function Seed-Profile($Install) { + Assert-OrdinaryPath $Install.Profile + if (Test-Path -LiteralPath $Install.Profile) { throw 'Profile unexpectedly exists before seed; refusing adoption.' } + $models = Join-Path $Install.Profile 'models\kokoro\v1.1-en-zh' + $null = New-Item -ItemType Directory -Path $models + foreach ($asset in $script:Assets) { Copy-Item -LiteralPath $asset.Path -Destination (Join-Path $models $asset.FileName) } + # Unrelated sibling and settings have exact preservation assertions. No credentials. + Set-Content -LiteralPath (Join-Path $models 'unrelated-sentinel.txt') -Value 'Synthetic PR2328 sentinel. Keep this file.' -Encoding utf8 + Set-Content -LiteralPath (Join-Path $Install.Profile 'settings.json') -Value '{"EnableNodeMode":false,"EnableMcpServer":false,"AutoStart":false}' -Encoding utf8 + $Install.Seeded = @(Get-Inventory $Install.Profile) + Write-Json "$($Install.Label)-seeded-files.json" $Install.Seeded +} +function Assert-Profile($Install, [switch]$Removed, [string]$Scenario) { + $inventory = @(Get-Inventory $Install.Profile) + Write-Json "$Scenario-files.json" $inventory + foreach ($expected in $Install.Seeded) { + $model = @($script:Assets | Where-Object { $expected.path -eq "models\kokoro\v1.1-en-zh\$($_.FileName)" }).Count -gt 0 + $actual = @($inventory | Where-Object { $_.path -eq $expected.path }) + if ($Removed -and $model) { + if ($actual.Count) { throw "Selected model retained: $($expected.path)" } + } elseif ($actual.Count -ne 1 -or $actual[0].sha256 -ne $expected.sha256 -or $actual[0].bytes -ne $expected.bytes) { + throw "Retained file changed or disappeared: $($expected.path)" + } + } +} +function Install-FullPayload([string]$Installer, [string]$Label, [switch]$Dev, $Previous) { + $name = if ($Dev) { 'OpenClawTray-Dev' } else { 'OpenClawTray' } + $root = Join-Path $env:LOCALAPPDATA $name + $profile = Join-Path $env:APPDATA $name + Assert-OrdinaryPath $root + if (Test-Path -LiteralPath $root) { + # Only this run's proven keep-uninstall permits reinstallation. No removal + # of leftovers to make an installation appear clean. + if (-not $Previous -or $Previous.Root -ine $root -or -not $Previous.Uninstalled) { throw 'Install directory already exists.' } + if (@(Get-Inventory $root).Count) { throw 'Unexpected installed files remain before candidate reinstall.' } + } + if (@(Get-RelatedRegistrations | Where-Object { + $_.Values.PSObject.Properties['InstallLocation'] -and $_.Values.InstallLocation.TrimEnd('\') -ieq $root + }).Count) { throw 'Target uninstall registration already exists.' } + $log = Join-Path $script:WorkDirectory "$Label-install.log" + $run = Start-OwnedProcess $Installer @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-', '/TASKS=', "/LOG=$log") "install-$Label" + $code = Wait-ProcessExit $run $script:InstallSeconds + if ($code -ne 0) { throw "Installer exited $code. See $log. No retry or adoption attempted." } + $expectedIdentity = if ($Dev) { 'dev' } else { 'release' } + foreach ($relative in @('app-identity.txt', 'OpenClaw.Tray.WinUI.exe', 'OpenClaw.Tray.WinUI.dll', + 'OpenClaw.Tray.WinUI.deps.json', 'OpenClaw.Tray.WinUI.runtimeconfig.json', 'Microsoft.UI.Xaml.dll')) { + $path = Join-Path $root $relative + Assert-OrdinaryPath $path + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Full production-shaped payload missing: $relative" } + } + if ((Get-Content -LiteralPath (Join-Path $root 'app-identity.txt') -Raw).Trim() -cne $expectedIdentity) { throw 'Installed identity mismatch.' } + $appAssembly = [Reflection.AssemblyName]::GetAssemblyName((Join-Path $root 'OpenClaw.Tray.WinUI.dll')) + if ($appAssembly.Name -ne 'OpenClaw.Tray.WinUI') { throw 'Invalid Companion assembly; stub payload refused.' } + $entries = @(Get-RelatedRegistrations | Where-Object { + $_.Values.PSObject.Properties['InstallLocation'] -and $_.Values.InstallLocation.TrimEnd('\') -ieq $root + }) + if ($entries.Count -ne 1) { throw 'Could not bind one exact installed Inno uninstall registration.' } + $command = [string]$entries[0].Values.UninstallString + # Accept exactly a path, optionally surrounded by one matched quote pair. No + # arguments, shell expansion, registry command execution or guessed fallback. + $uninstaller = $command + if ($command.StartsWith('"') -and $command.EndsWith('"')) { $uninstaller = $command.Substring(1, $command.Length - 2) } + if ($uninstaller.Contains('"') -or [IO.Path]::GetFileName($uninstaller) -notmatch '^unins[0-9]+\.exe$') { + throw "Uncertain uninstaller command refused: $command" + } + if ([IO.Path]::GetDirectoryName($uninstaller) -ine $root) { throw 'Uninstaller is outside the verified install root.' } + Assert-OrdinaryPath $uninstaller + if ($Dev) { + foreach ($relative in @('Uninstall-DownloadedModels.ps1', 'KokoroDownloadCatalog.cs', 'KokoroUninstallFiles.cs')) { + $source = if ($relative -like '*.cs') { Join-Path $PSScriptRoot "..\src\OpenClaw.Shared\Audio\$relative" } else { Join-Path $PSScriptRoot $relative } + if ((Get-Digest (Join-Path $root $relative)) -ne (Get-Digest $source)) { throw "Installed helper differs from current source: $relative" } + } + } + $payload = @(Get-Inventory $root) + Write-Json "$Label-installed-files.json" $payload + if (@(Get-CimInstance Win32_Process -OperationTimeoutSec $script:CimSeconds | Where-Object { + $_.ExecutablePath -ieq (Join-Path $root 'OpenClaw.Tray.WinUI.exe') + }).Count) { throw 'Silent installation unexpectedly launched Companion.' } + return [pscustomobject]@{ + Label = $Label; Root = $root; Profile = $profile; Uninstaller = $uninstaller + UninstallerHash = Get-Digest $uninstaller; RegistryKey = $entries[0].Key; Seeded = @() + Uninstalled = $false; Payload = $payload; AssemblyVersion = $appAssembly.Version.ToString() + ProductVersion = (Get-Item -LiteralPath (Join-Path $root 'OpenClaw.Tray.WinUI.exe')).VersionInfo.ProductVersion + } +} +function Start-Uninstall($Install, [string]$Scenario) { + if ((Get-Digest $Install.Uninstaller) -ne $Install.UninstallerHash) { throw 'Installed uninstaller changed.' } + # NEVER /SILENT or /VERYSILENT: real silent uninstall defaults Gateway cleanup + # to destructive removal. Every interactive Gateway choice below is No. + return Start-OwnedProcess $Install.Uninstaller @('/NORESTART', "/LOG=$(Join-Path $script:WorkDirectory "$Scenario-uninstall.log")") $Scenario -Uninstaller +} +function Wait-ModelDialog($Run) { + return Wait-Window $Run { param($w) + $w.Current.Name -eq 'Downloaded voice models' -and + $null -ne (Find-Control $w 'Check downloaded models' ([Windows.Automation.ControlType]::Button)) + } 'actual Downloaded voice models choice dialog' +} +function Assert-ReportedBytes([string]$Text, [string]$Label, [long]$Expected) { + $match = [regex]::Match($Text, [regex]::Escape($Label) + '\s*([0-9, .\u00a0\u202f]+) bytes') + if (-not $match.Success -or [long]($match.Groups[1].Value -replace '[^0-9]', '') -ne $Expected) { + throw "UI measured total differs from independently seeded bytes: $Label" + } +} +function Check-Models($Run, [string]$CaptureName) { + $window = Wait-ModelDialog $Run + $box = Find-Control $window 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) + if (-not $box -or $box.Current.IsEnabled -or + $box.GetCurrentPattern([Windows.Automation.TogglePattern]::Pattern).Current.ToggleState -ne [Windows.Automation.ToggleState]::Off) { + throw 'Removal must initially be disabled and unchecked.' + } + Invoke-Control $Run $window 'Check downloaded models' + $window = Wait-Window $Run { param($w) + if ($w.Current.Name -ne 'Downloaded voice models') { return $false } + $choice = Find-Control $w 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) + $continue = Find-Control $w 'Continue uninstall' ([Windows.Automation.ControlType]::Button) + if (-not $choice -or -not $choice.Current.IsEnabled -or -not $continue -or -not $continue.Current.IsEnabled) { return $false } + return (Get-WindowText $w) -match 'Verified downloads available for selection:' + } 'completed catalog scan and enabled unchecked selection' + $box = Find-Control $window 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) + if ($box.GetCurrentPattern([Windows.Automation.TogglePattern]::Pattern).Current.ToggleState -ne [Windows.Automation.ToggleState]::Off) { + throw 'Model scan selected destructive removal automatically.' + } + $text = Get-WindowText $window + Assert-ReportedBytes $text 'Verified downloads available for selection:' $script:ExpectedBytes + Assert-ReportedBytes $text 'Measured retained catalog files:' $script:ExpectedBytes + foreach ($asset in $script:Assets) { if (-not $text.Contains($asset.FileName)) { throw 'Measured file missing from model UI.' } } + Save-Window $Run $window $CaptureName + Hold-RecordedState $Run $window + return $window +} +function Complete-Uninstall($Install, $Run, [string]$Scenario, [switch]$Before, [switch]$RemoveModels) { + $state = @{ Confirmed = $false; Gateway = 'not encountered'; Summary = $false; Seen = @{} } + $null = Wait-Condition "$Scenario real uninstall completion" { + foreach ($window in @(Get-OwnedWindows $Run)) { + $text = Get-WindowText $window + $key = "$($window.Current.NativeWindowHandle):$text" + if ($state.Seen.ContainsKey($key)) { continue } + $button = [Windows.Automation.ControlType]::Button + if ($text -match 'Do you also want to remove the OpenClaw local WSL gateway\?') { + Save-Window $Run $window "$Scenario-gateway-keep" + Invoke-Control $Run $window 'No' + $state.Gateway = 'No'; $state.Seen[$key] = $true + } elseif ($text -match 'Are you sure you want to completely remove') { + if ($Before) { Save-Window $Run $window 'before' } + Invoke-Control $Run $window 'Yes' + $state.Confirmed = $true; $state.Seen[$key] = $true + } elseif ($window.Current.Name -eq 'Downloaded voice models' -and + $null -ne (Find-Control $window 'Close' $button)) { + if ($Before) { throw 'Baseline already contains the changed model dialog. Use a pre-change release.' } + if ($RemoveModels) { Assert-ReportedBytes $text 'Removed model file bytes:' $script:ExpectedBytes } + elseif ($text -notmatch 'No model removal was requested') { throw 'Keep summary does not confirm no model removal.' } + Save-Window $Run $window "$Scenario-summary" + Hold-RecordedState $Run $window + Invoke-Control $Run $window 'Close' + $state.Summary = $true; $state.Seen[$key] = $true + } elseif ($text -match '(?s)(could not (confirm whether your OpenClaw data was migrated|check whether OpenClaw from the Microsoft Store)|OpenClaw from the Microsoft Store is installed).*gateway.*(left in place|preserv)') { + Save-Window $Run $window "$Scenario-gateway-preserved-warning" + Invoke-Control $Run $window 'OK' + $state.Gateway = 'preserved by installer warning'; $state.Seen[$key] = $true + } elseif ($text -match 'successfully removed from your computer') { + Invoke-Control $Run $window 'OK'; $state.Seen[$key] = $true + } + # Unknown dialogs are never clicked; timeout retains the failed receipt. + } + return @($Run.Nodes.Values | Where-Object { -not $_.Process.HasExited }).Count -eq 0 + } + if (-not $state.Confirmed -or (-not $Before -and -not $state.Summary)) { throw 'Required confirmation/summary not observed.' } + if ($state.Gateway -eq 'not encountered') { throw 'Gateway preservation not confirmed by real UI.' } + if (Test-Path -LiteralPath $Install.RegistryKey) { throw 'Uninstall registration remains.' } + if (Test-Path -LiteralPath (Join-Path $Install.Root 'OpenClaw.Tray.WinUI.exe')) { throw 'Companion payload remains after uninstall.' } + foreach ($node in $Run.Nodes.Values | Where-Object UiAllowed) { + if ($node.Process.ExitCode -ne 0) { throw "Uninstaller PID $($node.Id) exited $($node.Process.ExitCode)." } + } + $Install.Uninstalled = $true + Assert-Profile $Install -Removed:$RemoveModels -Scenario $Scenario + $script:Proof.scenarios.Add(@{ + name = $Scenario; outcome = 'passed'; gateway = $state.Gateway; modelBytes = $script:ExpectedBytes + models = $(if ($RemoveModels) { 'removed' } else { 'retained, hashes unchanged' }) + uninstallerSha256 = $Install.UninstallerHash; install = $Install.Root; profile = $Install.Profile + processes = @($Run.Nodes.Values | ForEach-Object { @{ id = $_.Id; parent = $_.ParentId; path = $_.Path; startUtc = $_.StartUtc; uiAllowed = $_.UiAllowed } }) + }) + Save-Proof +} + +$outputReady = $false +try { + Assert-OrdinaryPath $OutputDirectory + $OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) + if (Test-Path -LiteralPath $OutputDirectory) { throw 'OutputDirectory must not exist. Preserve earlier evidence; choose a new directory.' } + foreach ($path in @($BeforeInstaller, $AfterInstaller)) { + Assert-OrdinaryPath $path + if (-not (Test-Path -LiteralPath $path -PathType Leaf) -or [IO.Path]::GetExtension($path) -ine '.exe') { throw 'Supply exact full Inno EXE paths.' } + } + $BeforeInstaller = (Resolve-Path -LiteralPath $BeforeInstaller).Path + $AfterInstaller = (Resolve-Path -LiteralPath $AfterInstaller).Path + if ($BeforeInstaller -ieq $AfterInstaller -or (Get-Digest $BeforeInstaller) -eq (Get-Digest $AfterInstaller)) { throw 'Before and after installers must differ.' } + $null = New-Item -ItemType Directory -Path $OutputDirectory + $outputReady = $true + # Task-owned non-public inputs/logs stay outside the media artifact directory. + # Only PNG/MP4 and sanitized JSON evidence are suitable for artifact delivery. + $script:WorkDirectory = Join-Path ([IO.Path]::GetTempPath()) ("openclaw-inno-media-" + [Guid]::NewGuid().ToString('N')) + Assert-OrdinaryPath $script:WorkDirectory + $null = New-Item -ItemType Directory -Path $script:WorkDirectory + $script:Proof.diagnosticsDirectory = $script:WorkDirectory + $script:Proof.before = @{ installer = $BeforeInstaller; sha256 = Get-Digest $BeforeInstaller; sourceRevision = $BeforeSourceRevision; buildIdentity = $BeforeBuildIdentity; releaseUrl = $BeforeReleaseUrl; provenance = 'caller-supplied release/source attribution; actual hash recorded' } + $script:Proof.after = @{ installer = $AfterInstaller; sha256 = Get-Digest $AfterInstaller; sourceRevision = $AfterSourceRevision; buildIdentity = $AfterBuildIdentity; identity = 'full locally built unsigned Dev installer' } + $git = (Get-Command git -CommandType Application -ErrorAction Stop).Source + $head = (Invoke-Native $git @('-C', (Join-Path $PSScriptRoot '..'), 'rev-parse', 'HEAD') 'source-revision').Trim() + if ($head -cne $AfterSourceRevision.ToLowerInvariant()) { throw 'AfterSourceRevision does not match capture checkout.' } + $script:Proof.captureScriptSha256 = Get-Digest $PSCommandPath + # Discover WinApp before native inspection. UIA is retained for Inno self-copy + # lifetime ownership; never invent version-specific WinApp selectors or flags. + $winapp = Get-Command winapp -CommandType Application -ErrorAction SilentlyContinue + if ($winapp) { + $script:Proof.tools.winapp = (Invoke-Native $winapp.Source @('--version') 'winapp-version').Trim() + $schema = Invoke-Native $winapp.Source @('--cli-schema') 'winapp-schema' + $schema | Set-Content -LiteralPath (Join-Path $OutputDirectory 'winapp-cli-schema.json') + $script:Proof.tools.ui = 'WinApp discovered; process-bound UIAutomation for Inno self-copy windows; ffmpeg live desktop.' + } else { + $script:Proof.tools.winapp = 'absent; no installation attempted' + $script:Proof.tools.ui = 'UIAutomationClient/InvokePattern scoped to Inno descendants; CopyFromScreen window crop.' + } + Save-Proof + $script:Ffmpeg = (Get-Command ffmpeg -CommandType Application -ErrorAction Stop).Source + $script:Ffprobe = (Get-Command ffprobe -CommandType Application -ErrorAction Stop).Source + $script:Proof.tools.ffmpeg = (Invoke-Native $script:Ffmpeg @('-version') 'ffmpeg-version').Split("`n")[0] + $gatewayBefore = Assert-FreshHost + Write-Json 'gateway-before.json' $gatewayBefore + Initialize-Desktop + Get-OfficialAssets + Save-Proof + + $baseline = Install-FullPayload $BeforeInstaller 'before' + Seed-Profile $baseline + $script:Proof.before.installedProductVersion = $baseline.ProductVersion + $script:Proof.before.installedAssemblyVersion = $baseline.AssemblyVersion + $run = Start-Uninstall $baseline 'before-keep' + Complete-Uninstall $baseline $run 'before-keep' -Before + + $candidate = Install-FullPayload $AfterInstaller 'after' -Dev + Seed-Profile $candidate + $script:Proof.after.installedProductVersion = $candidate.ProductVersion + $script:Proof.after.installedAssemblyVersion = $candidate.AssemblyVersion + + # Cancel after a completed read-only preview. Do not claim this tests the + # separate in-flight scan-cancellation race. + $run = Start-Uninstall $candidate 'after-cancel' + $window = Wait-ModelDialog $run + Start-Recording 'after-cancel' + $window = Check-Models $run 'after' + Invoke-Control $run $window 'Cancel' + $null = Wait-ProcessExit $run $script:StepSeconds + Stop-Recording + if (-not (Test-Path -LiteralPath $candidate.RegistryKey) -or + (Get-Digest $candidate.Uninstaller) -ne $candidate.UninstallerHash) { throw 'Cancel changed the installed application.' } + $cancelPayload = @(Get-Inventory $candidate.Root) + Write-Json 'after-cancel-installed-files.json' $cancelPayload + if (($candidate.Payload | ConvertTo-Json -Depth 4 -Compress) -cne ($cancelPayload | ConvertTo-Json -Depth 4 -Compress)) { + throw 'Cancel changed installed payload files.' + } + Assert-Profile $candidate -Scenario 'after-cancel' + $script:Proof.scenarios.Add(@{ name = 'after-cancel'; outcome = 'passed'; models = 'retained, hashes unchanged'; application = 'retained'; boundary = 'Cancel after completed preview; not mid-scan cancellation' }) + Save-Proof + + $run = Start-Uninstall $candidate 'after-keep' + $window = Wait-ModelDialog $run + Start-Recording 'after-keep' + $window = Check-Models $run 'after-keep-preview' + Invoke-Control $run $window 'Continue uninstall' + Complete-Uninstall $candidate $run 'after-keep' + Stop-Recording + + $reinstalled = Install-FullPayload $AfterInstaller 'after-reinstall' -Dev -Previous $candidate + $reinstalled.Seeded = $candidate.Seeded + Assert-Profile $reinstalled -Scenario 'after-reinstall' + $run = Start-Uninstall $reinstalled 'after-remove' + $window = Wait-ModelDialog $run + Start-Recording 'after-remove' + $window = Check-Models $run 'after-remove-preview' + Invoke-Control $run $window 'Remove the verified Kokoro downloads listed below' -Toggle + $window = Wait-Window $run { param($w) + $box = Find-Control $w 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) + return $box -and $box.GetCurrentPattern([Windows.Automation.TogglePattern]::Pattern).Current.ToggleState -eq [Windows.Automation.ToggleState]::On + } 'explicitly checked model removal' + Save-Window $run $window 'after-remove-selected' + Hold-RecordedState $run $window + Invoke-Control $run $window 'Continue uninstall' + Complete-Uninstall $reinstalled $run 'after-remove' -RemoveModels + Stop-Recording + + Assert-Profile $baseline -Scenario 'before-final-preservation' + $gatewayAfter = Get-GatewayInventory + Write-Json 'gateway-after.json' $gatewayAfter + if (($gatewayBefore | ConvertTo-Json -Depth 6 -Compress) -cne ($gatewayAfter | ConvertTo-Json -Depth 6 -Compress)) { + throw 'Gateway/WSL package inventory changed.' + } + $null = Wait-Condition 'owned UI actions to return' { @($script:Actions | Where-Object { -not $_.Done }).Count -eq 0 } $script:StopSeconds + foreach ($required in @('before.png', 'after.png', 'after-remove.mp4', 'after-remove-summary.png')) { + if (-not (Test-Path -LiteralPath (Join-Path $OutputDirectory $required))) { throw "Required evidence missing: $required" } + } + $script:Proof.status = 'passed; media requires visual review' +} catch { + $script:Proof.status = 'failed' + $script:Proof.failure = $_.Exception.Message + throw +} finally { + if ($script:Recording) { + try { Stop-Recording } catch { $script:Proof.cleanup += "Recording incomplete: $($_.Exception.Message)" } + } + # No blanket name-based stopping, recursive profile deletion, WSL unregister, + # or silent uninstall. Preserve leftovers for diagnosis and CI host disposal. + foreach ($run in $script:Runs) { + foreach ($node in @($run.Nodes.Values | Sort-Object StartUtc -Descending)) { + try { + if ($node.Process.HasExited) { continue } + $live = Get-Process -Id $node.Id -ErrorAction SilentlyContinue + if (-not $live -or $live.StartTime.ToUniversalTime() -ne $node.StartUtc -or $live.Path -ine $node.Path) { + $script:Proof.cleanup += "PID $($node.Id) no longer provably owned; not stopped."; continue + } + if ($live.ProcessName -match '^(wsl|wslhost|node|OpenClaw\.Tray\.WinUI|openclaw-wsl-keepalive|llama-server)$') { + $script:Proof.cleanup += "Protected process $($node.Id) left untouched; host disposal required."; continue + } + $live.Kill() + if (-not $live.WaitForExit($script:StopSeconds * 1000)) { throw 'Owned process stop unconfirmed.' } + $script:Proof.cleanup += "Stopped owned $($run.Purpose) PID $($node.Id)." + } catch { $script:Proof.cleanup += "Owned-process cleanup incomplete: $($_.Exception.Message)" } + } + } + if ($outputReady) { + $script:Proof.completedUtc = [DateTime]::UtcNow.ToString('o') + $script:Proof.artifacts = @(Get-ChildItem -LiteralPath $OutputDirectory -File | Where-Object Name -ne 'proof.json' | + Sort-Object Name | ForEach-Object { @{ file = $_.Name; bytes = $_.Length; sha256 = Get-Digest $_.FullName } }) + Save-Proof + } +} +Write-Host "Capture finished. Inspect before.png, after.png, after-remove.mp4 and proof.json in $OutputDirectory. CI host disposal is the cleanup boundary." From 7f6d508aad00feb8a9b5faa34e3e15e1d86b2801 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:26:46 +0000 Subject: [PATCH 5/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi - @jalehman Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> Co-authored-by: jalehman <550978+jalehman@users.noreply.github.com> OpenClaw-Publication: a09a0987-df78-4fe0-8ee4-cbfeee98d3ef --- scripts/capture-inno-model-uninstall.ps1 | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/scripts/capture-inno-model-uninstall.ps1 b/scripts/capture-inno-model-uninstall.ps1 index 0c4a5b4f45..2f6504c758 100644 --- a/scripts/capture-inno-model-uninstall.ps1 +++ b/scripts/capture-inno-model-uninstall.ps1 @@ -106,6 +106,9 @@ function Wait-Condition([string]$Description, [scriptblock]$Condition, [int]$Sec # an observed descendant, created during its parent's lifetime, with identical # bytes. Missing intermediate ancestry fails closed rather than guessing by name. function Start-OwnedProcess([string]$Path, [string[]]$Arguments, [string]$Purpose, [switch]$Uninstaller) { + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { + throw "Executable for $Purpose does not exist: $Path" + } $info = [Diagnostics.ProcessStartInfo]::new($Path) $info.UseShellExecute = $false $info.CreateNoWindow = -not $Uninstaller @@ -121,7 +124,9 @@ function Start-OwnedProcess([string]$Path, [string[]]$Arguments, [string]$Purpos $info.Arguments = $quoted -join ' ' $process = [Diagnostics.Process]::new() $process.StartInfo = $info - if (-not $process.Start()) { throw "Could not start $Purpose." } + try { + if (-not $process.Start()) { throw "Process.Start returned false." } + } catch { throw "Could not start $Purpose at ${Path}: $($_.Exception.Message)" } $node = [pscustomobject]@{ Process = $process; Id = $process.Id; StartUtc = $process.StartTime.ToUniversalTime() Path = $Path; UiAllowed = [bool]$Uninstaller; ParentId = $PID @@ -726,13 +731,13 @@ try { $script:Proof.diagnosticsDirectory = $script:WorkDirectory $script:Proof.before = @{ installer = $BeforeInstaller; sha256 = Get-Digest $BeforeInstaller; sourceRevision = $BeforeSourceRevision; buildIdentity = $BeforeBuildIdentity; releaseUrl = $BeforeReleaseUrl; provenance = 'caller-supplied release/source attribution; actual hash recorded' } $script:Proof.after = @{ installer = $AfterInstaller; sha256 = Get-Digest $AfterInstaller; sourceRevision = $AfterSourceRevision; buildIdentity = $AfterBuildIdentity; identity = 'full locally built unsigned Dev installer' } - $git = (Get-Command git -CommandType Application -ErrorAction Stop).Source + $git = (Get-Command git -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source $head = (Invoke-Native $git @('-C', (Join-Path $PSScriptRoot '..'), 'rev-parse', 'HEAD') 'source-revision').Trim() if ($head -cne $AfterSourceRevision.ToLowerInvariant()) { throw 'AfterSourceRevision does not match capture checkout.' } $script:Proof.captureScriptSha256 = Get-Digest $PSCommandPath # Discover WinApp before native inspection. UIA is retained for Inno self-copy # lifetime ownership; never invent version-specific WinApp selectors or flags. - $winapp = Get-Command winapp -CommandType Application -ErrorAction SilentlyContinue + $winapp = Get-Command winapp -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($winapp) { $script:Proof.tools.winapp = (Invoke-Native $winapp.Source @('--version') 'winapp-version').Trim() $schema = Invoke-Native $winapp.Source @('--cli-schema') 'winapp-schema' @@ -743,8 +748,8 @@ try { $script:Proof.tools.ui = 'UIAutomationClient/InvokePattern scoped to Inno descendants; CopyFromScreen window crop.' } Save-Proof - $script:Ffmpeg = (Get-Command ffmpeg -CommandType Application -ErrorAction Stop).Source - $script:Ffprobe = (Get-Command ffprobe -CommandType Application -ErrorAction Stop).Source + $script:Ffmpeg = (Get-Command ffmpeg -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source + $script:Ffprobe = (Get-Command ffprobe -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source $script:Proof.tools.ffmpeg = (Invoke-Native $script:Ffmpeg @('-version') 'ffmpeg-version').Split("`n")[0] $gatewayBefore = Assert-FreshHost Write-Json 'gateway-before.json' $gatewayBefore From 343f6fb63dff20e3240b1058f4b2f00c597fec60 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:41:46 +0000 Subject: [PATCH 6/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi - @jalehman Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> Co-authored-by: jalehman <550978+jalehman@users.noreply.github.com> OpenClaw-Publication: 4a214e0c-e5d3-452c-994e-e9056e0aa345 --- scripts/capture-inno-model-uninstall.ps1 | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/scripts/capture-inno-model-uninstall.ps1 b/scripts/capture-inno-model-uninstall.ps1 index 2f6504c758..1390c59879 100644 --- a/scripts/capture-inno-model-uninstall.ps1 +++ b/scripts/capture-inno-model-uninstall.ps1 @@ -164,8 +164,16 @@ function Update-OwnedTree($Run) { $uiAllowed = $false if ($Run.Uninstaller -and [IO.Path]::GetFileName($path) -ieq '_unins.tmp') { Assert-OrdinaryPath $path - if (-not $path.StartsWith([IO.Path]::GetTempPath(), [StringComparison]::OrdinalIgnoreCase) -or - (Get-Digest $path) -ne $Run.ImageHash) { throw 'Inno self-copy does not match the owned uninstaller.' } + # Inno can inherit an 8.3 TEMP spelling while .NET expands it. + # Compare the existing long paths, retaining the ancestry and byte checks. + $copyPath = [InnoCaptureWindow]::LongPath($path) + $tempRoot = [InnoCaptureWindow]::LongPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' + $copyHash = Get-Digest $path + if (-not $copyPath.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or + $copyHash -ne $Run.ImageHash) { + $script:Proof.rejectedSelfCopy = @{ path = $path; canonicalPath = $copyPath; tempRoot = $tempRoot; sha256 = $copyHash; expectedSha256 = $Run.ImageHash } + throw 'Inno self-copy does not match the owned uninstaller. See rejectedSelfCopy in proof.json.' + } $uiAllowed = $true } $Run.Nodes[$id] = [pscustomobject]@{ @@ -317,6 +325,15 @@ public static class InnoCaptureWindow { [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetLongPathName(string path, System.Text.StringBuilder result, uint size); + public static string LongPath(string path) { + var result = new System.Text.StringBuilder(32768); + uint count = GetLongPathName(path, result, (uint)result.Capacity); + if (count == 0 || count >= result.Capacity) + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Cannot resolve existing capture path."); + return result.ToString(); + } } '@ $null = [InnoCaptureWindow]::SetProcessDPIAware() From 636ab6e3c8312425448a6d6519bd0c8419232bb4 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:59:59 +0000 Subject: [PATCH 7/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi - @jalehman Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> Co-authored-by: jalehman <550978+jalehman@users.noreply.github.com> OpenClaw-Publication: ee2d8088-cf37-4c29-9335-afe975fb1cad --- scripts/capture-inno-model-uninstall.ps1 | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/capture-inno-model-uninstall.ps1 b/scripts/capture-inno-model-uninstall.ps1 index 1390c59879..d934d8f6e8 100644 --- a/scripts/capture-inno-model-uninstall.ps1 +++ b/scripts/capture-inno-model-uninstall.ps1 @@ -157,6 +157,9 @@ function Update-OwnedTree($Run) { if ($parent.Process.HasExited -and $created -gt $parent.Process.ExitTime.ToUniversalTime()) { continue } $process = Get-Process -Id $id -ErrorAction SilentlyContinue if (-not $process -or $process.HasExited) { continue } + # Get-Process opens its native handle lazily. Retain it while the child + # is alive so its terminal exit code remains queryable after teardown. + $null = $process.Handle # CIM and Process report the same kernel creation timestamp at different precision. if ([Math]::Abs(($process.StartTime.ToUniversalTime() - $created).TotalMilliseconds) -gt 1) { continue } if (-not $item.ExecutablePath) { throw "Cannot verify descendant path for PID $id." } From 85c5b34b9cf1609d05113804a63b620b066373a0 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:19:00 +0000 Subject: [PATCH 8/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi - @jalehman Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> Co-authored-by: jalehman <550978+jalehman@users.noreply.github.com> OpenClaw-Publication: c0cd2cec-53b7-4729-a978-18e339f4b8c8 --- scripts/capture-inno-model-uninstall.ps1 | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/capture-inno-model-uninstall.ps1 b/scripts/capture-inno-model-uninstall.ps1 index d934d8f6e8..b864c8809e 100644 --- a/scripts/capture-inno-model-uninstall.ps1 +++ b/scripts/capture-inno-model-uninstall.ps1 @@ -369,9 +369,18 @@ function Get-WindowText($Window) { } return $text -join "`n" } +function Test-ClientControl($Control) { + $parent = [Windows.Automation.TreeWalker]::ControlViewWalker.GetParent($Control) + while ($parent) { + if ($parent.Current.ControlType -eq [Windows.Automation.ControlType]::TitleBar) { return $false } + if ($parent.Current.ControlType -eq [Windows.Automation.ControlType]::Window) { return $true } + $parent = [Windows.Automation.TreeWalker]::ControlViewWalker.GetParent($parent) + } + return $false +} function Find-Control($Window, [string]$Name, $Type) { $matches = @($Window.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition) | - Where-Object { $_.Current.ControlType -eq $Type -and ($_.Current.Name -replace '&', '') -eq $Name -and -not $_.Current.IsOffscreen }) + Where-Object { $_.Current.ControlType -eq $Type -and ($_.Current.Name -replace '&', '') -eq $Name -and -not $_.Current.IsOffscreen -and (Test-ClientControl $_) }) if ($matches.Count -gt 1) { throw "Ambiguous owned control: $Name" } if ($matches.Count -eq 1) { return $matches[0] } return $null From d6d009dbdff909d2c2df459a0534cb410d753414 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:10:28 +0000 Subject: [PATCH 9/9] Publish openclaw/quick-shrimp-2 Worked on by: - @DonnieFi - @jalehman Co-authored-by: DonnieFi <44792682+DonnieFi@users.noreply.github.com> Co-authored-by: jalehman <550978+jalehman@users.noreply.github.com> OpenClaw-Publication: 5f887b48-f20a-4bdf-bb7e-d519400e5c1d --- .github/workflows/inno-uninstall-media.yml | 110 --- scripts/capture-inno-model-uninstall.ps1 | 892 --------------------- 2 files changed, 1002 deletions(-) delete mode 100644 .github/workflows/inno-uninstall-media.yml delete mode 100644 scripts/capture-inno-model-uninstall.ps1 diff --git a/.github/workflows/inno-uninstall-media.yml b/.github/workflows/inno-uninstall-media.yml deleted file mode 100644 index 29455c1fe0..0000000000 --- a/.github/workflows/inno-uninstall-media.yml +++ /dev/null @@ -1,110 +0,0 @@ -name: Inno uninstall media proof - -on: - pull_request: - branches: [main, master] - paths: - - installer.iss - - scripts/Uninstall-DownloadedModels.ps1 - - scripts/capture-inno-model-uninstall.ps1 - - src/OpenClaw.Shared/Audio/Kokoro*.cs - - .github/workflows/inno-uninstall-media.yml - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: inno-media-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - capture: - name: Real Inno uninstall screenshots and video - runs-on: windows-latest - timeout-minutes: 40 - env: - RequireSignedCleanupHost: 'false' - RequireSignedFileWorker: 'false' - OPENCLAW_REPO_ROOT: ${{ github.workspace }} - PROOF_PR_HEAD: ${{ github.event.pull_request.head.sha || github.sha }} - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - persist-credentials: false - - - uses: actions/setup-dotnet@v6 - with: - dotnet-version: 10.0.x - - - uses: actions/cache/restore@v6 - with: - path: ~/.nuget/packages - key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/Directory.Packages.props') }} - restore-keys: nuget-${{ runner.os }}- - - - name: Prepare installer and recording tools - shell: pwsh - run: | - choco install innosetup ffmpeg -y --no-progress - if ($LASTEXITCODE -ne 0) { throw 'Capture prerequisites could not be installed.' } - ffmpeg -version - ./scripts/Set-CiDesktopResolution.ps1 - - - name: Build complete candidate Dev installer - shell: pwsh - run: | - ./scripts/Initialize-ReactorPackages.ps1 - ./scripts/build-inno-local.ps1 -Arch x64 -Dev -Fast - if ($LASTEXITCODE -ne 0) { throw 'Candidate installer build failed.' } - - - name: Fetch verified released baseline - shell: pwsh - env: - GH_TOKEN: ${{ github.token }} - run: | - $ErrorActionPreference = 'Stop' - $baseline = git rev-parse 'v2026.11.3^{commit}' - if ($LASTEXITCODE -ne 0 -or $baseline -ne '66b9b5a559a0651da3aa6ce7ae3d183fbd87cb1c') { - throw 'The baseline release tag moved or is unavailable.' - } - $release = gh api "repos/$env:GITHUB_REPOSITORY/releases/tags/v2026.11.3" | ConvertFrom-Json - if ($LASTEXITCODE -ne 0) { throw 'Baseline release lookup failed.' } - $assets = @($release.assets | Where-Object name -eq 'OpenClawCompanion-Setup-x64.exe') - if ($assets.Count -ne 1 -or $assets[0].digest -notmatch '^sha256:[0-9a-fA-F]{64}$') { - throw 'Baseline requires one installer with a published SHA256 digest.' - } - $path = Join-Path $env:RUNNER_TEMP 'OpenClawCompanion-2026.11.3-baseline.exe' - Invoke-WebRequest -Uri $assets[0].browser_download_url -OutFile $path -TimeoutSec 180 - if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -ne $assets[0].digest.Substring(7)) { - throw 'Baseline installer digest mismatch.' - } - $signature = Get-AuthenticodeSignature -LiteralPath $path - if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'CN=OpenClaw Foundation(?:,|$)') { - throw 'Baseline installer signature is not the expected valid publisher.' - } - "INNO_BEFORE_INSTALLER=$path" >> $env:GITHUB_ENV - - - name: Capture real uninstall choices and outcomes - shell: powershell -NoProfile -STA -ExecutionPolicy Bypass -File {0} - run: | - $parameters = @{ - BeforeInstaller = $env:INNO_BEFORE_INSTALLER - AfterInstaller = (Resolve-Path 'Output/OpenClawCompanion-Dev-Setup-x64.exe').Path - BeforeRevision = '66b9b5a559a0651da3aa6ce7ae3d183fbd87cb1c' - AfterRevision = (git rev-parse HEAD) - OutputDirectory = (Join-Path $env:GITHUB_WORKSPACE 'TestResults/InnoUninstallMedia') - BeforeReleaseUrl = 'https://github.com/openclaw/openclaw-windows-node/releases/tag/v2026.11.3' - ConfirmDisposableHost = $true - } - ./scripts/capture-inno-model-uninstall.ps1 @parameters - - - name: Retain sanitized media and provenance - if: always() - uses: actions/upload-artifact@v7 - with: - name: inno-uninstall-media - path: TestResults/InnoUninstallMedia/ - if-no-files-found: error - retention-days: 14 diff --git a/scripts/capture-inno-model-uninstall.ps1 b/scripts/capture-inno-model-uninstall.ps1 deleted file mode 100644 index b864c8809e..0000000000 --- a/scripts/capture-inno-model-uninstall.ps1 +++ /dev/null @@ -1,892 +0,0 @@ -#requires -Version 5.1 -<# -.SYNOPSIS - Capture real installed Inno uninstall UI on an exclusive disposable CI desktop. -.DESCRIPTION - Uses full production/Dev installers, official hash-pinned Kokoro v1.1 assets, - process-bound UIA, cropped window PNGs and live ffmpeg desktop recordings. - Before: ordinary uninstall, keep Gateway/models. After: cancel, keep, reinstall - the same owned payload, select/remove models. Never silently uninstall, launch - Companion, remove Gateway/WSL, or sweep profiles. CI host disposal owns cleanup. - Run with Windows PowerShell 5.1 -STA for the in-box UIAutomation/Drawing assemblies. - ConfirmDisposableHost asserts an authorized exclusive unlocked Windows desktop - and disposable account with synthetic data only. Not for developer workstations. - Source/build attribution is supplied by the caller; actual installer/payload - hashes are recorded. This is unsigned Dev behavior, not signed acceptance. -.EXAMPLE - .\scripts\capture-inno-model-uninstall.ps1 -BeforeInstaller C:\inputs\released.exe ` - -AfterInstaller C:\inputs\candidate-Dev.exe -BeforeSourceRevision <40-hex-sha> ` - -AfterSourceRevision <40-hex-sha> -BeforeBuildIdentity 'release v2026.11.3' ` - -AfterBuildIdentity 'CI run 123, full Dev publish' -OutputDirectory C:\proof\uninstall ` - -ConfirmDisposableHost -#> -[CmdletBinding()] -param( - [Parameter(Mandatory)][string]$BeforeInstaller, - [Parameter(Mandatory)][string]$AfterInstaller, - [Parameter(Mandatory)][Alias('BeforeRevision')][ValidatePattern('^[0-9a-fA-F]{40}$')][string]$BeforeSourceRevision, - [Parameter(Mandatory)][Alias('AfterRevision')][ValidatePattern('^[0-9a-fA-F]{40}$')][string]$AfterSourceRevision, - [ValidateNotNullOrEmpty()][string]$BeforeBuildIdentity = 'Official production release (caller-verified asset)', - [ValidateNotNullOrEmpty()][string]$AfterBuildIdentity = 'Full locally built unsigned Dev installer', - [Parameter(Mandatory)][string]$OutputDirectory, - [string]$BeforeReleaseUrl, - [switch]$ConfirmDisposableHost -) -Set-StrictMode -Version Latest -$ErrorActionPreference = 'Stop' -if (-not $ConfirmDisposableHost) { throw 'Pass -ConfirmDisposableHost only for an authorized exclusive disposable CI desktop.' } -if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_ENVIRONMENT -ne 'github-hosted') { - throw 'This capture is restricted to a fresh GitHub-hosted disposable runner.' -} -if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Native Windows is required. No proof was captured.' } -if ($PSVersionTable.PSEdition -ne 'Desktop' -or [Threading.Thread]::CurrentThread.GetApartmentState() -ne 'STA') { - throw 'Use powershell.exe -NoProfile -STA -ExecutionPolicy Bypass -File for the in-box native UI assemblies.' -} -if (-not [Environment]::UserInteractive -or (Get-Process -Id $PID).SessionId -eq 0) { - throw 'Refusing a noninteractive/session-0 desktop.' -} - -# Named configurable hang guards, never readiness delays or blind retries. -function Get-Limit([string]$Name, [int]$Default, [int]$Maximum) { - $value = [Environment]::GetEnvironmentVariable("OPENCLAW_INNO_CAPTURE_$Name") - if ([string]::IsNullOrWhiteSpace($value)) { return $Default } - $number = 0 - if (-not [int]::TryParse($value, [ref]$number) -or $number -lt 1 -or $number -gt $Maximum) { - throw "Invalid capture limit $Name (1..$Maximum)." - } - return $number -} -$script:StepSeconds = Get-Limit STEP_SECONDS 300 900 -$script:InstallSeconds = Get-Limit INSTALL_SECONDS 600 1800 -$script:DownloadSeconds = Get-Limit DOWNLOAD_SECONDS 900 1800 -$script:VideoSeconds = Get-Limit VIDEO_SECONDS 480 900 -$script:StopSeconds = Get-Limit STOP_SECONDS 30 120 -$script:PollMilliseconds = Get-Limit POLL_MILLISECONDS 200 2000 -$script:CimSeconds = Get-Limit CIM_SECONDS 15 60 -$script:Runs = [Collections.Generic.List[object]]::new() -$script:Actions = [Collections.Generic.List[object]]::new() -$script:Recording = $null -$script:Proof = [ordered]@{ - schemaVersion = 1; status = 'running'; startedUtc = [DateTime]::UtcNow.ToString('o') - scope = 'Real installed Inno UI on exclusive disposable Windows CI desktop' - limits = 'Unsigned Dev behavior, not signed acceptance; no real Gateway installed or removed.' - authority = 'ConfirmDisposableHost on github-hosted runner'; prHead = $env:PROOF_PR_HEAD; scenarios = [Collections.Generic.List[object]]::new() - tools = [ordered]@{}; artifacts = @(); cleanup = @() -} -function Assert-OrdinaryPath([string]$Path) { - if ($Path -notmatch '^[A-Za-z]:\\') { - throw "Only fully qualified local drive paths are accepted: $Path" - } - $current = [IO.Path]::GetFullPath($Path) - while ($current) { - if (Test-Path -LiteralPath $current) { - $item = Get-Item -LiteralPath $current -Force - if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Redirected path refused: $current" } - } - $current = [IO.Path]::GetDirectoryName($current) - } -} -function Get-Digest([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } -function Write-Json([string]$Name, $Value) { - $Value | ConvertTo-Json -Depth 14 | Set-Content -LiteralPath (Join-Path $OutputDirectory $Name) -Encoding utf8 -} -function Save-Proof { Write-Json 'proof.json' $script:Proof } -function Wait-Condition([string]$Description, [scriptblock]$Condition, [int]$Seconds = $script:StepSeconds) { - $clock = [Diagnostics.Stopwatch]::StartNew() - do { - foreach ($action in $script:Actions) { if ($action.Error) { throw "Owned UI action failed: $($action.Error)" } } - $value = & $Condition - if ($value) { return $value } - if ($clock.Elapsed.TotalSeconds -ge $Seconds) { throw "Timed out waiting for $Description; outcome unconfirmed." } - Start-Sleep -Milliseconds $script:PollMilliseconds - } while ($true) -} - -# Process objects retain lifetimes after launcher exit. Inno's _unins.tmp must be -# an observed descendant, created during its parent's lifetime, with identical -# bytes. Missing intermediate ancestry fails closed rather than guessing by name. -function Start-OwnedProcess([string]$Path, [string[]]$Arguments, [string]$Purpose, [switch]$Uninstaller) { - if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { - throw "Executable for $Purpose does not exist: $Path" - } - $info = [Diagnostics.ProcessStartInfo]::new($Path) - $info.UseShellExecute = $false - $info.CreateNoWindow = -not $Uninstaller - $info.RedirectStandardOutput = -not $Uninstaller - $info.RedirectStandardError = -not $Uninstaller - $info.RedirectStandardInput = -not $Uninstaller - # Same Windows quoting policy as Uninstall-DownloadedModels.ps1: reject embedded - # quotes, surround every argument, and double trailing backslashes before closing. - $quoted = foreach ($argument in $Arguments) { - if ($argument.Contains('"')) { throw 'Embedded quote in process argument refused.' } - '"' + ($argument -replace '(\\+)$', '$1$1') + '"' - } - $info.Arguments = $quoted -join ' ' - $process = [Diagnostics.Process]::new() - $process.StartInfo = $info - try { - if (-not $process.Start()) { throw "Process.Start returned false." } - } catch { throw "Could not start $Purpose at ${Path}: $($_.Exception.Message)" } - $node = [pscustomobject]@{ - Process = $process; Id = $process.Id; StartUtc = $process.StartTime.ToUniversalTime() - Path = $Path; UiAllowed = [bool]$Uninstaller; ParentId = $PID - } - $run = [pscustomobject]@{ - Purpose = $Purpose; Root = $node; Nodes = @{}; Uninstaller = [bool]$Uninstaller - ImageHash = $(if ($Uninstaller) { Get-Digest $Path } else { $null }) - Stdout = $null; Stderr = $null - } - $run.Nodes[$node.Id] = $node - if (-not $Uninstaller) { - $run.Stdout = $process.StandardOutput.ReadToEndAsync() - $run.Stderr = $process.StandardError.ReadToEndAsync() - } - $script:Runs.Add($run) - return $run -} -function Update-OwnedTree($Run) { - $snapshot = @(Get-CimInstance Win32_Process -OperationTimeoutSec $script:CimSeconds) - do { - $added = $false - foreach ($item in $snapshot) { - $id = [int]$item.ProcessId - if ($Run.Nodes.ContainsKey($id) -or -not $Run.Nodes.ContainsKey([int]$item.ParentProcessId)) { continue } - $parent = $Run.Nodes[[int]$item.ParentProcessId] - $created = $item.CreationDate.ToUniversalTime() - if ($created -lt $parent.StartUtc) { continue } - if ($parent.Process.HasExited -and $created -gt $parent.Process.ExitTime.ToUniversalTime()) { continue } - $process = Get-Process -Id $id -ErrorAction SilentlyContinue - if (-not $process -or $process.HasExited) { continue } - # Get-Process opens its native handle lazily. Retain it while the child - # is alive so its terminal exit code remains queryable after teardown. - $null = $process.Handle - # CIM and Process report the same kernel creation timestamp at different precision. - if ([Math]::Abs(($process.StartTime.ToUniversalTime() - $created).TotalMilliseconds) -gt 1) { continue } - if (-not $item.ExecutablePath) { throw "Cannot verify descendant path for PID $id." } - $path = [string]$item.ExecutablePath - $uiAllowed = $false - if ($Run.Uninstaller -and [IO.Path]::GetFileName($path) -ieq '_unins.tmp') { - Assert-OrdinaryPath $path - # Inno can inherit an 8.3 TEMP spelling while .NET expands it. - # Compare the existing long paths, retaining the ancestry and byte checks. - $copyPath = [InnoCaptureWindow]::LongPath($path) - $tempRoot = [InnoCaptureWindow]::LongPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' - $copyHash = Get-Digest $path - if (-not $copyPath.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or - $copyHash -ne $Run.ImageHash) { - $script:Proof.rejectedSelfCopy = @{ path = $path; canonicalPath = $copyPath; tempRoot = $tempRoot; sha256 = $copyHash; expectedSha256 = $Run.ImageHash } - throw 'Inno self-copy does not match the owned uninstaller. See rejectedSelfCopy in proof.json.' - } - $uiAllowed = $true - } - $Run.Nodes[$id] = [pscustomobject]@{ - Process = $process; Id = $id; StartUtc = $process.StartTime.ToUniversalTime() - Path = $path; UiAllowed = $uiAllowed; ParentId = [int]$item.ParentProcessId - } - $added = $true - } - } while ($added) -} -function Wait-ProcessExit($Run, [int]$Seconds) { - $null = Wait-Condition "$($Run.Purpose) process-tree exit" { - Update-OwnedTree $Run - return @($Run.Nodes.Values | Where-Object { -not $_.Process.HasExited }).Count -eq 0 - } $Seconds - return $Run.Root.Process.ExitCode -} -function Read-ProcessOutput($Task) { - $null = Wait-Condition 'owned process output pipe closure' { $Task.IsCompleted } $script:StopSeconds - return $Task.GetAwaiter().GetResult() -} -function Invoke-Native([string]$Path, [string[]]$Arguments, [string]$Purpose, [int]$Seconds = $script:StepSeconds) { - $run = Start-OwnedProcess $Path $Arguments $Purpose - $code = Wait-ProcessExit $run $Seconds - $stdout = Read-ProcessOutput $run.Stdout - $stderr = Read-ProcessOutput $run.Stderr - if ($code -ne 0) { throw "$Purpose exited $code. $stderr" } - return $stdout -} -function Get-RelatedRegistrations { - foreach ($hive in @('HKCU:', 'HKLM:')) { - foreach ($view in @('Software', 'Software\WOW6432Node')) { - $root = "$hive\$view\Microsoft\Windows\CurrentVersion\Uninstall" - if (-not (Test-Path -LiteralPath $root)) { continue } - foreach ($key in Get-ChildItem -LiteralPath $root) { - $entry = Get-ItemProperty -LiteralPath $key.PSPath - if ($key.PSChildName -match 'M0LTB0T' -or - ($entry.PSObject.Properties['DisplayName'] -and $entry.DisplayName -match 'OpenClaw|Moltbot')) { - [pscustomobject]@{ Key = $key.PSPath; Values = $entry } - } - } - } - } -} -function Get-GatewayInventory { - # Read the distro registry without starting WSL or provisioning it. - $distros = @() - $lxss = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss' - if (Test-Path -LiteralPath $lxss) { - $distros = @(Get-ChildItem -LiteralPath $lxss | ForEach-Object { - $p = Get-ItemProperty -LiteralPath $_.PSPath - [pscustomobject]@{ Id = $_.PSChildName; Name = $p.DistributionName; BasePath = $p.BasePath } - } | Sort-Object Id) - } - # CIM avoids loading the Appx module in pwsh. Failure is not proof of absence. - $packages = @(Get-CimInstance -Namespace root/cimv2 -ClassName Win32_InstalledStoreProgram ` - -OperationTimeoutSec $script:CimSeconds | Where-Object { $_.Name -match 'OpenClaw|Moltbot' } | - Select-Object Name, PackageFullName | Sort-Object Name) - $packageKeys = @() - $packageRoot = 'HKCU:\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages' - if (Test-Path -LiteralPath $packageRoot) { - $packageKeys = @(Get-ChildItem -LiteralPath $packageRoot | Where-Object { - $_.PSChildName -match 'OpenClaw|Moltbot' - } | Select-Object -ExpandProperty PSChildName | Sort-Object) - } - return [pscustomobject]@{ Distros = $distros; RelatedPackages = $packages; RelatedPackageKeys = $packageKeys } -} -function Assert-FreshHost { - if ($env:APPDATA -ine [Environment]::GetFolderPath('ApplicationData') -or - $env:LOCALAPPDATA -ine [Environment]::GetFolderPath('LocalApplicationData') -or - $env:USERPROFILE -ine [Environment]::GetFolderPath('UserProfile')) { - throw 'Profile environment differs from Windows known folders used by Inno.' - } - foreach ($name in @('OPENCLAW_TRAY_DATA_DIR', 'OPENCLAW_TRAY_APPDATA_DIR', 'OPENCLAW_TRAY_LOCALAPPDATA_DIR', - 'OPENCLAW_TRAY_LOCAL_DATA_DIR', 'OPENCLAW_STATE_DIR', 'OPENCLAW_WSL_DISTRO_NAME', 'OPENCLAW_NATIVE_GATEWAY_DEV_PATCH')) { - if ([Environment]::GetEnvironmentVariable($name)) { throw "Path/runtime override refused: $name" } - } - $protected = @() - foreach ($root in @($env:APPDATA, $env:LOCALAPPDATA)) { - foreach ($name in @('OpenClawTray', 'OpenClawTray-Dev', 'OpenClawGatewayMSIX')) { $protected += Join-Path $root $name } - } - $protected += Join-Path $env:USERPROFILE '.openclaw' - $protected += Join-Path $env:USERPROFILE '.openclaw-dev' - $packageData = Join-Path $env:LOCALAPPDATA 'Packages' - if (Test-Path -LiteralPath $packageData) { - $protected += @(Get-ChildItem -LiteralPath $packageData -Directory -Force | Where-Object { - $_.Name -match 'OpenClaw|Moltbot' - } | Select-Object -ExpandProperty FullName) - } - foreach ($path in $protected) { - Assert-OrdinaryPath $path - if (Test-Path -LiteralPath $path) { throw "Existing installation/profile refused, including empty directories: $path" } - if ($OutputDirectory.StartsWith($path.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -or $OutputDirectory -ieq $path) { - throw 'Output directory overlaps a protected profile.' - } - } - if (@(Get-RelatedRegistrations).Count) { throw 'Existing OpenClaw uninstall registration refused.' } - foreach ($name in @('openclaw', 'openclaw-dev')) { - if (Test-Path -LiteralPath "HKCU:\Software\Classes\$name") { throw 'Existing OpenClaw protocol registration refused.' } - } - $runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' - if (Test-Path -LiteralPath $runKey) { - $autoruns = Get-ItemProperty -LiteralPath $runKey - if (@($autoruns.PSObject.Properties | Where-Object { $_.Name -match 'OpenClaw|Moltbot' }).Count) { - throw 'Existing OpenClaw autostart registration refused.' - } - } - if (@(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -match 'OpenClaw|Moltbot' }).Count) { - throw 'Existing OpenClaw scheduled task refused.' - } - $processes = @(Get-CimInstance Win32_Process -OperationTimeoutSec $script:CimSeconds | Where-Object { - $_.Name -match '^(OpenClaw|Moltbot|llama-server)' -or - ($_.Name -match '^(node|wsl|wslhost)\.exe$' -and $_.CommandLine -match 'openclaw|moltbot') - }) - if ($processes.Count) { throw 'Existing related processes refused. This helper will not stop them.' } - $inventory = Get-GatewayInventory - if ($inventory.RelatedPackages.Count -or $inventory.RelatedPackageKeys.Count -or - @($inventory.Distros | Where-Object { $_.Name -match 'OpenClaw|Moltbot' }).Count) { - throw 'Existing related Store/native package or WSL distro refused.' - } - return $inventory -} - -# Real pixels and asynchronous UIA patterns, not reconstructed dialogs. Dispatch -# patterns only after binding their containing HWND to the installed uninstaller. -function Initialize-Desktop { - Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes, System.Drawing, System.Windows.Forms - Add-Type -TypeDefinition @' -using System; -using System.Runtime.InteropServices; -using System.Threading; -public sealed class InnoCaptureAction { - public volatile bool Done; - public Exception Error; - public static InnoCaptureAction Start(object pattern, string method) { - var result = new InnoCaptureAction(); - var thread = new Thread(() => { - try { pattern.GetType().GetMethod(method).Invoke(pattern, null); } - catch (Exception ex) { result.Error = ex; } - finally { result.Done = true; } - }); - thread.IsBackground = true; thread.SetApartmentState(ApartmentState.MTA); thread.Start(); - return result; - } -} -public static class InnoCaptureWindow { - [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; } - [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out Rect r); - [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); - [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); - [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern uint GetLongPathName(string path, System.Text.StringBuilder result, uint size); - public static string LongPath(string path) { - var result = new System.Text.StringBuilder(32768); - uint count = GetLongPathName(path, result, (uint)result.Capacity); - if (count == 0 || count >= result.Capacity) - throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "Cannot resolve existing capture path."); - return result.ToString(); - } -} -'@ - $null = [InnoCaptureWindow]::SetProcessDPIAware() -} -function Test-OwnedWindow($Run, $Window) { - $id = $Window.Current.ProcessId - if (-not $Run.Nodes.ContainsKey($id)) { return $false } - $node = $Run.Nodes[$id] - if (-not $node.UiAllowed -or $node.Process.HasExited) { return $false } - $live = Get-Process -Id $id -ErrorAction SilentlyContinue - return $live -and $live.StartTime.ToUniversalTime() -eq $node.StartUtc -and $live.Path -ieq $node.Path -} -function Get-OwnedWindows($Run) { - Update-OwnedTree $Run - $children = [Windows.Automation.AutomationElement]::RootElement.FindAll( - [Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition) - foreach ($window in $children) { - try { - if (-not $window.Current.IsOffscreen -and (Test-OwnedWindow $Run $window)) { $window } - } catch [Windows.Automation.ElementNotAvailableException] { continue } - } -} -function Get-WindowText($Window) { - $text = [Collections.Generic.List[string]]::new() - $text.Add($Window.Current.Name) - foreach ($child in $Window.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition)) { - $text.Add($child.Current.Name) - $pattern = $null - if ($child.TryGetCurrentPattern([Windows.Automation.ValuePattern]::Pattern, [ref]$pattern)) { $text.Add($pattern.Current.Value) } - } - return $text -join "`n" -} -function Test-ClientControl($Control) { - $parent = [Windows.Automation.TreeWalker]::ControlViewWalker.GetParent($Control) - while ($parent) { - if ($parent.Current.ControlType -eq [Windows.Automation.ControlType]::TitleBar) { return $false } - if ($parent.Current.ControlType -eq [Windows.Automation.ControlType]::Window) { return $true } - $parent = [Windows.Automation.TreeWalker]::ControlViewWalker.GetParent($parent) - } - return $false -} -function Find-Control($Window, [string]$Name, $Type) { - $matches = @($Window.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition) | - Where-Object { $_.Current.ControlType -eq $Type -and ($_.Current.Name -replace '&', '') -eq $Name -and -not $_.Current.IsOffscreen -and (Test-ClientControl $_) }) - if ($matches.Count -gt 1) { throw "Ambiguous owned control: $Name" } - if ($matches.Count -eq 1) { return $matches[0] } - return $null -} -function Invoke-Control($Run, $Window, [string]$Name, [switch]$Toggle) { - if (-not (Test-OwnedWindow $Run $Window)) { throw 'UI ownership changed before invocation.' } - $type = if ($Toggle) { [Windows.Automation.ControlType]::CheckBox } else { [Windows.Automation.ControlType]::Button } - $control = Find-Control $Window $Name $type - if (-not $control -or -not $control.Current.IsEnabled) { throw "Owned control is not ready: $Name" } - $patternType = if ($Toggle) { [Windows.Automation.TogglePattern]::Pattern } else { [Windows.Automation.InvokePattern]::Pattern } - $pattern = $control.GetCurrentPattern($patternType) - $action = [InnoCaptureAction]::Start($pattern, $(if ($Toggle) { 'Toggle' } else { 'Invoke' })) - $script:Actions.Add($action) -} -function Wait-Window($Run, [scriptblock]$Predicate, [string]$Description) { - return Wait-Condition $Description { - foreach ($window in @(Get-OwnedWindows $Run)) { - try { if (& $Predicate $window) { return $window } } - catch [Windows.Automation.ElementNotAvailableException] { continue } - } - return $null - } -} -function Save-Window($Run, $Window, [string]$Name) { - if (-not (Test-OwnedWindow $Run $Window)) { throw 'Cannot capture a foreign window.' } - $handle = [IntPtr]$Window.Current.NativeWindowHandle - $null = [InnoCaptureWindow]::SetForegroundWindow($handle) - $state = @{ Last = ''; Count = 0; Rect = $null } - $null = Wait-Condition 'stable owned foreground window bounds' { - if ([InnoCaptureWindow]::GetForegroundWindow() -ne $handle -or -not (Test-OwnedWindow $Run $Window)) { return $false } - $rect = [InnoCaptureWindow+Rect]::new() - if (-not [InnoCaptureWindow]::GetWindowRect($handle, [ref]$rect)) { return $false } - $key = "$($rect.Left),$($rect.Top),$($rect.Right),$($rect.Bottom)" - if ($state.Last -eq $key) { $state.Count++ } else { $state.Count = 0; $state.Last = $key } - $state.Rect = $rect - return $state.Count -ge 2 -and $rect.Right -gt $rect.Left -and $rect.Bottom -gt $rect.Top - } - $r = $state.Rect - $bounds = [Windows.Forms.SystemInformation]::VirtualScreen - if ($r.Left -lt $bounds.Left -or $r.Top -lt $bounds.Top -or $r.Right -gt $bounds.Right -or $r.Bottom -gt $bounds.Bottom) { - throw 'Owned window is clipped by the desktop. Increase the CI desktop resolution.' - } - $bitmap = [Drawing.Bitmap]::new(($r.Right - $r.Left), ($r.Bottom - $r.Top)) - $graphics = [Drawing.Graphics]::FromImage($bitmap) - try { - $graphics.CopyFromScreen($r.Left, $r.Top, 0, 0, $bitmap.Size) - if ([InnoCaptureWindow]::GetForegroundWindow() -ne $handle) { throw 'Foreground changed during capture.' } - $bitmap.Save((Join-Path $OutputDirectory "$Name.png"), [Drawing.Imaging.ImageFormat]::Png) - } finally { $graphics.Dispose(); $bitmap.Dispose() } - Write-Json "$Name.window.json" @{ - processId = $Window.Current.ProcessId; hwnd = $handle.ToInt64(); text = Get-WindowText $Window - bounds = @{ left = $r.Left; top = $r.Top; width = $r.Right - $r.Left; height = $r.Bottom - $r.Top } - } -} -function Get-VideoFrames { - if (-not $script:Recording -or -not (Test-Path -LiteralPath $script:Recording.Progress)) { return 0 } - $frames = @(Get-Content -LiteralPath $script:Recording.Progress | Where-Object { $_ -match '^frame=\d+$' }) - if (-not $frames.Count) { return 0 } - return [int]($frames[-1] -replace '^frame=', '') -} -function Start-Recording([string]$Name) { - if ($script:Recording) { throw 'A capture is already active.' } - $path = Join-Path $OutputDirectory "$Name.mp4" - $progress = Join-Path $script:WorkDirectory "$Name.ffmpeg-progress.txt" - $run = Start-OwnedProcess $script:Ffmpeg @( - '-hide_banner', '-loglevel', 'warning', '-f', 'gdigrab', '-framerate', '12', '-draw_mouse', '0', - '-i', 'desktop', '-t', "$script:VideoSeconds", '-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2', '-c:v', 'libx264', - '-preset', 'veryfast', '-crf', '28', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-progress', $progress, $path - ) "record-$Name" - $script:Recording = [pscustomobject]@{ Run = $run; Path = $path; Progress = $progress; Name = $Name } - $null = Wait-Condition 'first live desktop video frames' { - if ($run.Root.Process.HasExited) { throw "ffmpeg exited early: $(Read-ProcessOutput $run.Stderr)" } - return (Get-VideoFrames) -gt 0 - } -} -function Hold-RecordedState($Run, $Window) { - # Deliberate presentation dwell measured in live encoded frames, not a sleep - # that substitutes for readiness. Verify ownership/foreground throughout. - $startFrame = Get-VideoFrames - $handle = [IntPtr]$Window.Current.NativeWindowHandle - $null = [InnoCaptureWindow]::SetForegroundWindow($handle) - $null = Wait-Condition '24 live frames of the verified UI state' { - if ($script:Recording.Run.Root.Process.HasExited) { throw 'Video ended before the scenario completed.' } - if (-not (Test-OwnedWindow $Run $Window) -or [InnoCaptureWindow]::GetForegroundWindow() -ne $handle) { - throw 'Owned UI lost foreground during its recording segment.' - } - return (Get-VideoFrames) -ge ($startFrame + 24) - } -} -function Stop-Recording { - if (-not $script:Recording) { return } - $recording = $script:Recording - $script:Recording = $null - $run = $recording.Run - $endedEarly = $run.Root.Process.HasExited - if (-not $endedEarly) { $run.Root.Process.StandardInput.WriteLine('q'); $run.Root.Process.StandardInput.Flush() } - $code = Wait-ProcessExit $run $script:StopSeconds - Read-ProcessOutput $run.Stderr | Set-Content -LiteralPath (Join-Path $script:WorkDirectory "$($recording.Name).ffmpeg.log") - if ($endedEarly -or $code -ne 0) { throw 'Recording incomplete or ended before the scenario.' } - $probe = Invoke-Native $script:Ffprobe @('-v', 'error', '-count_frames', '-select_streams', 'v:0', - '-show_entries', 'stream=codec_name,width,height,nb_read_frames:format=duration,size', '-of', 'json', $recording.Path) 'validate-video' - $parsed = $probe | ConvertFrom-Json - if ([double]$parsed.format.duration -le 0 -or [int]$parsed.streams[0].nb_read_frames -lt 24) { throw 'MP4 has no meaningful decoded live frames.' } - $probe | Set-Content -LiteralPath (Join-Path $OutputDirectory "$($recording.Name).video.json") - if ((Get-Item -LiteralPath $recording.Path).Length -gt 10000000) { - throw 'Recording exceeds 10 MB. Preserve native-resolution text readability when preparing delivery.' - } - if ($recording.Name -eq 'after-remove') { - # Six genuine decoded frames from the live video, not frames used to make - # the video. The sheet is an inspection aid, not a substitute recording. - $duration = [double]$parsed.format.duration - $frameFiles = @() - $samples = @() - for ($index = 0; $index -lt 6; $index++) { - $timestamp = (($index + 0.5) * $duration / 6).ToString('F3', [Globalization.CultureInfo]::InvariantCulture) - $frame = Join-Path $OutputDirectory ("after-remove-frame-{0:D2}.png" -f ($index + 1)) - $null = Invoke-Native $script:Ffmpeg @('-hide_banner', '-loglevel', 'error', '-ss', $timestamp, - '-i', $recording.Path, '-frames:v', '1', '-update', '1', $frame) 'extract-live-video-frame' - $frameFiles += $frame - $samples += @{ file = [IO.Path]::GetFileName($frame); seconds = $timestamp } - } - $first = [Drawing.Image]::FromFile($frameFiles[0]) - $width = $first.Width; $height = $first.Height; $first.Dispose() - $sheet = [Drawing.Bitmap]::new(($width * 3), ($height * 2)) - $graphics = [Drawing.Graphics]::FromImage($sheet) - try { - for ($index = 0; $index -lt 6; $index++) { - $image = [Drawing.Image]::FromFile($frameFiles[$index]) - try { $graphics.DrawImage($image, (($index % 3) * $width), ([int][Math]::Floor($index / 3) * $height), $width, $height) } - finally { $image.Dispose() } - } - $sheet.Save((Join-Path $OutputDirectory 'after-remove-contact-sheet.png'), [Drawing.Imaging.ImageFormat]::Png) - } finally { $graphics.Dispose(); $sheet.Dispose() } - Write-Json 'after-remove-frame-samples.json' $samples - } -} - -# Independent scenario pins must match the production catalog. No synthetic model, -# extracted Pascal function, helper replacement or UI-only stub is admissible. -$script:Assets = @( - @{ FileName = 'kokoro-v1.1-zh.onnx'; Size = 343605188L; Sha256 = 'eefec708cbc7aba8e8129b5c2f7cb92e1fe7d281af1e1dd451592d9ff0714a0d' }, - @{ FileName = 'voices-v1.1-zh.bin'; Size = 53792177L; Sha256 = 'e678019845e6cfe3b7c34531779396b28f509451b91e6535d5dc09bbf11a4be5' } -) -$script:ExpectedBytes = 397397365L -function Get-OfficialAssets { - $catalogPath = Join-Path $PSScriptRoot '..\src\OpenClaw.Shared\Audio\KokoroDownloadCatalog.cs' - $catalog = Get-Content -LiteralPath $catalogPath -Raw - $baseUrl = 'https://github.com/larroy/kokoro.cpp/releases/download/voices_model_files/' - if (-not $catalog.Contains($baseUrl)) { throw 'Source catalog no longer has the pinned official release URL.' } - $cache = Join-Path $script:WorkDirectory 'input-assets' - $null = New-Item -ItemType Directory -Path $cache - foreach ($asset in $script:Assets) { - if (-not $catalog.Contains($asset.FileName) -or -not $catalog.Contains($asset.Sha256) -or -not $catalog.Contains([string]$asset.Size)) { - throw 'Pinned media scenario does not match the production download catalog.' - } - $asset.Url = $baseUrl + $asset.FileName - $asset.Path = Join-Path $cache $asset.FileName - Invoke-WebRequest -UseBasicParsing -Uri $asset.Url -OutFile $asset.Path -TimeoutSec $script:DownloadSeconds - if ((Get-Item -LiteralPath $asset.Path).Length -ne $asset.Size -or (Get-Digest $asset.Path) -ne $asset.Sha256) { - throw "Official asset size/hash mismatch: $($asset.FileName)" - } - } - $script:Proof.assets = @($script:Assets | ForEach-Object { @{ file = $_.FileName; url = $_.Url; sha256 = $_.Sha256; bytes = $_.Size } }) -} -function Get-Inventory([string]$Root) { - if (-not (Test-Path -LiteralPath $Root)) { return @() } - Assert-OrdinaryPath $Root - $prefix = [IO.Path]::GetFullPath($Root).TrimEnd('\') + '\' - return @(Get-ChildItem -LiteralPath $Root -File -Recurse -Force | Sort-Object FullName | ForEach-Object { - Assert-OrdinaryPath $_.FullName - [pscustomobject]@{ path = $_.FullName.Substring($prefix.Length); bytes = $_.Length; sha256 = Get-Digest $_.FullName } - }) -} -function Seed-Profile($Install) { - Assert-OrdinaryPath $Install.Profile - if (Test-Path -LiteralPath $Install.Profile) { throw 'Profile unexpectedly exists before seed; refusing adoption.' } - $models = Join-Path $Install.Profile 'models\kokoro\v1.1-en-zh' - $null = New-Item -ItemType Directory -Path $models - foreach ($asset in $script:Assets) { Copy-Item -LiteralPath $asset.Path -Destination (Join-Path $models $asset.FileName) } - # Unrelated sibling and settings have exact preservation assertions. No credentials. - Set-Content -LiteralPath (Join-Path $models 'unrelated-sentinel.txt') -Value 'Synthetic PR2328 sentinel. Keep this file.' -Encoding utf8 - Set-Content -LiteralPath (Join-Path $Install.Profile 'settings.json') -Value '{"EnableNodeMode":false,"EnableMcpServer":false,"AutoStart":false}' -Encoding utf8 - $Install.Seeded = @(Get-Inventory $Install.Profile) - Write-Json "$($Install.Label)-seeded-files.json" $Install.Seeded -} -function Assert-Profile($Install, [switch]$Removed, [string]$Scenario) { - $inventory = @(Get-Inventory $Install.Profile) - Write-Json "$Scenario-files.json" $inventory - foreach ($expected in $Install.Seeded) { - $model = @($script:Assets | Where-Object { $expected.path -eq "models\kokoro\v1.1-en-zh\$($_.FileName)" }).Count -gt 0 - $actual = @($inventory | Where-Object { $_.path -eq $expected.path }) - if ($Removed -and $model) { - if ($actual.Count) { throw "Selected model retained: $($expected.path)" } - } elseif ($actual.Count -ne 1 -or $actual[0].sha256 -ne $expected.sha256 -or $actual[0].bytes -ne $expected.bytes) { - throw "Retained file changed or disappeared: $($expected.path)" - } - } -} -function Install-FullPayload([string]$Installer, [string]$Label, [switch]$Dev, $Previous) { - $name = if ($Dev) { 'OpenClawTray-Dev' } else { 'OpenClawTray' } - $root = Join-Path $env:LOCALAPPDATA $name - $profile = Join-Path $env:APPDATA $name - Assert-OrdinaryPath $root - if (Test-Path -LiteralPath $root) { - # Only this run's proven keep-uninstall permits reinstallation. No removal - # of leftovers to make an installation appear clean. - if (-not $Previous -or $Previous.Root -ine $root -or -not $Previous.Uninstalled) { throw 'Install directory already exists.' } - if (@(Get-Inventory $root).Count) { throw 'Unexpected installed files remain before candidate reinstall.' } - } - if (@(Get-RelatedRegistrations | Where-Object { - $_.Values.PSObject.Properties['InstallLocation'] -and $_.Values.InstallLocation.TrimEnd('\') -ieq $root - }).Count) { throw 'Target uninstall registration already exists.' } - $log = Join-Path $script:WorkDirectory "$Label-install.log" - $run = Start-OwnedProcess $Installer @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-', '/TASKS=', "/LOG=$log") "install-$Label" - $code = Wait-ProcessExit $run $script:InstallSeconds - if ($code -ne 0) { throw "Installer exited $code. See $log. No retry or adoption attempted." } - $expectedIdentity = if ($Dev) { 'dev' } else { 'release' } - foreach ($relative in @('app-identity.txt', 'OpenClaw.Tray.WinUI.exe', 'OpenClaw.Tray.WinUI.dll', - 'OpenClaw.Tray.WinUI.deps.json', 'OpenClaw.Tray.WinUI.runtimeconfig.json', 'Microsoft.UI.Xaml.dll')) { - $path = Join-Path $root $relative - Assert-OrdinaryPath $path - if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Full production-shaped payload missing: $relative" } - } - if ((Get-Content -LiteralPath (Join-Path $root 'app-identity.txt') -Raw).Trim() -cne $expectedIdentity) { throw 'Installed identity mismatch.' } - $appAssembly = [Reflection.AssemblyName]::GetAssemblyName((Join-Path $root 'OpenClaw.Tray.WinUI.dll')) - if ($appAssembly.Name -ne 'OpenClaw.Tray.WinUI') { throw 'Invalid Companion assembly; stub payload refused.' } - $entries = @(Get-RelatedRegistrations | Where-Object { - $_.Values.PSObject.Properties['InstallLocation'] -and $_.Values.InstallLocation.TrimEnd('\') -ieq $root - }) - if ($entries.Count -ne 1) { throw 'Could not bind one exact installed Inno uninstall registration.' } - $command = [string]$entries[0].Values.UninstallString - # Accept exactly a path, optionally surrounded by one matched quote pair. No - # arguments, shell expansion, registry command execution or guessed fallback. - $uninstaller = $command - if ($command.StartsWith('"') -and $command.EndsWith('"')) { $uninstaller = $command.Substring(1, $command.Length - 2) } - if ($uninstaller.Contains('"') -or [IO.Path]::GetFileName($uninstaller) -notmatch '^unins[0-9]+\.exe$') { - throw "Uncertain uninstaller command refused: $command" - } - if ([IO.Path]::GetDirectoryName($uninstaller) -ine $root) { throw 'Uninstaller is outside the verified install root.' } - Assert-OrdinaryPath $uninstaller - if ($Dev) { - foreach ($relative in @('Uninstall-DownloadedModels.ps1', 'KokoroDownloadCatalog.cs', 'KokoroUninstallFiles.cs')) { - $source = if ($relative -like '*.cs') { Join-Path $PSScriptRoot "..\src\OpenClaw.Shared\Audio\$relative" } else { Join-Path $PSScriptRoot $relative } - if ((Get-Digest (Join-Path $root $relative)) -ne (Get-Digest $source)) { throw "Installed helper differs from current source: $relative" } - } - } - $payload = @(Get-Inventory $root) - Write-Json "$Label-installed-files.json" $payload - if (@(Get-CimInstance Win32_Process -OperationTimeoutSec $script:CimSeconds | Where-Object { - $_.ExecutablePath -ieq (Join-Path $root 'OpenClaw.Tray.WinUI.exe') - }).Count) { throw 'Silent installation unexpectedly launched Companion.' } - return [pscustomobject]@{ - Label = $Label; Root = $root; Profile = $profile; Uninstaller = $uninstaller - UninstallerHash = Get-Digest $uninstaller; RegistryKey = $entries[0].Key; Seeded = @() - Uninstalled = $false; Payload = $payload; AssemblyVersion = $appAssembly.Version.ToString() - ProductVersion = (Get-Item -LiteralPath (Join-Path $root 'OpenClaw.Tray.WinUI.exe')).VersionInfo.ProductVersion - } -} -function Start-Uninstall($Install, [string]$Scenario) { - if ((Get-Digest $Install.Uninstaller) -ne $Install.UninstallerHash) { throw 'Installed uninstaller changed.' } - # NEVER /SILENT or /VERYSILENT: real silent uninstall defaults Gateway cleanup - # to destructive removal. Every interactive Gateway choice below is No. - return Start-OwnedProcess $Install.Uninstaller @('/NORESTART', "/LOG=$(Join-Path $script:WorkDirectory "$Scenario-uninstall.log")") $Scenario -Uninstaller -} -function Wait-ModelDialog($Run) { - return Wait-Window $Run { param($w) - $w.Current.Name -eq 'Downloaded voice models' -and - $null -ne (Find-Control $w 'Check downloaded models' ([Windows.Automation.ControlType]::Button)) - } 'actual Downloaded voice models choice dialog' -} -function Assert-ReportedBytes([string]$Text, [string]$Label, [long]$Expected) { - $match = [regex]::Match($Text, [regex]::Escape($Label) + '\s*([0-9, .\u00a0\u202f]+) bytes') - if (-not $match.Success -or [long]($match.Groups[1].Value -replace '[^0-9]', '') -ne $Expected) { - throw "UI measured total differs from independently seeded bytes: $Label" - } -} -function Check-Models($Run, [string]$CaptureName) { - $window = Wait-ModelDialog $Run - $box = Find-Control $window 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) - if (-not $box -or $box.Current.IsEnabled -or - $box.GetCurrentPattern([Windows.Automation.TogglePattern]::Pattern).Current.ToggleState -ne [Windows.Automation.ToggleState]::Off) { - throw 'Removal must initially be disabled and unchecked.' - } - Invoke-Control $Run $window 'Check downloaded models' - $window = Wait-Window $Run { param($w) - if ($w.Current.Name -ne 'Downloaded voice models') { return $false } - $choice = Find-Control $w 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) - $continue = Find-Control $w 'Continue uninstall' ([Windows.Automation.ControlType]::Button) - if (-not $choice -or -not $choice.Current.IsEnabled -or -not $continue -or -not $continue.Current.IsEnabled) { return $false } - return (Get-WindowText $w) -match 'Verified downloads available for selection:' - } 'completed catalog scan and enabled unchecked selection' - $box = Find-Control $window 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) - if ($box.GetCurrentPattern([Windows.Automation.TogglePattern]::Pattern).Current.ToggleState -ne [Windows.Automation.ToggleState]::Off) { - throw 'Model scan selected destructive removal automatically.' - } - $text = Get-WindowText $window - Assert-ReportedBytes $text 'Verified downloads available for selection:' $script:ExpectedBytes - Assert-ReportedBytes $text 'Measured retained catalog files:' $script:ExpectedBytes - foreach ($asset in $script:Assets) { if (-not $text.Contains($asset.FileName)) { throw 'Measured file missing from model UI.' } } - Save-Window $Run $window $CaptureName - Hold-RecordedState $Run $window - return $window -} -function Complete-Uninstall($Install, $Run, [string]$Scenario, [switch]$Before, [switch]$RemoveModels) { - $state = @{ Confirmed = $false; Gateway = 'not encountered'; Summary = $false; Seen = @{} } - $null = Wait-Condition "$Scenario real uninstall completion" { - foreach ($window in @(Get-OwnedWindows $Run)) { - $text = Get-WindowText $window - $key = "$($window.Current.NativeWindowHandle):$text" - if ($state.Seen.ContainsKey($key)) { continue } - $button = [Windows.Automation.ControlType]::Button - if ($text -match 'Do you also want to remove the OpenClaw local WSL gateway\?') { - Save-Window $Run $window "$Scenario-gateway-keep" - Invoke-Control $Run $window 'No' - $state.Gateway = 'No'; $state.Seen[$key] = $true - } elseif ($text -match 'Are you sure you want to completely remove') { - if ($Before) { Save-Window $Run $window 'before' } - Invoke-Control $Run $window 'Yes' - $state.Confirmed = $true; $state.Seen[$key] = $true - } elseif ($window.Current.Name -eq 'Downloaded voice models' -and - $null -ne (Find-Control $window 'Close' $button)) { - if ($Before) { throw 'Baseline already contains the changed model dialog. Use a pre-change release.' } - if ($RemoveModels) { Assert-ReportedBytes $text 'Removed model file bytes:' $script:ExpectedBytes } - elseif ($text -notmatch 'No model removal was requested') { throw 'Keep summary does not confirm no model removal.' } - Save-Window $Run $window "$Scenario-summary" - Hold-RecordedState $Run $window - Invoke-Control $Run $window 'Close' - $state.Summary = $true; $state.Seen[$key] = $true - } elseif ($text -match '(?s)(could not (confirm whether your OpenClaw data was migrated|check whether OpenClaw from the Microsoft Store)|OpenClaw from the Microsoft Store is installed).*gateway.*(left in place|preserv)') { - Save-Window $Run $window "$Scenario-gateway-preserved-warning" - Invoke-Control $Run $window 'OK' - $state.Gateway = 'preserved by installer warning'; $state.Seen[$key] = $true - } elseif ($text -match 'successfully removed from your computer') { - Invoke-Control $Run $window 'OK'; $state.Seen[$key] = $true - } - # Unknown dialogs are never clicked; timeout retains the failed receipt. - } - return @($Run.Nodes.Values | Where-Object { -not $_.Process.HasExited }).Count -eq 0 - } - if (-not $state.Confirmed -or (-not $Before -and -not $state.Summary)) { throw 'Required confirmation/summary not observed.' } - if ($state.Gateway -eq 'not encountered') { throw 'Gateway preservation not confirmed by real UI.' } - if (Test-Path -LiteralPath $Install.RegistryKey) { throw 'Uninstall registration remains.' } - if (Test-Path -LiteralPath (Join-Path $Install.Root 'OpenClaw.Tray.WinUI.exe')) { throw 'Companion payload remains after uninstall.' } - foreach ($node in $Run.Nodes.Values | Where-Object UiAllowed) { - if ($node.Process.ExitCode -ne 0) { throw "Uninstaller PID $($node.Id) exited $($node.Process.ExitCode)." } - } - $Install.Uninstalled = $true - Assert-Profile $Install -Removed:$RemoveModels -Scenario $Scenario - $script:Proof.scenarios.Add(@{ - name = $Scenario; outcome = 'passed'; gateway = $state.Gateway; modelBytes = $script:ExpectedBytes - models = $(if ($RemoveModels) { 'removed' } else { 'retained, hashes unchanged' }) - uninstallerSha256 = $Install.UninstallerHash; install = $Install.Root; profile = $Install.Profile - processes = @($Run.Nodes.Values | ForEach-Object { @{ id = $_.Id; parent = $_.ParentId; path = $_.Path; startUtc = $_.StartUtc; uiAllowed = $_.UiAllowed } }) - }) - Save-Proof -} - -$outputReady = $false -try { - Assert-OrdinaryPath $OutputDirectory - $OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) - if (Test-Path -LiteralPath $OutputDirectory) { throw 'OutputDirectory must not exist. Preserve earlier evidence; choose a new directory.' } - foreach ($path in @($BeforeInstaller, $AfterInstaller)) { - Assert-OrdinaryPath $path - if (-not (Test-Path -LiteralPath $path -PathType Leaf) -or [IO.Path]::GetExtension($path) -ine '.exe') { throw 'Supply exact full Inno EXE paths.' } - } - $BeforeInstaller = (Resolve-Path -LiteralPath $BeforeInstaller).Path - $AfterInstaller = (Resolve-Path -LiteralPath $AfterInstaller).Path - if ($BeforeInstaller -ieq $AfterInstaller -or (Get-Digest $BeforeInstaller) -eq (Get-Digest $AfterInstaller)) { throw 'Before and after installers must differ.' } - $null = New-Item -ItemType Directory -Path $OutputDirectory - $outputReady = $true - # Task-owned non-public inputs/logs stay outside the media artifact directory. - # Only PNG/MP4 and sanitized JSON evidence are suitable for artifact delivery. - $script:WorkDirectory = Join-Path ([IO.Path]::GetTempPath()) ("openclaw-inno-media-" + [Guid]::NewGuid().ToString('N')) - Assert-OrdinaryPath $script:WorkDirectory - $null = New-Item -ItemType Directory -Path $script:WorkDirectory - $script:Proof.diagnosticsDirectory = $script:WorkDirectory - $script:Proof.before = @{ installer = $BeforeInstaller; sha256 = Get-Digest $BeforeInstaller; sourceRevision = $BeforeSourceRevision; buildIdentity = $BeforeBuildIdentity; releaseUrl = $BeforeReleaseUrl; provenance = 'caller-supplied release/source attribution; actual hash recorded' } - $script:Proof.after = @{ installer = $AfterInstaller; sha256 = Get-Digest $AfterInstaller; sourceRevision = $AfterSourceRevision; buildIdentity = $AfterBuildIdentity; identity = 'full locally built unsigned Dev installer' } - $git = (Get-Command git -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source - $head = (Invoke-Native $git @('-C', (Join-Path $PSScriptRoot '..'), 'rev-parse', 'HEAD') 'source-revision').Trim() - if ($head -cne $AfterSourceRevision.ToLowerInvariant()) { throw 'AfterSourceRevision does not match capture checkout.' } - $script:Proof.captureScriptSha256 = Get-Digest $PSCommandPath - # Discover WinApp before native inspection. UIA is retained for Inno self-copy - # lifetime ownership; never invent version-specific WinApp selectors or flags. - $winapp = Get-Command winapp -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($winapp) { - $script:Proof.tools.winapp = (Invoke-Native $winapp.Source @('--version') 'winapp-version').Trim() - $schema = Invoke-Native $winapp.Source @('--cli-schema') 'winapp-schema' - $schema | Set-Content -LiteralPath (Join-Path $OutputDirectory 'winapp-cli-schema.json') - $script:Proof.tools.ui = 'WinApp discovered; process-bound UIAutomation for Inno self-copy windows; ffmpeg live desktop.' - } else { - $script:Proof.tools.winapp = 'absent; no installation attempted' - $script:Proof.tools.ui = 'UIAutomationClient/InvokePattern scoped to Inno descendants; CopyFromScreen window crop.' - } - Save-Proof - $script:Ffmpeg = (Get-Command ffmpeg -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source - $script:Ffprobe = (Get-Command ffprobe -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source - $script:Proof.tools.ffmpeg = (Invoke-Native $script:Ffmpeg @('-version') 'ffmpeg-version').Split("`n")[0] - $gatewayBefore = Assert-FreshHost - Write-Json 'gateway-before.json' $gatewayBefore - Initialize-Desktop - Get-OfficialAssets - Save-Proof - - $baseline = Install-FullPayload $BeforeInstaller 'before' - Seed-Profile $baseline - $script:Proof.before.installedProductVersion = $baseline.ProductVersion - $script:Proof.before.installedAssemblyVersion = $baseline.AssemblyVersion - $run = Start-Uninstall $baseline 'before-keep' - Complete-Uninstall $baseline $run 'before-keep' -Before - - $candidate = Install-FullPayload $AfterInstaller 'after' -Dev - Seed-Profile $candidate - $script:Proof.after.installedProductVersion = $candidate.ProductVersion - $script:Proof.after.installedAssemblyVersion = $candidate.AssemblyVersion - - # Cancel after a completed read-only preview. Do not claim this tests the - # separate in-flight scan-cancellation race. - $run = Start-Uninstall $candidate 'after-cancel' - $window = Wait-ModelDialog $run - Start-Recording 'after-cancel' - $window = Check-Models $run 'after' - Invoke-Control $run $window 'Cancel' - $null = Wait-ProcessExit $run $script:StepSeconds - Stop-Recording - if (-not (Test-Path -LiteralPath $candidate.RegistryKey) -or - (Get-Digest $candidate.Uninstaller) -ne $candidate.UninstallerHash) { throw 'Cancel changed the installed application.' } - $cancelPayload = @(Get-Inventory $candidate.Root) - Write-Json 'after-cancel-installed-files.json' $cancelPayload - if (($candidate.Payload | ConvertTo-Json -Depth 4 -Compress) -cne ($cancelPayload | ConvertTo-Json -Depth 4 -Compress)) { - throw 'Cancel changed installed payload files.' - } - Assert-Profile $candidate -Scenario 'after-cancel' - $script:Proof.scenarios.Add(@{ name = 'after-cancel'; outcome = 'passed'; models = 'retained, hashes unchanged'; application = 'retained'; boundary = 'Cancel after completed preview; not mid-scan cancellation' }) - Save-Proof - - $run = Start-Uninstall $candidate 'after-keep' - $window = Wait-ModelDialog $run - Start-Recording 'after-keep' - $window = Check-Models $run 'after-keep-preview' - Invoke-Control $run $window 'Continue uninstall' - Complete-Uninstall $candidate $run 'after-keep' - Stop-Recording - - $reinstalled = Install-FullPayload $AfterInstaller 'after-reinstall' -Dev -Previous $candidate - $reinstalled.Seeded = $candidate.Seeded - Assert-Profile $reinstalled -Scenario 'after-reinstall' - $run = Start-Uninstall $reinstalled 'after-remove' - $window = Wait-ModelDialog $run - Start-Recording 'after-remove' - $window = Check-Models $run 'after-remove-preview' - Invoke-Control $run $window 'Remove the verified Kokoro downloads listed below' -Toggle - $window = Wait-Window $run { param($w) - $box = Find-Control $w 'Remove the verified Kokoro downloads listed below' ([Windows.Automation.ControlType]::CheckBox) - return $box -and $box.GetCurrentPattern([Windows.Automation.TogglePattern]::Pattern).Current.ToggleState -eq [Windows.Automation.ToggleState]::On - } 'explicitly checked model removal' - Save-Window $run $window 'after-remove-selected' - Hold-RecordedState $run $window - Invoke-Control $run $window 'Continue uninstall' - Complete-Uninstall $reinstalled $run 'after-remove' -RemoveModels - Stop-Recording - - Assert-Profile $baseline -Scenario 'before-final-preservation' - $gatewayAfter = Get-GatewayInventory - Write-Json 'gateway-after.json' $gatewayAfter - if (($gatewayBefore | ConvertTo-Json -Depth 6 -Compress) -cne ($gatewayAfter | ConvertTo-Json -Depth 6 -Compress)) { - throw 'Gateway/WSL package inventory changed.' - } - $null = Wait-Condition 'owned UI actions to return' { @($script:Actions | Where-Object { -not $_.Done }).Count -eq 0 } $script:StopSeconds - foreach ($required in @('before.png', 'after.png', 'after-remove.mp4', 'after-remove-summary.png')) { - if (-not (Test-Path -LiteralPath (Join-Path $OutputDirectory $required))) { throw "Required evidence missing: $required" } - } - $script:Proof.status = 'passed; media requires visual review' -} catch { - $script:Proof.status = 'failed' - $script:Proof.failure = $_.Exception.Message - throw -} finally { - if ($script:Recording) { - try { Stop-Recording } catch { $script:Proof.cleanup += "Recording incomplete: $($_.Exception.Message)" } - } - # No blanket name-based stopping, recursive profile deletion, WSL unregister, - # or silent uninstall. Preserve leftovers for diagnosis and CI host disposal. - foreach ($run in $script:Runs) { - foreach ($node in @($run.Nodes.Values | Sort-Object StartUtc -Descending)) { - try { - if ($node.Process.HasExited) { continue } - $live = Get-Process -Id $node.Id -ErrorAction SilentlyContinue - if (-not $live -or $live.StartTime.ToUniversalTime() -ne $node.StartUtc -or $live.Path -ine $node.Path) { - $script:Proof.cleanup += "PID $($node.Id) no longer provably owned; not stopped."; continue - } - if ($live.ProcessName -match '^(wsl|wslhost|node|OpenClaw\.Tray\.WinUI|openclaw-wsl-keepalive|llama-server)$') { - $script:Proof.cleanup += "Protected process $($node.Id) left untouched; host disposal required."; continue - } - $live.Kill() - if (-not $live.WaitForExit($script:StopSeconds * 1000)) { throw 'Owned process stop unconfirmed.' } - $script:Proof.cleanup += "Stopped owned $($run.Purpose) PID $($node.Id)." - } catch { $script:Proof.cleanup += "Owned-process cleanup incomplete: $($_.Exception.Message)" } - } - } - if ($outputReady) { - $script:Proof.completedUtc = [DateTime]::UtcNow.ToString('o') - $script:Proof.artifacts = @(Get-ChildItem -LiteralPath $OutputDirectory -File | Where-Object Name -ne 'proof.json' | - Sort-Object Name | ForEach-Object { @{ file = $_.Name; bytes = $_.Length; sha256 = Get-Digest $_.FullName } }) - Save-Proof - } -} -Write-Host "Capture finished. Inspect before.png, after.png, after-remove.mp4 and proof.json in $OutputDirectory. CI host disposal is the cleanup boundary."