streamdeck: add the plugin, its installer and packaging
The plugin is a NativeAOT executable that speaks the Stream Deck SDK v2 WebSocket protocol itself, reads snapshot.json and draws each key as SVG (D10). The installer finds Elgato Stream Deck or OpenDeck, stages the shipped plugin beside the installed one, stops a running host, swaps and rolls back on failure (D11). tools/publish.py publishes the app, CLI and plugin for win-x64 or linux-x64 into one folder. Refs #1
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
using FinalToken.Core.StreamDeck;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Core.Tests.StreamDeck;
|
||||
|
||||
public sealed class InstallerTests : IDisposable
|
||||
{
|
||||
private readonly string root = Path.Combine(Path.GetTempPath(), "finaltoken-installer-" + Guid.NewGuid().ToString("N"));
|
||||
private string Shipped => Path.Combine(root, "shipped");
|
||||
private string Plugins => Path.Combine(root, "plugins");
|
||||
private string Installed => Path.Combine(Plugins, PluginInstaller.FolderName);
|
||||
public InstallerTests() => Write(Shipped, "1.0.0.0", "new");
|
||||
[Fact]
|
||||
public async Task FreshInstallDoesNotStartStoppedHost()
|
||||
{
|
||||
var process = new FakeProcesses();
|
||||
var installer = Create(process);
|
||||
Assert.Equal(PluginInstallState.NotInstalled, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal("new", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||
Assert.Equal(PluginInstallState.UpToDate, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||
Assert.Equal(0, process.Stops); Assert.Equal(0, process.Starts);
|
||||
}
|
||||
[Fact]
|
||||
public async Task UpdateStopsAndRestartsRunningHost()
|
||||
{
|
||||
Write(Installed, "0.9.0.0", "old");
|
||||
var process = new FakeProcesses { Running = true };
|
||||
var installer = Create(process);
|
||||
var outcomes = new List<InstallOutcome>(); installer.Outcome += outcomes.Add;
|
||||
Assert.Equal(PluginInstallState.Outdated, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal("new", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||
Assert.Equal(1, process.Stops); Assert.Equal(1, process.Starts);
|
||||
Assert.Contains(InstallOutcome.Updated, outcomes);
|
||||
Assert.Single(Directory.GetDirectories(Plugins));
|
||||
}
|
||||
[Fact]
|
||||
public async Task CurrentAndNewerVersionsAreNotReplaced()
|
||||
{
|
||||
Write(Installed, "2.0.0.0", "newer");
|
||||
var process = new FakeProcesses { Running = true };
|
||||
await Create(process).InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal("newer", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||
Assert.Equal(0, process.Stops);
|
||||
}
|
||||
[Fact]
|
||||
public async Task RestartFailureRollsBackAndRestartsOldPlugin()
|
||||
{
|
||||
Write(Installed, "0.9.0.0", "old");
|
||||
var process = new FakeProcesses { Running = true, FailFirstStart = true };
|
||||
var installer = Create(process);
|
||||
var outcomes = new List<InstallOutcome>(); installer.Outcome += outcomes.Add;
|
||||
await Assert.ThrowsAsync<IOException>(() => installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Equal("old", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||
Assert.Equal(2, process.Starts);
|
||||
Assert.Contains(InstallOutcome.RolledBack, outcomes);
|
||||
Assert.Single(Directory.GetDirectories(Plugins));
|
||||
}
|
||||
[Fact]
|
||||
public async Task NoHostAndMissingShippedPluginHaveExplicitStatus()
|
||||
{
|
||||
var installer = new PluginInstaller(Shipped, null);
|
||||
Assert.Equal(PluginInstallState.NoHostFound, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||
var missing = new PluginInstaller(Path.Combine(root, "missing"), new(Plugins, "fake", "fake"));
|
||||
Assert.Equal(PluginInstallState.NoShippedPlugin, (await missing.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => missing.InstallOrUpdateAsync(TestContext.Current.CancellationToken));
|
||||
}
|
||||
[Fact]
|
||||
public async Task StopFailureKeepsOldFolderAndAttemptsRestart()
|
||||
{
|
||||
Write(Installed, "0.9.0.0", "old");
|
||||
var process = new FakeProcesses { Running = true, FailStop = true };
|
||||
await Assert.ThrowsAsync<IOException>(() => Create(process).InstallOrUpdateAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Equal("old", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||
Assert.Equal(1, process.Starts);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(InstallMode.Off, InstallAction.Nothing)]
|
||||
[InlineData(InstallMode.Ask, InstallAction.Ask)]
|
||||
[InlineData(InstallMode.Automatic, InstallAction.Install)]
|
||||
public void PolicyHonorsInstallMode(InstallMode mode, InstallAction expected) =>
|
||||
Assert.Equal(expected, InstallPolicy.Decide(mode, new(PluginInstallState.NotInstalled, "1"), null));
|
||||
[Fact]
|
||||
public void PolicyHonorsDismissedVersionAndUnavailableHost()
|
||||
{
|
||||
Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Ask, new(PluginInstallState.Outdated, "1"), "1"));
|
||||
Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Automatic, new(PluginInstallState.NoHostFound), null));
|
||||
}
|
||||
private PluginInstaller Create(FakeProcesses process) => new(Shipped, new(Plugins, "fake", "fake"), process);
|
||||
private static void Write(string directory, string version, string binary)
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
File.WriteAllText(Path.Combine(directory, "manifest.json"), "{\"Version\":\"" + version + "\"}");
|
||||
File.WriteAllText(Path.Combine(directory, "binary"), binary);
|
||||
}
|
||||
public void Dispose() { if (Directory.Exists(root)) Directory.Delete(root, true); }
|
||||
private sealed class FakeProcesses : IHostProcesses
|
||||
{
|
||||
public bool Running { get; init; }
|
||||
public bool FailFirstStart { get; init; }
|
||||
public bool FailStop { get; init; }
|
||||
public int Stops { get; private set; }
|
||||
public int Starts { get; private set; }
|
||||
public Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct) => Task.FromResult(Running);
|
||||
public Task StopAsync(PluginHost host, CancellationToken ct) { Stops++; if (FailStop) throw new IOException("stop failed"); return Task.CompletedTask; }
|
||||
public Task StartAsync(PluginHost host, CancellationToken ct) { Starts++; if (FailFirstStart && Starts == 1) throw new IOException("start failed"); return Task.CompletedTask; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# StreamDeck tests
|
||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
|
||||
Placeholder test; owning worker replaces it.
|
||||
Use fake sockets and synthetic snapshots for protocol, settings and key rendering checks.
|
||||
Manifest tests read the copied plugin assets. Never require a running Stream Deck host.
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
using Xunit;
|
||||
namespace FinalToken.StreamDeck.Tests;
|
||||
public class PlaceholderTests { [Fact] public void FoundationBuilds() => Assert.True(true); }
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Text.Json;
|
||||
using System.Xml.Linq;
|
||||
using FinalToken.Core;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.StreamDeck.Tests;
|
||||
|
||||
public sealed class PluginTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||
private static Snapshot Snapshot(PaceState state = PaceState.Ahead) => new()
|
||||
{
|
||||
MadeAt = Now, RefreshInterval = TimeSpan.FromMinutes(1), AppPath = "app.exe",
|
||||
Providers = [new(Provider.Claude, ProviderStatus.Available, null,
|
||||
[new(new(Provider.Claude, "session", "Session", 65, Now.AddHours(2), TimeSpan.FromHours(5), Now, "test"), new(state, .6, 5)),
|
||||
new(new(Provider.Claude, "week", "Week", 42, Now.AddDays(2), TimeSpan.FromDays(7), Now, "test"), new(state, .5, -8))],
|
||||
new(Total: 12345), null, new(Total: 2345678))]
|
||||
};
|
||||
[Fact]
|
||||
public async Task RegistersAndSettingsRoundTripWithDeduplicatedDrawing()
|
||||
{
|
||||
var socket = new FakeSocket();
|
||||
var session = new PluginSession(socket, _ => Task.FromResult(true));
|
||||
await session.RegisterAsync(new(1234, "registration-id", "registerPlugin"), TestContext.Current.CancellationToken);
|
||||
Assert.Equal("registerPlugin", Read(socket.Sent[0], "event"));
|
||||
Assert.Equal("registration-id", Read(socket.Sent[0], "uuid"));
|
||||
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
|
||||
await session.HandleAsync("""{"event":"willAppear","action":"de.finalfactory.finaltoken.stat","context":"key","payload":{"settings":{}}}""", Now, TestContext.Current.CancellationToken);
|
||||
var count = socket.Sent.Count;
|
||||
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(count, socket.Sent.Count);
|
||||
await session.HandleAsync("""{"event":"sendToPlugin","context":"key","payload":{"settings":{"provider":"Claude","metric":"TokensWeek","window":"week"}}}""", Now, TestContext.Current.CancellationToken);
|
||||
using var settings = JsonDocument.Parse(socket.Sent.Single(s => Read(s, "event") == "setSettings"));
|
||||
Assert.Equal("TokensWeek", settings.RootElement.GetProperty("payload").GetProperty("metric").GetString());
|
||||
Assert.Equal("sendToPropertyInspector", Read(socket.Sent[^1], "event"));
|
||||
await session.HandleAsync("""{"event":"willDisappear","context":"key"}""", Now, TestContext.Current.CancellationToken);
|
||||
count = socket.Sent.Count;
|
||||
await session.UpdateAsync(new(null, true, null), Now, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(count, socket.Sent.Count);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task KeyPressLaunchesSnapshotAppAndAlertsFailure(bool success)
|
||||
{
|
||||
string? path = null;
|
||||
var socket = new FakeSocket();
|
||||
var session = new PluginSession(socket, value => { path = value; return Task.FromResult(success); });
|
||||
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
|
||||
await session.HandleAsync("""{"event":"keyDown","context":"key"}""", Now, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("app.exe", path);
|
||||
Assert.Equal(success ? 0 : 1, socket.Sent.Count);
|
||||
if (!success) Assert.Equal("showAlert", Read(socket.Sent[0], "event"));
|
||||
}
|
||||
[Theory]
|
||||
[InlineData("SessionPercent", "65%")]
|
||||
[InlineData("WeekPercent", "42%")]
|
||||
[InlineData("PaceDelta", "+5pp")]
|
||||
[InlineData("TimeToReset", "2h 0m")]
|
||||
[InlineData("TokensToday", "12.3k")]
|
||||
[InlineData("TokensWeek", "2.3M")]
|
||||
public void RendersEveryMetric(string metric, string value)
|
||||
{
|
||||
var svg = StatRenderer.Render(new(Snapshot(), false, null), new(Metric: metric), Now);
|
||||
Assert.Contains(value, svg);
|
||||
Assert.Equal("svg", XDocument.Parse(svg).Root!.Name.LocalName);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(PaceState.Ahead, "#ef6461")]
|
||||
[InlineData(PaceState.Behind, "#69a7ff")]
|
||||
[InlineData(PaceState.OnTrack, "#58d6a0")]
|
||||
[InlineData(PaceState.Unknown, "#a0a7b4")]
|
||||
public void RendersPaceColorAndMarker(PaceState state, string color)
|
||||
{
|
||||
var svg = StatRenderer.Render(new(Snapshot(state), false, null), new(), Now);
|
||||
Assert.Contains(color, svg);
|
||||
Assert.Contains("M42 56v11", svg);
|
||||
}
|
||||
[Fact]
|
||||
public void StaleMissingAndUnknownWindowAreExplicit()
|
||||
{
|
||||
Assert.Contains("offline", StatRenderer.Render(new(Snapshot(), true, null), new(), Now));
|
||||
Assert.Contains("offline", StatRenderer.Render(new(null, true, null), new(), Now));
|
||||
Assert.Contains("—", StatRenderer.Render(new(Snapshot(), false, null), new(Window: "removed"), Now));
|
||||
}
|
||||
[Fact]
|
||||
public void NullNestedSnapshotContentShowsOffline()
|
||||
{
|
||||
var snapshot = Snapshot() with { Providers = [new(Provider.Claude, ProviderStatus.Available, null, null!, new(), null, new())] };
|
||||
Assert.Contains("offline", StatRenderer.Render(new(snapshot, false, null), new(), Now));
|
||||
}
|
||||
[Fact]
|
||||
public void PaceAndResetUseAvailableWeekWhenNoSessionExists()
|
||||
{
|
||||
var provider = Snapshot().Providers[0];
|
||||
provider = provider with { Windows = [provider.Windows[1]] };
|
||||
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "PaceDelta"))?.Window.Id);
|
||||
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "TimeToReset"))?.Window.Id);
|
||||
Assert.Null(StatRenderer.SelectWindow(provider, new()));
|
||||
}
|
||||
[Fact]
|
||||
public async Task MalformedAndInvalidSettingsDoNotChangeKeys()
|
||||
{
|
||||
var socket = new FakeSocket();
|
||||
var session = new PluginSession(socket, _ => Task.FromResult(false));
|
||||
foreach (var json in new[] { "{", "[]", "null", """{"event":"willAppear","context":"key","payload":{"settings":{"provider":"Unknown"}}}""" })
|
||||
await session.HandleAsync(json, Now, TestContext.Current.CancellationToken);
|
||||
Assert.Empty(socket.Sent);
|
||||
}
|
||||
[Fact]
|
||||
public void RegistrationValidatesArguments()
|
||||
{
|
||||
Assert.NotNull(Registration.Parse(["-port", "1234", "-pluginUUID", "x", "-registerEvent", "registerPlugin", "-info", "{}"]));
|
||||
Assert.Null(Registration.Parse(["-port", "0"]));
|
||||
}
|
||||
[Fact]
|
||||
public void ManifestHasExpectedContractAndLocalAssets()
|
||||
{
|
||||
var folder = Path.Combine(AppContext.BaseDirectory, "plugin");
|
||||
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(folder, "manifest.json")));
|
||||
var root = manifest.RootElement;
|
||||
Assert.Equal(2, root.GetProperty("SDKVersion").GetInt32());
|
||||
Assert.Equal("de.finalfactory.finaltoken", root.GetProperty("UUID").GetString());
|
||||
Assert.Equal("FinalToken.StreamDeck.exe", root.GetProperty("CodePathWin").GetString());
|
||||
Assert.Equal("FinalToken.StreamDeck", root.GetProperty("CodePathLin").GetString());
|
||||
Assert.True(Version.TryParse(root.GetProperty("Version").GetString(), out _));
|
||||
Assert.Single(root.GetProperty("Actions").EnumerateArray());
|
||||
Assert.Equal(PluginSession.Action, root.GetProperty("Actions")[0].GetProperty("UUID").GetString());
|
||||
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("PropertyInspectorPath").GetString()!)));
|
||||
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("Icon").GetString()! + ".svg")));
|
||||
}
|
||||
private static string? Read(string json, string property)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
return doc.RootElement.GetProperty(property).GetString();
|
||||
}
|
||||
private sealed class FakeSocket : IPluginSocket
|
||||
{
|
||||
public List<string> Sent { get; } = [];
|
||||
public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; }
|
||||
public Task<string?> ReceiveAsync(CancellationToken cancellationToken) => Task.FromResult<string?>(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user