Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.2 4423710fb0 test(display): the monitor a game's window is on, asked by a named window as Observe is - and tested against the harness's window (Advanced PR-6; SonarCloud's coverage of PR-5's new code)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 19:21:11 +07:00
poli0981andClaude Fable 5.2 0627785a88 feat(ipc): GetAdvancedMachine - what the Agent's advanced reader last read, answered without touching a sensor, each request the page's hold on that reader; and the App's feed that asks while a page watches (Advanced PR-6, D101/D107)
Application.Ipc.AdvancedMachineResponder answers from IAdvancedHardware.Latest alone: the pipe's read loop awaits its
handler, so a driver call there would hold up Ping and StopSession. The first request acquires the shared reader and
each renews a five-second lease; a lease after the last one the hold is let go - a page that closes, an App that
exits and a pipe that drops all look the same. With telemetry.advanced off the answer is Error AdvancedOff and
nothing is held. The facts travel once, by their hash; a reading that is not a number is left out. Additive,
protocol 2.

App.Services.AdvancedMachineFeed asks once a second while a page holds Watch(), and keeps the facts, the last value
of every series with the tick it was read on, five minutes of each for the live charts and the sources' states.
It stores nothing, and no page watches it yet. Nothing in src/native changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 19:21:11 +07:00
18 changed files with 1260 additions and 6 deletions

No files matched your search

