Compare commits

...
1 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 14e82609a4 fix: a session that is not hooked is shown while it runs
A game with hooking off, one the guard refused, or one whose process could
not be read has been recorded since beta.5 (duration, sensors, the reason),
but SessionEventPublisher sent SessionStarted only at the ring attach and
progress only while attached. For as long as such a game ran the Dashboard
said "Nothing is being captured." and the tray stayed idle.

Agent:
- The hold's ticks carry the refusal (CaptureProgress.Held, with the pid the
  loop holds). The first held tick publishes SessionStarted ONCE, at tier 2,
  with an optional `hold` (the loop's reason and the guard's reason, family
  and signal - the words capture_notes will carry), and the refusal's own
  event at once instead of at the exit; it is not repeated at the end.
- Every held tick after feeds a new SessionHeld event (elapsed + sensors) at
  1 Hz while a client listens - never SessionProgress, whose required fields
  would put measured-looking zeros on the wire.
- ActiveSession carries the hold; SessionCompleted carries the entry's id and
  name; a faulted session also completes (finalize "faulted").
- All fields additive and optional: IpcProtocol.Version stays 2.

App:
- LiveSessions (App-lifetime) is seeded from the status on every (re)connect
  and moved by start/completion; the Dashboard seeds its card from it (it is
  rebuilt per visit). The tray and the updater seed their own lists from the
  same status; the updater no longer holds a download at Deferred on a
  status read hours earlier.
