diff --git a/src/FinalToken.Core/StreamDeck/PluginInstaller.cs b/src/FinalToken.Core/StreamDeck/PluginInstaller.cs new file mode 100644 index 0000000..f9523f0 --- /dev/null +++ b/src/FinalToken.Core/StreamDeck/PluginInstaller.cs @@ -0,0 +1,202 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace FinalToken.Core.StreamDeck; + +public sealed record PluginHost(string PluginDirectory, string Executable, string ProcessName, IReadOnlyList? Arguments = null, bool Flatpak = false); +public interface IHostProcesses +{ + Task IsRunningAsync(PluginHost host, CancellationToken ct); + Task StopAsync(PluginHost host, CancellationToken ct); + Task StartAsync(PluginHost host, CancellationToken ct); +} +public enum InstallOutcome { Installed, Updated, AlreadyCurrent, NoHost, NoShippedPlugin, RolledBack, Failed, HostStopped, HostRestarted, HostRestartFailed } + +/// D11: stage beside the destination, stop only a running host, swap and restore on failure. +public sealed class PluginInstaller(string shippedDirectory, PluginHost? host, IHostProcesses? processes = null) : IPluginInstaller +{ + public const string FolderName = "de.finalfactory.finaltoken.sdPlugin"; + private readonly IHostProcesses processes = processes ?? new HostProcesses(); + private readonly SemaphoreSlim gate = new(1, 1); + public event Action? Outcome; + public static PluginInstaller CreateDefault(string? appDirectory = null) => new( + Path.Combine(appDirectory ?? AppContext.BaseDirectory, "streamdeck", FolderName), HostDiscovery.Find()); + public Task GetStatusAsync(CancellationToken cancellationToken = default) => Task.Run(() => Status(), cancellationToken); + private PluginInstallStatus Status() + { + if (host is null) return new(PluginInstallState.NoHostFound); + var shipped = ReadVersion(shippedDirectory); + if (shipped is null) return new(PluginInstallState.NoShippedPlugin); + var installedPath = Path.Combine(host.PluginDirectory, FolderName); + var installed = ReadVersion(installedPath); + return new(installed is null ? PluginInstallState.NotInstalled : installed >= shipped ? PluginInstallState.UpToDate : PluginInstallState.Outdated, + shipped.ToString(), installed?.ToString()); + } + public async Task InstallOrUpdateAsync(CancellationToken cancellationToken = default) + { + await gate.WaitAsync(cancellationToken); + try { await Task.Run(() => Install(cancellationToken), cancellationToken); } + finally { gate.Release(); } + } + private async Task Install(CancellationToken ct) + { + var status = Status(); + if (status.State == PluginInstallState.NoHostFound) { Report(InstallOutcome.NoHost); return; } + if (status.State == PluginInstallState.NoShippedPlugin) { Report(InstallOutcome.NoShippedPlugin); throw new InvalidOperationException("Shipped plugin is missing or invalid."); } + if (status.State == PluginInstallState.UpToDate) { Report(InstallOutcome.AlreadyCurrent); return; } + var target = Path.Combine(host!.PluginDirectory, FolderName); + var suffix = Guid.NewGuid().ToString("N"); + var staged = target + ".stage-" + suffix; + var backup = target + ".backup-" + suffix; + var movedOld = false; + var movedNew = false; + var restart = false; + try + { + Directory.CreateDirectory(host.PluginDirectory); + Copy(shippedDirectory, staged, ct); + if (ReadVersion(staged)?.ToString() != status.ShippedVersion) throw new IOException("Staged plugin version changed."); + restart = await processes.IsRunningAsync(host, ct); + if (restart) { await processes.StopAsync(host, ct); Report(InstallOutcome.HostStopped); } + ct.ThrowIfCancellationRequested(); + if (Directory.Exists(target)) { Directory.Move(target, backup); movedOld = true; } + Directory.Move(staged, target); movedNew = true; + if (restart) { await processes.StartAsync(host, CancellationToken.None); restart = false; Report(InstallOutcome.HostRestarted); } + Report(movedOld ? InstallOutcome.Updated : InstallOutcome.Installed); + } + catch + { + try + { + if (movedNew) Directory.Delete(target, true); + if (movedOld) Directory.Move(backup, target); + Report(movedOld || movedNew ? InstallOutcome.RolledBack : InstallOutcome.Failed); + } + catch { Report(InstallOutcome.Failed); throw; } + throw; + } + finally + { + if (restart) + { + try { await processes.StartAsync(host, CancellationToken.None); Report(InstallOutcome.HostRestarted); } + catch { Report(InstallOutcome.HostRestartFailed); } + } + DeleteTemporary(staged); + // A backup left by a failed rollback must survive for recovery. + if (Directory.Exists(target) && ReadVersion(target)?.ToString() == status.ShippedVersion) DeleteTemporary(backup); + } + } + private void Report(InstallOutcome outcome) => Outcome?.Invoke(outcome); + private static void DeleteTemporary(string path) + { + try { if (Directory.Exists(path)) Directory.Delete(path, true); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { } + } + private static void Copy(string source, string destination, CancellationToken ct) + { + if ((File.GetAttributes(source) & FileAttributes.ReparsePoint) != 0) throw new IOException("Plugin links are unsupported."); + Directory.CreateDirectory(destination); + foreach (var file in Directory.EnumerateFiles(source)) + { + ct.ThrowIfCancellationRequested(); + if ((File.GetAttributes(file) & FileAttributes.ReparsePoint) != 0) throw new IOException("Plugin links are unsupported."); + var copied = Path.Combine(destination, Path.GetFileName(file)); + File.Copy(file, copied); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(copied, File.GetUnixFileMode(file)); + } + foreach (var directory in Directory.EnumerateDirectories(source)) Copy(directory, Path.Combine(destination, Path.GetFileName(directory)), ct); + } + public static Version? ReadVersion(string directory) + { + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(directory, "manifest.json"))); + return doc.RootElement.TryGetProperty("Version", out var version) && version.ValueKind == JsonValueKind.String && Version.TryParse(version.GetString(), out var parsed) ? parsed : null; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) { return null; } + } +} + +public static class HostDiscovery +{ + public const string FlatpakId = "me.amankhanna.opendeck"; + public static PluginHost? Find() + { + if (OperatingSystem.IsWindows()) + { + var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Elgato", "StreamDeck", "StreamDeck.exe"); + // A running installation can be outside Program Files. + foreach (var process in Process.GetProcessesByName("StreamDeck")) + { + using (process) + { + try { executable = process.MainModule?.FileName ?? executable; } + catch (Exception e) when (e is System.ComponentModel.Win32Exception or InvalidOperationException) { } + } + } + return File.Exists(executable) ? new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Elgato", "StreamDeck", "Plugins"), executable, "StreamDeck") : null; + } + if (!OperatingSystem.IsLinux()) return null; + var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + var config = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(home, ".config"); + var native = FindExecutable("opendeck"); + if (native is not null) return new(Path.Combine(config, "opendeck", "plugins"), native, "opendeck"); + var flatpak = FindExecutable("flatpak"); + var installed = Directory.Exists(Path.Combine(home, ".local", "share", "flatpak", "app", FlatpakId)) || + Directory.Exists(Path.Combine(Path.DirectorySeparatorChar.ToString(), "var", "lib", "flatpak", "app", FlatpakId)); + return flatpak is not null && installed ? new(Path.Combine(home, ".var", "app", FlatpakId, "config", "opendeck", "plugins"), flatpak, "opendeck", ["run", FlatpakId], true) : null; + } + private static string? FindExecutable(string name) => (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator) + .Where(Path.IsPathFullyQualified).Select(p => Path.Combine(p, name)).FirstOrDefault(File.Exists); +} + +public sealed class HostProcesses : IHostProcesses +{ + private static Process[] Matching(PluginHost host) => Process.GetProcessesByName(host.ProcessName); + public Task IsRunningAsync(PluginHost host, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + var processes = Matching(host); + foreach (var process in processes) process.Dispose(); + return Task.FromResult(processes.Length > 0); + } + public async Task StopAsync(PluginHost host, CancellationToken ct) + { + if (host.Flatpak) + { + using var kill = Process.Start(new ProcessStartInfo(host.Executable) { UseShellExecute = false, ArgumentList = { "kill", HostDiscovery.FlatpakId } }) + ?? throw new IOException("Could not stop OpenDeck."); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + try { await kill.WaitForExitAsync(timeout.Token); } + catch { if (!kill.HasExited) kill.Kill(true); throw; } + if (kill.ExitCode != 0) throw new IOException("OpenDeck stop failed."); + } + foreach (var process in Matching(host)) + { + using (process) + { + if (process.HasExited) continue; + process.CloseMainWindow(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(5)); + try { await process.WaitForExitAsync(timeout.Token); } + catch (OperationCanceledException) + { + if (!process.HasExited) process.Kill(true); + await process.WaitForExitAsync(CancellationToken.None); + ct.ThrowIfCancellationRequested(); + } + } + } + } + public Task StartAsync(PluginHost host, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + var start = new ProcessStartInfo(host.Executable) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(host.Executable)! }; + foreach (var argument in host.Arguments ?? []) start.ArgumentList.Add(argument); + using var process = Process.Start(start) ?? throw new IOException("Could not start Stream Deck host."); + return Task.CompletedTask; + } +} diff --git a/src/FinalToken.StreamDeck/AGENTS.md b/src/FinalToken.StreamDeck/AGENTS.md index 6af6faa..999a640 100644 --- a/src/FinalToken.StreamDeck/AGENTS.md +++ b/src/FinalToken.StreamDeck/AGENTS.md @@ -1,4 +1,6 @@ # Stream Deck -Buildable placeholder only. W3 replaces Program.cs and this guidance with the D10 plugin. -W3 also owns Core/StreamDeck. Read snapshots using SnapshotFile (D9); use Core DTOs. +D10 native SDK-v2 plugin. Read snapshots using SnapshotFile (D9); use Core DTOs. +Keep file IO off the socket owner loop. Never reconnect after the host closes the socket. +Protocol DTOs use PluginJsonContext. Assets and the local inspector live in plugin/. +Core/StreamDeck owns D11 deployment with injectable host process control. Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root. diff --git a/src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj b/src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj index 22754e5..b607cb1 100644 --- a/src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj +++ b/src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj @@ -4,4 +4,5 @@ true + diff --git a/src/FinalToken.StreamDeck/Program.cs b/src/FinalToken.StreamDeck/Program.cs index 78e0104..850a9d8 100644 --- a/src/FinalToken.StreamDeck/Program.cs +++ b/src/FinalToken.StreamDeck/Program.cs @@ -1 +1,77 @@ -Console.WriteLine("FinalToken Stream Deck placeholder; W3 supplies the plugin host."); +using System.Net.WebSockets; +using System.Threading.Channels; +using FinalToken.Core; +using FinalToken.StreamDeck; + +var registration = Registration.Parse(args); +if (registration is null) return 2; +using var stop = new CancellationTokenSource(); +try +{ + using var socket = new ClientWebSocket(); + await socket.ConnectAsync(new Uri($"ws://127.0.0.1:{registration.Port}"), stop.Token); + var transport = new PluginSocket(socket); + var session = new PluginSession(transport, PluginSession.LaunchAppAsync); + await session.RegisterAsync(registration, stop.Token); + await RollingLog.WriteAsync("registered"); + // D9: file IO runs on a separate worker; all state and WebSocket sends have one owner. + var updates = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest }); + var poll = Task.Run(async () => + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2)); + do { updates.Writer.TryWrite(SnapshotFile.Read(DataPaths.DataDirectory)); } + while (await timer.WaitForNextTickAsync(stop.Token)); + }); + var incoming = transport.ReceiveAsync(stop.Token); + var update = updates.Reader.ReadAsync(stop.Token).AsTask(); + try + { + while (true) + { + var ready = await Task.WhenAny(incoming, update); + if (ready == incoming) + { + var json = await incoming; + if (json is null) break; + await session.HandleAsync(json, DateTimeOffset.UtcNow, stop.Token); + incoming = transport.ReceiveAsync(stop.Token); + } + else + { + await session.UpdateAsync(await update, DateTimeOffset.UtcNow, stop.Token); + update = updates.Reader.ReadAsync(stop.Token).AsTask(); + } + } + } + finally + { + await stop.CancelAsync(); + try { await poll; } catch (OperationCanceledException) { } + try { await incoming; } catch (Exception e) when (e is OperationCanceledException or WebSocketException) { } + } + if (socket.State == WebSocketState.CloseReceived) + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await RollingLog.WriteAsync("host-closed"); + return 0; +} +catch (Exception e) when (e is WebSocketException or IOException or OperationCanceledException or UnauthorizedAccessException) +{ + await stop.CancelAsync(); + await RollingLog.WriteAsync("connection-ended"); + return 0; +} + +internal static class RollingLog +{ + public static async Task WriteAsync(string code) + { + try + { + var path = Path.Combine(DataPaths.DataDirectory, "streamdeck.log"); + var previous = File.Exists(path) ? await File.ReadAllTextAsync(path) : ""; + var lines = previous.Split('\n', StringSplitOptions.RemoveEmptyEntries).TakeLast(199); + await AtomicFile.WriteAsync(path, string.Join('\n', lines) + $"\n{DateTimeOffset.UtcNow:O} {code}\n"); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { } + } +} diff --git a/src/FinalToken.StreamDeck/Protocol.cs b/src/FinalToken.StreamDeck/Protocol.cs new file mode 100644 index 0000000..9e9dd33 --- /dev/null +++ b/src/FinalToken.StreamDeck/Protocol.cs @@ -0,0 +1,144 @@ +using System.Diagnostics; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using FinalToken.Core; + +namespace FinalToken.StreamDeck; + +public sealed record Registration(int Port, string Uuid, string Event) +{ + public static Registration? Parse(string[] args) + { + var values = new Dictionary(); + for (var i = 0; i + 1 < args.Length; i += 2) values[args[i]] = args[i + 1]; + return values.TryGetValue("-port", out var port) && int.TryParse(port, out var number) && number is > 0 and <= 65535 && + values.TryGetValue("-pluginUUID", out var uuid) && uuid.Length > 0 && + values.TryGetValue("-registerEvent", out var evt) && evt == "registerPlugin" && values.ContainsKey("-info") ? new(number, uuid, evt) : null; + } +} +public sealed record Command(string Event, string? Context = null, string? Uuid = null, string? Action = null, JsonElement? Payload = null); +public sealed record ImagePayload(string Image, int Target = 0); +public sealed record TitlePayload(string Title, int Target = 0); +public sealed record InspectorPayload(StatSettings Settings, WindowOption[] Windows); +public sealed record WindowOption(string Id, string Label); +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(Command))] +[JsonSerializable(typeof(ImagePayload))] +[JsonSerializable(typeof(TitlePayload))] +[JsonSerializable(typeof(StatSettings))] +[JsonSerializable(typeof(InspectorPayload))] +public partial class PluginJsonContext : JsonSerializerContext; + +public interface IPluginSocket +{ + Task SendAsync(string json, CancellationToken cancellationToken); + Task ReceiveAsync(CancellationToken cancellationToken); +} +public sealed class PluginSocket(ClientWebSocket socket) : IPluginSocket +{ + public async Task SendAsync(string json, CancellationToken cancellationToken) => + await socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, cancellationToken); + public async Task ReceiveAsync(CancellationToken cancellationToken) + { + var buffer = new byte[8192]; + using var message = new MemoryStream(); + while (true) + { + var result = await socket.ReceiveAsync(buffer.AsMemory(), cancellationToken); + if (result.MessageType == WebSocketMessageType.Close) return null; + if (result.MessageType != WebSocketMessageType.Text || message.Length + result.Count > 1_048_576) + throw new InvalidDataException("Invalid host frame."); + message.Write(buffer, 0, result.Count); + if (result.EndOfMessage) return Encoding.UTF8.GetString(message.ToArray()); + } + } +} + +public sealed class PluginSession(IPluginSocket socket, Func> launch) +{ + public const string Action = "de.finalfactory.finaltoken.stat"; + private readonly Dictionary keys = []; + private readonly Dictionary images = []; + private SnapshotReadResult read = new(null, true, null); + public Task RegisterAsync(Registration registration, CancellationToken ct = default) => Send(new(registration.Event, Uuid: registration.Uuid), ct); + public async Task UpdateAsync(SnapshotReadResult snapshot, DateTimeOffset now, CancellationToken ct = default) + { + read = StatRenderer.Validate(snapshot); + foreach (var (context, settings) in keys) await Draw(context, settings, now, ct); + } + public async Task HandleAsync(string json, DateTimeOffset now, CancellationToken ct = default) + { + try + { + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("event", out var evt) || evt.ValueKind != JsonValueKind.String) return; + if (evt.GetString() == "systemDidWakeUp") { images.Clear(); await UpdateAsync(read, now, ct); return; } + if (!root.TryGetProperty("context", out var ctx) || ctx.ValueKind != JsonValueKind.String || ctx.GetString() is not { Length: > 0 } context) return; + if (root.TryGetProperty("action", out var action) && action.GetString() != Action) return; + root.TryGetProperty("payload", out var payload); + switch (evt.GetString()) + { + case "willDisappear": keys.Remove(context); images.Remove(context); break; + case "willAppear": + case "didReceiveSettings": + var settings = ReadSettings(payload); + if (settings is null) return; + keys[context] = settings; + await Draw(context, settings, now, ct); + break; + case "keyDown": + if (!await launch(read.Snapshot?.AppPath)) await Send(new("showAlert", context), ct); + break; + case "sendToPlugin": + if (payload.ValueKind == JsonValueKind.Object && payload.TryGetProperty("settings", out _)) + { + var updated = ReadSettings(payload); + if (updated is null) return; + keys[context] = updated; + await Send(new("setSettings", context, Payload: JsonSerializer.SerializeToElement(updated, PluginJsonContext.Default.StatSettings)), ct); + await Draw(context, updated, now, ct); + } + await Inspector(context, ct); + break; + case "propertyInspectorDidAppear": await Inspector(context, ct); break; + } + } + catch (Exception e) when (e is JsonException or InvalidOperationException or ArgumentException) { } + } + private static StatSettings? ReadSettings(JsonElement payload) + { + if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty("settings", out var element)) return new(); + var settings = element.Deserialize(PluginJsonContext.Default.StatSettings); + return settings is { IsValid: true } ? settings : null; + } + private Task Inspector(string context, CancellationToken ct) + { + var settings = keys.GetValueOrDefault(context) ?? new(); + var windows = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider)?.Windows + .Select(w => new WindowOption(w.Window.Id, w.Window.Label)).ToArray() ?? []; + return Send(new("sendToPropertyInspector", context, Action: Action, + Payload: JsonSerializer.SerializeToElement(new InspectorPayload(settings, windows), PluginJsonContext.Default.InspectorPayload)), ct); + } + private async Task Draw(string context, StatSettings settings, DateTimeOffset now, CancellationToken ct) + { + var svg = StatRenderer.Render(read, settings, now); + if (images.GetValueOrDefault(context) == svg) return; + await Send(new("setTitle", context, Payload: JsonSerializer.SerializeToElement(new TitlePayload(""), PluginJsonContext.Default.TitlePayload)), ct); + await Send(new("setImage", context, Payload: JsonSerializer.SerializeToElement(new ImagePayload("data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(svg))), PluginJsonContext.Default.ImagePayload)), ct); + images[context] = svg; + } + private Task Send(Command command, CancellationToken ct) => socket.SendAsync(JsonSerializer.Serialize(command, PluginJsonContext.Default.Command), ct); + public static Task LaunchAppAsync(string? path) => Task.Run(() => + { + try + { + if (path is null || !Path.IsPathFullyQualified(path) || !File.Exists(path)) return false; + using var process = Process.Start(new ProcessStartInfo(path) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(path)! }); + return process is not null; + } + catch (Exception e) when (e is IOException or System.ComponentModel.Win32Exception or InvalidOperationException) { return false; } + }); +} diff --git a/src/FinalToken.StreamDeck/README.md b/src/FinalToken.StreamDeck/README.md new file mode 100644 index 0000000..667451e --- /dev/null +++ b/src/FinalToken.StreamDeck/README.md @@ -0,0 +1,35 @@ +# Stream Deck plugin + +D10 uses a native SDK-v2 WebSocket connection. There is one owner for key state and socket sends; +a separate worker polls the D9 Core reader every two seconds. Closing the connection exits. +Only changed SVGs are sent. The bounded log is `streamdeck.log` in FinalToken's data directory. + +Protocol sources checked on 2026-10-14: + +- [Elgato Plugin WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/plugin/) + — registration arguments, key/settings/wake events and drawing commands. +- [Elgato Property Inspector WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/ui/) + — inspector registration and messages. +- [Elgato Manifest](https://docs.elgato.com/streamdeck/sdk/references/manifest/) + — native entry points, SDK version, actions and resources. +- [OpenDeck README](https://github.com/aberja/opendeck) + — native plugins and host installation. +- [OpenDeck manifest parser](https://github.com/aberja/opendeck/blob/main/src-tauri/src/plugins/manifest.rs) + — `CodePathLin`. +- [OpenDeck plugin lifecycle](https://github.com/aberja/opendeck/blob/main/src-tauri/src/plugins/mod.rs) + and [shared paths](https://github.com/aberja/opendeck/blob/main/src-tauri/src/shared.rs) + — `app_config_dir()/plugins`; Tauri identifier `opendeck`. +- [OpenDeck installation script](https://github.com/aberja/opendeck/blob/main/install_opendeck.sh) + — executable `opendeck`, Flatpak ID `me.amankhanna.opendeck`. + +The D11 installer discovers Windows Stream Deck, Linux native OpenDeck and Flatpak OpenDeck. +Linux locations are `$XDG_CONFIG_HOME/opendeck/plugins` (default `~/.config/opendeck/plugins`) +and `~/.var/app/me.amankhanna.opendeck/config/opendeck/plugins`. +Deployment stages in a sibling folder, swaps with a backup and rolls back on failure. +`PluginInstaller.CreateDefault()` is the app entry point; `Outcome` reports installation steps. +The interface and install policy remain compatible with the original Core contract. + +`python -B tools/publish.py win-x64` builds the app, CLI and plugin into one folder and ZIP. +The Windows CLI is named `finaltoken-cli.exe` to avoid colliding with `FinalToken.exe`. +Use `--skip-app` while the desktop project is being replaced. Publish a Linux RID on Linux; +the .NET NativeAOT toolchain does not support cross-OS compilation. diff --git a/src/FinalToken.StreamDeck/StatRenderer.cs b/src/FinalToken.StreamDeck/StatRenderer.cs new file mode 100644 index 0000000..90832aa --- /dev/null +++ b/src/FinalToken.StreamDeck/StatRenderer.cs @@ -0,0 +1,69 @@ +using System.Globalization; +using System.Security; +using FinalToken.Core; + +namespace FinalToken.StreamDeck; + +public enum Metric { SessionPercent, WeekPercent, PaceDelta, TimeToReset, TokensToday, TokensWeek } +public sealed record StatSettings(string Provider = "Claude", string Metric = "SessionPercent", string Window = "") +{ + public bool IsValid => Enum.TryParse(Provider, out var p) && Enum.IsDefined(p) && + Enum.TryParse(Metric, out var m) && Enum.IsDefined(m) && Window is not null; +} + +public static class StatRenderer +{ + public static WindowSnapshot? SelectWindow(ProviderSnapshot provider, StatSettings settings) + { + if (settings.Window.Length > 0) return provider.Windows.FirstOrDefault(w => w.Window.Id == settings.Window); + if (settings.Metric is "PaceDelta" or "TimeToReset") + return provider.Windows.FirstOrDefault(w => w.Window.Length is { } length && length < TimeSpan.FromDays(1)) ?? provider.Windows.FirstOrDefault(); + var week = settings.Metric is "WeekPercent"; + return provider.Windows.FirstOrDefault(w => week ? w.Window.Length >= TimeSpan.FromDays(1) : + w.Window.Length is { } length && length < TimeSpan.FromDays(1)); + } + + public static string Render(SnapshotReadResult read, StatSettings settings, DateTimeOffset now) + { + read = Validate(read); + var provider = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider); + var offline = read.IsStale || provider is null; + var window = provider is null ? null : SelectWindow(provider, settings); + var metric = Enum.TryParse(settings.Metric, out var parsed) ? parsed : Metric.SessionPercent; + var state = offline ? PaceState.Unknown : window?.Pace.State ?? PaceState.Unknown; + var color = state switch { PaceState.Ahead => "#ef6461", PaceState.Behind => "#69a7ff", PaceState.OnTrack => "#58d6a0", _ => "#a0a7b4" }; + var label = metric switch { Metric.SessionPercent => "SESSION", Metric.WeekPercent => "WEEK", Metric.PaceDelta => "PACE", Metric.TimeToReset => "RESET", Metric.TokensToday => "TODAY", _ => "WEEK TOKENS" }; + var value = offline ? "offline" : metric switch + { + Metric.TokensToday => Compact(provider!.Today.Total), + Metric.TokensWeek => Compact(provider!.Week.Total), + Metric.PaceDelta => window?.Pace.Delta is { } delta ? delta.ToString("+0;-0;0", CultureInfo.InvariantCulture) + "pp" : "—", + Metric.TimeToReset => window?.Window.ResetsAt is { } reset ? Duration(reset - now) : "—", + _ => window is null ? "—" : window.Window.UsedPercent.ToString("0", CultureInfo.InvariantCulture) + "%" + }; + var bar = ""; + if (!offline && window is not null && metric is Metric.SessionPercent or Metric.WeekPercent) + { + var width = Math.Clamp(window.Window.UsedPercent, 0, 100) * .6; + bar = FormattableString.Invariant($""); + if (window.Pace.ElapsedFraction is { } e) + bar += FormattableString.Invariant($""); + } + return $"{SecurityElement.Escape(settings.Provider)}{label}{value}{bar}"; + } + // The reader rejects unsupported schemas; nested data is still an external trust boundary (D9). + public static SnapshotReadResult Validate(SnapshotReadResult read) + { + if (read.Snapshot is not { } snapshot) return new(null, true, read.Error); + if (snapshot.Providers is null || snapshot.Providers.Any(p => p is null || !Enum.IsDefined(p.Provider) || p.Windows is null || + p.Windows.Any(w => w is null || w.Window is null || w.Pace is null || w.Window.Id is null || w.Window.Label is null || + !double.IsFinite(w.Window.UsedPercent) || w.Window.UsedPercent is < 0 or > 100 || + w.Pace.ElapsedFraction is { } e && !double.IsFinite(e) || w.Pace.Delta is { } d && !double.IsFinite(d)))) + return new(null, true, "Invalid snapshot content."); + return read; + } + private static string Compact(long value) => value >= 1_000_000 ? (value / 1_000_000d).ToString("0.#", CultureInfo.InvariantCulture) + "M" : + value >= 1_000 ? (value / 1_000d).ToString("0.#", CultureInfo.InvariantCulture) + "k" : value.ToString(CultureInfo.InvariantCulture); + private static string Duration(TimeSpan time) => time <= TimeSpan.Zero ? "0m" : time.TotalDays >= 1 ? $"{(int)time.TotalDays}d {time.Hours}h" : + time.TotalHours >= 1 ? $"{(int)time.TotalHours}h {time.Minutes}m" : $"{Math.Ceiling(time.TotalMinutes):0}m"; +} diff --git a/src/FinalToken.StreamDeck/plugin/images/icon.svg b/src/FinalToken.StreamDeck/plugin/images/icon.svg new file mode 100644 index 0000000..086cfee --- /dev/null +++ b/src/FinalToken.StreamDeck/plugin/images/icon.svg @@ -0,0 +1 @@ + diff --git a/src/FinalToken.StreamDeck/plugin/images/key.svg b/src/FinalToken.StreamDeck/plugin/images/key.svg new file mode 100644 index 0000000..e21bf97 --- /dev/null +++ b/src/FinalToken.StreamDeck/plugin/images/key.svg @@ -0,0 +1 @@ +FinalTokenoffline diff --git a/src/FinalToken.StreamDeck/plugin/inspector/index.html b/src/FinalToken.StreamDeck/plugin/inspector/index.html new file mode 100644 index 0000000..f225f2d --- /dev/null +++ b/src/FinalToken.StreamDeck/plugin/inspector/index.html @@ -0,0 +1,5 @@ + +FinalToken Stat + + +

