diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e1e338..b1c9c56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ Notable changes to Wisp are recorded here. +## 2.7.8 - 2026-12-01 + +- Reading the current car’s tune works again on Forza Horizon 6 build 3.498.592.0 (Xbox app / Microsoft Store). +- When Wisp cannot verify the Tune reader for a game build, it checks for a compatibility update without waiting for the next scheduled check. +- The HUD recovers when Windows restarts desktop composition while a frame is being shown. +- Recording starts on graphics cards that change the video output format before the first encoded frame. +- A recorder failure is reported with its original cause when the recorder closes during a request. +- Starting the update helper by itself no longer replaces the result of an installation that is waiting to be reported. + ## 2.7.7 - 2026-11-26 - Winter mode is on by default. Ice-blue snowflakes fall and fade behind the dashboard readouts. Turn Winter mode off in Extras to return to wisps. diff --git a/LICENSES/library-sources-distribution.json b/LICENSES/library-sources-distribution.json index d234e81..71f1c92 100644 --- a/LICENSES/library-sources-distribution.json +++ b/LICENSES/library-sources-distribution.json @@ -1,8 +1,8 @@ { "schemaVersion": 1, - "version": "2.7.7", + "version": "2.7.8", "archive": { - "filename": "Wisp-2.7.7-library-sources.zip", + "filename": "Wisp-2.7.8-library-sources.zip", "sourceVersion": "2.6.8", "url": "https://github.com/Views2k/Wisp/releases/download/library-sources-2.6.8/Wisp-2.6.8-library-sources.zip", "bytes": 879043478, diff --git a/README.md b/README.md index 936ed49..a4aedfd 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ Wisp 2.7 is a reliability update. Clips keep recording when the graphics card is [Clips](#clips) · [Tune](#tune) · [Lap review](#lap-review) · [Live map and lap delta](#live-map-and-lap-delta) · [Install](#install) · [2.7 release notes](docs/releases/Wisp-2.7.0-release-notes.md) +### Wisp 2.7.8 + +Wisp 2.7.8 restores Tune readings on the current Xbox app build of Forza Horizon 6 and fixes HUD, Clips and update errors reported from 2.7.7. See the [2.7.8 release notes](docs/releases/Wisp-2.7.8-release-notes.md). + ### Wisp 2.7.7 Wisp 2.7.7 adds falling snow to the dashboard and checks Drift Zone scoring curves on newer Forza Horizon 6 builds. See the [2.7.7 release notes](docs/releases/Wisp-2.7.7-release-notes.md). diff --git a/docs/adaptive-game-compatibility.md b/docs/adaptive-game-compatibility.md index e1226e3..a547217 100644 --- a/docs/adaptive-game-compatibility.md +++ b/docs/adaptive-game-compatibility.md @@ -20,6 +20,10 @@ Both platforms require typed code witnesses for all 18 direct-gauge fields. Stea The field reader code carries the game's thread-local storage slot offset as an immediate operand (`mov edx, imm32` after the `gs:[0x58]` access). That offset is recompiled per build: 0x420 through 6.461.691.0 and 3.461.691.0, 0x42C from 6.483.970.0 and 3.483.970.0, where it rejected the direct gauge on every PC. The type function template and the 18 initializer templates declare it as a `threadLocalSlot` operand: it is masked like an address operand, it has no target, and every matched reader must carry the same 4-byte-aligned value below 64 KB. Getters do not contain it, and their member displacements are still compared byte for byte. +Three Store Tune guards pass a one-byte enumeration member to a call (`mov dl, imm8` before an indirect call). A game update that adds a member renumbers every member after it and changes nothing else in the guard: Store 3.498.592.0 moved all 30 such bytes up by one, which rejected Tune on that build while the HUD and the direct gauge kept working. The profile declares these bytes as `enumArgument` operands with their reference value. They are masked like an address operand and have no target. Every guard must agree on the value found for each reference value, the values must keep their order, and none may move by more than 8. A different opcode, member offset or constant beside the argument is still rejected. The Steam guards contain no such call. + +The same update renumbered a member that three other Store templates pass the same way: two of the four identity anchors of the HUD's UI service table, which left that table at its minimum of two matching anchors, and one binding of the direct gauge's child table, which fell back to its alternative. These four bytes are declared as `enumArgument` operands too. A template whose argument is outside the limit, or differs from the value already found for the same member, counts as changed: an optional anchor or an alternative binding is passed over, and a required guard is rejected. + A reference that two templates share may reach its target through a single 5-byte jump thunk on one side and directly on the other (Store 3.483.970.0 routes one Tune guard's call to a helper that the gauge templates call directly through such a thunk). Both shared-reference checks accept exactly that case and keep the helper itself; the thunk bytes join the proof. Any other disagreement between shared references is still rejected. Steam's secondary HUD table is linked to the already verified main HUD table through the same complete-object RTTI type and hierarchy. Its subobject offset, full inheritance topology and slot code must still match, and the candidate must be unique. Table spacing and numeric RTTI labels are not treated as stable identities. This relationship was checked in both retained versions of both platforms. @@ -60,6 +64,8 @@ Successful results retain addresses and small evidence hashes, not a full image ## Evidence and remaining validation +For a Tune compatibility fix, park the affected car with Forza in the foreground. Run `Wisp.UiReview.exe --tune-live-check --output artifacts/tune-check --expect-game-version ` from the checkout, using a fresh output directory and the exact four-part version from the affected installation. The report records the version from each capture and requires two complete, consistent reads of the current setup. Compare the reported values with the fitted settings in the game's Tune menu, using the same units. Record the platform, game version and result with the release evidence. + Reference profiles were generated from Steam 6.440.853.0 and Store 3.440.853.0. Production discovery was exercised against retained images from Steam 6.461.691.0 and Store 3.461.691.0 without supplying the new address maps to discovery. The new maps were used only as the result oracle. - Steam: all 115 core, Tune and direct-gauge roles matched the independently established new map in a replay combining the retained image with 8,206 bytes of accepted live field evidence. Only the captured absolute type-slot pointer was rebased; code and property names were unchanged. diff --git a/docs/releases/Wisp-2.7.8-release-notes.md b/docs/releases/Wisp-2.7.8-release-notes.md new file mode 100644 index 0000000..89f290d --- /dev/null +++ b/docs/releases/Wisp-2.7.8-release-notes.md @@ -0,0 +1,23 @@ +# Wisp 2.7.8 + +Wisp 2.7.8 restores Tune readings on the current Xbox app build of Forza Horizon 6 and fixes HUD, Clips and update errors reported from 2.7.7. + +[Download the latest Wisp release for Windows](https://github.com/Views2k/Wisp/releases/latest) + +## Tune + +- Reading the current car’s tune works again on Forza Horizon 6 build 3.498.592.0 (Xbox app / Microsoft Store). +- When Wisp cannot verify the Tune reader for a game build, it checks for a compatibility update without waiting for the next scheduled check. + +## HUD + +- The HUD recovers when Windows restarts desktop composition while a frame is being shown. + +## Clips + +- Recording starts on graphics cards that change the video output format before the first encoded frame. +- A recorder failure is reported with its original cause when the recorder closes during a request. + +## Updates + +- Starting the update helper by itself no longer replaces the result of an installation that is waiting to be reported. diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index b8457eb..b5fa569 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -296,46 +296,6 @@ function Invoke-UpdaterGuardSmoke { [System.IO.Directory]::CreateDirectory($smokeDirectory) | Out-Null $smokeUpdaterPath = Join-Path $smokeDirectory 'Wisp.Updater.exe' - $backupPath = Join-Path $smokeDirectory 'previous-update-result.bin' - $localApplicationData = [Environment]::GetFolderPath( - [Environment+SpecialFolder]::LocalApplicationData) - if ([string]::IsNullOrWhiteSpace($localApplicationData)) { - throw 'The local application-data directory is unavailable for the updater smoke test.' - } - $resultDirectory = Join-Path $localApplicationData 'Wisp' - $resultPath = Join-Path $resultDirectory 'update-result.json' - $resultDirectoryExisted = Test-Path -LiteralPath $resultDirectory -PathType Container - if (Test-Path -LiteralPath $resultDirectory) { - $resultDirectoryItem = Get-Item -LiteralPath $resultDirectory -Force - if (-not $resultDirectoryItem.PSIsContainer -or - ($resultDirectoryItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { - throw 'The updater diagnostic directory is not a regular local directory.' - } - } - - $hadResult = Test-Path -LiteralPath $resultPath -PathType Leaf - if ((Test-Path -LiteralPath $resultPath) -and -not $hadResult) { - throw 'The updater diagnostic path is not a regular file.' - } - $previousHash = $null - $previousAttributes = $null - $previousCreationTime = $null - $previousWriteTime = $null - if ($hadResult) { - $resultItem = Get-Item -LiteralPath $resultPath -Force - if (($resultItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { - throw 'The updater diagnostic file must not be a symbolic link.' - } - $previousHash = (Get-FileHash -LiteralPath $resultPath -Algorithm SHA256).Hash - $previousAttributes = $resultItem.Attributes - $previousCreationTime = $resultItem.CreationTimeUtc - $previousWriteTime = $resultItem.LastWriteTimeUtc - [System.IO.File]::Copy($resultPath, $backupPath, $false) - if ((Get-FileHash -LiteralPath $backupPath -Algorithm SHA256).Hash -ne $previousHash) { - throw 'The existing updater diagnostic could not be backed up for the smoke test.' - } - } - try { [System.IO.File]::Copy($UpdaterPath, $smokeUpdaterPath, $false) if ((Get-FileHash -LiteralPath $smokeUpdaterPath -Algorithm SHA256).Hash -ne @@ -348,6 +308,7 @@ function Invoke-UpdaterGuardSmoke { $startInfo.Arguments = '--packaging-smoke' $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $true + $startInfo.RedirectStandardError = $true $process = [System.Diagnostics.Process]::Start($startInfo) if ($null -eq $process) { throw 'The staged update helper did not start for its guard smoke test.' @@ -361,50 +322,18 @@ function Invoke-UpdaterGuardSmoke { if ($process.ExitCode -ne 2) { throw "The staged update helper returned unexpected guard exit code $($process.ExitCode)." } + if ($process.StandardError.ReadToEnd().Trim() -cne 'UPDATE_ARGUMENTS') { + throw 'The staged update helper returned an unexpected guard diagnostic.' + } } finally { $process.Dispose() } - - if (Test-Path -LiteralPath $resultPath -PathType Leaf) { - $diagnostic = ConvertFrom-Json ` - -InputObject ([System.IO.File]::ReadAllText($resultPath)) ` - -ErrorAction Stop - if ($diagnostic.schemaVersion -ne 1 -or $diagnostic.state -cne 'failed' -or - $diagnostic.sourceVersion -cne '' -or $diagnostic.targetVersion -cne '' -or - $diagnostic.errorCode -cne 'UPDATE_ARGUMENTS' -or - $diagnostic.message -cne 'The update helper received invalid arguments.') { - throw 'The staged update helper wrote an unexpected guard diagnostic.' - } - } - else { - throw 'The staged update helper wrote no guard diagnostic.' - } } finally { - if ($hadResult) { - [System.IO.File]::Copy($backupPath, $resultPath, $true) - [System.IO.File]::SetCreationTimeUtc($resultPath, $previousCreationTime) - [System.IO.File]::SetLastWriteTimeUtc($resultPath, $previousWriteTime) - [System.IO.File]::SetAttributes($resultPath, $previousAttributes) - if ((Get-FileHash -LiteralPath $resultPath -Algorithm SHA256).Hash -ne $previousHash) { - throw 'The updater diagnostic was not restored after the smoke test.' - } - } - elseif (Test-Path -LiteralPath $resultPath -PathType Leaf) { - [System.IO.File]::Delete($resultPath) - } - - if (-not $resultDirectoryExisted -and (Test-Path -LiteralPath $resultDirectory -PathType Container) -and - [System.IO.Directory]::GetFileSystemEntries($resultDirectory).Length -eq 0) { - [System.IO.Directory]::Delete($resultDirectory, $false) - } if (Test-Path -LiteralPath $smokeUpdaterPath -PathType Leaf) { [System.IO.File]::Delete($smokeUpdaterPath) } - if (Test-Path -LiteralPath $backupPath -PathType Leaf) { - [System.IO.File]::Delete($backupPath) - } if ((Test-Path -LiteralPath $smokeDirectory -PathType Container) -and [System.IO.Directory]::GetFileSystemEntries($smokeDirectory).Length -eq 0) { [System.IO.Directory]::Delete($smokeDirectory, $false) diff --git a/installer/Wisp.iss b/installer/Wisp.iss index 4e7ef21..86ad4d6 100644 --- a/installer/Wisp.iss +++ b/installer/Wisp.iss @@ -1,5 +1,5 @@ #define MyAppName "Wisp" -#define MyAppVersion "2.7.7" +#define MyAppVersion "2.7.8" #define MyAppDisplayVersion MyAppVersion #define MyAppOutputVersion MyAppVersion #define MyAppPublisher "Wisp" diff --git a/src/Wisp.App/AppController.Tunes.cs b/src/Wisp.App/AppController.Tunes.cs index 58f8244..94c2396 100644 --- a/src/Wisp.App/AppController.Tunes.cs +++ b/src/Wisp.App/AppController.Tunes.cs @@ -45,6 +45,17 @@ private async Task CaptureTuneAsync(CancellationToken token) var result = _tuneCapture is { } capture ? await capture.RequestSnapshotAsync(token) : new TuneCaptureResult(null, TuneCaptureStatus.Unavailable, "Current-car reading is unavailable in this preview. Saved tunes can still be opened."); + if (_tuneCapture is not null && _compatibilityUpdates.IsConfigured) + { + void ObserveCapture() + { + if (!_disposed && !token.IsCancellationRequested) + _compatibilitySchedule.ObserveTuneCapture(result); + } + + if (_dispatcher.CheckAccess()) ObserveCapture(); + else if (!_dispatcher.HasShutdownStarted) _ = _dispatcher.InvokeAsync(ObserveCapture); + } var outcome = _tuneCapture is null || result.Incident?.Reason == "not_ready" ? "idle" : result.Success && result.Snapshot is { IsComplete: true } ? "success" : result.Success ? "unknown" : result.Status switch { diff --git a/src/Wisp.App/ApplicationUpdateLauncher.cs b/src/Wisp.App/ApplicationUpdateLauncher.cs index 9d4997e..55bca70 100644 --- a/src/Wisp.App/ApplicationUpdateLauncher.cs +++ b/src/Wisp.App/ApplicationUpdateLauncher.cs @@ -325,6 +325,10 @@ internal static bool TryConsumeResult( return false; } + // Older helpers also left a result when launched independently without an apply request. + if (record is { State: "failed", ErrorCode: "UPDATE_ARGUMENTS", SourceVersion: null, TargetVersion: null }) + return false; + if (record.State == "installed" && record.TargetVersion is { } targetVersion) { var startedTarget = targetVersion == ApplicationVersionInfo.MachineVersion; diff --git a/src/Wisp.App/Clips/RecorderProcessClient.cs b/src/Wisp.App/Clips/RecorderProcessClient.cs index d656ee6..32d88db 100644 --- a/src/Wisp.App/Clips/RecorderProcessClient.cs +++ b/src/Wisp.App/Clips/RecorderProcessClient.cs @@ -212,7 +212,10 @@ internal sealed class RecorderProcessClient : IAsyncDisposable private readonly object _sync = new(); private IRecorderChild? _child; private Task? _output, _error, _exitReport; - private readonly Dictionary> _pending = new(); + // A pipe write or a cancelled wait can end the sender before it receives this completion. + // Only the sending operation throws. The private reply task can always be safely abandoned. + private readonly record struct CommandResult(RecorderReply? Reply, string? Failure = null); + private readonly Dictionary> _pending = new(); private long _nextRequest, _stopRequest; private bool _stopping, _configured; // A save, including its library copy, keeps the private buffer open until it ends. @@ -410,7 +413,7 @@ private async Task SendAsync(string command, Dictionary pending; + TaskCompletionSource pending; IRecorderChild child; long request; lock (_sync) @@ -431,11 +434,16 @@ private async Task SendAsync(string command, Dictionary? pending; + TaskCompletionSource? pending; lock (_sync) { if (!_pending.Remove(reply.Request, out pending)) throw new RecorderClientException("protocol_error"); } - pending.TrySetResult(reply); + pending.TrySetResult(new(reply)); } lock (_sync) { @@ -504,7 +512,7 @@ private async Task ReadOutputAsync(Stream output) // The helper ended after a stop request without answering it: the stop is done. if (_stopping && _pending.Count == 1 && _pending.Remove(_stopRequest, out var stop)) { - stop.TrySetResult(new(_stopRequest, true, "none")); + stop.TrySetResult(new(new RecorderReply(_stopRequest, true, "none"))); return; } } @@ -605,7 +613,7 @@ private async Task ReportExitAsync() // Caller owns _sync. Continuations always run outside this lock. private void FailPending(string reason) { - foreach (var pending in _pending.Values) pending.TrySetException(new RecorderClientException(reason)); + foreach (var pending in _pending.Values) pending.TrySetResult(new(null, reason)); _pending.Clear(); } diff --git a/src/Wisp.App/NativeCompatibility/NativeAdaptiveResolver.cs b/src/Wisp.App/NativeCompatibility/NativeAdaptiveResolver.cs index dcd596a..8683bff 100644 --- a/src/Wisp.App/NativeCompatibility/NativeAdaptiveResolver.cs +++ b/src/Wisp.App/NativeCompatibility/NativeAdaptiveResolver.cs @@ -14,6 +14,12 @@ internal sealed class NativeAdaptiveResolver // like an address operand, but it has no target; every reader must carry the same value. internal const string ThreadLocalSlotKind = "threadLocalSlot"; internal const uint ThreadLocalSlotLimit = 0x10000; + // A one-byte enumeration member the game passes to a call. A game update that adds a member + // renumbers the members after it and changes nothing else in the reader (Store 3.498.592.0 + // moved 30 such bytes in three Tune guards up by one). The byte is masked, it has no target, + // and the values found must be a consistent, order-preserving renumbering of the reference. + internal const string EnumArgumentKind = "enumArgument"; + internal const int EnumArgumentShiftLimit = 8; private readonly NativeAdaptiveImage _image; private readonly JsonElement _profile; private readonly Dictionary _signatures; @@ -21,6 +27,7 @@ internal sealed class NativeAdaptiveResolver private readonly Dictionary _resolved = new(StringComparer.Ordinal); private readonly Dictionary _relationships = []; private readonly Dictionary _matched = new(StringComparer.Ordinal); + private readonly Dictionary _enumArguments = []; private readonly HashSet? _activePaths; private readonly HashSet? _capabilities; private readonly JsonElement? _gaugeFieldProfile; @@ -99,6 +106,7 @@ internal IReadOnlyDictionary Resolve() throw new InvalidDataException("Adaptive table changed: " + group.Key); ValidateFields(); ValidateRelationships(); + CheckEnumArguments(_enumArguments); return _resolved; } @@ -114,6 +122,7 @@ internal bool TryEnableCapability(string capability, out string reason) var resolved = _resolved.ToArray(); var relationships = _relationships.ToArray(); var matched = _matched.ToArray(); + var enumArguments = _enumArguments.ToArray(); var active = _activePaths.ToArray(); var proof = _image.SaveProof(); _capabilities.Add(capability); @@ -135,6 +144,8 @@ internal bool TryEnableCapability(string capability, out string reason) foreach (var entry in relationships) _relationships.Add(entry.Key, entry.Value); _matched.Clear(); foreach (var entry in matched) _matched.Add(entry.Key, entry.Value); + _enumArguments.Clear(); + foreach (var entry in enumArguments) _enumArguments.Add(entry.Key, entry.Value); _image.RestoreProof(proof); return false; } @@ -269,7 +280,7 @@ private bool Match(Signature signature, uint rva, bool remember) var normalized = bytes.ToArray(); foreach (var relocation in signature.Relocations) { - if (relocation.Kind == ThreadLocalSlotKind) + if (relocation.Kind is ThreadLocalSlotKind or EnumArgumentKind) { normalized.AsSpan(relocation.Offset, relocation.Width).Clear(); continue; @@ -282,6 +293,7 @@ private bool Match(Signature signature, uint rva, bool remember) normalized.AsSpan(relocation.Offset, relocation.Width).Clear(); } if (!CryptographicOperations.FixedTimeEquals(SHA256.HashData(normalized), signature.Hash)) return false; + if (!EnumArgumentsAgree(signature, bytes)) return false; if (remember) { _image.Remember(rva, bytes); @@ -290,11 +302,57 @@ private bool Match(Signature signature, uint rva, bool remember) _matched[signature.Id] = rva; BindRelationship(signature.ReferenceRva, rva); foreach (var relocation in signature.Relocations) - if (relocation.Kind != ThreadLocalSlotKind) BindRelationship(relocation.TargetRva, Target(signature, rva, relocation)); + if (relocation.Kind == EnumArgumentKind) BindEnumArgument(relocation.ReferenceValue, bytes[relocation.Offset]); + else if (relocation.Kind != ThreadLocalSlotKind) BindRelationship(relocation.TargetRva, Target(signature, rva, relocation)); } return true; } + // A value outside the limit, or one that does not fit the renumbering already found (another + // number for the same member, or members out of order), makes this a changed reader like any + // other changed byte. A required guard is then rejected, and an optional anchor or an + // alternative binding is passed over, so a core role that has another binding keeps it. + private bool EnumArgumentsAgree(Signature signature, ReadOnlySpan bytes) + { + Dictionary? found = null; + foreach (var relocation in signature.Relocations) + { + if (relocation.Kind != EnumArgumentKind) continue; + var reference = relocation.ReferenceValue; + var current = bytes[relocation.Offset]; + if (Math.Abs(current - reference) > EnumArgumentShiftLimit || !Fits(_enumArguments) || found is not null && !Fits(found)) return false; + (found ??= [])[reference] = current; + + bool Fits(Dictionary known) + { + foreach (var (knownReference, knownCurrent) in known) + if (knownReference.CompareTo(reference) != knownCurrent.CompareTo(current)) return false; + return true; + } + } + return true; + } + + private void BindEnumArgument(byte reference, byte current) + { + if (_enumArguments.TryGetValue(reference, out var existing) && existing != current) + throw new InvalidDataException("Adaptive enumerated argument differs between readers"); + _enumArguments[reference] = current; + } + + // Members keep their order when the enumeration grows or shrinks, and a single update moves + // them by a few places at most. Anything else is a changed call, not a renumbered one. + internal static void CheckEnumArguments(IReadOnlyDictionary arguments) + { + var previous = -1; + foreach (var (reference, current) in arguments.OrderBy(a => a.Key)) + { + if (Math.Abs(current - reference) > EnumArgumentShiftLimit || current <= previous) + throw new InvalidDataException("Adaptive enumerated argument changed"); + previous = current; + } + } + private void BindRelationship(uint previous, uint current) { if (_relationships.TryGetValue(previous, out var existing) && existing != current) @@ -712,12 +770,15 @@ internal Signature(JsonElement value) Relocations = value.GetProperty("relocations").EnumerateArray().Select(r => new Relocation( r.GetProperty("offset").GetInt32(), r.GetProperty("width").GetInt32(), r.GetProperty("next").GetInt32(), r.GetProperty("kind").GetString()!, r.GetProperty("targetRva").GetUInt32(), r.GetProperty("expectedTargetSection").GetString()!, - r.TryGetProperty("internalOffset", out var inner) && inner.ValueKind == JsonValueKind.Number ? inner.GetUInt32() : null)).ToArray(); + r.TryGetProperty("internalOffset", out var inner) && inner.ValueKind == JsonValueKind.Number ? inner.GetUInt32() : null, + r.TryGetProperty("referenceValue", out var reference) ? reference.GetByte() : (byte)0)).ToArray(); if (Length is < 1 or > 8192 || Hash.Length != 32 || AnchorOffset < 0 || AnchorOffset > Length - Anchor.Length || CanDiscover && Anchor.Length < 4 || Relocations.Any(r => r.Width is not (1 or 4 or 8) || r.Offset < 0 || r.Offset > Length - r.Width || r.Kind == "relative" && (r.Next < r.Offset + r.Width || r.Next > Length) || r.Kind == "absolute" && r.Width != 8 || r.Kind == "image" && r.Width != 4 || r.Kind == "relative" && r.Width == 8 || - r.Kind == ThreadLocalSlotKind && r.Width != 4)) + r.Kind == ThreadLocalSlotKind && r.Width != 4 || r.Kind == EnumArgumentKind && r.Width != 1) || + value.GetProperty("relocations").EnumerateArray().Any(r => + r.TryGetProperty("referenceValue", out _) != (r.GetProperty("kind").GetString() == EnumArgumentKind))) throw new InvalidDataException("Adaptive signature bounds"); var occupied = new bool[Length]; foreach (var relocation in Relocations) @@ -738,5 +799,6 @@ internal Signature(JsonElement value) internal bool CanDiscover { get; } internal Relocation[] Relocations { get; } } - private sealed record Relocation(int Offset, int Width, int Next, string Kind, uint TargetRva, string Section, uint? InternalOffset); + private sealed record Relocation(int Offset, int Width, int Next, string Kind, uint TargetRva, string Section, uint? InternalOffset, + byte ReferenceValue); } diff --git a/src/Wisp.App/NativeCompatibility/NativeCompatibilityUpdateSchedule.cs b/src/Wisp.App/NativeCompatibility/NativeCompatibilityUpdateSchedule.cs index 496ad40..41c8be5 100644 --- a/src/Wisp.App/NativeCompatibility/NativeCompatibilityUpdateSchedule.cs +++ b/src/Wisp.App/NativeCompatibility/NativeCompatibilityUpdateSchedule.cs @@ -1,3 +1,4 @@ +using Wisp.App.Tunes; using Wisp.Core; namespace Wisp.App; @@ -19,6 +20,9 @@ internal sealed class NativeCompatibilityUpdateSchedule private bool _unsupported; private bool _checking; private int _retryIndex; + private bool _tuneCheckRequested; + private DateTimeOffset _tuneAllowedAt = DateTimeOffset.MinValue; + private int _tuneRetryIndex; internal void ObserveBuild(NativeAssistProviderStatus status, string identity, DateTimeOffset now) { @@ -37,8 +41,20 @@ internal void ObserveBuild(NativeAssistProviderStatus status, string identity, D // Menus, absent telemetry and game restarts must not restart the retry cadence. } + internal void ObserveTuneCapture(TuneCaptureResult result) + { + if (result.Status == TuneCaptureStatus.UnsupportedBuild && + result.Incident is { Category: "tune", FailureStage: "tune-read", Reason: "compatibility-unavailable" }) + _tuneCheckRequested = true; + else if (result.Success) + { + _tuneCheckRequested = false; + _tuneRetryIndex = 0; + } + } + internal bool IsDue(DateTimeOffset now) => !_checking && now >= _automaticAllowedAt && - (now >= _routineAt || _unsupported && now >= _unsupportedAt); + (now >= _routineAt || _unsupported && now >= _unsupportedAt || _tuneCheckRequested && now >= _tuneAllowedAt); // Manual checks bypass the automatic delay and join the transport's existing operation. // Only its first caller owns the completion that advances this schedule. @@ -56,6 +72,14 @@ internal void CompleteCheck(DateTimeOffset now, bool success) var retry = RetryIntervals[_retryIndex]; var waitingForBuild = _unsupportedAt != DateTimeOffset.MaxValue; _routineAt = now + (success ? TimeSpan.FromDays(1) : retry); + // One completed feed check covers every explicit Tune request observed through completion. + if (_tuneCheckRequested) + { + _tuneCheckRequested = false; + _tuneAllowedAt = now + RetryIntervals[_tuneRetryIndex]; + _tuneRetryIndex = Math.Min(_tuneRetryIndex + 1, RetryIntervals.Length - 1); + } + if (!success && _tuneAllowedAt < _routineAt) _tuneAllowedAt = _routineAt; if (waitingForBuild) _unsupportedAt = now + retry; if (!success || waitingForBuild) _retryIndex = Math.Min(_retryIndex + 1, RetryIntervals.Length - 1); diff --git a/src/Wisp.App/NativeCompatibility/adaptive-store.json b/src/Wisp.App/NativeCompatibility/adaptive-store.json index 6870bad..122ca38 100644 --- a/src/Wisp.App/NativeCompatibility/adaptive-store.json +++ b/src/Wisp.App/NativeCompatibility/adaptive-store.json @@ -37000,7 +37000,7 @@ "id": "code-02A10E70-4412", "referenceRva": 44109424, "length": 4412, - "normalizedSha256": "EA8B9C45900FD4ED82256A80EAF31FDB8568E651FFBF541BEBCF43D8D42D15BA", + "normalizedSha256": "E8620C17DD283930BA68A722D142D8BD8C801B1D5B77C8F181073A9ABD9F4FD0", "anchorOffset": 1765, "anchorHex": "904889B3E08F00004889B3E88F00004889B3F08F00004889B3F88F00000F57C00F1183009000000F1183109000000F11832090000089B3309000004889B33890", "section": "code", @@ -38067,6 +38067,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3690, + "width": 1, + "next": 3691, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 12 + }, { "offset": 3698, "width": 4, @@ -38076,6 +38086,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3720, + "width": 1, + "next": 3721, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 12 + }, { "offset": 3728, "width": 4, @@ -38085,6 +38105,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3750, + "width": 1, + "next": 3751, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3758, "width": 4, @@ -38094,6 +38124,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3780, + "width": 1, + "next": 3781, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3788, "width": 4, @@ -38103,6 +38143,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3810, + "width": 1, + "next": 3811, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3818, "width": 4, @@ -38112,6 +38162,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3840, + "width": 1, + "next": 3841, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3848, "width": 4, @@ -38121,6 +38181,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3870, + "width": 1, + "next": 3871, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3878, "width": 4, @@ -38130,6 +38200,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3897, + "width": 1, + "next": 3898, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 37 + }, { "offset": 3905, "width": 4, @@ -38139,6 +38219,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3927, + "width": 1, + "next": 3928, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 37 + }, { "offset": 3935, "width": 4, @@ -38148,6 +38238,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3957, + "width": 1, + "next": 3958, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3965, "width": 4, @@ -38157,6 +38257,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 3987, + "width": 1, + "next": 3988, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 3995, "width": 4, @@ -38166,6 +38276,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 4017, + "width": 1, + "next": 4018, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 18 + }, { "offset": 4025, "width": 4, @@ -38175,6 +38295,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 4047, + "width": 1, + "next": 4048, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 18 + }, { "offset": 4055, "width": 4, @@ -38184,6 +38314,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 4077, + "width": 1, + "next": 4078, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 18 + }, { "offset": 4101, "width": 4, @@ -38373,9 +38513,9 @@ "id": "code-02A16030-2950", "referenceRva": 44130352, "length": 2950, - "normalizedSha256": "1E4A3DE9CC50E502ECB3968777EB898688E8C819D6E1B8E48BE00D5BD24D2BAD", - "anchorOffset": 845, - "anchorHex": "488B084C8B51384D8BCC41B80B000100B20C488BC841FFD240886B744533F64C89B368050000488B8BC0770000E8", + "normalizedSha256": "DC00D5A1A0EBC9AC475F71626D02C3E1FBE5925FF22B8949B3A513F686784755", + "anchorOffset": 0, + "anchorHex": "48895C241048896C241848897424205741544155415641574883EC30488BD948", "section": "code", "relocations": [ { @@ -38432,6 +38572,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 123, + "width": 1, + "next": 124, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 18 + }, { "offset": 131, "width": 4, @@ -38441,6 +38591,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 152, + "width": 1, + "next": 153, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 18 + }, { "offset": 160, "width": 4, @@ -38450,6 +38610,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 181, + "width": 1, + "next": 182, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 18 + }, { "offset": 189, "width": 4, @@ -38459,6 +38629,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 210, + "width": 1, + "next": 211, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 218, "width": 4, @@ -38468,6 +38648,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 239, + "width": 1, + "next": 240, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 247, "width": 4, @@ -38477,6 +38667,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 268, + "width": 1, + "next": 269, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 276, "width": 4, @@ -38486,6 +38686,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 297, + "width": 1, + "next": 298, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 305, "width": 4, @@ -38495,6 +38705,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 326, + "width": 1, + "next": 327, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 334, "width": 4, @@ -38504,6 +38724,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 355, + "width": 1, + "next": 356, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 363, "width": 4, @@ -38513,6 +38743,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 384, + "width": 1, + "next": 385, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 23 + }, { "offset": 392, "width": 4, @@ -38522,6 +38762,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 410, + "width": 1, + "next": 411, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 37 + }, { "offset": 418, "width": 4, @@ -38531,6 +38781,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 439, + "width": 1, + "next": 440, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 37 + }, { "offset": 447, "width": 4, @@ -38540,6 +38800,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 468, + "width": 1, + "next": 469, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 12 + }, { "offset": 476, "width": 4, @@ -38549,6 +38819,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 497, + "width": 1, + "next": 498, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 12 + }, { "offset": 520, "width": 1, @@ -38720,6 +39000,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 862, + "width": 1, + "next": 863, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 12 + }, { "offset": 891, "width": 4, @@ -39944,7 +40234,7 @@ "id": "code-02A29280-3340", "referenceRva": 44208768, "length": 3340, - "normalizedSha256": "D256147E180F96EBE329D5F350D3ABBCBC51215C45383EE7DB90172648A71EAC", + "normalizedSha256": "93A7AB10D0DC5C84E7C11DDF4FB4B0B9F51744DB451CD319FE73C8D125BFBC96", "anchorOffset": 1804, "anchorHex": "488B8EE00200004881C1A0010000488D85700200000F10000F11010F1048100F1149100F1040200F1141200F1048300F1149300F1040400F1141400F1048500F", "section": "code", @@ -40453,6 +40743,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 2223, + "width": 1, + "next": 2224, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 12 + }, { "offset": 2235, "width": 1, @@ -43875,7 +44175,7 @@ "id": "code-02FF7B70-660", "referenceRva": 50297712, "length": 660, - "normalizedSha256": "7094E812CAB63508724EBAE3197ECE1EC320AFBB82D60413BF061B8B5A087AA2", + "normalizedSha256": "7866C053AA9130F7866DE4774EEF7BC4BA3AF4A6C6240FBBF7735A1343338575", "anchorOffset": 0, "anchorHex": "405355565741564883EC204C8BF2488BF133FF897C2458BA0C0A00004533C0488D4C2450E8", "section": "code", @@ -43997,6 +44297,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 168, + "width": 1, + "next": 169, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 47 + }, { "offset": 178, "width": 1, @@ -44015,6 +44325,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 198, + "width": 1, + "next": 199, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 47 + }, { "offset": 206, "width": 4, @@ -45397,7 +45717,7 @@ "id": "code-030072D0-185", "referenceRva": 50361040, "length": 185, - "normalizedSha256": "B7E9D60F341A6EA1291F99C9171473B56AFB6E30EAEF5EFFB083D4D64C11BD2E", + "normalizedSha256": "A220BA422FD5CC4D8F5DF7589B9DAD7CDE5CA1DF05DB2D7B07213CECAE6A4A94", "anchorOffset": 0, "anchorHex": "48895C2410574883EC2033FF488BD94889B9A0000000488B89A80000004889BBA80000004885C974", "section": "code", @@ -45420,6 +45740,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 64, + "width": 1, + "next": 65, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 47 + }, { "offset": 96, "width": 1, @@ -51152,7 +51482,7 @@ "id": "code-037F63B0-1307", "referenceRva": 58680240, "length": 1307, - "normalizedSha256": "86D59F649611ECDA5DDE7DCB8D62AA23BE7ABB9964C3916DAB9B4E96DAC5B810", + "normalizedSha256": "1D201A099ED27A22FBF3D542392C15DA63CE59A963E5526C6EB923A8CC654EBD", "anchorOffset": 98, "anchorHex": "0F5BC0F30F1187F40000004489AFF800000048C787FC000000FFFFFFFFC78704010000FFFFFFFFC78708010000010101014488AF0C010000C787100100000C00", "section": "code", @@ -51832,6 +52162,16 @@ "expectedTargetSection": "code", "internalOffset": null }, + { + "offset": 1253, + "width": 1, + "next": 1254, + "kind": "enumArgument", + "targetRva": 0, + "expectedTargetSection": "none", + "internalOffset": null, + "referenceValue": 47 + }, { "offset": 1262, "width": 4, diff --git a/src/Wisp.App/NativeRendering/HudNativeHost.cs b/src/Wisp.App/NativeRendering/HudNativeHost.cs index 0c09982..bcc579c 100644 --- a/src/Wisp.App/NativeRendering/HudNativeHost.cs +++ b/src/Wisp.App/NativeRendering/HudNativeHost.cs @@ -302,26 +302,33 @@ private float EffectiveOpacity(FrameworkElement control) private void OnPresented(HudWindowSnapshot presented) { if (_window.Dispatcher.HasShutdownStarted) return; - _window.Dispatcher.BeginInvoke(new Action(() => + _window.Dispatcher.BeginInvoke(new Action(() => ApplyPresented(presented))); + } + private void ApplyPresented(HudWindowSnapshot presented) + { + if (_disposed || _failed || _retryPending || _hostRecovery.RebuildPending || _snapshot is null || !presented.CompatibleWith(_snapshot)) return; + try { _compositionWindow?.SetLayoutCloaked(!_interactive); } + catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException) + { OnHostFailure(error.HResult); return; } + _recovery.Reset(); + _hostRecovery.Presented(); + var visibleIds = presented.Layers.Select(layer => layer.Id).ToHashSet(); + foreach (var source in _sources) { - if (_disposed || _failed || _hostRecovery.RebuildPending || _snapshot is null || !presented.CompatibleWith(_snapshot)) return; - _recovery.Reset(); - _hostRecovery.Presented(); - try { _compositionWindow?.SetLayoutCloaked(!_interactive); } - catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException) - { OnHostFailure(error.HResult); return; } - var visibleIds = presented.Layers.Select(layer => layer.Id).ToHashSet(); - foreach (var source in _sources) - { - if (!visibleIds.Contains(source.Id) || IsPresented(source.Control)) continue; - source.Control.SetValue(PresentedProperty, true); - } - if (_vm is not null) _vm.ReportRendererHost(this, RendererHostState.Ready, _vm.ActiveCpuRendering - ? "HUD renderer: CPU (WARP) / DirectComposition" : "HUD renderer: Direct3D 11 / DirectComposition"); - })); + if (!visibleIds.Contains(source.Id) || IsPresented(source.Control)) continue; + source.Control.SetValue(PresentedProperty, true); + } + if (_vm is not null) _vm.ReportRendererHost(this, RendererHostState.Ready, _vm.ActiveCpuRendering + ? "HUD renderer: CPU (WARP) / DirectComposition" : "HUD renderer: Direct3D 11 / DirectComposition"); } private void OnHostFailure(int hresult) { + // The desktop compositor can restart between presenting the frame and cloaking its layout window. + if (unchecked((uint)hresult) is 0xD0000701u or 0x80263001u) // STATUS_MESSAGE_LOST, DWM_E_COMPOSITIONDISABLED + { + RetryHostWindow(hresult, "desktop composition"); + return; + } DebugLogging.HealthContextRecorder.Current.RecordRendererFailure(hresult, DebugLogging.HealthFailureStage.RendererHost); OnStatus(false, hresult); } @@ -329,11 +336,12 @@ private void OnHostFailure(int hresult) // A host-window Win32 call failed; HudNativeHostRecovery bounds the retries, the rebuild on the // next game attach and the retirement. The report names the call and carries HRESULT_FROM_WIN32 // of its error code, once per episode, since every Win32Exception reports E_FAIL itself. - private void OnHostInterop(Win32Exception error) + private void OnHostInterop(Win32Exception error) => + RetryHostWindow(NativeHostInteropException.FailureCodeOf(error), NativeHostInteropException.CallOf(error)); + + private void RetryHostWindow(int hresult, string call) { if (_disposed || _failed || _retryPending || _hostRecovery.RebuildPending) return; - var hresult = NativeHostInteropException.FailureCodeOf(error); - var call = NativeHostInteropException.CallOf(error); if (_hostRecovery.Retries == 0) DebugLogging.HealthContextRecorder.Current.RecordRendererFailure(hresult, DebugLogging.HealthFailureStage.RendererHost); switch (_hostRecovery.Fail()) diff --git a/src/Wisp.App/ReleaseNotesCatalog.cs b/src/Wisp.App/ReleaseNotesCatalog.cs index eba8c28..9087fa9 100644 --- a/src/Wisp.App/ReleaseNotesCatalog.cs +++ b/src/Wisp.App/ReleaseNotesCatalog.cs @@ -14,12 +14,30 @@ public static class ReleaseNotesCatalog { public static IReadOnlyList Entries { get; } = [ + new( + "2.7.8", + "December 1, 2026", + "MAINTENANCE", + "Wisp 2.7.8 restores Tune readings on the current Xbox app build of Forza Horizon 6 and fixes HUD, Clips and update errors reported from 2.7.7.", + true, + [ + Group("Tune", + "Reading the current car’s tune works again on Forza Horizon 6 build 3.498.592.0 (Xbox app / Microsoft Store).", + "When Wisp cannot verify the Tune reader for a game build, it checks for a compatibility update without waiting for the next scheduled check."), + Group("HUD", + "The HUD recovers when Windows restarts desktop composition while a frame is being shown."), + Group("Clips", + "Recording starts on graphics cards that change the video output format before the first encoded frame.", + "A recorder failure is reported with its original cause when the recorder closes during a request."), + Group("Updates", + "Starting the update helper by itself no longer replaces the result of an installation that is waiting to be reported.") + ]), new( "2.7.7", "November 26, 2026", "WINTER", "Wisp 2.7.7 adds falling snow to the dashboard and checks Drift Zone scoring curves on newer Forza Horizon 6 builds.", - true, + false, [ Group("Appearance", "Winter mode is on by default. Ice-blue snowflakes fall and fade behind the dashboard readouts. Turn Winter mode off in Extras to return to wisps.", diff --git a/src/Wisp.App/Wisp.App.csproj b/src/Wisp.App/Wisp.App.csproj index 6ed4fa1..1b1c94b 100644 --- a/src/Wisp.App/Wisp.App.csproj +++ b/src/Wisp.App/Wisp.App.csproj @@ -11,9 +11,9 @@ Wisp Wisp Wheel-indicated speed and G-force display for Forza Horizon 6. - 2.7.7 - 2.7.7.0 - 2.7.7.0 + 2.7.8 + 2.7.8.0 + 2.7.8.0 true false false diff --git a/src/Wisp.App/app.manifest b/src/Wisp.App/app.manifest index 4fe36e1..89edb74 100644 --- a/src/Wisp.App/app.manifest +++ b/src/Wisp.App/app.manifest @@ -1,6 +1,6 @@ - + diff --git a/src/Wisp.Updater/UpdaterApplication.cs b/src/Wisp.Updater/UpdaterApplication.cs index d6bb86d..1098271 100644 --- a/src/Wisp.Updater/UpdaterApplication.cs +++ b/src/Wisp.Updater/UpdaterApplication.cs @@ -28,9 +28,9 @@ public void Signal(string eventName) internal sealed class UpdaterApplication { - internal int Run(string[] args) + internal int Run(string[] args, string? localApplicationDataPath = null) { - var localApplicationDataPath = Environment.GetFolderPath( + localApplicationDataPath ??= Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData); var resultFile = new UpdateResultFile(localApplicationDataPath); ValidatedUpdateRequest? request = null; @@ -71,6 +71,13 @@ internal int Run(string[] args) } return (int)UpdaterExitCode.Success; } + catch (UpdateFailureException exception) when (exception.ErrorCode == "UPDATE_ARGUMENTS") + { + // No update was requested. Leave any previous install result for Wisp to consume. + try { Console.Error.WriteLine(exception.ErrorCode); } + catch (IOException) { } + return (int)exception.ExitCode; + } catch (UpdateFailureException exception) { var recoveryState = RecoverIfSafe( diff --git a/src/Wisp.Updater/Wisp.Updater.csproj b/src/Wisp.Updater/Wisp.Updater.csproj index e676d0b..68a57d9 100644 --- a/src/Wisp.Updater/Wisp.Updater.csproj +++ b/src/Wisp.Updater/Wisp.Updater.csproj @@ -12,9 +12,9 @@ Wisp Wisp Update Helper Applies verified Wisp updates after the app exits. - 2.7.7 - 2.7.7.0 - 2.7.7.0 + 2.7.8 + 2.7.8.0 + 2.7.8.0 diff --git a/tests/Wisp.App.Tests/ApplicationUpdateResultTests.cs b/tests/Wisp.App.Tests/ApplicationUpdateResultTests.cs index 8caa4c1..a7b89db 100644 --- a/tests/Wisp.App.Tests/ApplicationUpdateResultTests.cs +++ b/tests/Wisp.App.Tests/ApplicationUpdateResultTests.cs @@ -5,6 +5,14 @@ namespace Wisp.App.Tests; public sealed class ApplicationUpdateResultTests { + [Fact] + public void StandaloneHelperRejectionIsConsumedWithoutReportingAnInstall() + { + using var layout = new ResultLayout("""{"schemaVersion":1,"state":"failed","sourceVersion":"","targetVersion":"","errorCode":"UPDATE_ARGUMENTS","recoveryState":"application-still-running"}"""); + Assert.False(ApplicationUpdateLauncher.TryConsumeResult(layout.Root, out _)); + Assert.False(File.Exists(layout.ResultPath)); + } + [Theory] [InlineData("UPDATE_INSTALLER_EXIT_FAILED", "restarted", 5u, "update-installer-exit-failed")] [InlineData("UPDATE_INSTALLER_HASH_MISMATCH", "application-still-running", null, "update-installer-hash-mismatch")] diff --git a/tests/Wisp.App.Tests/HudNativeHostRecoveryTests.cs b/tests/Wisp.App.Tests/HudNativeHostRecoveryTests.cs index 88d88fa..73904a4 100644 --- a/tests/Wisp.App.Tests/HudNativeHostRecoveryTests.cs +++ b/tests/Wisp.App.Tests/HudNativeHostRecoveryTests.cs @@ -126,6 +126,25 @@ internal static void AssertHostRebuildOnAttach(OverlayWindow window, HudNativeHo Assert.Equal(0, recovery.Retries); Assert.Equal(0, recovery.FailedEpisodes); + foreach (var code in new[] { 0xD0000701u, 0x80263001u }) + { + var hresult = unchecked((int)code); + var start = DateTimeOffset.UtcNow.AddMilliseconds(-1); + Callback(host, "OnHostFailure", hresult); + Callback(host, "OnHostFailure", hresult); + Assert.Equal(1, recovery.Retries); + Assert.True(Field(host, "_retryPending")); + Assert.Equal(HealthFailureStage.RendererHost, Assert.Single(RendererFailures(start, hresult)).FailureStage); + // A frame queued before synchronization was retried must not clear the retry budget. + Callback(host, "ApplyPresented", Field(host, "_snapshot")); + Assert.Equal(1, recovery.Retries); + PumpUntil(() => !Field(host, "_retryPending") && recovery.Retries == 0 && + controller.ViewModel.NativeRendererStatus.Contains("DirectComposition", StringComparison.Ordinal), 4000, + () => $"step=composition-retry; code={code:X8}; retries={recovery.Retries}"); + Assert.Same(worker, Worker(host)); + Assert.Equal(retired, HudNativeHost.PresentationHandle(window)); + } + // A first failure is reported once, with the call and HRESULT_FROM_WIN32 of its error code, // and the same window is synchronized again after the retry delay. var before = DateTimeOffset.UtcNow.AddMilliseconds(-1); @@ -198,10 +217,10 @@ internal static void AssertHostRebuildOnAttach(OverlayWindow window, HudNativeHo finally { WindowZOrder.DetachFromGame(window); } } - // The breadcrumbs of the injected Win32 failure, apart from anything the renderer itself reports. - private static HealthBreadcrumb[] RendererFailures(DateTimeOffset since) => + // Isolate the injected failure from anything the renderer itself reports. + private static HealthBreadcrumb[] RendererFailures(DateTimeOffset since, int hresult = InvalidWindowHandleResult) => HealthContextRecorder.Current.CaptureForReport().Breadcrumbs.Where(crumb => - crumb.Code == HealthEventCode.RendererFailed && crumb.ErrorCode == InvalidWindowHandleResult && + crumb.Code == HealthEventCode.RendererFailed && crumb.ErrorCode == hresult && crumb.TimestampUtc >= since).ToArray(); private static AnalogHudRenderWorker Worker(HudNativeHost host) => diff --git a/tests/Wisp.App.Tests/InstallerPackagingContractTests.cs b/tests/Wisp.App.Tests/InstallerPackagingContractTests.cs index e16b9af..422f431 100644 --- a/tests/Wisp.App.Tests/InstallerPackagingContractTests.cs +++ b/tests/Wisp.App.Tests/InstallerPackagingContractTests.cs @@ -207,11 +207,8 @@ public void PackagingPublishesAndBundlesValidatedUpdateHelperBeforeCompilation() Assert.Contains("-p:EnableCompressionInSingleFile=true", script, StringComparison.Ordinal); Assert.Contains("$startInfo.Arguments = '--packaging-smoke'", script, StringComparison.Ordinal); Assert.Contains("if ($process.ExitCode -ne 2)", script, StringComparison.Ordinal); - Assert.Contains("$diagnostic.errorCode -cne 'UPDATE_ARGUMENTS'", script, StringComparison.Ordinal); - Assert.Contains( - "$diagnostic.message -cne 'The update helper received invalid arguments.'", - script, - StringComparison.Ordinal); + Assert.Contains("$startInfo.RedirectStandardError = $true", script, StringComparison.Ordinal); + Assert.Contains("$process.StandardError.ReadToEnd().Trim() -cne 'UPDATE_ARGUMENTS'", script, StringComparison.Ordinal); Assert.Contains("($characteristics -band 0x2000) -ne 0", script, StringComparison.Ordinal); Assert.Contains("$versionPadding = [char[]]@([char]0, [char]0x20)", script, StringComparison.Ordinal); Assert.Contains("([string]$versionInfo.ProductName).TrimEnd($versionPadding)", script, StringComparison.Ordinal); diff --git a/tests/Wisp.App.Tests/NativeAdaptiveCompatibilityTests.cs b/tests/Wisp.App.Tests/NativeAdaptiveCompatibilityTests.cs index 940b5d9..029d46e 100644 --- a/tests/Wisp.App.Tests/NativeAdaptiveCompatibilityTests.cs +++ b/tests/Wisp.App.Tests/NativeAdaptiveCompatibilityTests.cs @@ -20,6 +20,85 @@ public void ThreadLocalSlotsMustAgreeAndStayBounded() Assert.Throws(() => NativeAdaptiveResolver.CheckThreadLocalSlots(new HashSet { 0x10000 })); } + [Fact] + public void EnumArgumentsMustBeAnOrderPreservingRenumberingWithinTheLimit() + { + NativeAdaptiveResolver.CheckEnumArguments(new Dictionary()); + NativeAdaptiveResolver.CheckEnumArguments(new Dictionary { [0x0c] = 0x0c, [0x12] = 0x12 }); + // Store 3.498.592.0: one member added below 0x0C moved every later member up by one. + NativeAdaptiveResolver.CheckEnumArguments(new Dictionary { [0x0c] = 0x0d, [0x12] = 0x13, [0x17] = 0x18, [0x25] = 0x26 }); + NativeAdaptiveResolver.CheckEnumArguments(new Dictionary { [0x05] = 0x05, [0x0c] = 0x0d, [0x25] = 0x27 }); + Assert.Throws(() => NativeAdaptiveResolver.CheckEnumArguments(new Dictionary { [0x0c] = 0x13, [0x12] = 0x13 })); + Assert.Throws(() => NativeAdaptiveResolver.CheckEnumArguments(new Dictionary { [0x0c] = 0x13, [0x12] = 0x0d })); + Assert.Throws(() => NativeAdaptiveResolver.CheckEnumArguments(new Dictionary { [0x0c] = 0x15 })); + } + + [Theory] + [InlineData(0x0c, 0x17, 0x0c, true)] // The reference values. + [InlineData(0x0d, 0x18, 0x0d, true)] // Renumbered by an added member. + [InlineData(0x0d, 0x18, 0x0c, false)] // One member with two numbers. + [InlineData(0x18, 0x17, 0x18, false)] // Order not preserved. + [InlineData(0x2c, 0x37, 0x2c, false)] // Moved further than one update renumbers. + public void ARenumberedEnumArgumentResolvesOnlyWhenEveryReaderAgrees(byte first, byte second, byte third, bool valid) + { + var fixture = new Fixture(enumArguments: true); + fixture.Bytes[0x1120 + 1] = first; + fixture.Bytes[0x1120 + 3] = second; + fixture.Bytes[0x1120 + 5] = third; + if (valid) Assert.Equal(0x1120U, fixture.Resolve()["/leadVtableRva"]); + else Assert.Throws(() => fixture.Resolve()); + } + + [Fact] + public void AChangedInstructionBesideARenumberedEnumArgumentIsRejected() + { + var fixture = new Fixture(enumArguments: true); + fixture.Bytes[0x1120 + 1] = 0x0d; + fixture.Bytes[0x1120 + 3] = 0x18; + fixture.Bytes[0x1120 + 5] = 0x0d; + fixture.Bytes[0x1120 + 2] ^= 1; // The opcode that loads the second argument. + Assert.Throws(() => fixture.Resolve()); + } + + [Theory] + [InlineData(0x0d, 0x18, 0x0c)] // One member with two numbers. + [InlineData(0x18, 0x17, 0x18)] // Order not preserved. + [InlineData(0x2c, 0x37, 0x2c)] // Moved further than one update renumbers. + public void AnEnumArgumentThatDoesNotFitLeavesTheRoleToItsAlternativeBinding(byte first, byte second, byte third) + { + var fixture = new Fixture(enumArguments: true); + fixture.Bytes[0x1120 + 1] = first; + fixture.Bytes[0x1120 + 3] = second; + fixture.Bytes[0x1120 + 5] = third; + // A second reader of the same threshold without enum arguments: nop; lea rcx, [rip+rel32]; ret. + var alternative = Convert.FromHexString("90488D0D00000000C3"); + alternative.CopyTo(fixture.Bytes, 0x1200); + fixture.Write32(0x1200 + 4, 0x3580 - (0x1200 + 8)); + var profile = JsonNode.Parse(fixture.Profile.RootElement.GetRawText())!.AsObject(); + profile["signatures"]!.AsArray().Add(JsonNode.Parse(JsonSerializer.Serialize(new + { + id = "alternative", + referenceRva = 0x1180, + length = alternative.Length, + normalizedSha256 = Convert.ToHexString(SHA256.HashData(alternative)), + anchorOffset = 0, + anchorHex = "90488D0D", + section = "code", + relocations = new[] { new { offset = 4, width = 4, next = 8, kind = "relative", targetRva = 0x3500, expectedTargetSection = "readonly" } } + }))); + profile["bindings"] = JsonNode.Parse(JsonSerializer.Serialize(new object[] + { + new { path = "/thresholdRva", kind = "reference", signature = "reader", operandOffset = 15 }, + new { path = "/thresholdRva", kind = "reference", signature = "alternative", operandOffset = 4 } + })); + profile["checks"] = new JsonArray(); + using var document = JsonDocument.Parse(profile.ToJsonString()); + + var resolved = new NativeAdaptiveResolver(fixture.Image(), document.RootElement).Resolve(); + + Assert.Equal(0x3580U, resolved["/thresholdRva"]); + } + private static int _nextProcess = 600_000; [Theory] @@ -255,7 +334,7 @@ private sealed class Fixture internal bool RejectReads { get; init; } internal JsonDocument Profile { get; } - internal Fixture() + internal Fixture(bool enumArguments = false) { Write16(0, 0x5a4d); Write32(0x3c, 0x80); Write32(0x80, 0x4550); Write16(0x84, 0x8664); Write16(0x86, 3); Write16(0x94, 0xf0); @@ -263,26 +342,37 @@ internal Fixture() Section(0, ".text", 0x1000, 0x2000, 0x60000020); Section(1, ".rdata", 0x3000, 0x2000, 0x40000040); Section(2, ".data", 0x5000, 0x2000, 0xc0000040); - var body = Convert.FromHexString("8B8120000000488D1500000000C3"); + // With enum arguments the reader starts with three "mov dl, imm8" instructions. + var prefix = enumArguments ? 6 : 0; + var body = Convert.FromHexString((enumArguments ? "B20CB217B20C" : "") + "8B8120000000488D1500000000C3"); body.CopyTo(Bytes, 0x1120); - Write32(0x1120 + 9, 0x3580 - (0x1120 + 13)); + Write32(0x1120 + prefix + 9, 0x3580 - (0x1120 + prefix + 13)); + var normalized = body.ToArray(); + object[] relocations = [new { offset = prefix + 9, width = 4, next = prefix + 13, kind = "relative", targetRva = 0x3500, expectedTargetSection = "readonly" }]; + if (enumArguments) + foreach (var offset in new[] { 1, 3, 5 }) + { + relocations = [.. relocations, new { offset, width = 1, next = offset + 1, kind = "enumArgument", targetRva = 0, + expectedTargetSection = "none", referenceValue = body[offset] }]; + normalized[offset] = 0; + } var signature = new { id = "reader", referenceRva = 0x1100, length = body.Length, - normalizedSha256 = Convert.ToHexString(SHA256.HashData(body)), - anchorOffset = 0, + normalizedSha256 = Convert.ToHexString(SHA256.HashData(normalized)), + anchorOffset = prefix, anchorHex = "8B8120000000488D15", section = "code", - relocations = new[] { new { offset = 9, width = 4, next = 13, kind = "relative", targetRva = 0x3500, expectedTargetSection = "readonly" } } + relocations }; Profile = JsonDocument.Parse(JsonSerializer.Serialize(new { schemaVersion = 1, signatures = new[] { signature }, bindings = new object[] { - new { path = "/thresholdRva", kind = "reference", signature = "reader", operandOffset = 9 }, + new { path = "/thresholdRva", kind = "reference", signature = "reader", operandOffset = prefix + 9 }, new { path = "/leadVtableRva", kind = "signature", signature = "reader" } }, checks = new object[] { new { path = "/leadVtableRva", kind = "bytes", signature = "reader" } } diff --git a/tests/Wisp.App.Tests/NativeCompatibilityUpdateScheduleTests.cs b/tests/Wisp.App.Tests/NativeCompatibilityUpdateScheduleTests.cs index ec8afa2..5697c17 100644 --- a/tests/Wisp.App.Tests/NativeCompatibilityUpdateScheduleTests.cs +++ b/tests/Wisp.App.Tests/NativeCompatibilityUpdateScheduleTests.cs @@ -1,3 +1,4 @@ +using Wisp.App.Tunes; using Wisp.Core; using Xunit; @@ -132,6 +133,86 @@ public void ChangedUnsupportedIdentityCanPromptCheckWithoutResettingGlobalMinimu Assert.True(schedule.IsDue(second.AddMinutes(1))); } + [Fact] + public void UnsupportedTuneWithReadyHudGetsOneCheckAtTheAutomaticFloor() + { + var schedule = CheckedSuccessfully(); + var observed = Start.AddSeconds(2); + schedule.ObserveTuneCapture(UnsupportedTune()); + schedule.ObserveBuild(NativeAssistProviderStatus.Ready, "verified", observed); + Assert.False(schedule.IsDue(Start.AddSeconds(59))); + var due = Start.AddMinutes(1); + Assert.True(schedule.IsDue(due)); + Assert.True(schedule.TryBeginCheck(due)); + schedule.ObserveTuneCapture(UnsupportedTune()); + Assert.False(schedule.IsDue(due.AddSeconds(5))); + schedule.CompleteCheck(due.AddSeconds(10), success: true); + Assert.False(schedule.IsDue(due.AddHours(1))); + Assert.True(schedule.IsDue(due.AddSeconds(10).AddDays(1))); + } + + [Theory] + [InlineData(TuneCaptureStatus.UnsupportedBuild, false, "compatibility-unavailable")] + [InlineData(TuneCaptureStatus.UnsupportedBuild, true, "layout-unverified")] + [InlineData(TuneCaptureStatus.Unavailable, true, "compatibility-unavailable")] + public void OtherCaptureOutcomesKeepTheDailyCheck(TuneCaptureStatus status, bool reading, string reason) + { + var schedule = CheckedSuccessfully(); + var stage = reading ? TuneCaptureStage.ReadTune : TuneCaptureStage.OpenGame; + var result = new TuneCaptureResult(null, status, "") { Incident = TuneCaptureService.TuneIncident(stage, reason) }; + schedule.ObserveTuneCapture(result); + Assert.False(schedule.IsDue(Start.AddHours(2))); + } + + [Fact] + public void VerifiedTuneCaptureClearsAPendingCheck() + { + var schedule = CheckedSuccessfully(); + schedule.ObserveTuneCapture(UnsupportedTune()); + schedule.ObserveTuneCapture(new TuneCaptureResult(Wisp.UiReview.TuneUiFixture.Read(), TuneCaptureStatus.Ready, "")); + Assert.False(schedule.IsDue(Start.AddHours(2))); + } + + [Fact] + public void RepeatedUnsupportedTuneRequestsFollowBackoffAndDoNotStartAPollingLoop() + { + var schedule = CheckedSuccessfully(); + var now = Start.AddHours(1); + foreach (var minutes in new[] { 1, 5, 15, 60, 60 }) + { + schedule.ObserveTuneCapture(UnsupportedTune()); + Assert.True(schedule.IsDue(now)); + Assert.True(schedule.TryBeginCheck(now)); + schedule.CompleteCheck(now, success: true); + var next = now.AddMinutes(minutes); + Assert.False(schedule.IsDue(next)); + schedule.ObserveTuneCapture(UnsupportedTune()); + schedule.ObserveBuild(NativeAssistProviderStatus.Ready, "verified", now); + Assert.False(schedule.IsDue(next.AddTicks(-1))); + Assert.True(schedule.IsDue(next)); + now = next; + } + } + + [Fact] + public void UnsupportedTuneDoesNotShortenAnExistingTransportRetry() + { + var schedule = new NativeCompatibilityUpdateSchedule(); + Assert.True(schedule.TryBeginCheck(Start)); + schedule.CompleteCheck(Start, success: false); + var next = Start.AddMinutes(1); + Assert.True(schedule.TryBeginCheck(next)); + schedule.CompleteCheck(next, success: false); + schedule.ObserveTuneCapture(UnsupportedTune()); + Assert.False(schedule.IsDue(next.AddMinutes(5).AddTicks(-1))); + Assert.True(schedule.IsDue(next.AddMinutes(5))); + } + + private static TuneCaptureResult UnsupportedTune() => new(null, TuneCaptureStatus.UnsupportedBuild, "") + { + Incident = TuneCaptureService.TuneIncident(TuneCaptureStage.ReadTune, "compatibility-unavailable") + }; + [Fact] public void ManualChecksBypassDelayButJoinOneScheduledOperation() { diff --git a/tests/Wisp.App.Tests/RecorderProcessClientTests.cs b/tests/Wisp.App.Tests/RecorderProcessClientTests.cs index abfc650..046eb4a 100644 --- a/tests/Wisp.App.Tests/RecorderProcessClientTests.cs +++ b/tests/Wisp.App.Tests/RecorderProcessClientTests.cs @@ -347,6 +347,48 @@ public async Task MismatchedResponseFailsClosedAndDoesNotRestart() Assert.Equal(1, launches); } + [Fact] + public async Task BrokenWriteReportsTheTransportFailureWithoutFaultingAnUnawaitedReply() + { + using var fixture = new Fixture(); + var child = new FakeChild(); + await using var client = new RecorderProcessClient(fixture.Helper, _ => child, fixture.BufferRoot); + Task? pending = null; + child.BeforeCommand = () => + { + pending = PendingReplyTask(client); + throw new IOException("Synthetic pipe failure"); + }; + + var error = await Assert.ThrowsAsync(() => client.OpenAsync(Recording, fixture.Directory, TestToken)); + Assert.Same(client.ClientFailure, error); + Assert.Equal("protocol_error", error.Reason); + Assert.Equal("helper-config", error.FailureStage); + Assert.False(error.NativeRequestRejected); + Assert.True(child.Exited); + Assert.NotNull(pending); + Assert.True(pending.IsCompletedSuccessfully); + } + + [Fact] + public async Task HelperExitWithAnOutstandingSaveRemainsALocalFailure() + { + using var fixture = new Fixture(); + var child = new FakeChild { HoldSave = true }; + await using var client = new RecorderProcessClient(fixture.Helper, _ => child, fixture.BufferRoot); + await client.OpenAsync(Recording, fixture.Directory, TestToken); + var id = Guid.NewGuid(); + var save = client.SaveAsync(new(id, DateTimeOffset.UtcNow, Recording, Path.Combine(fixture.Directory, $"{id:N}.mp4")), TestToken); + await child.SaveArrived.Task.WaitAsync(TimeSpan.FromSeconds(3), TestToken); + var pending = PendingReplyTask(client); + child.CompleteOutput(); + var error = await Assert.ThrowsAsync(() => save); + Assert.Equal("helper_exited", error.Reason); + Assert.False(error.NativeRequestRejected); + Assert.False(error.SaveCompletedWithoutMedia); + Assert.True(pending.IsCompletedSuccessfully); + } + [Fact] public async Task CancellationStopsExactOwnedChildAndFailsPendingSave() { @@ -358,8 +400,10 @@ public async Task CancellationStopsExactOwnedChildAndFailsPendingSave() var id = Guid.NewGuid(); var save = client.SaveAsync(new(id, DateTimeOffset.UtcNow, Recording, Path.Combine(fixture.Directory, $"{id:N}.mp4")), cancelled.Token); await child.SaveArrived.Task.WaitAsync(TimeSpan.FromSeconds(3), TestToken); + var pending = PendingReplyTask(client); cancelled.Cancel(); await Assert.ThrowsAnyAsync(() => save); + Assert.True(pending.IsCompletedSuccessfully); Assert.True(child.Exited); Assert.True(child.Kills > 0); Assert.Single(child.Commands, command => command.GetProperty("command").GetString() == "save"); @@ -607,6 +651,14 @@ public async Task OnlyAcknowledgedEmptyNativeFailuresMayDropReservations(string await client.StopAsync(TestToken); } + private static Task PendingReplyTask(RecorderProcessClient client) + { + var field = typeof(RecorderProcessClient).GetField("_pending", BindingFlags.Instance | BindingFlags.NonPublic)!; + var requests = (System.Collections.IDictionary)field.GetValue(client)!; + var completion = Assert.Single(requests.Values.Cast()); + return (Task)completion.GetType().GetProperty("Task")!.GetValue(completion)!; + } + private sealed class Fixture : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "WispRecorderClientTests", Guid.NewGuid().ToString("N")); @@ -627,6 +679,7 @@ private sealed class FakeChild : IRecorderChild internal bool SilentSave { get; init; } internal bool WrongRequest { get; init; } internal bool HoldSave { get; init; } + internal Action? BeforeCommand { get; set; } internal bool ExitOnStop { get; init; } internal string? RejectSaveReason { get; init; } internal bool RejectedSaveLeavesFile { get; init; } @@ -667,6 +720,7 @@ internal void Terminal(Guid session, string state, string reason) } private void Receive(byte[] bytes) { + BeforeCommand?.Invoke(); using var document = JsonDocument.Parse(bytes); var command = document.RootElement.Clone(); Commands.Add(command); var name = command.GetProperty("command").GetString(); diff --git a/tests/Wisp.App.Tests/TuneLiveReviewTests.cs b/tests/Wisp.App.Tests/TuneLiveReviewTests.cs new file mode 100644 index 0000000..1c63a68 --- /dev/null +++ b/tests/Wisp.App.Tests/TuneLiveReviewTests.cs @@ -0,0 +1,77 @@ +using Wisp.App.Supplementary; +using Wisp.App.Tunes; +using Wisp.UiReview; +using Xunit; + +namespace Wisp.App.Tests; + +public sealed class TuneLiveReviewTests +{ + [Fact] + public void VersionPinIsOptionalAndRequiresFourCanonicalComponents() + { + string[] args = ["--tune-live-check", "--output", "review"]; + var original = TuneLiveReview.ParseArguments(args); + Assert.Equal("review", original.Output); + Assert.Null(original.ExpectedGameVersion); + Assert.Equal("3.498.592.0", TuneLiveReview.ParseArguments([.. args, "--expect-game-version", "3.498.592.0"]).ExpectedGameVersion); + foreach (var invalid in new[] { "3.498.592", "03.498.592.0", "3.498.592.0 suffix" }) + Assert.Throws(() => TuneLiveReview.ParseArguments([.. args, "--expect-game-version", invalid])); + Assert.Throws(() => TuneLiveReview.ParseArguments([.. args, "--expect-game-version"])); + } + + [Theory] + [InlineData("first")] + [InlineData("confirmation")] + public void EachReadUsesItsOwnValidatedSnapshotForThePin(string read) + { + var snapshot = TuneUiFixture.Read(); + var capture = new TuneCaptureResult(snapshot, TuneCaptureStatus.Ready, ""); + Assert.Equal(snapshot.Identity.GameVersion, TuneLiveReview.CaptureGameVersion(capture)); + Assert.Same(snapshot, TuneLiveReview.Validate(capture, read, null)); + Assert.Same(snapshot, TuneLiveReview.Validate(capture, read, snapshot.Identity.GameVersion)); + var wrong = Assert.Throws(() => TuneLiveReview.Validate(capture, read, "1.0.0.0")); + Assert.Equal($"{read}-game-version-mismatch", wrong.Code); + } + + [Fact] + public void FailureCanReportAnAdmittedVersionButCannotSatisfyThePin() + { + var pack = NativeHudBuildContract.StoreBuiltIn; + var capture = new TuneCaptureResult(null, TuneCaptureStatus.UnsupportedBuild, "", + TuneCaptureDetails.Create(TuneCaptureStage.ReadTune, pack)); + Assert.Equal(pack.GameVersion, TuneLiveReview.CaptureGameVersion(capture)); + var rejected = Assert.Throws(() => TuneLiveReview.Validate(capture, "first", pack.GameVersion)); + Assert.Equal("first-capture-UnsupportedBuild", rejected.Code); + Assert.Null(TuneLiveReview.CaptureGameVersion(capture with { Details = TuneCaptureDetails.Create(TuneCaptureStage.OpenGame) })); + Assert.Null(TuneLiveReview.CaptureGameVersion(capture with { Details = "Wisp Tune read details\nGame version: 3.498.592.0 private" })); + } + + [Theory] + [InlineData("Adaptive reader role unavailable: /tune/providerSlots/private/value", "role-unavailable", "provider-slot")] + [InlineData("Adaptive reader guard changed: /tune/codeGuards/7/rva", "guard-changed", "code-guard")] + [InlineData("Adaptive reader region changed: /tune/rvas/private", "region-changed", "tune-data")] + [InlineData("Adaptive table changed: /gauge/providerSlots/1", null, null)] + [InlineData("Adaptive table changed: /tune/unknown/1", null, null)] + [InlineData("Unknown failure: /tune/rvas/private", null, null)] + public void OnlyFixedTuneReasonAndRoleCategoriesAreReported(string message, string? reason, string? role) + { + var failure = TuneLiveReview.GetTuneValidationFailure(message); + Assert.Equal(reason is null ? null : new TuneLiveReview.TuneValidationFailure(reason, role!), failure); + } + + [Theory] + [InlineData("tune-read", "compatibility-unavailable", true)] + [InlineData("tune-open", "compatibility-unavailable", false)] + [InlineData("tune-read", "layout-unverified", false)] + public void OnlyAnOptionalTuneRejectionReceivesTheObservedReason(string stage, string reason, bool reported) + { + var observed = new TuneLiveReview.TuneValidationFailure("guard-changed", "code-guard"); + var result = new TuneCaptureResult(null, TuneCaptureStatus.UnsupportedBuild, "") + { + Incident = SupplementaryIncidentSchema.Create("tune", reason, stage) + }; + Assert.Equal(reported ? observed : null, TuneLiveReview.ReportedValidation(result, observed)); + Assert.Null(TuneLiveReview.ReportedValidation(result with { Status = TuneCaptureStatus.Ready }, observed)); + } +} diff --git a/tests/Wisp.App.Tests/Wisp.App.Tests.csproj b/tests/Wisp.App.Tests/Wisp.App.Tests.csproj index a675b31..c552849 100644 --- a/tests/Wisp.App.Tests/Wisp.App.Tests.csproj +++ b/tests/Wisp.App.Tests/Wisp.App.Tests.csproj @@ -18,6 +18,7 @@ + diff --git a/tests/Wisp.Updater.Tests/CommandAndErrorTests.cs b/tests/Wisp.Updater.Tests/CommandAndErrorTests.cs index f56b1ad..42cca18 100644 --- a/tests/Wisp.Updater.Tests/CommandAndErrorTests.cs +++ b/tests/Wisp.Updater.Tests/CommandAndErrorTests.cs @@ -48,6 +48,25 @@ public void InvalidRequestExitCodeIsTheSharedContractValue() Assert.Equal(2, (int)UpdaterExitCode.InvalidRequest); } + [Fact] + public void InvalidInvocationLeavesThePendingInstallationResultAlone() + { + var directory = Directory.CreateTempSubdirectory("wisp-updater-arguments-"); + try + { + var application = new UpdaterApplication(); + var result = Path.Combine(directory.FullName, "Wisp", "update-result.json"); + Assert.Equal((int)UpdaterExitCode.InvalidRequest, application.Run([], directory.FullName)); + Assert.False(File.Exists(result)); + Directory.CreateDirectory(Path.GetDirectoryName(result)!); + File.WriteAllText(result, """{"schemaVersion":1,"state":"installed","targetVersion":"2.7.7"}"""); + var original = File.ReadAllBytes(result); + Assert.Equal((int)UpdaterExitCode.InvalidRequest, application.Run(["--invalid"], directory.FullName)); + Assert.Equal(original, File.ReadAllBytes(result)); + } + finally { directory.Delete(recursive: true); } + } + [Fact] public void ResultFileIsAtomicLocalConciseAndHasNoUtf8Bom() { diff --git a/tools/Wisp.RecorderPrototype/HardwareEncoder.cpp b/tools/Wisp.RecorderPrototype/HardwareEncoder.cpp index 4067886..d082bb0 100644 --- a/tools/Wisp.RecorderPrototype/HardwareEncoder.cpp +++ b/tools/Wisp.RecorderPrototype/HardwareEncoder.cpp @@ -160,10 +160,11 @@ namespace recorder::encoder } } - ComPtr MediaType(bool compressed, const EncodeConfig& configuration) + ComPtr MediaType(bool compressed, const EncodeConfig& configuration, IMFMediaType* advertised = nullptr) { ComPtr type; Check(MFCreateMediaType(&type), "media_type_creation_failed"); + if (advertised) Check(advertised->CopyAllItems(type.Get()), "media_type_attribute_failed"); Check(type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "media_type_attribute_failed"); Check(type->SetGUID(MF_MT_SUBTYPE, compressed ? MFVideoFormat_H264 : MFVideoFormat_NV12), "media_type_attribute_failed"); Check(MFSetAttributeSize(type.Get(), MF_MT_FRAME_SIZE, configuration.width, configuration.height), "media_type_attribute_failed"); @@ -192,6 +193,40 @@ namespace recorder::encoder return type; } + template + bool SetInitialOutputType(Transform& transform, DWORD stream, const EncodeConfig& configuration, + UINT outputSamples, bool& retyped, DWORD status, DWORD bufferStatus) + { + if (retyped || outputSamples || status != 0 || bufferStatus != MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE) + return false; + const auto required = MediaType(true, configuration); + for (DWORD index = 0; index < 32; ++index) + { + ComPtr offered; + const HRESULT next = transform.GetOutputAvailableType(stream, index, &offered); + if (next == MF_E_NO_MORE_TYPES) break; + Check(next, "encoder_output_type_changed"); + GUID major{}, subtype{}; + if (!offered || FAILED(offered->GetGUID(MF_MT_MAJOR_TYPE, &major)) || major != MFMediaType_Video || + FAILED(offered->GetGUID(MF_MT_SUBTYPE, &subtype)) || subtype != MFVideoFormat_H264) continue; + BOOL matches = FALSE; + Check(required->Compare(offered.Get(), MF_ATTRIBUTES_MATCH_INTERSECTION, &matches), "output_type_readback_failed"); + if (!matches) continue; + // Advertised types may omit preset fields or add the encoder's sequence header. + const auto complete = MediaType(true, configuration, offered.Get()); + const HRESULT set = transform.SetOutputType(stream, complete.Get(), 0); + if (set == MF_E_INVALIDMEDIATYPE) continue; + CheckCodecSuccess(set, "encoder_output_type_changed"); + ComPtr current; + Check(transform.GetOutputCurrentType(stream, ¤t), "output_type_readback_failed"); + if (!current) return false; + Check(required->Compare(current.Get(), MF_ATTRIBUTES_MATCH_OUR_ITEMS, &matches), "output_type_readback_failed"); + retyped = matches != FALSE; + return retyped; + } + return false; + } + void VerifyOutput(HardwareSession& session, const EncodeConfig& configuration, Evidence& evidence) { ComPtr current; @@ -235,6 +270,7 @@ namespace recorder::encoder Require(requiredGopFrames == 0 || requiredGopFrames == 2 * configuration.frameRate, "gop_request_invalid"); evidence.requestedGopFrames = requiredGopFrames; Require(device && !session.transform && candidateIndex <= 15, "invalid_initializer_arguments"); + session.initialOutputRetyped = false; if (requireGameClosed) Require(!ForzaRunning(), "forza_running"); ComPtr dxgi; Check(device->QueryInterface(IID_PPV_ARGS(&dxgi)), "device_dxgi_query_failed"); @@ -420,7 +456,7 @@ namespace recorder::encoder } } - void ReadOutput(HardwareSession& session, const EncodeConfig&, Evidence& evidence, FixtureObserver* observer, + void ReadOutput(HardwareSession& session, const EncodeConfig& configuration, Evidence& evidence, FixtureObserver* observer, LONGLONG expectedTime100ns, bool checksum, GopTracker* gop) { MFT_OUTPUT_STREAM_INFO info{}; @@ -445,7 +481,14 @@ namespace recorder::encoder if (output.pSample && output.pSample != owned.Get()) provided.Attach(output.pSample); ComPtr events; events.Attach(output.pEvents); - if (hr == MF_E_TRANSFORM_STREAM_CHANGE) throw Failure{ "encoder_output_type_changed", hr }; + if (hr == MF_E_TRANSFORM_STREAM_CHANGE) + { + if (!SetInitialOutputType(*session.transform.Get(), session.outputId, configuration, evidence.outputSamples, + session.initialOutputRetyped, status, output.dwStatus)) + throw Failure{ "encoder_output_type_changed", hr }; + VerifyOutput(session, configuration, evidence); + return; // The next HaveOutput event owns the next ProcessOutput call. + } Check(hr, "hardware_process_output_failed"); Require(output.pSample != nullptr && (output.dwStatus & MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE) != MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE, @@ -854,6 +897,72 @@ namespace recorder::encoder UINT RunContractTests() noexcept { UINT passed = 0; + try + { + Runtime runtime; + runtime.Start(); + struct Formats + { + std::array, 3> offered; + ComPtr selected; + DWORD queried = 0, setCalls = 0; + bool wrongReadback = false; + HRESULT GetOutputAvailableType(DWORD stream, DWORD index, IMFMediaType** type) + { + ++queried; + if (stream != 7) return E_INVALIDARG; + if (index >= offered.size()) return MF_E_NO_MORE_TYPES; + return offered[index].CopyTo(type); + } + HRESULT SetOutputType(DWORD stream, IMFMediaType* type, DWORD flags) + { + if (stream != 7 || flags != 0) return E_INVALIDARG; + ++setCalls; + selected = type; + return S_OK; + } + HRESULT GetOutputCurrentType(DWORD stream, IMFMediaType** type) + { + if (stream != 7 || !selected) return E_INVALIDARG; + return wrongReadback ? offered[0].CopyTo(type) : selected.CopyTo(type); + } + } formats; + EncodeConfig preset; + formats.offered[0] = MediaType(true, preset); + formats.offered[1] = MediaType(true, preset); + formats.offered[2] = MediaType(true, preset); + const BYTE header[] = { 0x67, 0x42 }; + if (FAILED(formats.offered[0]->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_HEVC)) || + FAILED(formats.offered[1]->SetUINT32(MF_MT_VIDEO_PRIMARIES, MFVideoPrimaries_BT2020)) || + FAILED(formats.offered[2]->DeleteItem(MF_MT_FRAME_RATE)) || + FAILED(formats.offered[2]->SetBlob(MF_MT_MPEG_SEQUENCE_HEADER, header, sizeof(header)))) return 0; + bool retyped = false; + const DWORD change = MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE; + if (SetInitialOutputType(formats, 7, preset, 1, retyped, 0, change) || + SetInitialOutputType(formats, 7, preset, 0, retyped, MFT_PROCESS_OUTPUT_STATUS_NEW_STREAMS, change) || + SetInitialOutputType(formats, 7, preset, 0, retyped, 0, MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE) || + formats.queried != 0) return 0; + ++passed; + if (!SetInitialOutputType(formats, 7, preset, 0, retyped, 0, change) || !retyped || + formats.queried != 3 || formats.setCalls != 1) return 0; + UINT32 rate = 0, denominator = 0, bytes = 0; + BYTE retained[sizeof(header)]{}; + if (FAILED(MFGetAttributeRatio(formats.selected.Get(), MF_MT_FRAME_RATE, &rate, &denominator)) || + rate != preset.frameRate || denominator != 1 || + FAILED(formats.selected->GetBlob(MF_MT_MPEG_SEQUENCE_HEADER, retained, sizeof(retained), &bytes)) || + bytes != sizeof(header) || !std::equal(std::begin(header), std::end(header), std::begin(retained))) return 0; + ++passed; + if (SetInitialOutputType(formats, 7, preset, 0, retyped, 0, change) || formats.queried != 3) return 0; + ++passed; + retyped = false; + formats.wrongReadback = true; + if (SetInitialOutputType(formats, 7, preset, 0, retyped, 0, change) || retyped) return 0; + ++passed; + formats.offered[2] = formats.offered[1]; + if (SetInitialOutputType(formats, 7, preset, 0, retyped, 0, change) || formats.setCalls != 2) return 0; + ++passed; + } + catch (...) { return 0; } Options parsed; const wchar_t* defaults[]{ L"fixture" }; if (!ParseOptions(1, defaults, parsed) || parsed.mode != Mode::Help) return 0; diff --git a/tools/Wisp.RecorderPrototype/HardwareEncoder.h b/tools/Wisp.RecorderPrototype/HardwareEncoder.h index 24c0478..2471bd5 100644 --- a/tools/Wisp.RecorderPrototype/HardwareEncoder.h +++ b/tools/Wisp.RecorderPrototype/HardwareEncoder.h @@ -39,7 +39,7 @@ namespace recorder::encoder EncodeConfig configuration{}; }; - // Parsing and contract tests do not initialize COM, MF, graphics or capture. + // Parsing initializes nothing. Contract tests start COM and Media Foundation, and no graphics or capture. bool ParseOptions(int argc, const wchar_t* const* argv, Options& result) noexcept; UINT RunContractTests() noexcept; // Zero denotes failure; otherwise checks passed. @@ -106,6 +106,7 @@ namespace recorder::encoder DWORD inputId = 0; DWORD outputId = 0; bool streaming = false; + bool initialOutputRetyped = false; HardwareSession() = default; ~HardwareSession(); HardwareSession(const HardwareSession&) = delete; diff --git a/tools/Wisp.UiReview/Program.cs b/tools/Wisp.UiReview/Program.cs index ba53713..5ac7949 100644 --- a/tools/Wisp.UiReview/Program.cs +++ b/tools/Wisp.UiReview/Program.cs @@ -99,8 +99,11 @@ private static int Main(string[] args) if (args.Length == 7 && args[0] == "--clips-lossless-playback-check" && args[1] == "--source" && args[3] == "--sha256" && args[5] == "--output") return LosslessPlaybackReview.Run(args[2], args[4], PrepareOutput(args[6])); - if (args.Length == 3 && args[0] == "--tune-live-check" && args[1] == "--output") - return TuneLiveReview.RunAsync(PrepareOutput(args[2])).GetAwaiter().GetResult(); + if (args.Length > 0 && args[0] == "--tune-live-check") + { + var (output, version) = TuneLiveReview.ParseArguments(args); + return TuneLiveReview.RunAsync(PrepareOutput(output), version).GetAwaiter().GetResult(); + } if (args.Length == 5 && args[0] == "--clips-playback-check" && args[1] == "--source" && args[3] == "--output") { var output = PrepareOutput(args[4]); @@ -243,7 +246,7 @@ private static int Main(string[] args) Console.WriteLine("Fixtures: " + string.Join(", ", Fixture.All.Select(fixture => fixture.Name))); Console.WriteLine("--clips-check --output checks the actual detached Clips page at 720/980/1464 widths and 96/144 DPI, generated posters, empty/pending/player layouts and closed selector templates. Isolated placeholder files only; no shown window, recorder helper, media playback or installed library access."); Console.WriteLine("--tune-check --output checks detached current/saved/comparison Tune views and name/description dialogs in both interfaces at 720/1280 widths and 96/144 DPI. Embedded offline fixtures and isolated storage only; no shown window or game reads."); - Console.WriteLine("--tune-live-check --output explicitly reads the real foreground Forza tune twice through the production reader and checks completeness, session and setup consistency. No shown windows or game writes; 15-second cancellation budget, 30-second process limit. Requires separately confirmed readiness; never changes focus."); + Console.WriteLine("--tune-live-check --output [--expect-game-version ] explicitly reads the real foreground Forza tune twice through the production reader and checks completeness, session and setup consistency. When supplied, both captures must match the exact game version. No shown windows or game writes; 15-second cancellation budget, 30-second process limit. Requires separately confirmed readiness; never changes focus."); Console.WriteLine("--tune-asset-diagnostic --reference --output explicitly compares bounded foreground game metadata with the pinned local reference. Scalars and projection hashes only; no raw database files, game writes or product acceptance. Requires fresh readiness. --tune-asset-offline-check uses the same arguments and only controlled mutations of the retained reference; no game access. Both have a 30-second hard limit."); Console.WriteLine("--clips-large-playback-check --source --metadata --output copies one explicitly selected 20-second-or-longer clip (at most 4 GiB) into an isolated library, then checks the actual muted Clips player for 15 seconds plus preparation and transport. Metadata contains only recording and media records. Requires Forza and Wisp closed; passive window, 90-second watchdog, no source writes or capture. Private fixture copy is retained; output contains scalar timing/state only."); Console.WriteLine("--clips-lossless-product-check --source --output checks the actual Clips page's lossless thumbnail and paused transport, replay and cleanup. Fixed silent 128-frame/60-fps fixture; isolated library, passive window, 20-second work budget and 30-second hard limit. Requires Forza and Wisp closed. No screenshots, gameplay, A/V sync or performance claim."); diff --git a/tools/Wisp.UiReview/TuneLiveReview.cs b/tools/Wisp.UiReview/TuneLiveReview.cs index 684a4e5..d36c7e1 100644 --- a/tools/Wisp.UiReview/TuneLiveReview.cs +++ b/tools/Wisp.UiReview/TuneLiveReview.cs @@ -18,15 +18,31 @@ internal static class TuneLiveReview Converters = { new JsonStringEnumConverter() } }; - internal static async Task RunAsync(string output) + internal static (string Output, string? ExpectedGameVersion) ParseArguments(string[] args) => args switch { - var report = new LiveReport(); + ["--tune-live-check", "--output", var output] => (output, null), + ["--tune-live-check", "--output", var output, "--expect-game-version", var version] when IsGameVersion(version) => (output, version), + _ => throw new ArgumentException("Invalid Tune live review arguments.") + }; + + private static bool IsGameVersion(string value) => value.Length <= 32 && Version.TryParse(value, out var version) && + version.Revision >= 0 && version.ToString() == value; + + internal static async Task RunAsync(string output, string? expectedGameVersion = null) + { + var report = new LiveReport { ExpectedGameVersion = expectedGameVersion }; + TuneValidationFailure? tuneValidationFailure = null; void ObserveReadFailure(object? sender, FirstChanceExceptionEventArgs args) { if (args.Exception is not (IOException or InvalidDataException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or DllNotFoundException or EntryPointNotFoundException or ArgumentException or OverflowException)) return; - var frames = new StackTrace(true).GetFrames() + var stack = new StackTrace(true).GetFrames(); + if (args.Exception is InvalidDataException invalid && GetTuneValidationFailure(invalid.Message) is { } failure && + stack.Any(frame => frame.GetMethod() is { Name: nameof(NativeAdaptiveResolver.Resolve) } method && + method.DeclaringType == typeof(NativeAdaptiveResolver))) + Interlocked.CompareExchange(ref tuneValidationFailure, failure, null); + var frames = stack .Where(frame => frame.GetMethod()?.DeclaringType?.Namespace == "Wisp.App.Tunes") .Take(12) .Select(frame => new ReadFailureFrame(frame.GetMethod()!.DeclaringType!.Name, @@ -58,7 +74,8 @@ System.ComponentModel.Win32Exception or DllNotFoundException or EntryPointNotFou var first = await CaptureAsync(service, budget.Token).ConfigureAwait(false); report.FirstCaptureMilliseconds = first.ElapsedMilliseconds; report.FirstStatus = first.Result.Status; - var snapshot = Validate(first.Result, "first"); + report.FirstGameVersion = CaptureGameVersion(first.Result); + var snapshot = Validate(first.Result, "first", expectedGameVersion); report.Snapshot = snapshot; Require(snapshot.IsComplete, "incomplete-tune", "One or more tuning controls are unavailable; inspect the field statuses."); report.FirstWasCurrent = service.IsCurrent(snapshot); @@ -72,7 +89,8 @@ System.ComponentModel.Win32Exception or DllNotFoundException or EntryPointNotFou var confirmation = await CaptureAsync(service, budget.Token).ConfigureAwait(false); report.ConfirmationCaptureMilliseconds = confirmation.ElapsedMilliseconds; report.ConfirmationStatus = confirmation.Result.Status; - var confirmed = Validate(confirmation.Result, "confirmation"); + report.ConfirmationGameVersion = CaptureGameVersion(confirmation.Result); + var confirmed = Validate(confirmation.Result, "confirmation", expectedGameVersion); Require(confirmed.IsComplete, "incomplete-confirmation", "The confirmation read contains unavailable tuning controls."); report.SessionStillCurrent = service.IsCurrent(snapshot) && service.IsCurrent(confirmed); Require(report.SessionStillCurrent, "session-changed", "The car or game session changed between the two reads."); @@ -147,14 +165,58 @@ System.ComponentModel.Win32Exception or DllNotFoundException or EntryPointNotFou { token.ThrowIfCancellationRequested(); report.CaptureRequests++; + Interlocked.Exchange(ref tuneValidationFailure, null); var captureStarted = Stopwatch.GetTimestamp(); var result = await capture.RequestSnapshotAsync(token).ConfigureAwait(false); + report.TuneValidation = ReportedValidation(result, Volatile.Read(ref tuneValidationFailure)); token.ThrowIfCancellationRequested(); return (result, Stopwatch.GetElapsedTime(captureStarted).TotalMilliseconds); } } - private static TuneSnapshot Validate(TuneCaptureResult result, string read) + internal static TuneValidationFailure? ReportedValidation(TuneCaptureResult result, TuneValidationFailure? failure) => + result.Status == TuneCaptureStatus.UnsupportedBuild && + result.Incident is { Reason: "compatibility-unavailable", FailureStage: "tune-read" } ? failure : null; + + internal static TuneValidationFailure? GetTuneValidationFailure(string message) + { + var separator = message.IndexOf(": /tune/", StringComparison.Ordinal); + if (separator < 0) return null; + var reason = message[..separator] switch + { + "Adaptive reader role unavailable" => "role-unavailable", + "Adaptive reader region changed" => "region-changed", + "Adaptive reader guard changed" => "guard-changed", + "Adaptive table changed" => "table-changed", + _ => null + }; + var role = message[(separator + ": /tune/".Length)..].Split('/')[0] switch + { + "codeGuards" => "code-guard", + "providerSlots" => "provider-slot", + "rvas" => "tune-data", + _ => null + }; + return reason is not null && role is not null ? new(reason, role) : null; + } + + internal static string? CaptureGameVersion(TuneCaptureResult result) + { + if (result.Snapshot is { } snapshot) + return snapshot.Identity?.GameVersion is { } observed && IsGameVersion(observed) ? observed : null; + using var details = new StringReader(result.Details); + if (details.ReadLine() != "Wisp Tune read details") return null; + const string label = "Game version: "; + while (details.ReadLine() is { } line) + { + if (!line.StartsWith(label, StringComparison.Ordinal)) continue; + var value = line[label.Length..]; + return IsGameVersion(value) ? value : null; + } + return null; + } + + internal static TuneSnapshot Validate(TuneCaptureResult result, string read, string? expectedGameVersion) { if (!result.Success || result.Snapshot is null) { @@ -170,6 +232,8 @@ private static TuneSnapshot Validate(TuneCaptureResult result, string read) } if (!TuneSnapshotValidator.TryValidate(result.Snapshot, out _)) Fail($"{read}-snapshot-invalid", "The captured snapshot failed the production consistency validator."); + if (expectedGameVersion is not null && result.Snapshot!.Identity.GameVersion != expectedGameVersion) + Fail($"{read}-game-version-mismatch", "The captured tune belongs to a different game version than requested."); return result.Snapshot!; } @@ -179,7 +243,7 @@ private static void Require(bool condition, string code, string reason) } private static void Fail(string code, string reason) => throw new ReviewFailure(code, reason); - private sealed class ReviewFailure(string code, string reason) : Exception(reason) + internal sealed class ReviewFailure(string code, string reason) : Exception(reason) { internal string Code { get; } = code; } @@ -193,6 +257,8 @@ private sealed class LiveReport public string? Reason { get; set; } public string? ExceptionType { get; set; } public ReadFailureDetails? ReadFailure { get; set; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public TuneValidationFailure? TuneValidation { get; set; } public AssetStreamDetails? AssetStream { get; set; } public int? ExceptionHResult { get; set; } public bool? ForegroundAtStart { get; set; } @@ -201,6 +267,9 @@ private sealed class LiveReport public int CaptureRequests { get; set; } public TuneCaptureStatus? FirstStatus { get; set; } public TuneCaptureStatus? ConfirmationStatus { get; set; } + public string? ExpectedGameVersion { get; set; } + public string? FirstGameVersion { get; set; } + public string? ConfirmationGameVersion { get; set; } public bool FirstWasCurrent { get; set; } public bool SessionStillCurrent { get; set; } public bool SetupMatched { get; set; } @@ -219,6 +288,7 @@ private sealed class LiveReport } private sealed record ReadFailureFrame(string Type, string Method, int Line); + internal sealed record TuneValidationFailure(string Reason, string Role); private sealed record ReadFailureDetails(string Type, int HResult, ReadFailureFrame[] Frames); private sealed record AssetStreamDetails(byte Flag, uint ChunkSize, uint Allocated, ulong Length, long VectorBytes); }