- The live card shows a held session with the T2 badge, elapsed, temperatures,
  "Recording duration and sensors only - nothing is measured." and why (the
  summary's own sentence), with no FPS readout. A tier-2 session without a
  hold is starting, not held. A hooked session takes the card, never the
  reverse. Stop clears the name; the notice names the completed session; a
  faulted completion is no notice.
- Formats: RefusedConsentMissing reads "the game's executable changed since
  hooking was turned on" instead of the enum name (en/vi/ja).

Tests: publisher (held announce once, reason once, no progress, status hold,
faulted completion), event table, codec (additive fields, beta.5 payloads),
capture session (ticks carry the hold and pid), live card, LiveSessions,
Dashboard, tray, updater, Tier2Reason, and a pipe end-to-end case with a
hooking-off harness. Docs: 07_IPC, 08_UI, 04_CAPTURE, 11_UPDATER (gap
closed), HANDOFF, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 02:45:19 +07:00
37 changed files with 1092 additions and 79 deletions

No files matched your search

+13
View File
@@ -54,6 +54,19 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
report, and the next file is recovered. The `FAULTED` and end-of-session log lines now name the session, the game and
its executable, and the Agent's host logs its own warnings and errors into `agent-*.log`.
- **A game that is recorded without measuring is shown while it runs.** A game with hooking off, one the guard
refused, or one whose process could not be read is recorded (duration, sensors, the reason) since beta.5 — but the
Agent announced only hooked sessions, so for as long as such a game ran the Dashboard said "Nothing is being
captured." and the tray stayed idle. Now the live card shows it with the T2 badge, the elapsed time, the
temperatures, "Recording duration and sensors only — nothing is measured." and why, in the sentence its summary will
use (no FPS readout: nothing is measured, so nothing is shown); the tray turns to recording-only; the refusal notice
appears when the game starts rather than when it exits. A Dashboard opened after a game started shows it at once
(it used to wait for the next start), a session running when the App connects is in the tray, the notice after a
session names that session's game (it could name the previous one), a session that fails is let go of instead of
staying on the card, and an update downloaded after a session ends is ready to install instead of waiting for the
App to reconnect. A game whose executable changed since hooking was turned on — after a store update, usually — now
says so in its summary instead of `RefusedConsentMissing`.
## [0.1.0-beta.5] - 2026-09-22
**The fifth pre-release: the guard override is gone, Tier 2 exists, and a drive that changes its letter is followed.**
+7
View File
@@ -424,6 +424,13 @@ Crash-within-60s-of-injection happening twice for the same game ⇒ **hooking au
> stands alone with the census qualifier (`FgLadder.PresentedQualifier`, the row's). CPU temperature is null until the Agent composes a
> CPU sensor, and every other unmeasured field is null, never 0. Rate-limited to 1 Hz inside the observer's `Tick`, computed only while
> a client is connected, and a fault in the computation is counted rather than allowed to end the session.
>
> **A held session is live too (2026-09-23).** The hold's ticks carry the refusal (`CaptureProgress.Held`, with the pid the loop
> holds, 0 for a hooking-off hold that never opened the process). The publisher's first held tick announces the session —
> `SessionStarted` at tier 2 with its `hold`, and the refusal's own event at once rather than when the game exits — and every tick
> after feeds `SessionHeld` (elapsed and sensors, nothing measured) at the same 1 Hz while a client listens. It is never run through
> `SessionProgressCalculator`, whose window over no records would still emit a qualifier. A session whose task faults now also
> completes on the pipe (`finalize: faulted`, `07_IPC`), so nothing is left shown as running.
## Overhead rules (NFR-1)
+12 -4
View File
@@ -324,7 +324,7 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
| Type | Dir | Payload / notes |
|---|---|---|
| `Hello` | UI→A | `{ appVersion, protocol: 2 }` → `HelloAck { agentVersion, protocol, pid, elevated, overlayBuildId, vulkanLayerRegistered, telemetrySource /* composite, e.g. l1+lhm+nvapi */, cpuTempAvailable, disclosureVersion /* P3 PR-4, D14: the FR-2.1 text this Agent stamps against */, ~~etwAvailable~~ }` — `etwAvailable` struck 2026-09-13 with the tier it described (2026-08-28); `pid` added. `vulkanLayerRegistered` is **false by construction** today (the layer is per-launch, never registered) and `cpuTempAvailable` false unelevated; `telemetrySource` is the composite stood up once on the first `Hello` |
| `GetStatus` | UI→A | → `StatusAck { state, activeSession?, tier? }` |
| `GetStatus` | UI→A | → `StatusAck { state, activeSession?, tier? }` — and `activeSessions[]`, one `{ sessionGuid, gameId, gameName?, pid, tier, startedAt, hold? }` per running session. **`hold` added 2026-09-23, optional:** present on a session held unhooked (Tier 2), with the same words `SessionStarted.hold` carries; a session listed at tier 2 WITHOUT a `hold` has not attached yet — it is starting, not held. The App reads this list on every (re)connect (§Client behavior) |
| `SetWatchlist` | UI→A | `{ entries: [{ gameId?, exePath }] }` — ~~full replace~~ **ensure, never remove** (built 2026-09-13, PR-1b): each entry's path is normalised by the Agent, its row ensured with hooking OFF when new, and the ack is `WatchlistAck { games: [{ gameId, exePath, name }], unreadable: [exePath] }`; `gameId` in a request is a hint and never trusted over the path. UI re-sends on connect. **Carries no hooking state** (see §The pipe is not a trust boundary). *Since the App writes `games` rows itself under `06_DATA_MODEL` §Writer ownership (HANDOFF §P3 D15), this is the pipe's way of adding a row, not the only one; the watcher reads the table at 1 Hz either way.* |
| `LaunchGame` | UI→A | `{ gameId, arguments? }` → ~~suspended-launch~~ launch mode as built ("inject late", `04_CAPTURE` §Launch mode) → `LaunchAck { gameId, accepted, outcome, sessionGuid? }` — `outcome` is `Accepted` · `UnknownGame` · `SessionRunning` (one per game at a time) · `Unavailable`. *(Built 2026-09-13, PR-1b: `CaptureOrchestrator.LaunchAsync` over an `ILaunchRecorderFactory` the Agent composes with the Vulkan layer's environment — or none when FR-2.4's switch is on — and the launcher election runs after, as the console's `launch` does; the elected session is not addressable by the launch's guid.)* |
| `SetHookEnabled` | UI→A | `{ gameId, enabled, disclosureVersion? }` — Agent re-runs the static AC pre-scan and may reply `Refused`. **The Agent stamps the consent timestamp itself.** *(Built 2026-09-13, PR-1b, as far as it can be: `enabled: false` → `RevokeAsync` → `HookEnabledAck { gameId, enabled: false, outcome }`; `enabled: true` → the pre-scan of the executable's directory, a refusal or a "could not verify" recorded through `RecordGuardBlockAsync` and answered `Refused { gameId, reason, family?, signal? }`; a clean scan → ~~**`Error DisclosureUnavailable`, nothing stamped** — the reviewed FR-2.1 text does not exist, and a client's `disclosureVersion` is a claim, not a disclosure shown. PR-4 replaces that last branch with the stamp~~ **since PR-4 (2026-09-13): the client's `disclosureVersion` compared with the Agent's own `SafetyDisclosure.Version`; equal → the stamp from the Agent's clock with `ConsentProvenance.ConsentDialog`, answered `HookEnabledAck { enabled, outcome, prescan: "clean" }`; anything else → `Error DisclosureVersionMismatch`, nothing written (D14). `DisclosureUnavailable` remains for a composition that wired no version, which `--serve` never is.)* |
@@ -333,13 +333,14 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
| `UpdateRules` | UI→A | **no payload** — a trigger, not a source. The Agent re-reads only its own `%LOCALAPPDATA%\FrameLedger\rules\` copy → `UpdateRulesAck { outcome }`. *(Built 2026-09-13, PR-1b: the seeder's `EnsureSeededAsync` outcome; a payload naming a path is ignored, and a test sends one to prove it.)* |
| `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`.)* |
| `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.)* |
| `SessionStarted` | A→UI | `{ sessionGuid, gameId, gameName, pid, tier, startedAt }` — **published at the attach**, i.e. when the session becomes Tier 1 and the live card has something to show; a session that never attaches has no `SessionStarted`, only its `SessionCompleted` (tier 2) and, when a refusal or error caused that, the event below that names it |
| `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? }` — how long it has run and the machine's sensors. **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? }` — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **`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 |
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length), or `game_removed` when its entry was removed with its sessions while it ran (2026-09-23); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason` |
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason, gameId?, gameName? }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length), or `game_removed` when its entry was removed with its sessions while it ran (2026-09-23), or **`faulted` when the session's task threw before it could finalize** (2026-09-23: it follows the `CaptureError SessionFaulted`, with `exitStatus` `interrupted` and `reason` `SessionFaulted`, so the live card and the tray let go of a session that no longer runs; the `.partial` stays for recovery); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason`. **`gameId` / `gameName` added 2026-09-23, optional:** the entry the session was stored under — the finalizer's owner when it re-keyed a session whose entry was removed, else the one it started under — so the notice names the session that completed, not whatever the live card last showed |
| `CaptureRefused` | A→UI | `{ gameId, gameName, reason, family?, signal?, hookingTurnedOff }` — **guard fired**; `hookingTurnedOff` (2026-09-22) is true when the finding turned the game's hooking off (`19_SAFETY` §What a finding does to the game); UI shows the plain-language explanation — ~~and the Tier-2 offer~~; there is no alternative measurement to offer, only the option to record the session unmeasured (`08_UI` §Safety events). *(Built: for `RefusedByGuard`, `RefusedPreviouslyBlocked`, `RefusedKillSwitch` and `PreScanCouldNotVerify` — the last with no family, because "could not verify" is neither a hit nor a pass; `family`/`signal` are the verdict's. A game merely not enabled or not consented raises nothing: that is an ordinary Tier-2 row, not a refusal to explain.)* |
| `CaptureDegraded` | A→UI | `{ sessionGuid, from: 1, to: 2, reason }` — Tier 1 → Tier 2 mid-flight, or overlay self-disabled. **Under a two-rung ladder this means measurement STOPPED**, not that it continued at lower fidelity, and the notice must say so. *(Built: `SupervisionLost`, `WriterSelfDisabled`, `WriterStoppedBlocklisted`, `WriterNeverInstalledHooks`, `SupervisionFaulted`, `KillSwitchEngaged` — `RecordedSessionEvents.Classify` is the table.)* |
| `SafetyUnhook` | A→UI | `{ sessionGuid, family?, signal?, hookingTurnedOff }` — anti-cheat appeared mid-session; prominent UI notice; `hookingTurnedOff` as on `CaptureRefused`. *(Built: the verdict that FIRED, not the pass that started the session — `CaptureOutcome.Verdict` carries the supervisor's last verdict on this reason since 2026-09-13.)* |
| `CaptureError` | A→UI | `{ sessionGuid?, code, message }` — `InjectFailed`, `RingVersionMismatch`, `AttachRefused`, ~~`EtwAccessDenied`~~ (struck 2026-09-13 with the tier), ~~`PresentMonMissing`~~ (retired with the tool, 2026-08-27 — a code naming an implementation nobody chose), `TelemetryUnavailable`, `DbWriteFailed`, `SessionFaulted` (the session's task threw before finalize; the `.partial` stays for recovery, and no `SessionCompleted` follows). *(Built: `RingVersionMismatch` for a layout / record-size / build-id refusal — the "restart the game after an update" case — `AttachRefused` for the rest of the ring's refusals, `InjectFailed` for a target that could not be started, pinned, read or singled out.)* |
| `CaptureError` | A→UI | `{ sessionGuid?, code, message }` — `InjectFailed`, `RingVersionMismatch`, `AttachRefused`, ~~`EtwAccessDenied`~~ (struck 2026-09-13 with the tier), ~~`PresentMonMissing`~~ (retired with the tool, 2026-08-27 — a code naming an implementation nobody chose), `TelemetryUnavailable`, `DbWriteFailed`, `SessionFaulted` (the session's task threw before finalize; the `.partial` stays for recovery, and ~~no `SessionCompleted` follows~~ a `SessionCompleted` with `finalize: faulted` follows since 2026-09-23). *(Built: `RingVersionMismatch` for a layout / record-size / build-id refusal — the "restart the game after an update" case — `AttachRefused` for the rest of the ring's refusals, `InjectFailed` for a target that could not be started, pinned, read or singled out.)* |
| `Ping`/`Pong` | ~~both~~ UI→A | 15 s keepalive, **client-driven** (built 2026-09-13): the client pings, the Agent answers; the Agent initiates nothing on an idle connection |
## The pipe is not a trust boundary
@@ -380,6 +381,13 @@ message, and that message always re-scans.
## Client behavior (UI)
- **The running sessions are the status's, then the events' (2026-09-23).** Every list of running sessions the App
keeps is seeded from `StatusAck.activeSessions` on every (re)connect and moved by `SessionStarted` /
`SessionCompleted` after that; a lost Agent empties it. The Dashboard reads the App-lifetime `LiveSessions`
service (it is rebuilt per visit, so a list of its own would start empty); the tray and the updater seed their
own from the same status. Before this a Dashboard opened after a game started read "Nothing is being captured.",
the tray stayed idle for a session that began before the App connected, and the updater held an update at
*Deferred* on a status read hours earlier.
- Connect with 250 ms × 8 backoff; on failure start the Agent, retry; then show an Agent status banner with Repair.
> **Amended 2026-09-17: never a second Agent.** A round that ends without a connection starts one only when no
+13
View File
@@ -147,6 +147,19 @@ All screens are `Page`s registered with the navigation page provider and navigat
> session reloads the lists (the row is in SQLite, `07_IPC` §Client behavior). Totals = the library's games,
> `SummariseByGameAsync` playtime, `CountSinceAsync(now − 7 d)`. Capability badges and the Repair button are
> PR-8's with the Agent section.
>
> **Amended 2026-09-23: the card shows every running session, measured or not.** A session held unhooked
> (Tier 2 — hooking off, refused, unreadable) shows its name, the T2 badge, the elapsed time and the
> machine's temperatures from `SessionHeld`, the line "Recording duration and sensors only — nothing is
> measured." and **why**, in the sentence its summary will carry (`Formats.Tier2HoldReason` over the start's
> `hold`, the same words `Tier2Reason` reads from `capture_notes`) — and no `FpsReadout` at all. A session the
> status lists at tier 2 with no `hold` has not attached yet: its name and badge until the attach's start arrives,
> never the held line and never the "Attached — waiting" one. A hooked session takes the card from a held one,
> never the reverse. The card is seeded from the
> App-lifetime `LiveSessions` when the Dashboard is built, so a session that started while another page was
> open is on it at once; the completion notice names the session that completed (`SessionCompleted.gameName`)
> and a `faulted` completion is no notice (the strip's `CaptureError` already said it). Until this date the
> Agent announced only hooked sessions: every other game read "Nothing is being captured." while it ran.
### Games (grid → detail)
- `GridView`-style panel of cover cards (`ui:CardAction`): name, platform badge, engine badge, total playtime, last played, mini trend sparkline (avg Native FPS last 10 sessions). Sort/filter/`ui:AutoSuggestBox` search.
+5 -2
View File
@@ -58,10 +58,13 @@ flow, and the tests run the flow over a fake client because nothing here may tou
- **FR-12 is the shape of the flow, not a check at the end.** A downloaded package is `Ready` only while the Agent
reports no session (its `StatusAck` at connect, then `SessionStarted` / `SessionCompleted` on the pipe);
otherwise it is `Deferred`, the button is disabled and the body says why, and it becomes `Ready` when the last
session ends. The apply is refused again inside if a session started meanwhile. A recording-only (Tier 2)
session ends. The apply is refused again inside if a session started meanwhile. ~~A recording-only (Tier 2)
session that began before the App connected is covered by the status; one that begins afterwards raises no
`SessionStarted` (that event is the ring's) and is not — a known gap, recorded rather than hidden: the Overlay
is not on disk under such a session, so the rule's reason does not apply to it.
is not on disk under such a session, so the rule's reason does not apply to it.~~ **Closed 2026-09-23:** a held
(Tier 2) session raises its own `SessionStarted`, so it defers an update like any other; and the status read at
connect SEEDS the running set rather than being OR-ed with it forever — before, a session running when the App
connected held every download at `Deferred` until the next reconnect, hours after it ended.
- **Apply:** `Shutdown` to the Agent over the pipe, the connection's relaunch held (`IAgentLink.SetLaunchHold`),
the pipe watched until it drops (10 s; an Agent that does not stop leaves everything as it was and says so),
then `WaitExitThenApplyUpdates(asset, silent: false, restart: true)` and the host ends. The restarted App
+18
View File
@@ -1497,6 +1497,24 @@ runtime its .NET launcher starts); no launcher-following in beta.6.
were a removal (to clean up an `H:` twin) under a running session. The finalize now resolves the owner; a test that
deletes a row mid-session must expect `GameRemoved` or a re-keyed row, never an exception.
**Tier 2 on the wire (item 4a, owner: "capture still does not show when some titles are launched").** `SessionStarted`
is published ONCE per session — at the attach, or at a held session's first tick carrying `hold` — so the card never
flickers between tiers; a held session's 1 Hz is `SessionHeld`, never `SessionProgress` (its required fields would put
zeros that look measured on the wire); the refusal's event goes out when the hold begins and is not repeated at the
end; a faulted session completes with `finalize: faulted`. Every list of running sessions the App keeps is seeded from
the status at each connect (`07_IPC` §Client behavior). All fields are additive: `IpcProtocol.Version` stays 2.
**Traps.**
- **Only `hold` means held.** The status lists every session that has not attached yet at tier 2 (beta.5's shape,
kept), so a tier-2 `ActiveSession` without `hold` is a session STARTING. The card shows its name and badge and
nothing else; "nothing is measured" and "Attached — waiting for the first frames…" would both be false there.
- **`sed -i` in this machine's Git Bash writes a CRLF file back as LF.** Twice on 2026-09-23 a one-line `sed -i` turned
a test file into `w/lf` (`git ls-files --eol`), which `dotnet format` then fails on for no visible reason. Check
`git ls-files --eol -m -o --exclude-standard | grep -v w/crlf` after any shell edit; `unix2dos` repairs it.
- **Heredocs that carry C# with nested quotes can fail to parse in the Bash tool** ("unexpected EOF while looking for
matching `'`") even when quoted `<<'EOF'` — write the script with the Write tool and run it by path, as the traps
above already say for patches.
## Owner-only — no PR can close these
1. **§S23-2 — branch protection.** `Rules / validate` is not a required status check on
+18 -10
View File
@@ -268,16 +268,7 @@ public partial class App : System.Windows.Application
builder.Services.AddSingleton(closePolicy);
builder.Services.AddSingleton<IThemeApplier, WpfThemeApplier>();
// The Agent over the pipe (07_IPC §Client behavior): connect, start it when it is not there, tell the shell.
builder.Services.AddSingleton<IAgentLauncher, AgentLauncher>();
builder.Services.AddSingleton(static sp => new AgentConnection(
sp.GetRequiredService<IAgentLauncher>(),
static () => new PipeClient(),
new AgentConnectionOptions(),
UiIdentity.Version));
builder.Services.AddHostedService<AgentConnectionHostedService>();
builder.Services.AddSingleton<IAgentRequests>(static sp => sp.GetRequiredService<AgentConnection>());
builder.Services.AddSingleton<IAgentLink>(static sp => sp.GetRequiredService<AgentConnection>());
AddAgentLink(builder.Services);
// FR-2.1 (P3 PR-4): the consent dialog and the request it ends in; the toggle that opens it is the game page's (PR-5).
builder.Services.AddSingleton<IConsentPrompt, ConsentPrompt>();
@@ -309,6 +300,23 @@ public partial class App : System.Windows.Application
return builder.Build();
}
/// <summary>The Agent over the pipe (07_IPC §Client behavior): connect, start it when it is not there, tell the shell.</summary>
private static void AddAgentLink(IServiceCollection services)
{
services.AddSingleton<IAgentLauncher, AgentLauncher>();
services.AddSingleton(static sp => new AgentConnection(
sp.GetRequiredService<IAgentLauncher>(),
static () => new PipeClient(),
new AgentConnectionOptions(),
UiIdentity.Version));
services.AddHostedService<AgentConnectionHostedService>();
services.AddSingleton<IAgentRequests>(static sp => sp.GetRequiredService<AgentConnection>());
services.AddSingleton<IAgentLink>(static sp => sp.GetRequiredService<AgentConnection>());
// What the Agent runs right now (2026-09-23), for the pages rebuilt on every visit; built before the connection's
// first round by AgentConnectionHostedService, so it never misses a session.
services.AddSingleton(static sp => new LiveSessions(sp.GetRequiredService<IAgentLink>()));
}
/// <summary>
/// The library (P3 PR-5): the ports the pages read and write, the selection that travels between pages, and the
/// pickers, prompts and confirmations behind interfaces so the view models are testable without a window.
+8 -2
View File
@@ -10,7 +10,8 @@
<StackPanel Style="{StaticResource PageRoot}">
<ui:TextBlock FontTypography="Title" Text="{x:Static vm:DashboardViewModel.Header}" />
<!-- 08_UI §Dashboard: the live capture card, fed by SessionStarted / SessionProgress / SessionCompleted. -->
<!-- 08_UI §Dashboard: the live capture card, fed by SessionStarted / SessionProgress / SessionHeld / SessionCompleted.
A session recorded without measuring (Tier 2) shows why, and no readout (2026-09-23). -->
<ui:Card Margin="0,16,0,0" HorizontalAlignment="Stretch">
<StackPanel>
<StackPanel Orientation="Horizontal">
@@ -26,7 +27,12 @@
<ui:TextBlock Appearance="Secondary" Text="{Binding ViewModel.Live.ElapsedText}" />
<ui:TextBlock Appearance="Secondary" Text="{x:Static vm:LiveCaptureViewModel.WaitingText}"
Visibility="{Binding ViewModel.Live.WaitingForFrames, Converter={StaticResource BoolToVis}}" />
<controls:FpsReadout Margin="0,8,0,0" Model="{Binding ViewModel.Live.Readout}" />
<StackPanel Margin="0,8,0,0" Visibility="{Binding ViewModel.Live.IsHeld, Converter={StaticResource BoolToVis}}">
<ui:TextBlock Text="{x:Static vm:LiveCaptureViewModel.HeldText}" TextWrapping="Wrap" />
<ui:TextBlock Appearance="Secondary" Text="{Binding ViewModel.Live.HeldReason}" TextWrapping="Wrap" />
</StackPanel>
<controls:FpsReadout Margin="0,8,0,0" Model="{Binding ViewModel.Live.Readout}"
Visibility="{Binding ViewModel.Live.IsHeld, Converter={StaticResource InverseBoolToVis}}" />
<WrapPanel Margin="0,8,0,0">
<ui:TextBlock Margin="0,0,16,0" Text="{Binding ViewModel.Live.ResolutionText}" />
<ui:TextBlock Margin="0,0,16,0" Text="{Binding ViewModel.Live.UpscalerText}" />
@@ -3,9 +3,15 @@ using Microsoft.Extensions.Hosting;
namespace FrameLedger.App.Services;
/// <summary>Runs <see cref="AgentConnection"/> for the life of the host.</summary>
internal sealed class AgentConnectionHostedService(AgentConnection connection) : BackgroundService
internal sealed class AgentConnectionHostedService(AgentConnection connection, LiveSessions sessions) : BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken) => connection.RunAsync(stoppingToken);
// The running-session view is built with this service, before the first round, so the first connect's status seeds
// it and no event after it is missed (2026-09-23).
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
GC.KeepAlive(sessions);
return connection.RunAsync(stoppingToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
+13 -2
View File
@@ -143,9 +143,17 @@ public static class Formats
/// Why a Tier-2 session measured nothing, from <c>capture_notes</c> (2026-09-22): hooking off, a block on the row,
/// the guard's refusal by family, a process that could not be opened, or the end reason by name.
/// </summary>
public static string Tier2Reason(string? captureNotes)
public static string Tier2Reason(string? captureNotes) => Tier2Reason(Application.Recording.CaptureNotes.Parse(captureNotes));
/// <summary>The same words for a session still running (2026-09-23): the hold its <c>SessionStarted</c> carried.</summary>
public static string Tier2HoldReason(Shared.Ipc.SessionHold hold)
{
ArgumentNullException.ThrowIfNull(hold);
return Tier2Reason(new Application.Recording.CaptureNotes(hold.Reason, hold.GuardReason, hold.Family, hold.Signal));
}
private static string Tier2Reason(Application.Recording.CaptureNotes n)
{
Application.Recording.CaptureNotes n = Application.Recording.CaptureNotes.Parse(captureNotes);
switch (n.End)
{
case null:
@@ -158,6 +166,9 @@ public static class Formats
return string.Format(CultureInfo.CurrentCulture, Strings.Summary_Tier2_Why_Guard_Format, family, n.GuardSignal ?? Strings.Common_NotAvailable);
case "TargetUnreadable":
return Strings.Summary_Tier2_Why_Unreadable;
case "RefusedConsentMissing":
// Common after a store update (2026-09-23): the consent is about the executable that was enabled, and this is a newer one.
return Strings.Summary_Tier2_Why_ConsentChanged;
default:
return string.Format(CultureInfo.CurrentCulture, Strings.Summary_Tier2_Why_Other_Format, n.End);
}
@@ -0,0 +1,94 @@
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Services;
/// <summary>
/// The sessions the Agent is running right now, kept for the App's whole life (2026-09-23): seeded from the status the
/// Agent answers on every (re)connect, then moved by <c>SessionStarted</c> and <c>SessionCompleted</c>. Until this date the
/// Dashboard, the tray and the updater each kept their own list from events alone — a Dashboard opened after a game
/// started (it is rebuilt on every visit) showed "Nothing is being captured.", the updater read a status hours old, and a
/// session the Agent never announced (every Tier-2 one) was in none of them.
/// </summary>
public sealed class LiveSessions : IDisposable
{
private readonly IAgentLink _agent;
private readonly Lock _lock = new();
private readonly Dictionary<Guid, RunningSession> _sessions = [];
public LiveSessions(IAgentLink agent)
{
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_agent.Changed += OnAgentChanged;
_agent.EventReceived += OnAgentEvent;
Reseed();
}
/// <summary>Raised on any change, on the thread that caused it; a view model marshals it as it does the link's own events.</summary>
public event EventHandler? Changed;
/// <summary>A snapshot, oldest first.</summary>
public IReadOnlyList<RunningSession> Current
{
get
{
lock (_lock)
{
return [.. _sessions.Values.OrderBy(static s => s.StartedAt)];
}
}
}
public void Dispose()
{
_agent.Changed -= OnAgentChanged;
_agent.EventReceived -= OnAgentEvent;
}
// The link raises Changed with a fresh StatusAck whenever it (re)connects, and on every state it leaves Connected for.
private void OnAgentChanged(object? sender, EventArgs e) => Reseed();
private void Reseed()
{
StatusAck? status = _agent.State == AgentConnectionState.Connected ? _agent.Status : null;
lock (_lock)
{
_sessions.Clear();
foreach (ActiveSession a in status?.ActiveSessions ?? [])
{
_sessions[a.SessionGuid] = new RunningSession(a.SessionGuid, a.GameId, a.GameName, a.Tier, a.StartedAt, a.Hold);
}
}
Changed?.Invoke(this, EventArgs.Empty);
}
private void OnAgentEvent(object? sender, AgentEventArgs e)
{
switch (e.Envelope.Type)
{
case IpcMessageType.SessionStarted when IpcCodec.Payload<SessionStartedEvent>(e.Envelope) is { } started:
lock (_lock)
{
_sessions[started.SessionGuid] = new RunningSession(started.SessionGuid, started.GameId, started.GameName, started.Tier, started.StartedAt, started.Hold);
}
Changed?.Invoke(this, EventArgs.Empty);
break;
case IpcMessageType.SessionCompleted when IpcCodec.Payload<SessionCompletedEvent>(e.Envelope) is { } completed:
bool removed;
lock (_lock)
{
removed = _sessions.Remove(completed.SessionGuid);
}
if (removed)
{
Changed?.Invoke(this, EventArgs.Empty);
}
break;
default:
break;
}
}
}
@@ -0,0 +1,6 @@
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Services;
/// <summary>One session the Agent is running, as the App knows it: its entry, its tier and — for Tier 2 — why nothing is measured.</summary>
public sealed record RunningSession(Guid SessionGuid, long GameId, string? GameName, int Tier, DateTimeOffset StartedAt, SessionHold? Hold);
+6
View File
@@ -147,6 +147,7 @@ public static class Strings
nameof(Dashboard_Live_GpuTemp_Format),
nameof(Dashboard_Live_Header),
nameof(Dashboard_Live_Idle),
nameof(Dashboard_Live_RecordingOnly),
nameof(Dashboard_Live_Rt_On),
nameof(Dashboard_Live_Vram_Format),
nameof(Dashboard_Live_Waiting),
@@ -542,6 +543,7 @@ public static class Strings
nameof(Summary_Tags_Placeholder),
nameof(Summary_Tier2_Body),
nameof(Summary_Tier2_Why_Blocked_Format),
nameof(Summary_Tier2_Why_ConsentChanged),
nameof(Summary_Tier2_Why_Guard_Format),
nameof(Summary_Tier2_Why_HookOff),
nameof(Summary_Tier2_Why_Other_Format),
@@ -876,6 +878,8 @@ public static class Strings
public static string Dashboard_Live_Idle => ResourceManager.GetString(nameof(Dashboard_Live_Idle), Culture) ?? nameof(Dashboard_Live_Idle);
public static string Dashboard_Live_RecordingOnly => ResourceManager.GetString(nameof(Dashboard_Live_RecordingOnly), Culture) ?? nameof(Dashboard_Live_RecordingOnly);
public static string Dashboard_Live_Rt_On => ResourceManager.GetString(nameof(Dashboard_Live_Rt_On), Culture) ?? nameof(Dashboard_Live_Rt_On);
public static string Dashboard_Live_Vram_Format => ResourceManager.GetString(nameof(Dashboard_Live_Vram_Format), Culture) ?? nameof(Dashboard_Live_Vram_Format);
@@ -1666,6 +1670,8 @@ public static class Strings
public static string Summary_Tier2_Why_Blocked_Format => ResourceManager.GetString(nameof(Summary_Tier2_Why_Blocked_Format), Culture) ?? nameof(Summary_Tier2_Why_Blocked_Format);
public static string Summary_Tier2_Why_ConsentChanged => ResourceManager.GetString(nameof(Summary_Tier2_Why_ConsentChanged), Culture) ?? nameof(Summary_Tier2_Why_ConsentChanged);
public static string Summary_Tier2_Why_Guard_Format => ResourceManager.GetString(nameof(Summary_Tier2_Why_Guard_Format), Culture) ?? nameof(Summary_Tier2_Why_Guard_Format);
public static string Summary_Tier2_Why_HookOff => ResourceManager.GetString(nameof(Summary_Tier2_Why_HookOff), Culture) ?? nameof(Summary_Tier2_Why_HookOff);
+8
View File
@@ -481,6 +481,10 @@
<value>現在キャプチャ中のものはありません。</value>
<comment>review</comment>
</data>
<data name="Dashboard_Live_RecordingOnly" xml:space="preserve">
<value>時間とセンサーのみを記録中 — 計測は行っていません。</value>
<comment>review</comment>
</data>
<data name="Dashboard_Live_Rt_On" xml:space="preserve">
<value>RT 有効</value>
<comment>review</comment>
@@ -1229,6 +1233,10 @@
<value>理由: このゲームのフックはオフです — ガードが {0} を検出しました。</value>
<comment>review</comment>
</data>
<data name="Summary_Tier2_Why_ConsentChanged" xml:space="preserve">
<value>理由: フックをオンにした後にゲームの実行ファイルが変わった(通常はアップデート)ため、その同意は適用されません — このゲームのフックをもう一度オンにしてください。</value>
<comment>review</comment>
</data>
<data name="Summary_Tier2_Why_Guard_Format" xml:space="preserve">
<value>理由: ガードが拒否しました — {0}({1})。</value>
<comment>review</comment>
+6
View File
@@ -366,6 +366,9 @@
<data name="Dashboard_Live_Idle" xml:space="preserve">
<value>Nothing is being captured.</value>
</data>
<data name="Dashboard_Live_RecordingOnly" xml:space="preserve">
<value>Recording duration and sensors only — nothing is measured.</value>
</data>
<data name="Dashboard_Live_Rt_On" xml:space="preserve">
<value>RT active</value>
</data>
@@ -927,6 +930,9 @@
<data name="Summary_Tier2_Why_Blocked_Format" xml:space="preserve">
<value>Why: hooking is off for this game — the guard found {0}.</value>
</data>
<data name="Summary_Tier2_Why_ConsentChanged" xml:space="preserve">
<value>Why: the game's executable changed since hooking was turned on (an update, usually), so that consent no longer applies — turn hooking on again for it.</value>
</data>
<data name="Summary_Tier2_Why_Guard_Format" xml:space="preserve">
<value>Why: the guard refused — {0} ({1}).</value>
</data>
+6
View File
@@ -361,6 +361,9 @@
<data name="Dashboard_Live_Idle" xml:space="preserve">
<value>Không có gì đang được thu thập.</value>
</data>
<data name="Dashboard_Live_RecordingOnly" xml:space="preserve">
<value>Chỉ ghi thời lượng và cảm biến — không đo gì.</value>
</data>
<data name="Dashboard_Live_Rt_On" xml:space="preserve">
<value>RT đang bật</value>
</data>
@@ -922,6 +925,9 @@
<data name="Summary_Tier2_Why_Blocked_Format" xml:space="preserve">
<value>Lý do: hooking đang tắt cho game này — guard đã phát hiện {0}.</value>
</data>
<data name="Summary_Tier2_Why_ConsentChanged" xml:space="preserve">
<value>Lý do: file thực thi của game đã đổi kể từ khi bật hooking (thường là do cập nhật), nên sự đồng ý đó không còn áp dụng — hãy bật lại hooking cho game.</value>
</data>
<data name="Summary_Tier2_Why_Guard_Format" xml:space="preserve">
<value>Lý do: guard đã từ chối — {0} ({1}).</value>
</data>
+15 -17
View File
@@ -19,9 +19,6 @@ namespace FrameLedger.App.Update;
/// </summary>
public sealed partial class UpdateService : ObservableObject, IDisposable
{
/// <summary><c>StatusAck.State</c> when no session runs.</summary>
private const string _idleState = "idle";
private static readonly TimeSpan _defaultAgentStopTimeout = TimeSpan.FromSeconds(10);
private readonly TimeSpan _agentStopTimeout;
@@ -64,20 +61,13 @@ public sealed partial class UpdateService : ObservableObject, IDisposable
/// <summary>Raised once per release found, for the tray's toast; the banner follows <see cref="Stage"/>.</summary>
public event EventHandler<UpdateAvailableEventArgs>? Available;
/// <summary>A session runs (hooked or recording): the Agent said so at connect, or a <c>SessionStarted</c> arrived without its <c>SessionCompleted</c>.</summary>
public bool IsSessionActive
{
get
{
if (_running.Count > 0)
{
return true;
}
StatusAck? status = _agent.Status;
return status is not null && (!string.Equals(status.State, _idleState, StringComparison.Ordinal) || status.ActiveSessions.Count > 0);
}
}
/// <summary>
/// A session runs (hooked or recording): one the Agent listed when this App (re)connected, or a <c>SessionStarted</c>
/// since, without its <c>SessionCompleted</c>. Until 2026-09-23 it also OR-ed the status read at connect, which is
/// never read again — so a session running when the App connected held every update at Deferred until the next
/// reconnect, hours after it ended. The connect-time list now seeds the set and the completions empty it.
/// </summary>
public bool IsSessionActive => _running.Count > 0;
public void Dispose()
{
@@ -311,6 +301,14 @@ public sealed partial class UpdateService : ObservableObject, IDisposable
private void OnAgentChanged(object? sender, EventArgs e) => Post(() =>
{
_running.Clear();
if (_agent.State == AgentConnectionState.Connected && _agent.Status is { } status)
{
foreach (ActiveSession a in status.ActiveSessions)
{
_running.Add(a.SessionGuid);
}
}
Settle();
});
@@ -54,10 +54,13 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
private bool _recentEmpty = true;
private readonly IShellPresence? _presence;
private readonly LiveSessions? _sessions;
public DashboardViewModel(IAgentLink agent, GameLibrary library, GameSelection selection, IPageNavigator navigator, ISessionSummaryOpener summaries, IMessageStrip strip, IShellPresence? presence = null)
public DashboardViewModel(IAgentLink agent, GameLibrary library, GameSelection selection, IPageNavigator navigator, ISessionSummaryOpener summaries, IMessageStrip strip, IShellPresence? presence = null,
LiveSessions? sessions = null)
{
_presence = presence;
_sessions = sessions;
_agent = agent ?? throw new ArgumentNullException(nameof(agent));
_library = library ?? throw new ArgumentNullException(nameof(library));
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
@@ -66,7 +69,13 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
_agent.Changed += OnAgentChanged;
_agent.EventReceived += OnAgentEvent;
if (_sessions is not null)
{
_sessions.Changed += OnSessionsChanged;
}
Refresh();
SeedLive();
Pending = LoadAsync();
}
@@ -95,6 +104,10 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
{
_agent.Changed -= OnAgentChanged;
_agent.EventReceived -= OnAgentEvent;
if (_sessions is not null)
{
_sessions.Changed -= OnSessionsChanged;
}
}
public async Task LoadAsync(CancellationToken ct = default)
@@ -139,6 +152,27 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
private void OnAgentEvent(object? sender, AgentEventArgs e) => _ui.Post(() => Dispatch(e.Envelope));
private void OnSessionsChanged(object? sender, EventArgs e) => _ui.Post(() =>
{
SeedLive();
Refresh();
});
/// <summary>
/// A session already running takes the idle card (2026-09-23): the Dashboard is rebuilt on every visit, so one that
/// started while another page was open had no start event here and read "Nothing is being captured.". A hooked
/// session is preferred over one recorded without measuring.
/// </summary>
private void SeedLive()
{
if (Live.IsActive || _sessions?.Current is not { Count: > 0 } running)
{
return;
}
Live.Seed(running.FirstOrDefault(static s => s.Tier == 1) ?? running[0]);
}
/// <summary>The three session events drive the live card; a completed session reloads the lists (07_IPC §Client behavior: the row is in SQLite).</summary>
private void Dispatch(IpcEnvelope envelope)
{
@@ -150,9 +184,15 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
case IpcMessageType.SessionProgress when IpcCodec.Payload<SessionProgressEvent>(envelope) is { } progress:
Live.Update(progress);
break;
case IpcMessageType.SessionHeld when IpcCodec.Payload<SessionHeldEvent>(envelope) is { } held:
Live.Hold(held);
break;
case IpcMessageType.SessionCompleted when IpcCodec.Payload<SessionCompletedEvent>(envelope) is { } completed:
// The session's own name (2026-09-23): the card may show another session, and a Tier-2 one had none here.
string? name = completed.GameName ?? (Live.SessionGuid == completed.SessionGuid ? Live.GameName : null);
Live.Stop(completed);
Notice(completed);
Notice(completed, name);
SeedLive();
Pending = LoadAsync();
break;
default:
@@ -162,14 +202,15 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
/// <summary>FR-3.8's post-session notice, in-app while the window is on screen; the tray's balloon carries it otherwise (P3 PR-8b, one event → one channel). A safety stop is never a toast (08_UI §Notifications policy) — the shell's notices carry those.</summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format string is a resource that follows the UI culture, which changes at runtime")]
private void Notice(SessionCompletedEvent completed)
private void Notice(SessionCompletedEvent completed, string? name)
{
if (_presence is { IsShown: false })
// A faulted session is the strip's CaptureError already; "discarded" would say something that did not happen.
if (_presence is { IsShown: false } || string.Equals(completed.Finalize, "faulted", StringComparison.Ordinal))
{
return;
}
string game = Live.GameName.Length > 0 ? Live.GameName : Strings.Common_NotAvailable;
string game = name is { Length: > 0 } ? name : Strings.Common_NotAvailable;
if (completed.SessionId is not null)
{
_strip.Success(Strings.Dashboard_Live_Header, string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_SessionSaved_Format, game));
@@ -189,6 +230,8 @@ public sealed partial class DashboardViewModel : ObservableObject, IDisposable
TelemetrySource = hello?.TelemetrySource ?? Strings.Common_NotAvailable;
OverlayBuildId = hello?.OverlayBuildId ?? Strings.Common_NotAvailable;
Elevated = hello is null ? Strings.Common_NotAvailable : hello.Elevated ? Strings.Common_Yes : Strings.Common_No;
RunningSessions = status?.ActiveSessions.Count.ToString(CultureInfo.CurrentCulture) ?? Strings.Common_NotAvailable;
RunningSessions = _sessions is not null && _agent.State == AgentConnectionState.Connected
? _sessions.Current.Count.ToString(CultureInfo.CurrentCulture)
: status?.ActiveSessions.Count.ToString(CultureInfo.CurrentCulture) ?? Strings.Common_NotAvailable;
}
}
@@ -8,9 +8,15 @@ namespace FrameLedger.App.ViewModels;
/// <summary>
/// The Dashboard's live capture card (<c>08_UI</c> §Dashboard), fed by <c>SessionStarted</c> / <c>SessionProgress</c> /
/// <c>SessionCompleted</c>. Tier 1 shows measured settings as facts; the readout follows the FPS display rule at
/// 1 Hz, qualifier included. The sparkline is PR-6's.
/// <c>SessionHeld</c> / <c>SessionCompleted</c>. Tier 1 shows measured settings as facts; the readout follows the FPS
/// display rule at 1 Hz, qualifier included. The sparkline is PR-6's.
/// </summary>
/// <remarks>
/// <b>A session that is not measured is shown too (2026-09-23).</b> Its name, its tier, how long it has run, the machine's
/// temperatures, and why nothing is measured — the same words its summary will use — with no readout at all. Until this
/// date the Agent announced only hooked sessions, and a hooking-off or refused game read "Nothing is being captured." for
/// as long as it ran. When two sessions run, a hooked one takes the card.
/// </remarks>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime")]
public sealed partial class LiveCaptureViewModel : ObservableObject
{
@@ -20,6 +26,16 @@ public sealed partial class LiveCaptureViewModel : ObservableObject
[ObservableProperty]
private bool _waitingForFrames;
/// <summary>A Tier-2 session: recorded, not measured.</summary>
[ObservableProperty]
private bool _isHeld;
/// <summary>Why a held session measures nothing: the sentence its summary will carry.</summary>
[ObservableProperty]
private string _heldReason = string.Empty;
public static string HeldText => Strings.Dashboard_Live_RecordingOnly;
[ObservableProperty]
private string _gameName = string.Empty;
@@ -63,17 +79,60 @@ public sealed partial class LiveCaptureViewModel : ObservableObject
public static string RtOnText => Strings.Dashboard_Live_Rt_On;
/// <summary>The tier of the session on the card; 0 when there is none.</summary>
public int Tier { get; private set; }
public void Start(SessionStartedEvent started)
{
ArgumentNullException.ThrowIfNull(started);
SessionGuid = started.SessionGuid;
GameName = started.GameName ?? Strings.Common_NotAvailable;
TierText = started.Tier == 1 ? Strings.Tier_Hooked : Strings.Tier_NotHooked;
Show(started.SessionGuid, started.GameName, started.Tier, started.Hold);
}
/// <summary>A session that was already running when the card was built (the Dashboard is rebuilt on every visit).</summary>
public void Seed(RunningSession session)
{
ArgumentNullException.ThrowIfNull(session);
Show(session.SessionGuid, session.GameName, session.Tier, session.Hold);
}
/// <summary>A held session's 1 Hz tick: elapsed and the machine's temperatures.</summary>
public void Hold(SessionHeldEvent held)
{
ArgumentNullException.ThrowIfNull(held);
if (SessionGuid != held.SessionGuid)
{
return;
}
ElapsedText = string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_Live_Elapsed_Format, Formats.Duration(held.ElapsedS));
GpuTempText = held.GpuTempC is double g ? string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_Live_GpuTemp_Format, Math.Round(g)) : string.Empty;
CpuTempText = held.CpuTempC is double c ? string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_Live_CpuTemp_Format, Math.Round(c)) : string.Empty;
}
private void Show(Guid sessionGuid, string? gameName, int tier, SessionHold? hold)
{
// A hooked session takes the card from an unhooked one, never the other way round.
if (IsActive && SessionGuid is Guid shown && shown != sessionGuid && (Tier == 1 || tier != 1))
{
return;
}
SessionGuid = sessionGuid;
Tier = tier;
GameName = gameName ?? Strings.Common_NotAvailable;
TierText = tier == 1 ? Strings.Tier_Hooked : Strings.Tier_NotHooked;
ElapsedText = string.Empty;
Readout = FpsReadoutModel.Unavailable;
ResolutionText = UpscalerText = FgText = GpuTempText = CpuTempText = VramText = string.Empty;
RtActive = false;
WaitingForFrames = true;
// Held means the Agent said why (a Tier-2 start carries its hold). A session the status lists at tier 2 with no hold
// has not attached YET — it is starting: "nothing is measured" would be a claim nobody made, and the waiting line
// says "Attached", which it is not. It shows its name and badge until its attach's start arrives.
SessionHold? why = tier != 1 ? hold : null;
IsHeld = why is not null;
HeldReason = why is null ? string.Empty : Formats.Tier2HoldReason(why);
WaitingForFrames = tier == 1;
IsActive = true;
}
@@ -86,6 +145,9 @@ public sealed partial class LiveCaptureViewModel : ObservableObject
}
SessionGuid ??= progress.SessionGuid;
Tier = 1;
IsHeld = false;
HeldReason = string.Empty;
IsActive = true;
WaitingForFrames = progress.Presents5s == 0;
ElapsedText = string.Format(CultureInfo.CurrentCulture, Strings.Dashboard_Live_Elapsed_Format, Formats.Duration(progress.ElapsedS));
@@ -108,7 +170,10 @@ public sealed partial class LiveCaptureViewModel : ObservableObject
}
SessionGuid = null;
Tier = 0;
IsActive = false;
WaitingForFrames = false;
IsHeld = false;
HeldReason = GameName = TierText = ElapsedText = GpuTempText = CpuTempText = VramText = string.Empty;
}
}
@@ -143,9 +143,15 @@ public sealed partial class TrayViewModel : ObservableObject, IDisposable
IsPaused = status.Paused;
}
if (!_agent.IsConnected)
// What the Agent runs is re-read on every (re)connect (2026-09-23): a session that started before this App
// connected — or while it was away — was missing from the tray until it ended.
_running.Clear();
if (_agent.IsConnected && _agent.Status is { } running)
{
_running.Clear();
foreach (ActiveSession a in running.ActiveSessions)
{
_running[a.SessionGuid] = (a.Tier, a.GameName ?? Strings.Common_NotAvailable);
}
}
Recompute();
@@ -162,7 +168,8 @@ public sealed partial class TrayViewModel : ObservableObject, IDisposable
Recompute();
break;
case IpcMessageType.SessionCompleted when IpcCodec.Payload<SessionCompletedEvent>(envelope) is { } completed:
string name = _running.TryGetValue(completed.SessionGuid, out (int Tier, string Name) run) ? run.Name : Strings.Common_NotAvailable;
string name = completed.GameName
?? (_running.TryGetValue(completed.SessionGuid, out (int Tier, string Name) run) ? run.Name : Strings.Common_NotAvailable);
_running.Remove(completed.SessionGuid);
Recompute();
if (completed.SessionId is long id)
@@ -28,6 +28,12 @@ public sealed record CaptureProgress
public required NgxDriverState NgxDriver { get; init; }
/// <summary>
/// On a held session's tick (2026-09-23): the refusal it is held under — its reason, and the guard's verdict when the
/// guard spoke — so the pipe can say, while the game runs, why nothing is measured. Null on every hooked tick.
/// </summary>
public CaptureOutcome? Hold { get; init; }
/// <summary>The tick of a session that never attached (Tier 2, 2026-09-22): no records, no ring, nothing measured.</summary>
public static CaptureProgress Unhooked { get; } = new()
{
@@ -43,4 +49,11 @@ public sealed record CaptureProgress
RuntimeModules = RuntimeModuleSet.Empty,
NgxDriver = NgxDriverState.NotRun,
};
/// <summary>The tick of a session held unhooked under <paramref name="refusal"/> (2026-09-23): <see cref="Unhooked"/> with its reason.</summary>
public static CaptureProgress Held(CaptureOutcome refusal)
{
ArgumentNullException.ThrowIfNull(refusal);
return Unhooked with { Hold = refusal };
}
}
@@ -143,6 +143,10 @@ public sealed class CaptureSession(
}
DateTimeOffset? hardStop = options.MaxDuration > TimeSpan.Zero ? DateTimeOffset.UtcNow + options.MaxDuration : null;
// The ticks carry the refusal with the pid the loop holds, if any (2026-09-23: the pipe announces a held session from
// its first tick). A hooking-off hold never opened the process and says 0.
CaptureProgress held = CaptureProgress.Held(refusal with { TargetPid = pid ?? 0 });
while (!stop.IsCancellationRequested)
{
bool running = alive is not null ? !alive.HasExited : resolver.IsRunning(normalisedExePath);
@@ -151,11 +155,11 @@ public sealed class CaptureSession(
break;
}
observer?.Tick(CaptureProgress.Unhooked);
observer?.Tick(held);
await Task.Delay(options.HoldInterval, ct).ConfigureAwait(false);
}
observer?.Tick(CaptureProgress.Unhooked);
observer?.Tick(held);
return refusal with { HeldUnhooked = true, TargetPid = pid ?? 0, ExitCode = alive?.ExitCode };
}
@@ -59,14 +59,46 @@ public static class RecordedSessionEvents
_ => CaptureErrorCode.AttachRefused,
};
public static void PublishAll(IIpcEventPublisher pipe, RecordedSession session, SessionStartedInfo info)
/// <summary>
/// A finished session's events: its reason's safety/error event — unless <paramref name="reasonAlreadyPublished"/>, because
/// a held session said it when its hold began (2026-09-23) — then always <c>SessionCompleted</c>, naming the entry the
/// session was stored under.
/// </summary>
public static void PublishAll(IIpcEventPublisher pipe, RecordedSession session, SessionStartedInfo info, bool reasonAlreadyPublished = false)
{
ArgumentNullException.ThrowIfNull(pipe);
ArgumentNullException.ThrowIfNull(session);
ArgumentNullException.ThrowIfNull(info);
if (!reasonAlreadyPublished)
{
PublishReason(pipe, session.SessionGuid, session.Outcome, info);
}
CaptureOutcome o = session.Outcome;
Guid guid = session.SessionGuid;
pipe.Publish(IpcMessageType.SessionCompleted, new SessionCompletedEvent(
session.SessionGuid,
session.Finalize.SessionId,
Vocabulary.ExitStatusText(session.ExitStatus),
(int)session.Row.Tier,
FinalizeText(session.Finalize.Status),
o.Reason.ToString(),
session.Finalize.GameId ?? info.GameId,
info.GameName));
}
/// <summary>
/// The one safety or error event <paramref name="outcome"/>'s reason warrants, or nothing. At the end of a session, or —
/// for a session held unhooked (2026-09-23) — the moment its hold begins, so a refusal is said while the game runs and
/// not when it exits.
/// </summary>
public static void PublishReason(IIpcEventPublisher pipe, Guid sessionGuid, CaptureOutcome outcome, SessionStartedInfo info)
{
ArgumentNullException.ThrowIfNull(pipe);
ArgumentNullException.ThrowIfNull(outcome);
ArgumentNullException.ThrowIfNull(info);
CaptureOutcome o = outcome;
switch (Classify(o.Reason))
{
case Kind.Refused:
@@ -74,29 +106,41 @@ public static class RecordedSessionEvents
new CaptureRefusedEvent(info.GameId, info.GameName, o.Reason.ToString(), NullIfEmpty(o.Verdict.Family), NullIfEmpty(o.Verdict.Signal), o.HookingTurnedOff));
break;
case Kind.SafetyUnhook:
pipe.Publish(IpcMessageType.SafetyUnhook, new SafetyUnhookEvent(guid, NullIfEmpty(o.Verdict.Family), NullIfEmpty(o.Verdict.Signal), o.HookingTurnedOff));
pipe.Publish(IpcMessageType.SafetyUnhook, new SafetyUnhookEvent(sessionGuid, NullIfEmpty(o.Verdict.Family), NullIfEmpty(o.Verdict.Signal), o.HookingTurnedOff));
break;
case Kind.Degraded:
pipe.Publish(IpcMessageType.CaptureDegraded, new CaptureDegradedEvent(guid, From: 1, To: 2, o.Reason.ToString()));
pipe.Publish(IpcMessageType.CaptureDegraded, new CaptureDegradedEvent(sessionGuid, From: 1, To: 2, o.Reason.ToString()));
break;
case Kind.AttachError:
pipe.Publish(IpcMessageType.CaptureError,
new CaptureErrorEvent(guid, RingCode(o.AttachRefusal), $"the ring could not be attached: {o.AttachRefusal}"));
new CaptureErrorEvent(sessionGuid, RingCode(o.AttachRefusal), $"the ring could not be attached: {o.AttachRefusal}"));
break;
case Kind.TargetError:
pipe.Publish(IpcMessageType.CaptureError, new CaptureErrorEvent(guid, CaptureErrorCode.InjectFailed, o.Reason.ToString()));
pipe.Publish(IpcMessageType.CaptureError, new CaptureErrorEvent(sessionGuid, CaptureErrorCode.InjectFailed, o.Reason.ToString()));
break;
default:
break;
}
}
pipe.Publish(IpcMessageType.SessionCompleted, new SessionCompletedEvent(
guid,
session.Finalize.SessionId,
Vocabulary.ExitStatusText(session.ExitStatus),
(int)session.Row.Tier,
FinalizeText(session.Finalize.Status),
o.Reason.ToString()));
/// <summary><c>SessionCompleted.finalize</c> for a session whose task threw before it could finalize (2026-09-23).</summary>
public const string FaultedFinalize = "faulted";
/// <summary>
/// The words a held session's <c>capture_notes</c> will carry, for the wire (2026-09-23): the loop's reason and, when the
/// guard said anything but a plain allow, its reason, family and signal.
/// </summary>
public static SessionHold HoldOf(CaptureOutcome outcome)
{
ArgumentNullException.ThrowIfNull(outcome);
Domain.AntiCheat.AntiCheatVerdict v = outcome.Verdict;
bool guardSpoke = v.Reason != Domain.AntiCheat.AntiCheatRefusalReason.Allow;
return new SessionHold(
outcome.Reason.ToString(),
guardSpoke ? v.Reason.ToString() : null,
guardSpoke ? NullIfEmpty(v.Family) : null,
guardSpoke ? NullIfEmpty(v.Signal) : null,
outcome.HookingTurnedOff);
}
public static string FinalizeText(FinalizeStatus status) => status switch
@@ -105,6 +105,12 @@ public sealed class SessionEventPublisher : ISessionObserver
t.LastSystem = drained[^1].System;
}
if (progress.Hold is { } hold && t.AttachedAt is null)
{
Held(sessionGuid, t, hold);
return;
}
if (t.AttachedAt is null || !_pipe.HasClients)
{
return;
@@ -132,21 +138,72 @@ public sealed class SessionEventPublisher : ISessionObserver
if (t is not null)
{
RecordedSessionEvents.PublishAll(_pipe, session, t.Info);
RecordedSessionEvents.PublishAll(_pipe, session, t.Info, reasonAlreadyPublished: t.ReasonPublished);
}
}
public void Faulted(Guid sessionGuid, Exception exception)
{
ArgumentNullException.ThrowIfNull(exception);
Tracked? t;
lock (_lock)
{
_sessions.Remove(sessionGuid);
_sessions.Remove(sessionGuid, out t);
Republish();
}
_pipe.Publish(IpcMessageType.CaptureError,
new CaptureErrorEvent(sessionGuid, CaptureErrorCode.SessionFaulted, $"{exception.GetType().Name}: {exception.Message}"));
// And the session is over (2026-09-23): without a completion the live card and the tray stayed on a session that no
// longer ran. Nothing was stored — the .partial stays for recovery — which is what "faulted" says.
_pipe.Publish(IpcMessageType.SessionCompleted, new SessionCompletedEvent(
sessionGuid, SessionId: null, Vocabulary.ExitStatusText(Domain.Sessions.ExitStatus.Interrupted), t?.AttachedAt is null ? 2 : 1,
RecordedSessionEvents.FaultedFinalize, CaptureErrorCode.SessionFaulted, t?.Info.GameId, t?.Info.GameName));
}
/// <summary>
/// A held (Tier-2) session's tick (2026-09-23). The first one announces it — <c>SessionStarted</c> at tier 2 with why,
/// and the refusal's own event now rather than when the game exits — and every one after feeds <c>SessionHeld</c> at the
/// progress interval while a client listens. Until this date a held session sent nothing until it ended.
/// </summary>
private void Held(Guid sessionGuid, Tracked t, CaptureOutcome hold)
{
if (t.Hold is null)
{
SessionHold why = RecordedSessionEvents.HoldOf(hold);
lock (_lock)
{
t.Hold = why;
t.Pid = hold.TargetPid;
Republish();
}
_pipe.Publish(IpcMessageType.SessionStarted,
new SessionStartedEvent(sessionGuid, t.Info.GameId, t.Info.GameName, hold.TargetPid, Tier: 2, t.Info.StartedAt, why));
RecordedSessionEvents.PublishReason(_pipe, sessionGuid, hold, t.Info);
t.ReasonPublished = true;
}
if (!_pipe.HasClients)
{
return;
}
long now = _clock.GetTimestamp();
if (t.LastProgress is { } last && _clock.GetElapsedTime(last, now) < _interval)
{
return;
}
t.LastProgress = now;
_pipe.Publish(IpcMessageType.SessionHeld, new SessionHeldEvent(
sessionGuid,
Math.Max(0, (_clock.GetUtcNow() - t.Info.StartedAt).TotalSeconds),
t.LastGpu?.TempCoreC,
t.LastSystem.CpuTempC,
t.LastGpu?.LoadPct,
t.LastSystem.CpuLoadPct));
}
private void PublishProgress(Guid sessionGuid, Tracked t, CaptureProgress progress, long now)
@@ -177,7 +234,8 @@ public sealed class SessionEventPublisher : ISessionObserver
t.Info.GameName,
t.Pid,
t.AttachedAt is null ? 2 : 1,
t.AttachedAt ?? t.Info.StartedAt);
t.AttachedAt ?? t.Info.StartedAt,
t.AttachedAt is null ? t.Hold : null);
}
Volatile.Write(ref _status, new AgentStatus(sessions));
@@ -198,5 +256,11 @@ public sealed class SessionEventPublisher : ISessionObserver
public GpuSample? LastGpu { get; set; }
public SystemReading LastSystem { get; set; }
/// <summary>Why a held session measures nothing; set by its first held tick (2026-09-23).</summary>
public SessionHold? Hold { get; set; }
/// <summary>The refusal's event went out when the hold began, so the end does not say it again.</summary>
public bool ReasonPublished { get; set; }
}
}
@@ -23,6 +23,7 @@ namespace FrameLedger.Shared.Ipc;
[JsonSerializable(typeof(ErrorAck))]
[JsonSerializable(typeof(SessionStartedEvent))]
[JsonSerializable(typeof(SessionProgressEvent))]
[JsonSerializable(typeof(SessionHeldEvent))]
[JsonSerializable(typeof(SessionCompletedEvent))]
[JsonSerializable(typeof(CaptureRefusedEvent))]
[JsonSerializable(typeof(CaptureDegradedEvent))]
+32 -6
View File
@@ -51,6 +51,9 @@ public static class IpcMessageType
public const string SessionStarted = "SessionStarted";
public const string SessionProgress = "SessionProgress";
/// <summary>1 Hz while a session runs UNHOOKED (Tier 2) and a client listens (2026-09-23): elapsed and telemetry, nothing measured.</summary>
public const string SessionHeld = "SessionHeld";
public const string SessionCompleted = "SessionCompleted";
public const string CaptureRefused = "CaptureRefused";
public const string CaptureDegraded = "CaptureDegraded";
@@ -114,8 +117,18 @@ public sealed record HelloAck(
/// <summary><c>GetStatus</c>: no payload.</summary>
public sealed record GetStatusRequest;
/// <summary>One session the Agent is running right now. Tier 1 once the ring is attached, 2 until then or never.</summary>
public sealed record ActiveSession(Guid SessionGuid, long GameId, string? GameName, int Pid, int Tier, DateTimeOffset StartedAt);
/// <summary>
/// Why a session runs without being measured (2026-09-23): the words its <c>capture_notes</c> will carry — the loop's end
/// reason and, when the guard said it, the guard's reason, family and signal — so a live card can say what the summary
/// will. Sent with a Tier-2 <see cref="SessionStartedEvent"/> and on its <see cref="ActiveSession"/>; absent for Tier 1.
/// </summary>
public sealed record SessionHold(string Reason, string? GuardReason = null, string? Family = null, string? Signal = null, bool HookingTurnedOff = false);
/// <summary>
/// One session the Agent is running right now. Tier 1 once the ring is attached, 2 until then or never; <see cref="Hold"/>
/// says why a Tier-2 session measures nothing (2026-09-23, optional).
/// </summary>
public sealed record ActiveSession(Guid SessionGuid, long GameId, string? GameName, int Pid, int Tier, DateTimeOffset StartedAt, SessionHold? Hold = null);
/// <summary>
/// <c>StatusAck</c>. <see cref="State"/> is <c>idle</c>, <c>recording</c> (a session runs, nothing hooked) or
@@ -129,8 +142,19 @@ public sealed record PongAck;
public sealed record ErrorAck(string Code, string Message);
/// <summary>Published when the ring is attached — the moment a session becomes Tier 1 and the live card has something to show.</summary>
public sealed record SessionStartedEvent(Guid SessionGuid, long GameId, string? GameName, int Pid, int Tier, DateTimeOffset StartedAt);
/// <summary>
/// Published ONCE per session: when the ring is attached (Tier 1), or — since 2026-09-23 — when a session that will not
/// be hooked starts its hold (Tier 2, with <see cref="Hold"/>). Until then an unhooked session had no start event at all,
/// and the live card read "Nothing is being captured." for the whole of a hooking-off game.
/// </summary>
public sealed record SessionStartedEvent(Guid SessionGuid, long GameId, string? GameName, int Pid, int Tier, DateTimeOffset StartedAt, SessionHold? Hold = null);
/// <summary>
/// 1 Hz while a Tier-2 session is held and a client is connected (2026-09-23): how long it has run and the machine's
/// telemetry. Never a frame-derived value — there is none (CLAUDE.md rule 6 has nothing to show, and shows nothing).
/// Its own type rather than <see cref="SessionProgressEvent"/>, whose required fields would put measured-looking zeros on the wire.
/// </summary>
public sealed record SessionHeldEvent(Guid SessionGuid, double ElapsedS, double? GpuTempC = null, double? CpuTempC = null, double? GpuLoadPct = null, double? CpuLoadPct = null);
/// <summary>
/// 1 Hz while a hooked session runs and a client is connected (<c>04_CAPTURE</c> §Live progress). A 5 s rolling
@@ -218,9 +242,11 @@ public sealed record SessionProgressEvent
/// <summary>
/// The session is over and, when <see cref="SessionId"/> is set, in SQLite; the UI loads the row from there
/// (<c>07_IPC</c> §Client behavior). <see cref="Finalize"/> is <c>saved</c> or <c>discarded</c>.
/// (<c>07_IPC</c> §Client behavior). <see cref="Finalize"/> is <c>saved</c>, <c>discarded</c>, <c>game_removed</c> or
/// <c>faulted</c>. <see cref="GameId"/> and <see cref="GameName"/> (2026-09-23, optional) name the entry it belongs to, so a
/// notice about it never borrows another session's name.
/// </summary>
public sealed record SessionCompletedEvent(Guid SessionGuid, long? SessionId, string ExitStatus, int Tier, string Finalize, string Reason);
public sealed record SessionCompletedEvent(Guid SessionGuid, long? SessionId, string ExitStatus, int Tier, string Finalize, string Reason, long? GameId = null, string? GameName = null);
/// <summary>The gate or the guard said no before anything was injected (<c>08_UI</c> §Safety events: never a toast).</summary>
public sealed record CaptureRefusedEvent(long GameId, string? GameName, string Reason, string? Family, string? Signal, bool HookingTurnedOff = false);
@@ -118,6 +118,34 @@ public sealed class PipeEndToEndTests : IDisposable
}
}
/// <summary>
/// A game whose hooking is off is recorded without measuring (Tier 2), and since 2026-09-23 the pipe says so while it
/// runs: a tier-2 <c>SessionStarted</c> carrying why, <c>SessionHeld</c> ticks and never a <c>SessionProgress</c>, the
/// status listing it with its hold, and — when the harness exits — the completion under the entry's own name.
/// Nothing is injected: the row has no consent, and the loop never opens the process.
/// </summary>
[Fact]
public async Task AWatchedHarnessWithHookingOffIsHeldAndNarratedAtTierTwo()
{
StageTarget();
var paths = new AgentPaths(_dataDir);
Directory.CreateDirectory(paths.Logs);
Directory.CreateDirectory(paths.Tmp);
LedgerDatabase db = await LedgerDatabase.OpenAsync(paths.Database, ct: Ct).ConfigureAwait(true);
await using (db.ConfigureAwait(true))
{
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
GameRow row = await new SqliteGameRepository(db).EnsureAsync(fingerprint, "Held harness", Ct).ConfigureAwait(true);
row.HookEnabled.Should().BeFalse("a row that was merely added has hooking off");
ServiceProvider services = new ServiceCollection().AddFrameLedgerAgent(db, paths, _pipeName).BuildServiceProvider();
await using (services.ConfigureAwait(true))
{
await RunHeldScenarioAsync(services, row.Id).ConfigureAwait(true);
}
}
}
private void StageTarget()
{
File.Exists(Harness).Should().BeTrue("hook-harness.exe must be staged beside the test binary (FrameLedger.DrainFixtures.targets)");
@@ -235,6 +263,53 @@ public sealed class PipeEndToEndTests : IDisposable
}
}
private async Task RunHeldScenarioAsync(ServiceProvider services, long gameId)
{
PipeServer server = services.GetRequiredService<PipeServer>();
CaptureOrchestrator orchestrator = services.GetRequiredService<CaptureOrchestrator>();
using var stop = new CancellationTokenSource();
Task serving = server.RunAsync(stop.Token);
Task watching = orchestrator.RunAsync(stop.Token);
Process? harness = null;
PipeClient? client = null;
try
{
client = NewClient();
await client.ConnectAsync(TimeSpan.FromSeconds(10), Ct).ConfigureAwait(false);
await HelloAsync(client).ConfigureAwait(false);
harness = Process.Start(new ProcessStartInfo(ConsentedExecutable, "--real --hold-presenting 40") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true })!;
Narration story = await ReadStoryAsync(client, s => s.GameId == gameId, static s => s.Held >= 2).ConfigureAwait(false);
story.Started.Should().NotBeNull("a held session is announced while it runs, not only when it ends");
story.Started!.Tier.Should().Be(2);
story.Started.Pid.Should().Be(0, "a hooking-off hold never opens the process");
story.Started.Hold.Should().NotBeNull();
story.Started.Hold!.Reason.Should().Be(nameof(Application.Capture.SessionEndReason.RefusedHookNotEnabled));
story.Held.Should().BeGreaterThanOrEqualTo(2);
story.Progress.Should().BeEmpty("nothing is measured, so nothing measured-looking goes on the wire");
StatusAck status = await client.GetStatusAsync(_ack, Ct).ConfigureAwait(false);
status.State.Should().Be("recording");
status.ActiveSessions.Should().ContainSingle().Which.Hold.Should().Be(story.Started.Hold, "an App that connects now learns why from the status");
harness.Kill(entireProcessTree: true);
Guid guid = story.Started.SessionGuid;
Narration ended = await ReadStoryAsync(client, s => s.SessionGuid == guid, static s => s.Completed is not null, guid).ConfigureAwait(false);
ended.Completed.Should().NotBeNull("the hold ends with the game");
ended.Completed!.Tier.Should().Be(2);
ended.Completed.GameId.Should().Be(gameId);
ended.Completed.GameName.Should().Be("Held harness");
server.RejectedClients.Should().Be(0);
}
finally
{
await TearDownAsync(client, harness, stop).ConfigureAwait(false);
await JoinAsync(serving, watching).ConfigureAwait(false);
}
}
/// <summary>The serve loop and the pipe end with the token; both tasks are locals of the caller, joined here.</summary>
private static async Task JoinAsync(Task serving, Task watching)
{
@@ -396,6 +471,9 @@ public sealed class PipeEndToEndTests : IDisposable
public List<TimeSpan> ProgressSpacing { get; } = [];
/// <summary>The <c>SessionHeld</c> ticks a session held unhooked sent (2026-09-23).</summary>
public int Held { get; set; }
public SessionCompletedEvent? Completed { get; set; }
}
@@ -441,6 +519,13 @@ public sealed class PipeEndToEndTests : IDisposable
}
lastProgress = clock.Elapsed;
break;
case IpcMessageType.SessionHeld when ours is { } g:
if (IpcCodec.Payload<SessionHeldEvent>(e)!.SessionGuid == g)
{
story.Held++;
}
break;
case IpcMessageType.SessionCompleted when ours is { } g:
SessionCompletedEvent completed = IpcCodec.Payload<SessionCompletedEvent>(e)!;
@@ -156,4 +156,71 @@ public sealed class DashboardViewModelTests
vm.Live.IsActive.Should().BeFalse();
vm.Recent.Should().ContainSingle();
}
/// <summary>
/// A session already running is on the card when the Dashboard is built (2026-09-23) — it is rebuilt on every visit —
/// and a held one says why; its completion names its own game.
/// </summary>
[Fact]
public async Task ARunningHeldSessionIsOnTheCardAtOnceAndItsCompletionNamesIt()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Alpha");
var guid = Guid.NewGuid();
var link = new FakeLink
{
Status = new StatusAck("recording", null, null, [new ActiveSession(guid, game.Id, "Alpha", 42, 2, DateTimeOffset.UtcNow, new SessionHold("RefusedHookNotEnabled"))]),
};
using var sessions = new LiveSessions(link);
var strip = new RecordingStrip();
using var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), strip, sessions: sessions);
Task loaded = vm.Pending;
await loaded;
vm.Live.IsActive.Should().BeTrue("until 2026-09-23 this read \"Nothing is being captured.\" for as long as the game ran");
vm.Live.IsHeld.Should().BeTrue();
vm.Live.GameName.Should().Be("Alpha");
vm.RunningSessions.Should().Be("1");
link.Raise(IpcMessageType.SessionHeld, new SessionHeldEvent(guid, 30));
vm.Live.ElapsedText.Should().NotBeEmpty();
long id = await s.SessionAsync(game.Id, DateTimeOffset.UtcNow.AddMinutes(-1), seconds: 30);
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(guid, id, "normal", 2, "saved", "RefusedHookNotEnabled", game.Id, "Alpha"));
Task reloaded = vm.Pending;
await reloaded;
vm.Live.IsActive.Should().BeFalse();
strip.Shown.Should().ContainSingle().Which.Body.Should().Contain("Alpha");
vm.RunningSessions.Should().Be("0");
}
[Fact]
public async Task TheNoticeNamesTheCompletedSessionAndAFaultIsNotANotice()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var link = new FakeLink();
using var sessions = new LiveSessions(link);
var strip = new RecordingStrip();
using var vm = new DashboardViewModel(link, s.Library, new GameSelection(), new FakeNavigator(), new NoSummaries(), strip, sessions: sessions);
Task loaded = vm.Pending;
await loaded;
var hooked = Guid.NewGuid();
var held = Guid.NewGuid();
link.Raise(IpcMessageType.SessionStarted, new SessionStartedEvent(hooked, 1, "Hooked", 1, 1, DateTimeOffset.UtcNow));
link.Raise(IpcMessageType.SessionStarted, new SessionStartedEvent(held, 2, "Held", 2, 2, DateTimeOffset.UtcNow, new SessionHold("RefusedHookNotEnabled")));
vm.Live.GameName.Should().Be("Hooked", "a hooked session keeps the card");
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(held, null, "normal", 2, "discarded", "RefusedHookNotEnabled", 2, "Held"));
Task first = vm.Pending;
await first;
strip.Shown.Should().ContainSingle().Which.Body.Should().Contain("Held", "the completed session's own name, not the card's");
vm.Live.GameName.Should().Be("Hooked");
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(hooked, null, "interrupted", 1, "faulted", "SessionFaulted", 1, "Hooked"));
Task second = vm.Pending;
await second;
strip.Shown.Should().ContainSingle("a faulted session is the strip's CaptureError already; \"discarded\" would say what did not happen");
vm.Live.IsActive.Should().BeFalse();
}
}
@@ -0,0 +1,86 @@
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Tests;
/// <summary>
/// The live card's two kinds of session (2026-09-23): a hooked one reads its readout; one held without measuring reads its
/// name, its tier, its elapsed time and why — never a readout — and a hooked session takes the card from it, never the
/// reverse. In the culture collection because it compares against the resources it reads.
/// </summary>
[Collection(StringsCultureCollection.Name)]
public sealed class LiveCaptureViewModelTests
{
private static SessionStartedEvent Started(Guid guid, int tier, string name, SessionHold? hold = null) => new(guid, 7, name, 42, tier, DateTimeOffset.UnixEpoch, hold);
[Fact]
public void AHeldSessionShowsWhyAndNoReadoutAndItsEndClearsEverything()
{
var card = new LiveCaptureViewModel();
var guid = Guid.NewGuid();
card.Start(Started(guid, 2, "Held", new SessionHold("TargetUnreadable")));
card.IsActive.Should().BeTrue();
card.IsHeld.Should().BeTrue();
card.WaitingForFrames.Should().BeFalse("nothing will ever arrive to wait for");
card.TierText.Should().Be(Strings.Tier_NotHooked);
card.HeldReason.Should().Be(Strings.Summary_Tier2_Why_Unreadable, "the sentence its summary will carry");
card.Readout.Should().BeSameAs(FpsReadoutModel.Unavailable);
card.Hold(new SessionHeldEvent(Guid.NewGuid(), 99, GpuTempC: 80));
card.ElapsedText.Should().BeEmpty("another session's tick");
card.Hold(new SessionHeldEvent(guid, 65, GpuTempC: 61.4, CpuTempC: 55.2));
card.ElapsedText.Should().Contain(Formats.Duration(65));
card.GpuTempText.Should().Contain("61");
card.CpuTempText.Should().Contain("55");
card.Stop(new SessionCompletedEvent(guid, 3, "normal", 2, "saved", "TargetUnreadable"));
card.IsActive.Should().BeFalse();
card.IsHeld.Should().BeFalse();
card.GameName.Should().BeEmpty("until 2026-09-23 the name stayed, and the next notice could name the last game");
card.HeldReason.Should().BeEmpty();
card.ElapsedText.Should().BeEmpty();
card.Tier.Should().Be(0);
}
[Fact]
public void ASessionThatHasNotAttachedYetIsStartingNotHeld()
{
var card = new LiveCaptureViewModel();
var guid = Guid.NewGuid();
card.Seed(new RunningSession(guid, 7, "Starting", 2, DateTimeOffset.UnixEpoch, Hold: null));
card.IsHeld.Should().BeFalse("the status lists a session at tier 2 until its attach; only a hold says nothing is measured");
card.WaitingForFrames.Should().BeFalse("the waiting line says \"Attached\", and it is not yet");
card.HeldReason.Should().BeEmpty();
card.GameName.Should().Be("Starting");
card.Start(Started(guid, 1, "Starting"));
card.Tier.Should().Be(1);
card.TierText.Should().Be(Strings.Tier_Hooked);
card.WaitingForFrames.Should().BeTrue();
}
[Fact]
public void AHookedSessionTakesTheCardFromAHeldOneNeverTheReverse()
{
var card = new LiveCaptureViewModel();
var hooked = Guid.NewGuid();
card.Start(Started(Guid.NewGuid(), 2, "Held", new SessionHold("RefusedHookNotEnabled")));
card.Start(Started(hooked, 1, "Hooked"));
card.SessionGuid.Should().Be(hooked);
card.IsHeld.Should().BeFalse();
card.Start(Started(Guid.NewGuid(), 2, "Another held", new SessionHold("RefusedHookNotEnabled")));
card.Seed(new RunningSession(Guid.NewGuid(), 9, "Another hooked", 1, DateTimeOffset.UnixEpoch, Hold: null));
card.SessionGuid.Should().Be(hooked, "the card keeps a hooked session until it ends");
card.GameName.Should().Be("Hooked");
}
}
@@ -0,0 +1,46 @@
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Tests;
/// <summary>
/// The App's one list of running sessions (2026-09-23): the Agent's status on every (re)connect, then the start and
/// completion events; nothing while the Agent is away.
/// </summary>
public sealed class LiveSessionsTests
{
private static ActiveSession Active(Guid guid, int tier, string name, SessionHold? hold = null) => new(guid, 7, name, 42, tier, DateTimeOffset.UnixEpoch, hold);
[Fact]
public void TheStatusSeedsItTheEventsMoveItAndALostAgentEmptiesIt()
{
var held = Guid.NewGuid();
var link = new FakeAgentLink { Status = new StatusAck("recording", null, null, [Active(held, 2, "Held", new SessionHold("TargetUnreadable"))]) };
using var sessions = new LiveSessions(link);
int changes = 0;
sessions.Changed += (_, _) => changes++;
sessions.Current.Should().ContainSingle()
.Which.Should().Be(new RunningSession(held, 7, "Held", 2, DateTimeOffset.UnixEpoch, new SessionHold("TargetUnreadable")), "a session that began before the App is there from the start");
var hooked = Guid.NewGuid();
link.Raise(IpcMessageType.SessionStarted, new SessionStartedEvent(hooked, 8, "Hooked", 43, 1, DateTimeOffset.UnixEpoch.AddSeconds(5)));
sessions.Current.Select(static s => s.GameName).Should().Equal("Held", "Hooked");
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(held, 3, "normal", 2, "saved", "TargetUnreadable"));
sessions.Current.Should().ContainSingle().Which.SessionGuid.Should().Be(hooked);
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(Guid.NewGuid(), 4, "normal", 1, "saved", "TargetExited"));
changes.Should().Be(2, "a completion for a session not in the list changes nothing");
link.State = AgentConnectionState.Offline;
link.RaiseChanged();
sessions.Current.Should().BeEmpty("a session the Agent can no longer report is not shown as running");
link.State = AgentConnectionState.Connected;
link.Status = new StatusAck("capturing", null, 1, [Active(hooked, 1, "Hooked")]);
link.RaiseChanged();
sessions.Current.Should().ContainSingle().Which.Tier.Should().Be(1, "the reconnect's status is the truth");
}
}
@@ -1,6 +1,7 @@
using System.Globalization;
using FluentAssertions;
using FrameLedger.App.Services;
using FrameLedger.Shared.Ipc;
namespace FrameLedger.App.Tests;
@@ -21,5 +22,19 @@ public sealed class Tier2ReasonTests
Formats.Tier2Reason("end=AttachRefused; tier2: attach=BuildIdMismatch")
.Should().Be(string.Format(CultureInfo.CurrentCulture, Strings.Summary_Tier2_Why_Other_Format, "AttachRefused"));
Formats.Tier2Reason(null).Should().BeEmpty();
Formats.Tier2Reason("end=RefusedConsentMissing; tier2: attach=NotEvaluated; guard=ConsentMissing/consent/stale")
.Should().Be(Strings.Summary_Tier2_Why_ConsentChanged, "a store update changes the executable the consent was given for");
}
/// <summary>The live card says what the summary will (2026-09-23): a running session's hold reads through the same sentences as its row's notes.</summary>
[Fact]
public void ARunningHoldReadsLikeTheRowItWillBecome()
{
Formats.Tier2HoldReason(new SessionHold("RefusedHookNotEnabled", "PreviouslyBlocked", "previously blocked", "BlockedModule: Easy Anti-Cheat EasyAntiCheat_EOS.dll"))
.Should().Be(Formats.Tier2Reason("end=RefusedHookNotEnabled; tier2: attach=NotEvaluated; guard=PreviouslyBlocked/previously blocked/BlockedModule: Easy Anti-Cheat EasyAntiCheat_EOS.dll"));
Formats.Tier2HoldReason(new SessionHold("RefusedByGuard", "BlockedDriver", "Riot Vanguard", "vgk.sys"))
.Should().Be(Formats.Tier2Reason("end=RefusedByGuard; tier2: attach=NotEvaluated; guard=BlockedDriver/Riot Vanguard/vgk.sys"));
Formats.Tier2HoldReason(new SessionHold("RefusedHookNotEnabled", "HookNotEnabled", "not enabled", "hooking is off")).Should().Be(Strings.Summary_Tier2_Why_HookOff);
Formats.Tier2HoldReason(new SessionHold("TargetUnreadable")).Should().Be(Strings.Summary_Tier2_Why_Unreadable);
}
}
@@ -203,6 +203,30 @@ public sealed class TrayViewModelTests
shell.Exits.Should().Be(1);
}
/// <summary>
/// A session running when the App (re)connects is in the tray at once (2026-09-23): the tray learned of a session only
/// from its start event, so one that began before the App connected — and every Tier-2 hold, which sent none — left it idle.
/// </summary>
[Fact]
public void ASessionRunningWhenTheAppConnectsIsInTheTrayAndItsCompletionNamesIt()
{
var link = new FakeAgentLink();
using UpdateService updates = Updates(link);
using var vm = new TrayViewModel(link, new FakeShell { IsShown = false }, new FakeSummaries(), new NoNavigation(), updates);
var toasts = new List<TrayToastEventArgs>();
vm.ToastRequested += (_, t) => toasts.Add(t);
var guid = Guid.NewGuid();
link.Status = new StatusAck("recording", null, null, [new ActiveSession(guid, 7, "Held Game", 42, 2, DateTimeOffset.UtcNow, new SessionHold("RefusedHookNotEnabled"))]);
link.RaiseChanged();
vm.State.Should().Be(TrayState.RecordingOnly);
vm.Tooltip.Should().Contain("Held Game");
link.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(guid, 12, "normal", 2, "saved", "RefusedHookNotEnabled", 7, "Held Game"));
vm.State.Should().Be(TrayState.Idle);
toasts.Should().ContainSingle().Which.Body.Should().Contain("Held Game");
}
[Fact]
public void ADisconnectClearsTheRunningSessions()
{
@@ -130,6 +130,7 @@ public sealed class UpdateServiceTests
{
var h = new Harness();
h.Agent.Status = Status("capturing", 1);
h.Agent.RaiseChanged();
h.Client.Next = Candidate();
await h.Service.CheckSilentlyAsync(Ct);
@@ -146,6 +147,29 @@ public sealed class UpdateServiceTests
h.Service.Stage.Should().Be(UpdateStage.Ready);
}
[Fact]
public async Task ASessionListedAtConnectEndsWithItsCompletionNotAtTheNextReconnect()
{
var h = new Harness();
StatusAck status = Status("capturing", 1);
h.Agent.Status = status;
h.Agent.RaiseChanged();
h.Client.Next = Candidate();
await h.Service.CheckSilentlyAsync(Ct);
h.Service.Stage.Should().Be(UpdateStage.Deferred);
Guid running = status.ActiveSessions[0].SessionGuid;
h.Agent.Raise(IpcMessageType.SessionCompleted, new SessionCompletedEvent(running, 5, "normal", 1, "saved", "exit"));
h.Service.Stage.Should().Be(UpdateStage.Ready, "until 2026-09-23 the connect-time status held this at Deferred until the App reconnected, hours later");
h.Service.IsSessionActive.Should().BeFalse();
h.Agent.State = AgentConnectionState.Offline;
h.Agent.RaiseChanged();
h.Service.IsSessionActive.Should().BeFalse("a lost Agent lists nothing; its sessions come back with the next connect's status");
}
[Fact]
public async Task AStartupFailureIsALogLineNotADialog()
{
@@ -304,6 +328,7 @@ public sealed class UpdateServiceTests
await h.Service.CheckSilentlyAsync(Ct);
h.Service.Stage.Should().Be(UpdateStage.Ready);
h.Agent.Status = Status("capturing", 1);
h.Agent.RaiseChanged();
await h.Service.RestartToUpdateAsync(Ct);
@@ -229,6 +229,9 @@ public sealed class CaptureSessionTests : IAsyncDisposable
{
public int Ticks { get; private set; }
/// <summary>What each tick said the session is held under (2026-09-23: the pipe announces a hold from its first tick).</summary>
public List<CaptureOutcome?> Holds { get; } = [];
public void Attached(int pid, FlShmHandshake handshake)
{
}
@@ -236,6 +239,7 @@ public sealed class CaptureSessionTests : IAsyncDisposable
public void Tick(CaptureProgress progress)
{
Ticks++;
Holds.Add(progress.Hold);
progress.Records.Should().BeEmpty("a held session has no ring to drain");
}
}
@@ -938,6 +942,13 @@ public sealed class CaptureSessionTests : IAsyncDisposable
resolver.ResolveCalls.Should().Be(0, "a hooking-off row is never resolved, so its process is never opened");
guard.InjectCalls.Should().Be(0);
ticks.Ticks.Should().BeGreaterThanOrEqualTo(3, "duration and telemetry accrue on the hold's ticks");
ticks.Holds.Should().AllSatisfy(static h =>
{
h.Should().NotBeNull("every held tick says why, so the pipe can say it while the game runs");
h!.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled);
h.Verdict.Reason.Should().Be(AntiCheatRefusalReason.HookNotEnabled);
h.TargetPid.Should().Be(0);
});
}
[Fact]
@@ -990,6 +1001,12 @@ public sealed class CaptureSessionTests : IAsyncDisposable
r.ExitCode.Should().Be(7, "the game's own end is the session's end, crash and all");
ticks.Ticks.Should().BeGreaterThanOrEqualTo(3);
guard.InjectCalls.Should().Be(1, "the guard was asked once and refused; the hold asks nothing more");
ticks.Holds.Should().AllSatisfy(h =>
{
h!.Reason.Should().Be(SessionEndReason.RefusedByGuard);
h.Verdict.Family.Should().Be("Riot Vanguard");
h.TargetPid.Should().Be(_pid, "the pipe's start names the process the loop holds");
});
}
[Fact]
@@ -93,6 +93,53 @@ public sealed class RecordedSessionEventsTests
done.Tier.Should().Be(2);
}
/// <summary>A held session said its refusal when the hold began (2026-09-23); its end says only that it completed.</summary>
[Fact]
public void AReasonAlreadySaidIsNotSaidAgainAtTheEnd()
{
var pipe = new RecordingPublisher();
RecordedSession session = Session(SessionEndReason.RefusedByGuard, ExitStatus.Normal, new FinalizeOutcome(FinalizeStatus.Saved, 3, 0),
verdict: AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedModule, "eac", "EasyAntiCheat.dll"), tier: CaptureTier.NotHooked);
RecordedSessionEvents.PublishAll(pipe, session, _info, reasonAlreadyPublished: true);
pipe.Published.Select(static p => p.Type).Should().Equal(IpcMessageType.SessionCompleted);
}
/// <summary>
/// The completion names the entry the session was stored under (2026-09-23): the finalizer's owner when it re-keyed a
/// session whose entry was removed, else the one it started under — so the App's notice needs no name of its own.
/// </summary>
[Fact]
public void TheCompletionNamesTheEntryTheSessionWasStoredUnder()
{
var pipe = new RecordingPublisher();
RecordedSessionEvents.PublishAll(pipe, Session(SessionEndReason.TargetExited, ExitStatus.Normal, new FinalizeOutcome(FinalizeStatus.Saved, 1, 0, GameId: 9)), _info);
RecordedSessionEvents.PublishAll(pipe, Session(SessionEndReason.TargetExited, ExitStatus.Normal, new FinalizeOutcome(FinalizeStatus.Discarded, null, 0)), _info);
pipe.Of<SessionCompletedEvent>().Select(static e => e.GameId).Should().Equal(9L, 7L);
pipe.Of<SessionCompletedEvent>().Should().OnlyContain(static e => e.GameName == "Title");
}
[Fact]
public void AHoldCarriesTheGuardsWordsOnlyWhenTheGuardSpoke()
{
RecordedSessionEvents.HoldOf(new CaptureOutcome { Reason = SessionEndReason.RefusedHookNotEnabled, Verdict = AntiCheatVerdict.Allowed() })
.Should().Be(new SessionHold("RefusedHookNotEnabled"));
RecordedSessionEvents.HoldOf(new CaptureOutcome
{
Reason = SessionEndReason.TargetUnreadable,
Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.ProcessUnreadable, "", ""),
}).Should().Be(new SessionHold("TargetUnreadable", "ProcessUnreadable"), "an empty family or signal is no word at all");
RecordedSessionEvents.HoldOf(new CaptureOutcome
{
Reason = SessionEndReason.RefusedByGuard,
Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedModule, "eac", "EasyAntiCheat.dll"),
HookingTurnedOff = true,
}).Should().Be(new SessionHold("RefusedByGuard", "BlockedModule", "eac", "EasyAntiCheat.dll", HookingTurnedOff: true));
}
/// <summary>The finding turned the game's hooking off (2026-09-22): both safety events carry that, so the notice can say it.</summary>
[Fact]
public void WhenTheFindingTurnedHookingOffBothSafetyEventsSaySo()
@@ -152,7 +152,92 @@ public sealed class SessionEventPublisherTests
error.SessionGuid.Should().Be(_info.SessionGuid);
error.Code.Should().Be(CaptureErrorCode.SessionFaulted);
error.Message.Should().Contain("InvalidOperationException").And.Contain("the ledger is locked");
pipe.Of<SessionCompletedEvent>().Should().BeEmpty("nothing was finalized");
// And the session is over for the App (2026-09-23): before this the card and the tray stayed on it.
pipe.Published.Select(static p => p.Type).Should().Equal(IpcMessageType.CaptureError, IpcMessageType.SessionCompleted);
SessionCompletedEvent done = pipe.Of<SessionCompletedEvent>().Single();
done.SessionGuid.Should().Be(_info.SessionGuid);
done.SessionId.Should().BeNull("nothing was finalized; the .partial stays for recovery");
done.Finalize.Should().Be(RecordedSessionEvents.FaultedFinalize);
done.ExitStatus.Should().Be("interrupted");
done.Tier.Should().Be(2, "it never attached");
done.Reason.Should().Be(CaptureErrorCode.SessionFaulted);
done.GameId.Should().Be(7);
done.GameName.Should().Be("Title");
}
/// <summary>
/// A session held unhooked (2026-09-23) used to send nothing until the game exited, so the Dashboard said nothing was
/// being captured and the tray stayed idle. Its first held tick announces it once, at tier 2 with why, says the refusal
/// at once, and every tick after feeds <c>SessionHeld</c> at the interval — never <c>SessionProgress</c>.
/// </summary>
[Fact]
public void AHeldSessionIsAnnouncedOnceAtTierTwoWithWhyAndItsRefusalIsSaidAtOnce()
{
var pipe = new RecordingPublisher();
var clock = new ManualClock();
var publisher = new SessionEventPublisher(pipe, clock);
CaptureOutcome refusal = new()
{
Reason = SessionEndReason.RefusedByGuard,
Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedModule, "eac", "EasyAntiCheat.dll"),
HookingTurnedOff = true,
TargetPid = 4242,
};
publisher.Started(_info);
clock.Advance(TimeSpan.FromSeconds(3));
publisher.Tick(_info.SessionGuid, CaptureProgress.Held(refusal), SessionFixtures.Sensors(seconds: 1, temp: 60));
pipe.Published.Select(static p => p.Type).Should().Equal(IpcMessageType.SessionStarted, IpcMessageType.CaptureRefused, IpcMessageType.SessionHeld);
SessionStartedEvent started = pipe.Of<SessionStartedEvent>().Single();
started.Tier.Should().Be(2);
started.Pid.Should().Be(4242);
started.StartedAt.Should().Be(_info.StartedAt, "a held session started when the recorder did, not at an attach");
started.Hold.Should().Be(new SessionHold("RefusedByGuard", "BlockedModule", "eac", "EasyAntiCheat.dll", HookingTurnedOff: true));
pipe.Of<CaptureRefusedEvent>().Single().HookingTurnedOff.Should().BeTrue();
SessionHeldEvent held = pipe.Of<SessionHeldEvent>().Single();
held.ElapsedS.Should().BeApproximately(3, 0.001);
held.GpuTempC.Should().Be(60);
StatusAck ack = publisher.Status.ToAck();
ack.State.Should().Be(AgentStatus.RecordingState);
ActiveSession active = ack.ActiveSessions.Should().ContainSingle().Subject;
active.Tier.Should().Be(2);
active.Pid.Should().Be(4242);
active.Hold.Should().Be(started.Hold, "an App that connects mid-session learns why from the status");
clock.Advance(TimeSpan.FromMilliseconds(400));
publisher.Tick(_info.SessionGuid, CaptureProgress.Held(refusal), []);
clock.Advance(TimeSpan.FromMilliseconds(700));
publisher.Tick(_info.SessionGuid, CaptureProgress.Held(refusal), []);
pipe.Of<SessionStartedEvent>().Should().ContainSingle("announced once: no flicker between tiers");
pipe.Of<CaptureRefusedEvent>().Should().ContainSingle();
pipe.Of<SessionHeldEvent>().Should().HaveCount(2, "one per interval");
pipe.Of<SessionProgressEvent>().Should().BeEmpty("a held session has nothing measured to put on the wire");
publisher.ProgressPublished.Should().Be(0);
publisher.Ended(Recorded(_info.SessionGuid) with { Outcome = refusal });
pipe.Of<CaptureRefusedEvent>().Should().ContainSingle("said when the hold began, not again at the exit");
pipe.Published[^1].Type.Should().Be(IpcMessageType.SessionCompleted);
publisher.Status.State.Should().Be(AgentStatus.IdleState);
}
[Fact]
public void AHeldSessionWithNoClientIsStillInTheStatusAndSendsNoHeldTick()
{
var pipe = new RecordingPublisher { HasClients = false };
var publisher = new SessionEventPublisher(pipe, new ManualClock());
CaptureOutcome off = new() { Reason = SessionEndReason.RefusedHookNotEnabled, Verdict = AntiCheatVerdict.Allowed(), TargetPid = 77 };
publisher.Started(_info);
publisher.Tick(_info.SessionGuid, CaptureProgress.Held(off), []);
pipe.Of<SessionHeldEvent>().Should().BeEmpty();
pipe.Of<SessionStartedEvent>().Single().Hold.Should().Be(new SessionHold("RefusedHookNotEnabled"), "the guard said nothing, so only the loop's reason");
publisher.Status.ToAck().ActiveSessions.Single().Hold!.Reason.Should().Be("RefusedHookNotEnabled");
}
[Fact]
@@ -107,4 +107,36 @@ public sealed class IpcCodecTests
json.Should().NotContain("nativeFps5s").And.NotContain("upscaler").And.NotContain("gpuTempC")
.And.Contain("\"presentedQualifier\":\"census_not_run\"").And.Contain("\"fgMode\":\"na\"");
}
/// <summary>
/// The held session's fields (2026-09-23) are additive, so the protocol stays 2: a held session's tick carries no
/// measured field at all, its <c>hold</c> rides only on a Tier-2 start, and a beta.5 payload without either still reads.
/// </summary>
[Fact]
public void TheHeldSessionsFieldsAreAdditiveAndCarryNothingMeasured()
{
var guid = Guid.NewGuid();
string held = Encoding.UTF8.GetString(IpcCodec.Encode(IpcMessageType.SessionHeld, null, new SessionHeldEvent(guid, 12.5, GpuTempC: 61)));
held.Should().Contain("\"elapsedS\":12.5").And.Contain("\"gpuTempC\":61")
.And.NotContain("cpuTempC").And.NotContain("fps", "a held session has nothing measured");
var started = new SessionStartedEvent(guid, 3, "Title", 42, 2, DateTimeOffset.UnixEpoch, new SessionHold("RefusedByGuard", "BlockedModule", "eac", "EasyAntiCheat.dll", HookingTurnedOff: true));
IpcCodec.Payload<SessionStartedEvent>(IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.SessionStarted, null, started))).Should().Be(started);
string hooked = Encoding.UTF8.GetString(IpcCodec.Encode(IpcMessageType.SessionStarted, null, started with { Tier = 1, Hold = null }));
hooked.Should().NotContain("hold", "a hooked session has no hold and says nothing about one");
const string beta5Start = "{\"type\":\"SessionStarted\",\"payload\":{\"sessionGuid\":\"6ae6087f-0000-0000-0000-000000000000\",\"gameId\":3,"
+ "\"gameName\":\"Title\",\"pid\":42,\"tier\":1,\"startedAt\":\"2026-09-22T00:00:00+00:00\"}}";
IpcCodec.Payload<SessionStartedEvent>(IpcCodec.Decode(Encoding.UTF8.GetBytes(beta5Start)))!.Hold.Should().BeNull();
const string beta5Done = "{\"type\":\"SessionCompleted\",\"payload\":{\"sessionGuid\":\"6ae6087f-0000-0000-0000-000000000000\",\"sessionId\":5,"
+ "\"exitStatus\":\"normal\",\"tier\":1,\"finalize\":\"saved\",\"reason\":\"TargetExited\"}}";
SessionCompletedEvent done = IpcCodec.Payload<SessionCompletedEvent>(IpcCodec.Decode(Encoding.UTF8.GetBytes(beta5Done)))!;
done.GameId.Should().BeNull();
done.GameName.Should().BeNull();
var status = new StatusAck("recording", null, null, [new ActiveSession(guid, 3, "Title", 42, 2, DateTimeOffset.UnixEpoch, new SessionHold("RefusedHookNotEnabled"))]);
IpcCodec.Payload<StatusAck>(IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.StatusAck, "1", status)))!.ActiveSessions.Single().Hold
.Should().Be(new SessionHold("RefusedHookNotEnabled"));
}
}