Press the key to open FinalToken. Keep FinalToken running to refresh stats.

diff --git a/src/FinalToken.StreamDeck/plugin/inspector/inspector.js b/src/FinalToken.StreamDeck/plugin/inspector/inspector.js new file mode 100644 index 0000000..627bd47 --- /dev/null +++ b/src/FinalToken.StreamDeck/plugin/inspector/inspector.js @@ -0,0 +1,27 @@ +'use strict'; +let connection, context; +const provider = document.getElementById('provider'), metric = document.getElementById('metric'), windowSelect = document.getElementById('window'); +function apply(settings) { + provider.value = settings.provider || 'Claude'; metric.value = settings.metric || 'SessionPercent'; + if (!Array.from(windowSelect.options).some(o => o.value === settings.window) && settings.window) windowSelect.add(new Option(settings.window, settings.window)); + windowSelect.value = settings.window || ''; +} +function send(payload) { if (connection && connection.readyState === WebSocket.OPEN) connection.send(JSON.stringify({event:'sendToPlugin',action:'de.finalfactory.finaltoken.stat',context,payload})); } +window.connectElgatoStreamDeckSocket = (port, uuid, event, info, actionInfo) => { + const action = JSON.parse(actionInfo); context = action.context; apply(action.payload.settings || {}); + connection = new WebSocket(`ws://127.0.0.1:${port}`); + connection.onopen = () => { connection.send(JSON.stringify({event,uuid})); send({request:'windows'}); }; + connection.onmessage = message => { + const data = JSON.parse(message.data); + if (data.event === 'didReceiveSettings') apply(data.payload.settings); + if (data.event === 'sendToPropertyInspector') { + windowSelect.replaceChildren(new Option('Automatic', '')); + for (const item of data.payload.windows || []) windowSelect.add(new Option(item.label, item.id)); + apply(data.payload.settings); + } + }; +}; +for (const element of [provider,metric,windowSelect]) element.addEventListener('change', () => { + if (element === provider) windowSelect.value = ''; + send({settings:{provider:provider.value,metric:metric.value,window:windowSelect.value}}); +}); diff --git a/src/FinalToken.StreamDeck/plugin/inspector/style.css b/src/FinalToken.StreamDeck/plugin/inspector/style.css new file mode 100644 index 0000000..29d70ee --- /dev/null +++ b/src/FinalToken.StreamDeck/plugin/inspector/style.css @@ -0,0 +1 @@ +:root{color-scheme:dark}body{margin:16px 12px;background:#2d2d2d;color:#d8d8d8;font:12px Arial,sans-serif}label{display:grid;grid-template-columns:72px 1fr;align-items:center;gap:8px;margin-bottom:12px}select{min-width:0;background:#3d3d3d;color:#eee;border:1px solid #555;border-radius:3px;padding:6px}select:focus{outline:1px solid #2ea8ff}p{line-height:1.5;color:#aaa} diff --git a/src/FinalToken.StreamDeck/plugin/manifest.json b/src/FinalToken.StreamDeck/plugin/manifest.json new file mode 100644 index 0000000..f8384ac --- /dev/null +++ b/src/FinalToken.StreamDeck/plugin/manifest.json @@ -0,0 +1,24 @@ +{ + "UUID": "de.finalfactory.finaltoken", + "Name": "FinalToken", + "Author": "Final Factory", + "Description": "Claude and Codex usage from FinalToken.", + "Version": "1.0.0.1", + "SDKVersion": 2, + "CodePathWin": "FinalToken.StreamDeck.exe", + "CodePathLin": "FinalToken.StreamDeck", + "Icon": "images/icon", + "Category": "FinalToken", + "CategoryIcon": "images/icon", + "PropertyInspectorPath": "inspector/index.html", + "Software": { "MinimumVersion": "7.0" }, + "OS": [ { "Platform": "windows", "MinimumVersion": "10" }, { "Platform": "linux", "MinimumVersion": "0" } ], + "Actions": [ { + "UUID": "de.finalfactory.finaltoken.stat", + "Name": "Stat", + "Tooltip": "Show usage. Press to open FinalToken.", + "Icon": "images/icon", + "SupportedInMultiActions": false, + "States": [ { "Image": "images/key", "ShowTitle": false } ] + } ] +} diff --git a/tests/FinalToken.Core.Tests/StreamDeck/InstallerTests.cs b/tests/FinalToken.Core.Tests/StreamDeck/InstallerTests.cs new file mode 100644 index 0000000..a1268d6 --- /dev/null +++ b/tests/FinalToken.Core.Tests/StreamDeck/InstallerTests.cs @@ -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(); 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(); installer.Outcome += outcomes.Add; + await Assert.ThrowsAsync(() => 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(() => 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(() => 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 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; } + } +} + diff --git a/tests/FinalToken.StreamDeck.Tests/AGENTS.md b/tests/FinalToken.StreamDeck.Tests/AGENTS.md index 6e21735..a09ff9e 100644 --- a/tests/FinalToken.StreamDeck.Tests/AGENTS.md +++ b/tests/FinalToken.StreamDeck.Tests/AGENTS.md @@ -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. diff --git a/tests/FinalToken.StreamDeck.Tests/PlaceholderTests.cs b/tests/FinalToken.StreamDeck.Tests/PlaceholderTests.cs deleted file mode 100644 index 6888cb3..0000000 --- a/tests/FinalToken.StreamDeck.Tests/PlaceholderTests.cs +++ /dev/null @@ -1,3 +0,0 @@ -using Xunit; -namespace FinalToken.StreamDeck.Tests; -public class PlaceholderTests { [Fact] public void FoundationBuilds() => Assert.True(true); } diff --git a/tests/FinalToken.StreamDeck.Tests/PluginTests.cs b/tests/FinalToken.StreamDeck.Tests/PluginTests.cs new file mode 100644 index 0000000..dbdeb97 --- /dev/null +++ b/tests/FinalToken.StreamDeck.Tests/PluginTests.cs @@ -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 Sent { get; } = []; + public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; } + public Task ReceiveAsync(CancellationToken cancellationToken) => Task.FromResult(null); + } +} + + diff --git a/tools/publish.py b/tools/publish.py new file mode 100644 index 0000000..81ab5d0 --- /dev/null +++ b/tools/publish.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""D1/D11: publish the three NativeAOT programs and bundle the plugin assets.""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import zipfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('rid', choices=['win-x64', 'linux-x64']) + parser.add_argument('--out', type=Path) + parser.add_argument('--skip-app', action='store_true') + args = parser.parse_args() + root = Path(__file__).resolve().parent.parent + output = (args.out or root / 'artifacts' / 'publish' / args.rid).resolve() + output.mkdir(parents=True, exist_ok=True) + if any(output.iterdir()): + parser.error('Output directory must be empty; existing files are never deleted.') + plugin = output / 'streamdeck' / 'de.finalfactory.finaltoken.sdPlugin' + with tempfile.TemporaryDirectory(prefix='finaltoken-publish-') as temporary: + for name in ['App', 'Cli', 'StreamDeck']: + if name == 'App' and args.skip_app: + continue + stage = Path(temporary) / name + subprocess.run(['dotnet', 'publish', str(root / 'src' / ('FinalToken.' + name)), + '-c', 'Release', '-r', args.rid, '-p:PublishAot=true', + '-o', str(stage)], cwd=root, check=True) + destination = plugin if name == 'StreamDeck' else output + destination.mkdir(parents=True, exist_ok=True) + for file in stage.iterdir(): + if file.suffix in ['.pdb', '.dbg']: + continue + # Windows paths ignore case: FinalToken.exe (app) and finaltoken.exe (CLI) + # cannot share a folder. Keep the desktop activation path stable. + filename = 'finaltoken-cli.exe' if name == 'Cli' and file.name == 'finaltoken.exe' else file.name + target = destination / filename + if target.exists(): + if file.is_file() and target.is_file() and file.read_bytes() == target.read_bytes(): + continue + raise RuntimeError('Publish outputs collide: ' + str(target)) + if file.is_dir(): + shutil.copytree(file, target) + else: + shutil.copy2(file, target) + shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True) + archive = output.parent / (output.name + '.zip') + if archive.exists(): + raise RuntimeError('Archive already exists: ' + str(archive)) + temporary_zip = archive.with_suffix('.zip.tmp') + with zipfile.ZipFile(temporary_zip, 'w', zipfile.ZIP_DEFLATED) as bundle: + for file in sorted(output.rglob('*')): + if file.is_file(): + bundle.write(file, file.relative_to(output)) + os.replace(temporary_zip, archive) + for file in sorted(output.rglob('*')): + if file.is_file(): + print(str(file.relative_to(output)) + ' (' + str(file.stat().st_size) + ' bytes)') + print('Archive: ' + str(archive)) + + +if __name__ == '__main__': + main()