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:
Florian Schmidt
2026-10-14 20:08:11 +02:00
parent c633c2bd3f
commit cd1fd5a306
18 changed files with 915 additions and 7 deletions
+2 -1
View File
@@ -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);
}
}