* feat: an alpha says what it is and asks first - the Alpha notice with its own tick box, the alpha Agent's wait, ALPHA badge and banner, the ledger copy before an alpha opens it; EULA 1.6, Disclaimer 2.12 (D73-D75) (beta.32 PR-2) The owner's decisions of 2026-10-31, asked while planning: the alpha replaces the beta and shares its data folder, copying the ledger before it first opens it (D73); a versioned Alpha notice with its own tick box in the Legal Gate, the alpha's Agent waiting for it, a badge and a banner (D74); the EULA and the Disclaimer made true about alphas (D75). Nothing of it shows in a beta. - legal/ALPHA_NOTICE.md 1.0 (the approved text), embedded; Shared.AlphaNotice holds its key and version for both processes. LegalDocuments.Load(BuildLine) adds it after the four on the alpha line; About lists it on every line, for information. - First run: on an alpha's gate a second warning box with the tick box; Accept is disabled until it is ticked. While the notice is outstanding the App holds the Agent's start - a hold of its own beside the updater's, set before the host starts (the connection's first round runs under the first-run window) - and Accept releases it and starts the Agent at once. - Agent: an alpha's --serve reads legal_acceptance after opening the ledger and exits 8 until the notice is accepted at this build's version (the logon task can start it first); maintenance verbs are not held. Its log names the release line and the runtime. - The shell: ALPHA badge beside the Agent pill (tooltip: the runtime), window title "FrameLedger Alpha", a Warning InfoBar at every start, closable for the run, opening the notice. About and --diag name the runtime; Settings locks the update channel on an alpha and says why. - The ledger: LedgerDatabase.OpenAsync(backupFirst:) - an alpha copies the ledger with SQLite's online backup into backups\ledger-before-<version>.db before anything opens it for writing, once per version, under a lock of its own (the migration lock's 30 s would time a slow copy out); the newest three are kept and the copy just made is never pruned; a copy that cannot be made refuses the open (App: start-failure dialog; Agent: exit 7). Never for a viewer. - EULA 1.6 (§2B) and Disclaimer 2.12 (§0): "pre-release builds - betas, and alphas". 12 strings in en/vi/ja (ja marked review). - Docs: 08_UI, 06_DATA_MODEL §Migrations, 01_ARCHITECTURE §Lifecycle and §Data directory, 11_UPDATER, 12_BUILD, LIMITATIONS §Alpha builds, guide/11-alpha-builds.md (+ contents, sidebar, the App's page list), guide/01-install, terms-in-plain-words, wiki/Releasing, CHANGELOG. - Tests: FirstRunViewModel (tick, hold release), LegalDocuments (both lines; the constant equals the document's version), AgentConnection (the notice hold survives the updater's release), SettingsViewModel (locked picker), LedgerBackup (once per version, rows copied, keep three, the copy just made survives a skewed clock, a copy that cannot be made refuses the open, no request copies nothing), AlphaNoticeGate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: the ALPHA badge in the accent appearance, the picker's alpha lock on a container, About's legal list in its test (beta.32 PR-2) The local gate's three reds on the previous commit, each a design test doing its job: - ContrastTests: a badge's literal Appearance may not be a palette one (Danger paints outside the theme dictionaries, 08_UI §Contrast) - the ALPHA badge is Primary, the accent with its own text. - ViewerModeTests: the update-channel picker keeps the viewer switch on the control itself; the alpha line's lock is a Grid around it bound to CanChooseUpdateChannel. - DocumentWindowsTests: About's legal list now names legal/ALPHA_NOTICE.md (on every line, D74). App.Tests 725/725. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: the alpha's start logic out of App.xaml.cs into AlphaStart, tested; the notice window, the exception, the no-op holds (beta.32 PR-2) SonarCloud's quality gate on #346: new-code coverage 69.3 % against 80 %. The uncovered new lines were the App's start helpers, DocumentWindows.ShowAlphaNotice, MainWindowViewModel's alpha properties, LedgerBackupException's constructors and two default interface members. - Services/AlphaStart: BackupFor (the copy only for an alpha over its own folder) and HoldTheAgentForTheNoticeAsync (the hold only while the notice is outstanding), which App.xaml.cs now calls; AlphaStartTests covers both and the viewer's and a window set's no-op members. - DocumentWindowsTests: the alpha banner's button opens the notice in one window and asking again reveals it. LedgerBackupTests: the exception's three constructors. App.Tests 730/730; dotnet format clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: one Changed heading under [Unreleased] after main came in (beta.32 PR-2) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
395 lines
16 KiB
C#
395 lines
16 KiB
C#
// SPDX-License-Identifier: GPL-3.0-only
|
||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||
|
||
using System.IO;
|
||
using FluentAssertions;
|
||
using FrameLedger.App.Services;
|
||
using FrameLedger.Application.Ipc;
|
||
using FrameLedger.Infrastructure.Ipc;
|
||
using FrameLedger.Infrastructure.Startup;
|
||
using FrameLedger.Shared.Ipc;
|
||
|
||
namespace FrameLedger.App.Tests;
|
||
|
||
/// <summary>
|
||
/// <c>07_IPC</c> §Client behavior as a state machine, against a real <see cref="PipeServer"/> in this process on
|
||
/// a test-named pipe: connect rounds, starting the Agent when it is absent, <c>Hello</c> on connect, offline
|
||
/// when the server goes, and connected again when it returns. The launcher is a fake that can start the server.
|
||
/// </summary>
|
||
public sealed class AgentConnectionTests : IAsyncDisposable
|
||
{
|
||
private static readonly TimeSpan _wait = TimeSpan.FromSeconds(15);
|
||
private static readonly AgentIdentity _identity = new("agent-test", Environment.ProcessId, Elevated: false, "build-x", VulkanLayerRegistered: false, CpuTempAvailable: false);
|
||
private static readonly AgentConnectionOptions _fast = new()
|
||
{
|
||
ConnectAttempts = 3,
|
||
ConnectBackoff = TimeSpan.FromMilliseconds(30),
|
||
ConnectTimeout = TimeSpan.FromMilliseconds(300),
|
||
RetryInterval = TimeSpan.FromMilliseconds(200),
|
||
Keepalive = TimeSpan.FromMilliseconds(400),
|
||
RequestTimeout = TimeSpan.FromSeconds(5),
|
||
};
|
||
|
||
private readonly string _pipeName = "FrameLedger.test." + Guid.NewGuid().ToString("N");
|
||
private readonly CancellationTokenSource _stop = new();
|
||
private readonly List<AgentConnectionState> _seen = [];
|
||
private PipeServer? _server;
|
||
private Task? _serving;
|
||
private CancellationTokenSource? _serverStop;
|
||
private AgentConnection? _connection;
|
||
private Task? _running;
|
||
|
||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||
|
||
/// <summary>A launcher that can be told whether an Agent is beside the App, and whose start brings the server up.</summary>
|
||
private sealed class FakeLauncher(Func<bool> start) : IAgentLauncher
|
||
{
|
||
public bool CanLaunch { get; set; }
|
||
|
||
/// <summary>What <see cref="IAgentLauncher.RunningAgent"/> answers: an Agent that is up, whether or not it answers.</summary>
|
||
public string? Running { get; set; }
|
||
|
||
public string? RunningAgent => Running;
|
||
|
||
public int Starts { get; private set; }
|
||
|
||
/// <summary>beta.10: whether the start would show Windows' administrator prompt.</summary>
|
||
public bool Asks { get; set; }
|
||
|
||
public bool WillAskForElevation => Asks;
|
||
|
||
public bool TryStart()
|
||
{
|
||
Starts++;
|
||
return start();
|
||
}
|
||
}
|
||
|
||
public async ValueTask DisposeAsync()
|
||
{
|
||
await _stop.CancelAsync().ConfigureAwait(false);
|
||
if (_running is not null)
|
||
{
|
||
Task running = _running;
|
||
try
|
||
{
|
||
await running.ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
}
|
||
}
|
||
|
||
if (_connection is not null)
|
||
{
|
||
await _connection.DisposeAsync().ConfigureAwait(false);
|
||
}
|
||
|
||
await StopServerAsync().ConfigureAwait(false);
|
||
_stop.Dispose();
|
||
}
|
||
|
||
private void StartServer()
|
||
{
|
||
_serverStop = new CancellationTokenSource();
|
||
_server = new PipeServer(new PipeServerOptions { PipeName = _pipeName },
|
||
new AgentRequestHandler(_identity, static () => "l1", static () => AgentStatus.Idle));
|
||
_serving = _server.RunAsync(_serverStop.Token);
|
||
}
|
||
|
||
private async Task StopServerAsync()
|
||
{
|
||
if (_serverStop is null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
await _serverStop.CancelAsync().ConfigureAwait(false);
|
||
Task? serving = _serving;
|
||
if (serving is not null)
|
||
{
|
||
try
|
||
{
|
||
await serving.ConfigureAwait(false);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
}
|
||
}
|
||
|
||
_server?.Dispose();
|
||
_serverStop.Dispose();
|
||
_serverStop = null;
|
||
_server = null;
|
||
_serving = null;
|
||
}
|
||
|
||
private AgentConnection Start(FakeLauncher launcher, bool holdLaunches = false)
|
||
{
|
||
_connection = new AgentConnection(launcher, () => new PipeClient(_pipeName), _fast, "app-test");
|
||
_connection.SetLaunchHold(holdLaunches);
|
||
_connection.Changed += (s, _) =>
|
||
{
|
||
lock (_seen)
|
||
{
|
||
_seen.Add(((AgentConnection)s!).State);
|
||
}
|
||
};
|
||
_running = _connection.RunAsync(_stop.Token);
|
||
return _connection;
|
||
}
|
||
|
||
private static async Task WaitForAsync(Func<bool> condition, string because)
|
||
{
|
||
DateTimeOffset deadline = DateTimeOffset.UtcNow + _wait;
|
||
while (!condition() && DateTimeOffset.UtcNow < deadline)
|
||
{
|
||
await Task.Delay(25, Ct).ConfigureAwait(false);
|
||
}
|
||
|
||
condition().Should().BeTrue(because);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task WhileLaunchesAreHeldAnAbsentAgentIsNotStartedAndIsStartedOnceReleased()
|
||
{
|
||
// P4 PR-5: the update's apply asks the Agent to stop and must not have this loop start it again under the updater.
|
||
FakeLauncher? launcher = null;
|
||
launcher = new FakeLauncher(() =>
|
||
{
|
||
StartServer();
|
||
return true;
|
||
})
|
||
{ CanLaunch = true };
|
||
AgentConnection c = Start(launcher, holdLaunches: true);
|
||
|
||
await WaitForAsync(() => c.Rounds >= 2, "two rounds found nothing").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(0, "held");
|
||
c.LaunchesHeld.Should().BeTrue();
|
||
lock (_seen)
|
||
{
|
||
_seen.Should().NotContain(AgentConnectionState.Starting, "a held round never says it is starting one");
|
||
_seen.Should().NotContain(AgentConnectionState.Missing, "an Agent could be started, so the pill says Offline, not Missing");
|
||
}
|
||
|
||
c.SetLaunchHold(false);
|
||
c.RetryNow();
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "released: started, then connected").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(1);
|
||
}
|
||
|
||
/// <summary>
|
||
/// D74 (2026-10-31): an alpha's Legal Gate holds the start until its notice is accepted, on a hold of its own — the
|
||
/// updater's release, which runs on its own schedule, must not let an Agent start under an open gate.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task TheNoticeHoldIsItsOwnAndTheUpdatersReleaseDoesNotLiftIt()
|
||
{
|
||
FakeLauncher? launcher = null;
|
||
launcher = new FakeLauncher(() =>
|
||
{
|
||
StartServer();
|
||
return true;
|
||
})
|
||
{ CanLaunch = true };
|
||
AgentConnection c = Start(launcher, holdLaunches: true);
|
||
c.SetNoticeHold(true);
|
||
|
||
c.SetLaunchHold(false);
|
||
c.RetryNow();
|
||
await WaitForAsync(() => c.Rounds >= 2, "rounds ran with the notice still held").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(0, "the gate is still open");
|
||
c.NoticeHeld.Should().BeTrue();
|
||
c.LaunchesHeld.Should().BeFalse();
|
||
|
||
c.SetNoticeHold(false);
|
||
c.RetryNow();
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "accepted: started, then connected").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(1);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task WithNoAgentBesideTheAppTheStateIsMissingAndNothingIsStarted()
|
||
{
|
||
var launcher = new FakeLauncher(static () => false) { CanLaunch = false };
|
||
AgentConnection c = Start(launcher);
|
||
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Missing, "three attempts × 30 ms, nothing to start").ConfigureAwait(true);
|
||
await WaitForAsync(() => c.Rounds >= 2, "rounds continue in case an Agent appears").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(0);
|
||
c.Hello.Should().BeNull();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task ARunningAgentIsFoundHelloedAndReportedConnected()
|
||
{
|
||
StartServer();
|
||
var launcher = new FakeLauncher(static () => false) { CanLaunch = true };
|
||
AgentConnection c = Start(launcher);
|
||
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "the server is up").ConfigureAwait(true);
|
||
c.Hello!.AgentVersion.Should().Be("agent-test");
|
||
c.Status!.State.Should().Be(AgentStatus.IdleState);
|
||
launcher.Starts.Should().Be(0, "an answering Agent is never restarted");
|
||
|
||
// Keepalive: after a few intervals the connection is still connected (a ping that failed would drop it).
|
||
await Task.Delay(_fast.Keepalive * 3, Ct).ConfigureAwait(true);
|
||
c.State.Should().Be(AgentConnectionState.Connected);
|
||
(await c.RefreshStatusAsync(Ct).ConfigureAwait(true)).Should().NotBeNull();
|
||
}
|
||
|
||
[Fact]
|
||
public async Task WhenTheAgentIsAbsentItIsStartedFromBesideTheAppAndThenConnected()
|
||
{
|
||
// The fake launcher's "start" brings the server up, the way FrameLedger.Agent.exe --serve would.
|
||
FakeLauncher? launcher = null;
|
||
launcher = new FakeLauncher(() =>
|
||
{
|
||
StartServer();
|
||
return true;
|
||
})
|
||
{ CanLaunch = true };
|
||
AgentConnection c = Start(launcher);
|
||
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "started, then connected on the second try").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(1);
|
||
c.Launches.Should().Be(1);
|
||
lock (_seen)
|
||
{
|
||
_seen.Should().Contain(AgentConnectionState.Starting, "the pill said so on the way");
|
||
}
|
||
}
|
||
|
||
[Fact]
|
||
public async Task AnAgentThatIsUpButDoesNotAnswerIsReportedAndNeverStartedAgain()
|
||
{
|
||
// 2026-09-17: an elevated App was refused by the pipe of the Agent already serving, took the refusal for an absent
|
||
// Agent, and started one per round; four Agents recorded every session four times. Here nothing answers, the launcher
|
||
// knows an Agent holds the data folder, and a start would bring a server up — so it must never be called.
|
||
FakeLauncher? launcher = null;
|
||
launcher = new FakeLauncher(() =>
|
||
{
|
||
StartServer();
|
||
return true;
|
||
})
|
||
{ CanLaunch = true, Running = "an Agent already holds the test folder" };
|
||
AgentConnection c = Start(launcher);
|
||
|
||
await WaitForAsync(() => c.Rounds >= 3, "three rounds found no pipe").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(0, "one Agent per data folder, however many rounds fail");
|
||
c.Launches.Should().Be(0);
|
||
c.LastConnectFailure.Should().StartWith(nameof(TimeoutException), "why the round failed is kept, not swallowed");
|
||
lock (_seen)
|
||
{
|
||
_seen.Should().NotContain(AgentConnectionState.Starting);
|
||
}
|
||
|
||
launcher.Running = null;
|
||
c.RetryNow();
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "that Agent is gone: this App starts one and connects").ConfigureAwait(true);
|
||
launcher.Starts.Should().Be(1);
|
||
c.LastConnectFailure.Should().BeNull();
|
||
}
|
||
|
||
[Fact]
|
||
public void TheLauncherSeesAnAgentHoldingItsDataFolderWhoeverStartedIt()
|
||
{
|
||
string folder = Path.Combine(Path.GetTempPath(), "fl-launcher-" + Guid.NewGuid().ToString("N"));
|
||
var launcher = new AgentLauncher(folder);
|
||
launcher.RunningAgent.Should().BeNull("nothing holds a folder named for this test, and this launcher started nothing");
|
||
|
||
using (AgentInstanceLock? held = AgentInstanceLock.TryAcquire(folder))
|
||
{
|
||
held.Should().NotBeNull();
|
||
launcher.RunningAgent.Should().Contain(folder, "the logon task's Agent, a console's or another App's — the claim is the same");
|
||
}
|
||
|
||
launcher.RunningAgent.Should().BeNull("the claim went with its handle");
|
||
}
|
||
|
||
/// <summary>
|
||
/// beta.10 (the admin mode): a start that is waiting for Windows' administrator prompt counts as an Agent on its way, so
|
||
/// the App never shows a second prompt beside the logon task's; and the launcher asks only when the option is on and this
|
||
/// App is a standard user's.
|
||
/// </summary>
|
||
[Fact]
|
||
public void TheLauncherSeesAPendingElevationAndAsksOnlyWhenTheOptionIsOn()
|
||
{
|
||
string folder = Path.Combine(Path.GetTempPath(), "fl-launcher-" + Guid.NewGuid().ToString("N"));
|
||
var launcher = new AgentLauncher(folder, runElevated: static () => true);
|
||
using (ElevationMarker? pending = ElevationMarker.TryAcquire(folder))
|
||
{
|
||
pending.Should().NotBeNull();
|
||
launcher.RunningAgent.Should().Contain("administrator");
|
||
}
|
||
|
||
launcher.RunningAgent.Should().BeNull();
|
||
launcher.WillAskForElevation.Should().Be(!Environment.IsPrivilegedProcess, "an elevated App's Agent inherits its rights, and is never prompted for");
|
||
new AgentLauncher(folder).WillAskForElevation.Should().BeFalse("no ledger in the folder: the option reads off");
|
||
}
|
||
|
||
[Fact]
|
||
public async Task ALostAgentIsOfflineAndAReturningOneIsConnectedAgain()
|
||
{
|
||
StartServer();
|
||
var launcher = new FakeLauncher(static () => false) { CanLaunch = true };
|
||
AgentConnection c = Start(launcher);
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "up").ConfigureAwait(true);
|
||
|
||
await StopServerAsync().ConfigureAwait(true);
|
||
await WaitForAsync(() => c.State is AgentConnectionState.Offline or AgentConnectionState.Connecting or AgentConnectionState.Starting, "the pipe dropped").ConfigureAwait(true);
|
||
await WaitForAsync(() => c.Rounds >= 1, "a new round ran").ConfigureAwait(true);
|
||
|
||
StartServer();
|
||
c.RetryNow();
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected && c.Hello is not null, "back").ConfigureAwait(true);
|
||
}
|
||
|
||
/// <summary>beta.10 (the admin mode): a start that asks Windows for administrator rights says so on the pill while it waits.</summary>
|
||
/// <summary>
|
||
/// beta.22: every way the pipe can close under a request reaches a caller as ONE exception, an IOException. PipeClient fails a
|
||
/// request in flight with what ended its reader — an IpcFramingException or an ObjectDisposedException among them — and a
|
||
/// caller that knew only IOException ended in the App's crash dialog (beta.21's review of Play). What is not a closed pipe
|
||
/// passes through as it was, and an answer is the answer.
|
||
/// </summary>
|
||
[Fact]
|
||
public async Task EveryWayThePipeClosesUnderARequestIsOneIOException()
|
||
{
|
||
foreach (Exception closed in new Exception[] { new ObjectDisposedException("pipe"), new IpcFramingException("the frame ended early") })
|
||
{
|
||
Func<Task> request = () => AgentConnection.AnsweredAsync(() => Task.FromException<IpcEnvelope>(closed));
|
||
IOException said = (await request.Should().ThrowAsync<IOException>()).Which;
|
||
said.InnerException.Should().BeSameAs(closed, closed.GetType().Name);
|
||
}
|
||
|
||
Exception[] kept = [new IOException("the pipe closed before the Agent answered"), new TimeoutException(), new IpcRequestException(IpcErrorCode.SessionRunning, "running")];
|
||
foreach (Exception ex in kept)
|
||
{
|
||
Func<Task> request = () => AgentConnection.AnsweredAsync(() => Task.FromException<IpcEnvelope>(ex));
|
||
(await request.Should().ThrowAsync<Exception>()).Which.Should().BeSameAs(ex, ex.GetType().Name);
|
||
}
|
||
|
||
IpcEnvelope answer = IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.DeleteSessionsAck, "1", new DeleteSessionsAck(null, 0, 0)));
|
||
(await AgentConnection.AnsweredAsync(() => Task.FromResult(answer))).Should().BeSameAs(answer);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task AStartThatAsksForAdministratorRightsSaysSoOnThePill()
|
||
{
|
||
FakeLauncher? launcher = null;
|
||
launcher = new FakeLauncher(() =>
|
||
{
|
||
StartServer();
|
||
return true;
|
||
})
|
||
{ CanLaunch = true, Asks = true };
|
||
AgentConnection c = Start(launcher);
|
||
|
||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "started, then connected").ConfigureAwait(true);
|
||
lock (_seen)
|
||
{
|
||
_seen.Should().Contain(AgentConnectionState.Elevating).And.NotContain(AgentConnectionState.Starting);
|
||
}
|
||
}
|
||
}
|