+7
View File
@@ -93,6 +93,13 @@ numeric core and does not move; the heading is the full version — corrected 20
a session recorded while it was off is not filled in later. NVIDIA's figures are read once a second, the sensors
every five. **No page shows what is stored yet** — that is the next pull requests' — and none of it is in an
export or a bug report.
- **The App can ask the agent what this PC reads right now — and no page asks yet.** A new request,
`GetAdvancedMachine`, answers what the agent's shared reader last read: the PC's facts, the newest value of every
series, and which sources answer or why they do not. It never touches a sensor itself, so it cannot hold up the
pipe. Each request also keeps the reader running for five seconds, which is how "with no game running, sensors are
read only while the page is open" works without anything telling the agent that a page closed. With Advanced
metrics off it answers that it is off, and nothing is read. On the App's side `AdvancedMachineFeed` asks once a
second while a page watches it and keeps each value with the moment it was read.
- **The terms window shows the Privacy Policy 2.15 and the Disclaimer 2.15 once.** The Privacy Policy names what
Advanced metrics reads and stores, only while it is on, and what it never reads: a serial number, a display's
identification data, a list of other programs. The Disclaimer's two sentences about PawnIO and about running the
+3 -1
View File
@@ -113,7 +113,9 @@ src/
# NvapiAdvancedReader (the bridge's ABI 3) and LhmAdvancedReader (LhmGroups:
# the card; as administrator with PawnIO the processor, memory and board -
# never storage, D103). The Agent composes it since the switch, `telemetry.advanced`
# (PR-5, 2026-11-11: off by default; on, a session holds the hub). Recording/
# (PR-5, 2026-11-11: off by default; on, a session holds the hub), and
# Ipc/AdvancedMachineResponder answers GetAdvancedMachine from the hub's last
# snapshot - each request is the page's hold on it (PR-6, D107). Recording/
# AdvancedSessionBuilder stores what a session's samples carried (schema 0023:
# machine_profiles + session_advanced, adv.* series with NaN for a gap, D102).
FrameLedger.Infrastructure/ # SQLite, shm reader, vendor APIs, injector interop, parsers,
+1
View File
@@ -402,6 +402,7 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
| `Shutdown` | UI→A | graceful stop → `ShutdownAck`, then the host stops (sessions finalize inside its grace window). *(Built 2026-09-13, PR-1b: `IAgentLifetime`, the host's under `--serve`, a logged no-op under `--console`.)* |
| `DeleteSessions` | UI→A | **Added 2026-10-03 (beta.11, D40).** `{ gameId? }` — every session of that game, or of every game when it is null, with their segments, frame and sensor series and annotations (they cascade) → `DeleteSessionsAck { gameId?, games, sessions }`. `Error SessionRunning` and nothing deleted while a session of that game — of any game, for all — is being recorded (`CaptureOrchestrator.IsRecording` / `IsRecordingAny`). The client names no rows beyond the game: they are the Agent's (§Writer ownership). Additive: an older Agent answers `Error UnknownType`, which the App says as "restart the agent". Carries no safety fact. |
| `SweepRetention` | UI→A | **no payload** — a trigger, like `UpdateRules`: the Agent applies `06_DATA_MODEL` §Retention to every game with the `retention.raw_sessions_per_game` it reads itself → `SweepRetentionAck { keep, games, sessions }` (`keep` 0 = unlimited, and then nothing was swept). *(Built 2026-09-15, P4 PR-7, for Tools ▸ Database maintenance: `Application.Recording.RetentionSweep` over `ISessionRepository.SweepRetentionAllAsync`, composed into `AgentCommandHandler` under `--serve`. The client names no number because the rows are the Agent's (§Writer ownership). Additive: an older Agent answers `Error UnknownType`, which the dialog reads as "restart the Agent". Carries no safety fact.)* |
| `GetAdvancedMachine` | UI→A | **Added 2026-11-11 (Advanced PR-6, owner decisions D101/D107).** `{ factsHash? }` → `AdvancedMachineAck { ready, takenAtUnixMs, factsHash?, factsJson?, readings[{ series, value }], series[{ series, metricId, label }], nvapi, nvapiCode?, sensors, elevatedSensors }` — what the Agent's shared advanced reader last read about this PC (`18_GPU_VENDOR_APIS` §The page's feed). **The handler reads no sensor**: the answer is the reader's last snapshot, one reference, because the pipe's read loop awaits its handler and a driver call there would hold up `Ping` and `StopSession`; the one thing it awaits is the option, a `settings` row asked for at most every two seconds. **A request is the page's hold on the reader**: the first acquires it and each renews a five-second lease, so the App asks once a second while the page is open and nothing has to say that it closed (`Application.Ipc.AdvancedMachineResponder`). `ready: false` — held, not yet read — carries nothing else. `readings` are that tick's only: a slow source is read every few ticks and the client keeps the last value it saw; a value that is not a number is left out. `factsJson` is the PC's facts as the ledger stores them (`AdvancedJson.OfFacts`), left out when the request's `factsHash` is the Agent's own. The three states are `AdvancedSourceStatus` names; a name a client does not know reads as unknown. `Error AdvancedOff` while `telemetry.advanced` is off — nothing is read, and a hold a previous request took is let go at once. Additive, protocol 2: an older Agent answers `Error UnknownType`, which the page shows as such. Carries no safety fact and changes nothing. |
| `SessionStarted` | A→UI | `{ sessionGuid, gameId, gameName, pid, tier, startedAt, hold? }` — **published once per session**: at the attach (tier 1, `startedAt` the attach), or — **since 2026-09-23** — at the first tick of a session held unhooked (tier 2, `startedAt` the session's start, `pid` 0 when the loop never opened the process, as a hooking-off hold never does). ~~a session that never attaches has no `SessionStarted`, only its `SessionCompleted` (tier 2)~~ — that was the beta.5 wire, and every hooking-off, refused or unreadable game read "Nothing is being captured." for as long as it ran. **`hold` (optional, tier 2 only)** is why nothing is measured: `{ reason, guardReason?, family?, signal?, hookingTurnedOff }` — the loop's `SessionEndReason` and, when the guard said anything but allow, its reason, family and signal: the same words the row's `capture_notes` will carry, so the live card and the summary read one sentence (`Formats.Tier2HoldReason` / `Tier2Reason`). The refusal's own event (`CaptureRefused` and the rest, below) goes out with this start rather than when the game exits, and is not repeated at the end |
| `SessionHeld` | A→UI | **Added 2026-09-23.** 1 Hz while a client listens, for a session held unhooked only: `{ sessionGuid, elapsedS, gpuTempC?, cpuTempC?, gpuLoadPct?, cpuLoadPct?, gameVramDedicatedMb?, gameRamPrivateMb? }` — how long it has run and the machine's sensors (and since beta.12 the game process's own memory, read from outside it — optional, an older client ignores them). **Never `SessionProgress`**: its `presents5s`, `presentedQualifier` and `fgMode` are required, and zeros there would put measured-looking numbers on the wire for a session that measures nothing (rule 6 has nothing to show and shows nothing) |
| `SessionProgress` | A→UI | 1 Hz: `{ sessionGuid, elapsedS, presents5s, presentedFps5s?, presentedQualifier, nativeFps5s?, displayedFps5s?, fgFactor?, fgMode, upscaler?, upscalerQuality?, upscalerDriverReported?, renderW/H?, outputW/H?, rtActive?, gpuTempC?, cpuTempC?, cpuLoadPct?, vramProcMb?, latencyUs?, fgRefusal?, fgRuntimeCensus?, gameVramDedicatedMb?, gameRamPrivateMb? }` (the last two added 2026-10-03, beta.12, optional: the game process's dedicated GPU memory and private working set, MiB, from the newest telemetry tick; `vramProcMb` stays reserved for the in-process figure and has no producer) — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **`upscalerQualityOverride` added 2026-10-19 (beta.24, D63), optional:** the mode an NVIDIA App override set when the driver reports it applied in the target and DLSS super resolution ran there — `performance`, `balanced`, `quality`, `ultra_performance`, `ultra_quality`, `dlaa`, or `override` when the driver's report alone does not settle the mode (the profile is the stored session's); absent otherwise. **`upscalerDriverReported` added 2026-09-21, optional:** `dlss` when the NVIDIA driver reports an NGX super-resolution feature created and evaluated in the target (`03_METRICS` §The driver-reported rung), so the live card says `DLSS (driver-reported)` where no hook can name the upscaler; identity only. **`cpuLoadPct` added 2026-09-21, optional** (CPU time busy over the last telemetry tick, 0–100; `cpuTempC` has a producer from the same date, present only when the Agent is elevated with PawnIO). **Two fields added 2026-09-14, both optional (an older client ignores them, §C):** `fgRefusal` is the row's `fg_refusal` (schema 0003) — present when `fgMode` names a technology and `fgFactor` is absent, so the live card can say "DLSS-G active — factor not counted" rather than N/A; `fgRuntimeCensus` is the raw census so the `fg_runtime_loaded` chip can name the module. **Rule 6 at the wire (2026-09-13):** `nativeFps5s` / `displayedFps5s` / `fgFactor` are present only when frame generation was measured in the window; otherwise `presentedFps5s` stands alone with `presentedQualifier` (`census_not_run` · `no_fg_runtime` · `fg_runtime_loaded` · `none_withheld`, the row's `presented_qualifier` from the same function). Every unmeasured field is absent, never 0. Suppressed when no client is connected |
+16
View File
@@ -654,6 +654,22 @@ and motherboard groups in a session with the option on. The texts that state wha
Disclaimer 2.15 §5 and §5A (the owner's answer of 2026-11-11), the admin mode's disclosure (`agent-admin-dialog/2`),
Settings, the first run, the guide and `LIMITATIONS.md` — and Privacy Policy 2.15 names what is read and stored.
### The page's feed (built 2026-11-11, Advanced PR-6; shown by nothing yet)
With no game running the Agent reads sensors **only while the page is open** (D107), and nothing tells the Agent
that a page opened or closed:
- **`GetAdvancedMachine`** (`07_IPC` §Messages) is answered by `Application.Ipc.AdvancedMachineResponder` from
`IAdvancedHardware.Latest` alone. The first request acquires the shared reader and each one renews a five-second
lease; a lease after the last request the hold is let go, and the reader closes its sources ten seconds later
unless a session holds it. A page that closes, an App that exits and a pipe that drops all look the same: no
request. With the option off the answer is `Error AdvancedOff`, and nothing is held.
- **`App.Services.AdvancedMachineFeed`** asks once a second while a page holds `Watch()`, and keeps the facts (asked
for once, by their hash), **the last value of every series with the tick it was read on** — a sensor read every
fifth tick is "1400, as of then", never shown as new — five minutes of each series for the live charts, and the
sources' states. It stores nothing. Its states are the page's own words for why there is nothing to show: waiting
for the first read, off, no agent (a viewer never has one), an older agent.
### What belongs to what
| Scope | What it is | Stored | Shown |
@@ -256,11 +256,18 @@ internal static class AgentServices
services.AddSingleton<CapturePause>();
services.TryAddSingleton<IAgentLifetime, NoAgentLifetime>();
services.AddSingleton(static sp => CommandHandler(sp));
// GetAdvancedMachine (D101/D107): the App's page asks once a second while it is open, and each request is its
// hold on the shared reader for a few seconds - so nothing has to tell the Agent that the page closed.
services.AddSingleton(static sp => new AdvancedMachineResponder(
sp.GetRequiredService<IAdvancedHardware>(),
ct => sp.GetRequiredService<RegisteredSettings>().GetBooleanAsync(SettingsRegistry.TelemetryAdvanced, ct),
TimeProvider.System));
services.AddSingleton<IIpcRequestHandler>(static sp => new AgentRequestHandler(
AgentIdentityFactory.OfThisProcess(sp.GetRequiredService<AgentPaths>().VkLayerDirectory, sp.GetService<AgentElevationState>()?.Outcome),
TelemetryDescriptor(),
() => sp.GetRequiredService<SessionEventPublisher>().Status,
() => sp.GetRequiredService<AgentCommandHandler>()));
() => sp.GetRequiredService<AgentCommandHandler>(),
sp.GetRequiredService<AdvancedMachineResponder>()));
services.AddSingleton(static sp => new PipeServer(
sp.GetRequiredService<PipeServerOptions>(),
sp.GetRequiredService<IIpcRequestHandler>(),
+3
View File
@@ -483,6 +483,9 @@ public partial class App : System.Windows.Application
sp.GetRequiredService<Application.Play.IGogGalaxyLocator>(),
sp.GetRequiredService<IShellStarter>(),
sp.GetRequiredService<IAgentRequests>()));
// Advanced metrics (D101/D107): "this PC, now" for its page. It asks the Agent only while a page watches it, and a
// viewer's link is never connected - so it says "no agent" there.
services.AddSingleton(static sp => new AdvancedMachineFeed(sp.GetRequiredService<IAgentRequests>(), TimeProvider.System));
services.AddSingleton<IExecutableIdentitySource, ExecutableIdentitySource>();
services.AddSingleton(static sp => new LibraryImporter(
sp.GetServices<IStoreLibrarySource>(),
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.App.Services;
/// <summary>What <see cref="AdvancedMachineFeed"/> last learnt from the Agent about "this PC, now" (owner decision D101).</summary>
public enum AdvancedFeedState
{
/// <summary>Nobody watches: nothing is asked, and the Agent's reader is not held for the page.</summary>
Stopped,
/// <summary>Asked, and the Agent's reader has not finished its first read.</summary>
Waiting,
/// <summary>The last request was answered with a snapshot.</summary>
Live,
/// <summary>The Agent answered that Advanced metrics is off: it reads nothing.</summary>
Off,
/// <summary>No Agent answered — not connected, a viewer, a request that timed out or failed. What was shown stays, as old as it is.</summary>
NoAgent,
/// <summary>The Agent is an older one that does not know the request.</summary>
OlderAgent,
}
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.InteropServices;
namespace FrameLedger.App.Services;
/// <summary>One live reading of an advanced series: its value and when the Agent's reader read it.</summary>
/// <param name="At">The tick it was read on, by the Agent's clock.</param>
/// <param name="Value">The value, in the unit of its catalog entry.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct AdvancedLivePoint(DateTimeOffset At, double Value);
@@ -0,0 +1,296 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FrameLedger.Application.Advanced;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Shared.Ipc;
using Serilog;
namespace FrameLedger.App.Services;
/// <summary>
/// "This PC, now" for the Advanced page (owner decisions D101 and D107): while somebody watches, asks the Agent
/// <c>GetAdvancedMachine</c> once a second and keeps what it answered — the facts, the last value of every series, a
/// short history of each for the live charts, and which sources answer.
/// </summary>
/// <remarks>
/// <para>
/// <b>Watching is what makes the Agent read.</b> Each request keeps the Agent's shared reader running for a few
/// seconds (<c>Application.Ipc.AdvancedMachineResponder</c>), so nothing is asked — and with no game running no sensor
/// is read — unless a page holds <see cref="Watch"/>. The page lets go when it is unloaded or its window is hidden.
/// </para>
/// <para>
/// <b>Nothing here is stored.</b> The history lives in memory, a few minutes long, and is gone with the App; what a
/// session stores is the Agent's, in the ledger.
/// </para>
/// <para>
/// It fires <see cref="Changed"/> on the thread pool, like the Agent's link; a view model marshals through
/// <c>UiThread</c>.
/// </para>
/// </remarks>
public sealed class AdvancedMachineFeed : IDisposable
{
/// <summary>How many points of each series are kept for the live charts: five minutes at one a second.</summary>
public const int HistoryPoints = 300;
private static readonly TimeSpan _defaultInterval = TimeSpan.FromSeconds(1);
private readonly IAgentRequests _agent;
private readonly TimeProvider _clock;
private readonly TimeSpan _interval;
private readonly Lock _gate = new();
private readonly Dictionary<string, AdvancedLivePoint> _values = new(StringComparer.Ordinal);
private readonly Dictionary<string, Queue<AdvancedLivePoint>> _history = new(StringComparer.Ordinal);
private IReadOnlyList<AdvancedFact> _facts = [];
private string? _factsHash;
private long _lastTick = long.MinValue;
private IReadOnlyList<AdvancedSeriesInfo> _series = [];
private AdvancedSources _sources = AdvancedSources.Unknown;
private int _watchers;
private CancellationTokenSource? _stop;
private volatile AdvancedMachineView _current = AdvancedMachineView.Stopped;
/// <summary>Over the App's requests to the Agent — a viewer's link is never connected, and the feed says so.</summary>
public AdvancedMachineFeed(IAgentRequests agent, TimeProvider clock, TimeSpan? interval = null)
{
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_interval = interval ?? _defaultInterval;
}
/// <summary>After every request while watched, and once when the last watcher lets go.</summary>
public event EventHandler? Changed;
/// <summary>What was last learnt.</summary>
public AdvancedMachineView Current => _current;
/// <summary>
/// Asks the Agent once a second until the returned handle is disposed. The first watcher starts the asking and the
/// last one stops it; a handle disposed twice counts once.
/// </summary>
public IDisposable Watch()
{
lock (_gate)
{
if (_watchers++ == 0)
{
var stop = new CancellationTokenSource();
_stop = stop;
_ = Task.Run(() => RunAsync(stop.Token), CancellationToken.None);
}
}
return new Watcher(this);
}
/// <summary>The kept points of one series, oldest first; empty for a series never read.</summary>
public IReadOnlyList<AdvancedLivePoint> HistoryOf(string series)
{
lock (_gate)
{
return _history.TryGetValue(series, out Queue<AdvancedLivePoint>? points) ? [.. points] : [];
}
}
/// <summary>One request and what it came to. The loop's body, and what a test calls.</summary>
public async Task PollOnceAsync(CancellationToken ct = default)
{
AdvancedFeedState state;
AdvancedMachineAck? ack = null;
try
{
string? hash;
lock (_gate)
{
hash = _factsHash;
}
IpcEnvelope envelope = await _agent.RequestAsync(IpcMessageType.GetAdvancedMachine, new GetAdvancedMachineRequest(hash), ct).ConfigureAwait(false);
ack = IpcCodec.Payload<AdvancedMachineAck>(envelope);
state = ack switch
{
null => AdvancedFeedState.NoAgent,
{ Ready: false } => AdvancedFeedState.Waiting,
_ => AdvancedFeedState.Live,
};
}
catch (IpcRequestException ex) when (string.Equals(ex.Code, IpcErrorCode.AdvancedOff, StringComparison.Ordinal))
{
state = AdvancedFeedState.Off;
}
catch (IpcRequestException ex) when (string.Equals(ex.Code, IpcErrorCode.UnknownType, StringComparison.Ordinal))
{
state = AdvancedFeedState.OlderAgent;
}
catch (IpcRequestException ex)
{
Log.Warning("advanced: GetAdvancedMachine failed ({Code}: {Message})", ex.Code, ex.Message);
state = AdvancedFeedState.NoAgent;
}
catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or System.IO.IOException)
{
// Not connected (a viewer never is), no answer in time, or the pipe dropped: the next second asks again.
state = AdvancedFeedState.NoAgent;
}
if (!ct.IsCancellationRequested)
{
// A request still in flight when the last watcher let go answers nobody: "stopped" was already said.
Publish(state, ack);
}
}
public void Dispose()
{
CancellationTokenSource? stop;
lock (_gate)
{
_watchers = 0;
stop = _stop;
_stop = null;
}
stop?.Cancel();
stop?.Dispose();
}
private async Task RunAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(_interval, _clock);
try
{
do
{
await PollOnceAsync(ct).ConfigureAwait(false);
}
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException)
{
// The last watcher let go.
}
}
private void Release()
{
CancellationTokenSource? stop;
lock (_gate)
{
if (_watchers == 0 || --_watchers > 0)
{
return;
}
stop = _stop;
_stop = null;
}
stop?.Cancel();
stop?.Dispose();
Publish(AdvancedFeedState.Stopped, ack: null);
}
private void Publish(AdvancedFeedState state, AdvancedMachineAck? ack)
{
AdvancedMachineView view;
lock (_gate)
{
if (state == AdvancedFeedState.Off)
{
// Off means nothing is read: what was shown is not "now" any more, and is not kept as if it were.
Forget();
}
else if (state == AdvancedFeedState.Live && ack is not null)
{
Apply(ack);
}
view = new AdvancedMachineView(
state,
_lastTick == long.MinValue ? null : DateTimeOffset.FromUnixTimeMilliseconds(_lastTick),
_facts,
new Dictionary<string, AdvancedLivePoint>(_values, StringComparer.Ordinal),
_series,
_sources);
}
_current = view;
Changed?.Invoke(this, EventArgs.Empty);
}
private void Forget()
{
_values.Clear();
_history.Clear();
_facts = [];
_factsHash = null;
_lastTick = long.MinValue;
_series = [];
_sources = AdvancedSources.Unknown;
}
private void Apply(AdvancedMachineAck ack)
{
if (ack.FactsJson is not null)
{
_facts = AdvancedJson.ParseFacts(ack.FactsJson);
_factsHash = ack.FactsHash;
}
else if (!string.Equals(ack.FactsHash, _factsHash, StringComparison.Ordinal))
{
// The Agent holds other facts than the ones kept here and sent none: ask for them outright next time.
_factsHash = null;
}
_sources = new AdvancedSources(StatusOf(ack.Nvapi), ack.NvapiCode, StatusOf(ack.Sensors), StatusOf(ack.ElevatedSensors));
var series = new List<AdvancedSeriesInfo>(ack.Series.Count);
foreach (AdvancedSeriesLabel label in ack.Series)
{
series.Add(new AdvancedSeriesInfo(label.Series, label.MetricId, label.Label));
}
_series = series;
if (ack.TakenAtUnixMs == _lastTick)
{
// The same tick as a second ago - the reader's interval and this one are not in step: no new point.
return;
}
_lastTick = ack.TakenAtUnixMs;
DateTimeOffset at = DateTimeOffset.FromUnixTimeMilliseconds(ack.TakenAtUnixMs);
foreach (AdvancedReadingValue reading in ack.Readings)
{
var point = new AdvancedLivePoint(at, reading.Value);
_values[reading.Series] = point;
if (!_history.TryGetValue(reading.Series, out Queue<AdvancedLivePoint>? points))
{
points = new Queue<AdvancedLivePoint>();
_history[reading.Series] = points;
}
points.Enqueue(point);
while (points.Count > HistoryPoints)
{
points.Dequeue();
}
}
}
/// <summary>A state by its name on the wire; a name this build does not know — a newer Agent's — is unknown, never a guess.</summary>
private static AdvancedSourceStatus StatusOf(string? name) =>
Enum.TryParse(name, ignoreCase: false, out AdvancedSourceStatus status) && Enum.IsDefined(status) ? status : AdvancedSourceStatus.Unknown;
private sealed class Watcher(AdvancedMachineFeed feed) : IDisposable
{
private int _released;
public void Dispose()
{
if (Interlocked.Exchange(ref _released, 1) == 0)
{
feed.Release();
}
}
}
}
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FrameLedger.Application.Advanced;
namespace FrameLedger.App.Services;
/// <summary>
/// "This PC, now" as the App last learnt it from the Agent (owner decision D101). Immutable: the feed publishes a new
/// one after each request and a page keeps whichever it took.
/// </summary>
/// <param name="State">What the last request came to.</param>
/// <param name="TakenAt">The Agent's tick the newest values are of; null before the first snapshot.</param>
/// <param name="Facts">The PC's facts, as the ledger would store them.</param>
/// <param name="Values">
/// The last value seen of each series, with the tick it was read on. A slow source is read every few ticks and its
/// value is not repeated between, so "the value now" is the last one seen — and its age is part of it.
/// </param>
/// <param name="Series">The members of the catalog's families the reader has met, with the hardware's own labels.</param>
/// <param name="Sources">Which sources answer, and why the others do not.</param>
public sealed record AdvancedMachineView(
AdvancedFeedState State,
DateTimeOffset? TakenAt,
IReadOnlyList<AdvancedFact> Facts,
IReadOnlyDictionary<string, AdvancedLivePoint> Values,
IReadOnlyList<AdvancedSeriesInfo> Series,
AdvancedSources Sources)
{
/// <summary>Nothing asked, nothing known.</summary>
public static AdvancedMachineView Stopped { get; } = new(
AdvancedFeedState.Stopped,
TakenAt: null,
[],
new Dictionary<string, AdvancedLivePoint>(StringComparer.Ordinal),
[],
AdvancedSources.Unknown);
}
@@ -0,0 +1,249 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Security.Cryptography;
using System.Text;
using FrameLedger.Application.Advanced;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.Application.Ipc;
/// <summary>
/// Answers <c>GetAdvancedMachine</c> (<c>07_IPC</c> §Messages; owner decisions D101 and D107): what the Agent's shared
/// advanced reader last read, for the App's page while it is open.
/// </summary>
/// <remarks>
/// <para>
/// <b>It reads no sensor.</b> The pipe's read loop awaits its handler, so a driver call here would hold up
/// <c>Ping</c> and <c>StopSession</c>. The answer is <see cref="IAdvancedHardware.Latest"/> — a read of one reference —
/// and the only thing awaited is the option, one row of <c>settings</c>, asked for at most once every two seconds.
/// </para>
/// <para>
/// <b>A request is also the page's hold on the reader</b> (D107: with no game running, sensors are read only while the
/// page is open). The first request acquires the reader and each one renews a lease; when no request has come for the
/// lease's length — the page closed, the App gone, the pipe dropped — the hold is let go, and the reader closes its
/// sources some seconds later unless a session holds it too. Nothing has to tell the Agent that the page closed.
/// </para>
/// <para>
/// <b>Off means nothing is read</b> (D101): with <c>telemetry.advanced</c> off the answer is <c>Error AdvancedOff</c>,
/// and a hold a previous request took is let go at once.
/// </para>
/// </remarks>
public sealed class AdvancedMachineResponder : IDisposable
{
/// <summary>How long one request keeps the reader running. The page asks once a second; five rides out a slow one.</summary>
public static readonly TimeSpan DefaultLease = TimeSpan.FromSeconds(5);
private static readonly TimeSpan _optionFor = TimeSpan.FromSeconds(2);
private readonly IAdvancedHardware _hardware;
private readonly Func<CancellationToken, ValueTask<bool>> _isOn;
private readonly TimeProvider _clock;
private readonly TimeSpan _lease;
private readonly ITimer _timer;
private readonly Lock _gate = new();
private IDisposable? _hold;
private long _touched;
private bool _disposed;
private (bool Value, long At)? _option;
private (IReadOnlyList<AdvancedFact> Facts, string Json, string Hash)? _facts;
/// <summary>Over the Agent's one reader, the option as the Agent reads it, and the clock the lease is counted on.</summary>
public AdvancedMachineResponder(IAdvancedHardware hardware, Func<CancellationToken, ValueTask<bool>> isOn, TimeProvider clock, TimeSpan? lease = null)
{
_hardware = hardware ?? throw new ArgumentNullException(nameof(hardware));
_isOn = isOn ?? throw new ArgumentNullException(nameof(isOn));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_lease = lease ?? DefaultLease;
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(_lease, TimeSpan.Zero, nameof(lease));
_timer = clock.CreateTimer(static state => ((AdvancedMachineResponder)state!).ReleaseIfExpired(), this, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
/// <summary>Whether a request's lease holds the reader now.</summary>
public bool IsHolding
{
get
{
lock (_gate)
{
return _hold is not null;
}
}
}
/// <summary>The answer to one <c>GetAdvancedMachine</c>: <c>AdvancedMachineAck</c>, or <c>Error AdvancedOff</c>.</summary>
public async ValueTask<byte[]> AnswerAsync(IpcEnvelope request, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(request);
if (!await IsOnAsync(ct).ConfigureAwait(false))
{
Release();
return IpcCodec.Encode(IpcMessageType.Error, request.Id,
new ErrorAck(IpcErrorCode.AdvancedOff, "Advanced metrics is off (Settings, telemetry.advanced): nothing is read"));
}
Touch();
return IpcCodec.Encode(IpcMessageType.AdvancedMachineAck, request.Id, AckOf(_hardware.Latest, IpcCodec.Payload<GetAdvancedMachineRequest>(request)?.FactsHash));
}
/// <summary>
/// Lets the reader go when the last request is a lease old; otherwise waits for what is left of it. The timer's
/// callback — public only so that a test with a clock of its own can run it.
/// </summary>
public void ReleaseIfExpired()
{
IDisposable? hold;
lock (_gate)
{
if (_hold is null || _disposed)
{
return;
}
TimeSpan left = _lease - _clock.GetElapsedTime(_touched);
if (left > TimeSpan.Zero)
{
_timer.Change(left, Timeout.InfiniteTimeSpan);
return;
}
hold = _hold;
_hold = null;
}
hold.Dispose();
}
public void Dispose()
{
IDisposable? hold;
lock (_gate)
{
if (_disposed)
{
return;
}
_disposed = true;
hold = _hold;
_hold = null;
}
_timer.Dispose();
hold?.Dispose();
}
private async ValueTask<bool> IsOnAsync(CancellationToken ct)
{
(bool Value, long At)? cached;
lock (_gate)
{
cached = _option;
}
if (cached is { } known && _clock.GetElapsedTime(known.At) < _optionFor)
{
return known.Value;
}
bool value = await _isOn(ct).ConfigureAwait(false);
lock (_gate)
{
_option = (value, _clock.GetTimestamp());
}
return value;
}
private void Touch()
{
lock (_gate)
{
if (_disposed)
{
return;
}
_touched = _clock.GetTimestamp();
if (_hold is null)
{
// Returns at once (IAdvancedHardware.Acquire): the sources open on the reader's own thread.
_hold = _hardware.Acquire();
_timer.Change(_lease, Timeout.InfiniteTimeSpan);
}
}
}
private void Release()
{
IDisposable? hold;
lock (_gate)
{
hold = _hold;
_hold = null;
}
hold?.Dispose();
}
private AdvancedMachineAck AckOf(AdvancedSnapshot? snapshot, string? clientHash)
{
if (snapshot is null)
{
// Held, and the reader has not finished its first tick: the page shows that it is being read.
return new AdvancedMachineAck(Ready: false, TakenAtUnixMs: 0, FactsHash: null, FactsJson: null, Readings: [], Series: [],
nameof(AdvancedSourceStatus.Unknown), NvapiCode: null, nameof(AdvancedSourceStatus.Unknown), nameof(AdvancedSourceStatus.Unknown));
}
(string json, string hash) = FactsOf(snapshot.MachineFacts);
var readings = new List<AdvancedReadingValue>(snapshot.Readings.Count);
foreach (AdvancedReading reading in snapshot.Readings)
{
// JSON has no NaN; a reading that is not a number is one the reader did not make.
if (double.IsFinite(reading.Value))
{
readings.Add(new AdvancedReadingValue(reading.Series, reading.Value));
}
}
var series = new List<AdvancedSeriesLabel>(snapshot.Series.Count);
foreach (AdvancedSeriesInfo info in snapshot.Series)
{
series.Add(new AdvancedSeriesLabel(info.Series, info.MetricId, info.Label));
}
return new AdvancedMachineAck(
Ready: true,
snapshot.TakenAt.ToUnixTimeMilliseconds(),
hash,
string.Equals(hash, clientHash, StringComparison.Ordinal) ? null : json,
readings,
series,
snapshot.Sources.Nvapi.ToString(),
snapshot.Sources.NvapiCode,
snapshot.Sources.Sensors.ToString(),
snapshot.Sources.ElevatedSensors.ToString());
}
/// <summary>The facts as text and their hash, made once per list the reader publishes — it republishes the same one while nothing changes.</summary>
private (string Json, string Hash) FactsOf(IReadOnlyList<AdvancedFact> facts)
{
lock (_gate)
{
if (_facts is { } made && ReferenceEquals(made.Facts, facts))
{
return (made.Json, made.Hash);
}
}
string json = AdvancedJson.OfFacts(facts);
string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(json)));
lock (_gate)
{
_facts = (facts, json, hash);
}
return (json, hash);
}
}
@@ -6,7 +6,8 @@ using FrameLedger.Shared.Ipc;
namespace FrameLedger.Application.Ipc;
/// <summary>
/// The read half of <c>07_IPC</c> §Messages — <c>Hello</c>, <c>GetStatus</c>, <c>Ping</c> — and the front door
/// The read half of <c>07_IPC</c> §Messages — <c>Hello</c>, <c>GetStatus</c>, <c>Ping</c>, and
/// <c>GetAdvancedMachine</c> where an <see cref="AdvancedMachineResponder"/> is composed — and the front door
/// for the command half: anything else is offered to <see cref="AgentCommandHandler"/> when one is composed, and
/// answered <c>Error UnknownType</c> otherwise.
/// </summary>
@@ -20,18 +21,26 @@ public sealed class AgentRequestHandler : IIpcRequestHandler
private readonly Func<string?> _telemetryDescriptor;
private readonly Func<AgentStatus> _status;
private readonly Func<AgentCommandHandler?> _commands;
private readonly AdvancedMachineResponder? _advanced;
/// <summary>
/// <c>commands</c> is a function, resolved on the first command rather than at construction: the command
/// handler reaches the orchestrator, which reaches the recorder, whose observer publishes through the pipe
/// server that owns this handler — a cycle a container cannot build eagerly, and one a request can walk lazily.
/// </summary>
public AgentRequestHandler(AgentIdentity identity, Func<string?> telemetryDescriptor, Func<AgentStatus> status, Func<AgentCommandHandler?>? commands = null)
/// <param name="identity">What this Agent is, for <c>HelloAck</c>.</param>
/// <param name="telemetryDescriptor">The telemetry layers' descriptor, composed on demand.</param>
/// <param name="status">The Agent's status now.</param>
/// <param name="commands">The command half, resolved lazily; null answers every command <c>UnknownType</c>.</param>
/// <param name="advanced">Answers <c>GetAdvancedMachine</c> (D101); null — a host with no advanced reader — leaves it an unknown type.</param>
public AgentRequestHandler(AgentIdentity identity, Func<string?> telemetryDescriptor, Func<AgentStatus> status, Func<AgentCommandHandler?>? commands = null,
AdvancedMachineResponder? advanced = null)
{
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
_telemetryDescriptor = telemetryDescriptor ?? throw new ArgumentNullException(nameof(telemetryDescriptor));
_status = status ?? throw new ArgumentNullException(nameof(status));
_commands = commands ?? (static () => null);
_advanced = advanced;
}
public async ValueTask<byte[]> HandleAsync(IpcEnvelope request, CancellationToken ct)
@@ -45,6 +54,8 @@ public sealed class AgentRequestHandler : IIpcRequestHandler
return IpcCodec.Encode(IpcMessageType.StatusAck, request.Id, _status().ToAck(_commands()?.IsPaused ?? false));
case IpcMessageType.Ping:
return IpcCodec.Encode(IpcMessageType.Pong, request.Id, new PongAck());
case IpcMessageType.GetAdvancedMachine when _advanced is not null:
return await _advanced.AnswerAsync(request, ct).ConfigureAwait(false);
default:
AgentCommandHandler? commands = _commands();
byte[]? command = commands is null ? null : await commands.HandleAsync(request, ct).ConfigureAwait(false);
@@ -132,7 +132,12 @@ public sealed class WindowGeometryProbe : IDisplayProbe
/// no window yet. Advanced metrics (owner decision D101) asks the driver about that display; the name is the
/// monitor's place in Windows' list — not an identity of the monitor, and never stored.
/// </summary>
public static unsafe string? MonitorDeviceOf(IReadOnlyCollection<int> pids)
/// <param name="pids">The game's processes.</param>
/// <param name="hwnd">
/// A window to ask about instead of searching, as <see cref="Observe"/> takes one: used only when one of
/// <paramref name="pids"/> owns it. 0 searches for the largest visible window of those processes.
/// </param>
public static unsafe string? MonitorDeviceOf(IReadOnlyCollection<int> pids, ulong hwnd = 0)
{
ArgumentNullException.ThrowIfNull(pids);
if (pids.Count == 0)
@@ -140,7 +145,12 @@ public sealed class WindowGeometryProbe : IDisplayProbe
return null;
}
HWND window = Largest(pids);
HWND window = hwnd != 0 ? Root(new HWND((nint)hwnd), pids) : default;
if (window.IsNull)
{
window = Largest(pids);
}
if (window.IsNull)
{
return null;
@@ -58,6 +58,8 @@ namespace FrameLedger.Shared.Ipc;
[JsonSerializable(typeof(SweepRetentionAck))]
[JsonSerializable(typeof(DeleteSessionsRequest))]
[JsonSerializable(typeof(DeleteSessionsAck))]
[JsonSerializable(typeof(GetAdvancedMachineRequest))]
[JsonSerializable(typeof(AdvancedMachineAck))]
public sealed partial class IpcJsonContext : JsonSerializerContext
{
}
+43
View File
@@ -67,6 +67,15 @@ public static class IpcMessageType
public const string DeleteSessions = "DeleteSessions";
public const string DeleteSessionsAck = "DeleteSessionsAck";
/// <summary>
/// Advanced metrics (owner decisions D101 and D107, 2026-11-11): what the Agent's shared advanced reader last read
/// about this PC, asked once a second by the App's page while it is open - and each request keeps that reader
/// running a few seconds more. Answered <see cref="AdvancedMachineAck"/>, or <see cref="Error"/>
/// <see cref="IpcErrorCode.AdvancedOff"/> while the option is off.
/// </summary>
public const string GetAdvancedMachine = "GetAdvancedMachine";
public const string AdvancedMachineAck = "AdvancedMachineAck";
public const string SessionStarted = "SessionStarted";
public const string SessionProgress = "SessionProgress";
@@ -115,6 +124,9 @@ public static class IpcErrorCode
/// <summary>beta.11: <c>DeleteSessions</c> while a session of that game (or of any game, for all) is being recorded — nothing is deleted.</summary>
public const string SessionRunning = "SessionRunning";
/// <summary>D101: <c>GetAdvancedMachine</c> while <c>telemetry.advanced</c> is off - nothing is read, so there is nothing to answer.</summary>
public const string AdvancedOff = "AdvancedOff";
}
/// <summary>Codes a <see cref="CaptureErrorEvent"/> carries (<c>07_IPC</c> §Messages, <c>CaptureError</c>).</summary>
@@ -424,3 +436,34 @@ public sealed record DeleteSessionsRequest(long? GameId);
/// <summary>What was deleted: the sessions, and how many games they belonged to.</summary>
public sealed record DeleteSessionsAck(long? GameId, int Games, int Sessions);
/// <summary>
/// <c>GetAdvancedMachine</c> (D101/D107). <paramref name="FactsHash"/> is the hash of the facts the client already
/// holds: when it is the Agent's own, the answer leaves the facts out - they change when the hardware does.
/// </summary>
public sealed record GetAdvancedMachineRequest(string? FactsHash = null);
/// <summary>One value the reader read on its last tick: a series name of the catalog (<c>adv.</c>…) and its value.</summary>
public sealed record AdvancedReadingValue(string Series, double Value);
/// <summary>A member of a family - one fan, one core - with the catalog entry it belongs to and the hardware's own label.</summary>
public sealed record AdvancedSeriesLabel(string Series, string MetricId, string Label);
/// <summary>
/// The Agent's last advanced snapshot. <paramref name="Ready"/> false: the reader is held and has not read yet, and
/// every other member is empty. <paramref name="Readings"/> are what was read on THAT tick - a slow source is read
/// every few, so the client keeps the last value it saw. <paramref name="FactsJson"/> is the PC's facts in the form the
/// ledger stores them, absent when the request named <paramref name="FactsHash"/>. The three states are
/// <c>AdvancedSourceStatus</c> names: why a source answers nothing is part of the answer.
/// </summary>
public sealed record AdvancedMachineAck(
bool Ready,
long TakenAtUnixMs,
string? FactsHash,
string? FactsJson,
IReadOnlyList<AdvancedReadingValue> Readings,
IReadOnlyList<AdvancedSeriesLabel> Series,
string Nvapi,
int? NvapiCode,
string Sensors,
string ElevatedSensors);
@@ -0,0 +1,241 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.Application.Advanced;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Tests;
/// <summary>
/// "This PC, now" for the Advanced page (owner decisions D101 and D107): asked only while watched, the last value of
/// every series kept with its age, the facts asked for once, and every way the Agent can fail to answer named.
/// </summary>
public sealed class AdvancedMachineFeedTests
{
private const string _vram = "adv.nvapi.vram.in_use";
private const string _fan = "adv.lhm.gpu.fan.gpu-nvidia_0_1";
private static readonly DateTimeOffset _t0 = new(2026, 11, 11, 12, 0, 0, TimeSpan.Zero);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public void BeforeAnyoneWatchesNothingIsAskedAndNothingIsKnown()
{
var agent = new FakeAgentLink();
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
feed.Current.State.Should().Be(AdvancedFeedState.Stopped);
feed.Current.Values.Should().BeEmpty();
agent.Sent.Should().BeEmpty("D107: with no page open the App asks nothing, so the Agent's reader is not held for it");
}
[Fact]
public async Task ASnapshotBecomesTheViewAndTheFactsAreAskedForOnce()
{
var agent = new FakeAgentLink { Answer = static (_, _) => Ack(Tick(0, withFacts: true, (_vram, 5120), (_fan, 1400))) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
AdvancedMachineView view = feed.Current;
view.State.Should().Be(AdvancedFeedState.Live);
view.TakenAt.Should().Be(_t0);
view.Facts.Should().ContainSingle().Which.Id.Should().Be("nvapi.gpu.rt_cores");
view.Values[_vram].Should().Be(new AdvancedLivePoint(_t0, 5120));
view.Series.Should().ContainSingle().Which.Label.Should().Be("GPU Fan 1");
view.Sources.Should().Be(new AdvancedSources(AdvancedSourceStatus.Reading, NvapiCode: null, AdvancedSourceStatus.Reading, AdvancedSourceStatus.NotElevated));
agent.Sent.Single().Payload.Should().Be(new GetAdvancedMachineRequest(null), "the first request holds no facts");
agent.Answer = static (_, _) => Ack(Tick(1, withFacts: false, (_vram, 5200)));
await feed.PollOnceAsync(Ct);
agent.Sent[1].Payload.Should().Be(new GetAdvancedMachineRequest("hash-1"), "and every later one names the facts it holds, so they are not sent again");
feed.Current.Facts.Should().ContainSingle("an answer that leaves the facts out leaves the kept ones in place");
}
[Fact]
public async Task ASeriesNotReadOnATickKeepsItsLastValueAndItsAge()
{
// The sensors are read every fifth tick: between two readings the fan is still "1400, as of then".
var agent = new FakeAgentLink { Answer = static (_, _) => Ack(Tick(0, withFacts: true, (_vram, 5120), (_fan, 1400))) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
agent.Answer = static (_, _) => Ack(Tick(1, withFacts: false, (_vram, 5200)));
await feed.PollOnceAsync(Ct);
feed.Current.Values[_vram].Should().Be(new AdvancedLivePoint(_t0.AddSeconds(1), 5200));
feed.Current.Values[_fan].Should().Be(new AdvancedLivePoint(_t0, 1400), "the page shows the value with the tick it is of, never as if it were new");
feed.HistoryOf(_vram).Should().HaveCount(2);
feed.HistoryOf(_fan).Should().ContainSingle();
feed.HistoryOf("adv.never.read").Should().BeEmpty();
}
[Fact]
public async Task TheSameTickAnsweredTwiceAddsNoPoint()
{
var agent = new FakeAgentLink { Answer = static (_, _) => Ack(Tick(0, withFacts: true, (_vram, 5120))) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
await feed.PollOnceAsync(Ct);
feed.HistoryOf(_vram).Should().ContainSingle("the reader's second and this one are not in step; one tick is one point");
}
[Fact]
public async Task TheHistoryOfASeriesIsBounded()
{
int tick = 0;
var agent = new FakeAgentLink { Answer = (_, _) => Ack(Tick(tick++, withFacts: false, (_vram, tick))) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
for (int i = 0; i < AdvancedMachineFeed.HistoryPoints + 5; i++)
{
await feed.PollOnceAsync(Ct);
}
IReadOnlyList<AdvancedLivePoint> history = feed.HistoryOf(_vram);
history.Should().HaveCount(AdvancedMachineFeed.HistoryPoints);
history[0].At.Should().Be(_t0.AddSeconds(5), "the oldest points go first");
}
[Fact]
public async Task AReaderThatHasNotReadYetIsWaitingNotEmpty()
{
var agent = new FakeAgentLink
{
Answer = static (_, _) => Ack(new AdvancedMachineAck(Ready: false, 0, null, null, [], [], "Unknown", null, "Unknown", "Unknown")),
};
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
feed.Current.State.Should().Be(AdvancedFeedState.Waiting);
feed.Current.TakenAt.Should().BeNull();
}
[Fact]
public async Task OffForgetsWhatWasShown()
{
var agent = new FakeAgentLink { Answer = static (_, _) => Ack(Tick(0, withFacts: true, (_vram, 5120))) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
agent.Answer = static (_, _) => throw new IpcRequestException(IpcErrorCode.AdvancedOff, "off");
await feed.PollOnceAsync(Ct);
feed.Current.State.Should().Be(AdvancedFeedState.Off);
feed.Current.Values.Should().BeEmpty("off means nothing is read: a value from before is not 'now'");
feed.Current.Facts.Should().BeEmpty();
feed.HistoryOf(_vram).Should().BeEmpty();
agent.Answer = static (_, _) => Ack(Tick(9, withFacts: true, (_vram, 6000)));
await feed.PollOnceAsync(Ct);
agent.Sent[^1].Payload.Should().Be(new GetAdvancedMachineRequest(null), "and switched on again it asks for the facts afresh");
feed.Current.State.Should().Be(AdvancedFeedState.Live);
}
[Fact]
public async Task AnOlderAgentAndNoAgentAreSaidAndWhatWasShownStays()
{
var agent = new FakeAgentLink { Answer = static (_, _) => Ack(Tick(0, withFacts: true, (_vram, 5120))) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
agent.Answer = static (_, _) => throw new InvalidOperationException("not connected");
await feed.PollOnceAsync(Ct);
feed.Current.State.Should().Be(AdvancedFeedState.NoAgent);
feed.Current.Values[_vram].Value.Should().Be(5120, "the Agent restarting does not blank the page; the values keep their age");
agent.Answer = static (_, _) => throw new TimeoutException("no answer");
await feed.PollOnceAsync(Ct);
feed.Current.State.Should().Be(AdvancedFeedState.NoAgent);
agent.Answer = static (_, _) => throw new IpcRequestException(IpcErrorCode.UnknownType, "unknown message type GetAdvancedMachine");
await feed.PollOnceAsync(Ct);
feed.Current.State.Should().Be(AdvancedFeedState.OlderAgent);
agent.Answer = static (_, _) => throw new IpcRequestException(IpcErrorCode.HandlerFaulted, "boom");
await feed.PollOnceAsync(Ct);
feed.Current.State.Should().Be(AdvancedFeedState.NoAgent, "any other error is no answer, and the next second asks again");
}
[Fact]
public async Task ASourceStateThisBuildDoesNotKnowIsUnknownNeverAGuess()
{
AdvancedMachineAck ack = Tick(0, withFacts: true, (_vram, 1)) with { Nvapi = "SomethingNewer", Sensors = "7" };
var agent = new FakeAgentLink { Answer = (_, _) => Ack(ack) };
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System);
await feed.PollOnceAsync(Ct);
feed.Current.Sources.Nvapi.Should().Be(AdvancedSourceStatus.Unknown);
feed.Current.Sources.Sensors.Should().Be(AdvancedSourceStatus.Unknown, "a number is not a name");
}
[Fact]
public async Task WatchingAsksUntilTheLastWatcherLetsGoThenSaysStopped()
{
int asked = 0;
var agent = new FakeAgentLink
{
Answer = (_, _) =>
{
Interlocked.Increment(ref asked);
return Ack(Tick(0, withFacts: true, (_vram, 5120)));
},
};
using var feed = new AdvancedMachineFeed(agent, TimeProvider.System, TimeSpan.FromMilliseconds(20));
int changes = 0;
feed.Changed += (_, _) => Interlocked.Increment(ref changes);
IDisposable one = feed.Watch();
IDisposable two = feed.Watch();
await UntilAsync(() => Volatile.Read(ref asked) >= 1);
one.Dispose();
one.Dispose();
int before = Volatile.Read(ref asked);
await UntilAsync(() => Volatile.Read(ref asked) >= before + 2);
feed.Current.State.Should().Be(AdvancedFeedState.Live, "a second watcher still holds it, and a handle disposed twice counts once");
two.Dispose();
feed.Current.State.Should().Be(AdvancedFeedState.Stopped);
Volatile.Read(ref changes).Should().BeGreaterThan(0);
await Task.Delay(100, Ct);
int after = Volatile.Read(ref asked);
await Task.Delay(200, Ct);
Volatile.Read(ref asked).Should().Be(after, "D107: nobody watches, so nothing is asked and the Agent lets its reader go");
feed.Current.State.Should().Be(AdvancedFeedState.Stopped, "and a request that was in flight does not speak after 'stopped'");
}
private static async Task UntilAsync(Func<bool> met)
{
DateTime deadline = DateTime.UtcNow.AddSeconds(30);
while (!met())
{
DateTime.UtcNow.Should().BeBefore(deadline, "the feed asks every 20 ms while watched");
await Task.Delay(10, Ct).ConfigureAwait(false);
}
}
private static IpcEnvelope Ack(AdvancedMachineAck ack) => FakeAgentLink.Envelope(IpcMessageType.AdvancedMachineAck, ack);
private static AdvancedMachineAck Tick(int second, bool withFacts, params (string Series, double Value)[] readings) => new(
Ready: true,
_t0.AddSeconds(second).ToUnixTimeMilliseconds(),
"hash-1",
withFacts ? AdvancedJson.OfFacts([new AdvancedFact("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84))]) : null,
[.. readings.Select(static r => new AdvancedReadingValue(r.Series, r.Value))],
[new AdvancedSeriesLabel(_fan, "lhm.gpu.fan", "GPU Fan 1")],
nameof(AdvancedSourceStatus.Reading),
NvapiCode: null,
nameof(AdvancedSourceStatus.Reading),
nameof(AdvancedSourceStatus.NotElevated));
}
@@ -0,0 +1,278 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Application.Advanced;
using FrameLedger.Application.Ipc;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.Application.Tests.Ipc;
/// <summary>
/// <c>GetAdvancedMachine</c> (owner decisions D101 and D107): the answer is what the shared reader last read and
/// nothing else, a request is the page's hold on that reader for a lease, and off means nothing is held or answered.
/// </summary>
public sealed class AdvancedMachineResponderTests
{
private static readonly TimeSpan _lease = TimeSpan.FromSeconds(5);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task WithTheOptionOffTheAnswerIsAdvancedOffAndTheReaderIsNeverHeld()
{
var hub = new FakeHub { Latest = Snapshot() };
var clock = new ManualClock();
using var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(false), clock, _lease);
IpcEnvelope answer = await AskAsync(responder, hash: null);
answer.Type.Should().Be(IpcMessageType.Error);
IpcCodec.Payload<ErrorAck>(answer).Should().BeOfType<ErrorAck>().Which.Code.Should().Be(IpcErrorCode.AdvancedOff);
hub.Acquired.Should().Be(0, "D101: off means nothing is read, the page included");
responder.IsHolding.Should().BeFalse();
}
[Fact]
public async Task TheFirstRequestHoldsTheReaderAndSaysItHasNotReadYet()
{
var hub = new FakeHub { Latest = null };
using var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(true), new ManualClock(), _lease);
AdvancedMachineAck ack = Ack(await AskAsync(responder, hash: null));
hub.Acquired.Should().Be(1);
ack.Ready.Should().BeFalse("the reader opens its sources on a thread of its own; the page shows that it is being read");
ack.Readings.Should().BeEmpty();
ack.FactsJson.Should().BeNull();
ack.Nvapi.Should().Be(nameof(AdvancedSourceStatus.Unknown));
}
[Fact]
public async Task ASnapshotIsAnsweredAsItWasReadWithItsSourcesByName()
{
var hub = new FakeHub { Latest = Snapshot() };
using var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(true), new ManualClock(), _lease);
AdvancedMachineAck ack = Ack(await AskAsync(responder, hash: null));
ack.Ready.Should().BeTrue();
ack.TakenAtUnixMs.Should().Be(Snapshot().TakenAt.ToUnixTimeMilliseconds());
ack.Readings.Should().Equal(new AdvancedReadingValue("adv.nvapi.vram.in_use", 5120));
ack.Series.Should().Equal(new AdvancedSeriesLabel("adv.lhm.gpu.fan.gpu-nvidia_0_1", "lhm.gpu.fan", "GPU Fan 1"));
ack.Nvapi.Should().Be(nameof(AdvancedSourceStatus.Reading));
ack.Sensors.Should().Be(nameof(AdvancedSourceStatus.Reading));
ack.ElevatedSensors.Should().Be(nameof(AdvancedSourceStatus.NotElevated), "why a source answers nothing is part of the answer");
AdvancedJson.ParseFacts(ack.FactsJson).Should().ContainSingle().Which.Id.Should().Be("nvapi.gpu.rt_cores");
ack.FactsHash.Should().MatchRegex("^[0-9a-f]{64}$");
}
[Fact]
public async Task AReadingThatIsNotANumberIsLeftOutBecauseTheWireHasNoWordForIt()
{
AdvancedSnapshot snapshot = Snapshot() with
{
Readings = [new AdvancedReading("adv.nvapi.vram.in_use", double.NaN), new AdvancedReading("adv.nvapi.pstate", 0)],
};
var hub = new FakeHub { Latest = snapshot };
using var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(true), new ManualClock(), _lease);
AdvancedMachineAck ack = Ack(await AskAsync(responder, hash: null));
ack.Readings.Should().Equal(new AdvancedReadingValue("adv.nvapi.pstate", 0));
}
[Fact]
public async Task TheFactsAreSentOnceAndLeftOutWhileTheClientNamesTheirHash()
{
var hub = new FakeHub { Latest = Snapshot() };
using var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(true), new ManualClock(), _lease);
AdvancedMachineAck first = Ack(await AskAsync(responder, hash: null));
AdvancedMachineAck second = Ack(await AskAsync(responder, first.FactsHash));
second.FactsJson.Should().BeNull("the facts change when the hardware does, not every second");
second.FactsHash.Should().Be(first.FactsHash);
second.Readings.Should().NotBeEmpty("and everything else is answered as before");
AdvancedMachineAck stale = Ack(await AskAsync(responder, "not-the-hash"));
stale.FactsJson.Should().Be(first.FactsJson, "a client that holds other facts gets these");
}
[Fact]
public async Task RequestsRenewOneHoldAndTheReaderIsLetGoALeaseAfterTheLast()
{
var hub = new FakeHub { Latest = Snapshot() };
var clock = new ManualClock();
using var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(true), clock, _lease);
await AskAsync(responder, hash: null);
clock.Advance(TimeSpan.FromSeconds(4));
await AskAsync(responder, hash: null);
clock.Advance(TimeSpan.FromSeconds(4));
responder.ReleaseIfExpired();
hub.Acquired.Should().Be(1, "a page open for a minute holds the reader once");
hub.Released.Should().Be(0, "eight seconds after the first request and four after the last: the lease still runs");
clock.LastDue.Should().Be(TimeSpan.FromSeconds(1), "and the timer waits for what is left of it");
clock.Advance(TimeSpan.FromSeconds(1));
responder.ReleaseIfExpired();
hub.Released.Should().Be(1, "D107: the page closed - nothing asked for a lease - so the reader is let go");
responder.IsHolding.Should().BeFalse();
await AskAsync(responder, hash: null);
hub.Acquired.Should().Be(2, "and the page opening again holds it again");
}
[Fact]
public async Task SwitchingTheOptionOffLetsGoOfAHoldAtTheNextRequest()
{
bool on = true;
var hub = new FakeHub { Latest = Snapshot() };
var clock = new ManualClock();
using var responder = new AdvancedMachineResponder(hub, _ => ValueTask.FromResult(on), clock, _lease);
await AskAsync(responder, hash: null);
on = false;
clock.Advance(TimeSpan.FromSeconds(1));
IpcEnvelope cached = await AskAsync(responder, hash: null);
cached.Type.Should().Be(IpcMessageType.AdvancedMachineAck, "the option is asked for at most every two seconds");
clock.Advance(TimeSpan.FromSeconds(2));
IpcEnvelope answer = await AskAsync(responder, hash: null);
answer.Type.Should().Be(IpcMessageType.Error);
hub.Released.Should().Be(1, "off means nothing is read: the hold goes at once, not a lease later");
}
[Fact]
public async Task TheOptionIsReadAtMostOnceInTwoSeconds()
{
int asked = 0;
var clock = new ManualClock();
using var responder = new AdvancedMachineResponder(new FakeHub(), _ =>
{
asked++;
return ValueTask.FromResult(true);
}, clock, _lease);
await AskAsync(responder, hash: null);
clock.Advance(TimeSpan.FromSeconds(1));
await AskAsync(responder, hash: null);
asked.Should().Be(1, "the pipe's read loop awaits this handler; one settings row every two seconds is all it reads");
clock.Advance(TimeSpan.FromSeconds(1));
await AskAsync(responder, hash: null);
asked.Should().Be(2);
}
[Fact]
public async Task DisposingLetsGoOfTheHold()
{
var hub = new FakeHub();
var responder = new AdvancedMachineResponder(hub, static _ => ValueTask.FromResult(true), new ManualClock(), _lease);
await AskAsync(responder, hash: null);
responder.Dispose();
responder.Dispose();
hub.Released.Should().Be(1);
}
[Fact]
public async Task TheRequestHandlerAnswersItOnlyWhereAResponderIsComposed()
{
var identity = new AgentIdentity("1.0.0", 1, Elevated: false, "build", VulkanLayerRegistered: false, CpuTempAvailable: false, "d", "e");
using var responder = new AdvancedMachineResponder(new FakeHub { Latest = Snapshot() }, static _ => ValueTask.FromResult(true), new ManualClock(), _lease);
var with = new AgentRequestHandler(identity, static () => "l1", static () => AgentStatus.Idle, advanced: responder);
var without = new AgentRequestHandler(identity, static () => "l1", static () => AgentStatus.Idle);
IpcEnvelope request = IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.GetAdvancedMachine, "7", new GetAdvancedMachineRequest()));
IpcEnvelope answered = IpcCodec.Decode(await with.HandleAsync(request, Ct));
IpcEnvelope unknown = IpcCodec.Decode(await without.HandleAsync(request, Ct));
answered.Type.Should().Be(IpcMessageType.AdvancedMachineAck);
answered.Id.Should().Be("7");
unknown.Type.Should().Be(IpcMessageType.Error);
IpcCodec.Payload<ErrorAck>(unknown).Should().BeOfType<ErrorAck>().Which.Code.Should().Be(IpcErrorCode.UnknownType,
"which is what an App of this version gets from an older Agent, and shows as such");
}
private static async Task<IpcEnvelope> AskAsync(AdvancedMachineResponder responder, string? hash)
{
IpcEnvelope request = IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.GetAdvancedMachine, "1", new GetAdvancedMachineRequest(hash)));
return IpcCodec.Decode(await responder.AnswerAsync(request, Ct).ConfigureAwait(false));
}
private static AdvancedMachineAck Ack(IpcEnvelope envelope)
{
envelope.Type.Should().Be(IpcMessageType.AdvancedMachineAck);
return IpcCodec.Payload<AdvancedMachineAck>(envelope).Should().BeOfType<AdvancedMachineAck>().Subject;
}
private static AdvancedSnapshot Snapshot() => new(
new DateTimeOffset(2026, 11, 11, 12, 0, 0, TimeSpan.Zero),
[new AdvancedReading("adv.nvapi.vram.in_use", 5120)],
_facts,
[new AdvancedSeriesInfo("adv.lhm.gpu.fan.gpu-nvidia_0_1", "lhm.gpu.fan", "GPU Fan 1")],
new AdvancedSources(AdvancedSourceStatus.Reading, NvapiCode: null, AdvancedSourceStatus.Reading, AdvancedSourceStatus.NotElevated));
private static readonly IReadOnlyList<AdvancedFact> _facts = [new AdvancedFact("nvapi.gpu.rt_cores", Instance: null, AdvancedValue.Of(84))];
/// <summary>The Agent's shared reader, counted: how often it was held and let go.</summary>
private sealed class FakeHub : IAdvancedHardware
{
public int Acquired { get; private set; }
public int Released { get; private set; }
public AdvancedSnapshot? Latest { get; init; }
public IDisposable Acquire()
{
Acquired++;
return new Hold(this);
}
public IReadOnlyList<AdvancedFact> ReadSessionFacts(AdvancedSessionTarget target) => [];
private sealed class Hold(FakeHub hub) : IDisposable
{
public void Dispose() => hub.Released++;
}
}
/// <summary>A clock the test moves, whose one timer never fires by itself: the test runs the callback's work.</summary>
private sealed class ManualClock : TimeProvider
{
private long _ticks;
/// <summary>What the timer was last set to wait.</summary>
public TimeSpan LastDue { get; private set; }
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override long GetTimestamp() => _ticks;
public void Advance(TimeSpan by) => _ticks += by.Ticks;
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) => new Timer(this);
private sealed class Timer(ManualClock clock) : ITimer
{
public bool Change(TimeSpan dueTime, TimeSpan period)
{
clock.LastDue = dueTime;
return true;
}
public void Dispose()
{
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}
@@ -65,6 +65,11 @@ public sealed partial class WindowGeometryProbeTests
// one that belongs to someone else is not the game's — and this test process shows no window of its own.
probe.Observe([Environment.ProcessId], hwnd).Should().BeNull();
probe.Observe([], hwnd).Should().BeNull("no process, no window");
// Advanced metrics (D101) asks the driver about the display the game's window is on: its GDI device name, from
// Windows. The same rule for whose window it is - and a name, never an identity of the monitor.
WindowGeometryProbe.MonitorDeviceOf([harness.Id], hwnd).Should().StartWith(@"\\.\DISPLAY", "the window is on a monitor, and Windows names the monitor's place in its list");
WindowGeometryProbe.MonitorDeviceOf([Environment.ProcessId], hwnd).Should().BeNull("a window another process owns is not this one's, and this test process shows none");
}
finally
{
@@ -82,6 +87,14 @@ public sealed partial class WindowGeometryProbeTests
}
}
[Fact]
public void WithNoProcessOrNoWindowThereIsNoMonitorToName()
{
WindowGeometryProbe.MonitorDeviceOf([]).Should().BeNull("no process, no window");
WindowGeometryProbe.MonitorDeviceOf([Environment.ProcessId]).Should().BeNull("this test process shows no window");
WindowGeometryProbe.MonitorDeviceOf([Environment.ProcessId], 0xDEAD_0000_BEEF).Should().BeNull("a handle that is no window names no monitor");
}
[Fact]
public void AHandleThatIsNoWindowIsNotRead() =>
new WindowGeometryProbe().Observe([Environment.ProcessId], 0xDEAD_0000_BEEF).Should().BeNull();