build: one version for the app and the plugin

D11 replaces an installed plugin only when the shipped manifest is
newer, but the manifest version was kept by hand and still said
1.0.0.1, the version of a test build installed before the snapshot
sharing and appPath fixes, so that stale plugin was never replaced.
Directory.Build.props now holds the only version, 1.0.1; publish.py
stamps it into the shipped manifest and the app shows it in its title.

Tests that waited on real time (file retry, popup expiry) use
controlled timers, and real process waits have wider margins.

Refs #1
This commit is contained in:
Florian Schmidt
2026-10-14 21:08:22 +02:00
parent 5c5973aa6c
commit 15c7e684bb
15 changed files with 126 additions and 18 deletions
+4 -1
View File
@@ -105,6 +105,8 @@ agents edit the same files at once.
## Building and testing
Releasing: bump `<Version>` in `Directory.Build.props`, then publish; the tool stamps the plugin manifest.
Run every command from the repository root.
| Command | What it does |
@@ -124,7 +126,8 @@ a screenshot of each changed view: compiling is not working.
- `tools/agent-review.sh`: posts an agent review and sets the `agent-review` status; see
`docs/agents/review.md`.
- `tools/publish.py`: publishes the app, `finaltoken-cli` and Stream Deck plugin with NativeAOT
into an empty output directory and creates a ZIP beside it. Run on the target OS.
into an empty output directory and creates a ZIP beside it. Run on the target OS. It stamps
the plugin manifest's `Version` from `<Version>`; its test is `python -B tools/test_publish.py`.
## Writing
+1
View File
@@ -1,5 +1,6 @@
<Project>
<PropertyGroup>
<Version>1.0.1</Version>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
+1 -1
View File
@@ -31,7 +31,7 @@ public sealed class PanelWindow : Window
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload)
{
this.model = model;
Title = "FinalToken"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500;
var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
header.Children.Add(Ui.Text("FinalToken", 28));
header.Children.Add(Ui.Button("Refresh now", refresh));
+5 -4
View File
@@ -41,7 +41,7 @@ public sealed class PopupWindow : Window
(alert.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State));
}
public sealed class PopupStack(Action open) : IDisposable
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
{
private readonly List<PopupWindow> windows = [];
public void Pace(PopupEvent alert) => Show(PopupWindow.Pace(alert, open));
@@ -50,9 +50,10 @@ public sealed class PopupStack(Action open) : IDisposable
windows.Add(window);
window.Closed += (_, _) => { windows.Remove(window); Position(); };
window.Show(); Position();
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(8) };
timer.Tick += (_, _) => { timer.Stop(); window.Close(); };
window.Closed += (_, _) => timer.Stop(); timer.Start();
// D8: timer callbacks are off the UI thread; closing always marshals back.
var timer = (clock ?? TimeProvider.System).CreateTimer(_ => Dispatcher.UIThread.Post(window.Close),
null, TimeSpan.FromSeconds(8), Timeout.InfiniteTimeSpan);
window.Closed += (_, _) => timer.Dispose();
}
private void Position()
{
+4 -2
View File
@@ -5,7 +5,9 @@ namespace FinalToken.Core;
public static class AtomicFile
{
// D5: same-directory rename; a reader sees either complete version.
public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default)
public static Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default)
=> WriteAsync(path, contents, cancellationToken, TimeProvider.System);
public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken, TimeProvider timeProvider)
{
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
@@ -33,7 +35,7 @@ public static class AtomicFile
{
// Windows can report ACCESS_DENIED for an open destination as well as SHARING_VIOLATION.
if (attempt == 10) throw new IOException("Atomic replacement remained blocked after 500 ms.", e);
await Task.Delay(TimeSpan.FromMilliseconds(50), cancellationToken).ConfigureAwait(false);
await Task.Delay(TimeSpan.FromMilliseconds(50), timeProvider, cancellationToken).ConfigureAwait(false);
}
}
}
+2
View File
@@ -2,5 +2,7 @@
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/.
Directory.Build.props is the release version source. tools/publish.py stamps the published manifest;
the repository manifest is an asset template, not the shipped version.
Core/StreamDeck owns D11 deployment with injectable host process control.
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
+1
View File
@@ -4,3 +4,4 @@ Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
View-model tests use public Core queries. Headless tests run on a dedicated UI thread with
Skia and HarfBuzz, exercise settings and popup actions, and save seven PNG screenshots outside
the repo at ../runs/shots/w2. FINALTOKEN_SCREENSHOT_DIR overrides that path.
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
+24 -2
View File
@@ -31,6 +31,7 @@ public sealed class HeadlessTests
var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
@@ -74,7 +75,8 @@ public sealed class HeadlessTests
var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++);
install.Show(); install.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Update").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.Equal(1, installed);
using var stack = new PopupStack(() => { });
var popupClock = new PopupClock();
using var stack = new PopupStack(() => { }, popupClock);
var first = PopupWindow.Pace(new(Provider.Claude, "a", "Session", PaceState.Ahead, 20, null), () => { });
var second = PopupWindow.Pace(new(Provider.Codex, "b", "Week", PaceState.Behind, -20, null), () => { });
stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y);
@@ -94,8 +96,9 @@ public sealed class HeadlessTests
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
Thread.Sleep(8200); Dispatcher.UIThread.RunJobs();
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
completion.SetResult();
void Save(Window window, string name, string? destination = null)
{
@@ -112,4 +115,23 @@ public sealed class HeadlessTests
}
public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(new FluentTheme()); }
private sealed class PopupClock : TimeProvider
{
public List<PopupTimer> Timers { get; } = [];
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
Assert.Equal(TimeSpan.FromSeconds(8), dueTime);
Assert.Equal(Timeout.InfiniteTimeSpan, period);
var timer = new PopupTimer(callback, state); Timers.Add(timer); return timer;
}
public void Fire() { foreach (var timer in Timers.Where(t => !t.Disposed)) timer.Fire(); }
}
private sealed class PopupTimer(TimerCallback callback, object? state) : ITimer
{
public bool Disposed { get; private set; }
public void Fire() => callback(state);
public bool Change(TimeSpan dueTime, TimeSpan period) => throw new NotSupportedException();
public void Dispose() => Disposed = true;
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}
@@ -28,7 +28,7 @@ public class IntegrationTests
process.Start();
try
{
await process.WaitForExitAsync(TestContext.Current.CancellationToken);
await process.WaitForExitAsync(TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(90), TestContext.Current.CancellationToken);
using var report = JsonDocument.Parse(File.ReadAllText(reportPath));
Assert.False(report.RootElement.GetProperty("HostHasConsole").GetBoolean());
Assert.False(report.RootElement.GetProperty("HostInputValid").GetBoolean());
+1 -1
View File
@@ -31,7 +31,7 @@ public class ProcessTests
{
using var directory = new TestDirectory();
var result = await new ProcessRunner().RunAsync(new(new("dotnet", []), ["--info"], directory.Path,
TimeSpan.FromSeconds(10), OutputLimit: 50), TestContext.Current.CancellationToken);
TimeSpan.FromSeconds(60), OutputLimit: 50), TestContext.Current.CancellationToken);
Assert.Equal(0, result.ExitCode);
Assert.Equal(50, result.Output.Length);
Assert.True(result.OutputTruncated);
+14 -6
View File
@@ -1,4 +1,3 @@
using System.Diagnostics;
using FinalToken.Core.Collectors;
using Xunit;
@@ -59,9 +58,15 @@ public class ReworkTests
using var directory = new TestDirectory();
var path = directory.Write("blocked.json", "old");
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var watch = Stopwatch.StartNew();
await Assert.ThrowsAsync<IOException>(() => AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken));
Assert.InRange(watch.Elapsed.TotalMilliseconds, 400, 3000);
var clock = new TestClock();
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken, clock);
for (var attempt = 0; attempt < 10; attempt++)
{
Assert.Equal(TimeSpan.FromMilliseconds(50), await clock.NextTimerAsync(TestContext.Current.CancellationToken));
Assert.False(write.IsCompleted);
clock.Advance(TimeSpan.FromMilliseconds(50));
}
await Assert.ThrowsAsync<IOException>(() => write);
Assert.Equal("old", File.ReadAllText(path));
Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp"));
}
@@ -196,9 +201,12 @@ public class ReworkTests
using var directory = new TestDirectory();
var path = directory.Write("briefly-blocked.json", "old");
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken);
await Task.Delay(TimeSpan.FromMilliseconds(120), TestContext.Current.CancellationToken);
var clock = new TestClock();
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken, clock);
Assert.Equal(TimeSpan.FromMilliseconds(50), await clock.NextTimerAsync(TestContext.Current.CancellationToken));
Assert.False(write.IsCompleted);
reader.Dispose();
clock.Advance(TimeSpan.FromMilliseconds(50));
await write;
Assert.Equal("new", File.ReadAllText(path));
}
@@ -11,6 +11,24 @@ public sealed class InstallerTests : IDisposable
private string Installed => Path.Combine(Plugins, PluginInstaller.FolderName);
public InstallerTests() => Write(Shipped, "1.0.0.0", "new");
[Fact]
public async Task ReleasePluginReportsOldDevelopmentCopyAsOutdated()
{
var shipped = Environment.GetEnvironmentVariable("FINALTOKEN_TEST_SHIPPED_PLUGIN");
if (shipped is null)
{
Write(Shipped, typeof(PluginInstaller).Assembly.GetName().Version!.ToString(), "new");
shipped = Shipped;
}
Write(Installed, "1.0.0.1", "old development copy");
var process = new FakeProcesses();
var installer = new PluginInstaller(shipped, new(Plugins, "fake", "fake"), process);
var status = await installer.GetStatusAsync(TestContext.Current.CancellationToken);
Assert.Equal(PluginInstallState.Outdated, status.State);
Assert.Equal(typeof(PluginInstaller).Assembly.GetName().Version!.ToString(), status.ShippedVersion);
Assert.Equal("1.0.0.1", status.InstalledVersion);
Assert.Equal(0, process.Stops); Assert.Equal(0, process.Starts);
}
[Fact]
public async Task FreshInstallDoesNotStartStoppedHost()
{
var process = new FakeProcesses();
@@ -1,4 +1,5 @@
using FinalToken.Core.Processes;
using System.Threading.Channels;
namespace FinalToken.Core.Tests;
@@ -18,6 +19,8 @@ public sealed class TestDirectory : IDisposable
public sealed class TestClock : TimeProvider
{
private readonly Channel<TimeSpan> scheduled = Channel.CreateUnbounded<TimeSpan>();
public ValueTask<TimeSpan> NextTimerAsync(CancellationToken cancellationToken) => scheduled.Reader.ReadAsync(cancellationToken);
private readonly Lock gate = new();
private DateTimeOffset now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
private readonly List<TestTimer> timers = [];
@@ -40,6 +43,7 @@ public sealed class TestClock : TimeProvider
var timer = new TestTimer(this, callback, state, period);
timer.Change(dueTime, period);
timers.Add(timer);
scheduled.Writer.TryWrite(dueTime);
return timer;
}
}
+12
View File
@@ -1,12 +1,14 @@
#!/usr/bin/env python3
"""D1/D11: publish the three NativeAOT programs and bundle the plugin assets."""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import zipfile
import xml.etree.ElementTree as ET
def main():
@@ -16,6 +18,11 @@ def main():
parser.add_argument('--skip-app', action='store_true')
args = parser.parse_args()
root = Path(__file__).resolve().parent.parent
version = ET.parse(root / 'Directory.Build.props').findtext('.//Version')
parts = (version or '').split('.')
if len(parts) != 3 or not all(part.isascii() and part.isdigit() for part in parts):
parser.error('Directory.Build.props must define a three-part numeric Version.')
plugin_version = version + '.0'
output = (args.out or root / 'artifacts' / 'publish' / args.rid).resolve()
output.mkdir(parents=True, exist_ok=True)
if any(output.iterdir()):
@@ -44,6 +51,10 @@ def main():
else:
shutil.copy2(file, target)
shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True)
manifest_path = plugin / 'manifest.json'
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
manifest['Version'] = plugin_version
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
archive = output.parent / (output.name + '.zip')
if archive.exists():
raise RuntimeError('Archive already exists: ' + str(archive))
@@ -57,6 +68,7 @@ def main():
if file.is_file():
print(str(file.relative_to(output)) + ' (' + str(file.stat().st_size) + ' bytes)')
print('Archive: ' + str(archive))
print('Plugin Version: ' + plugin_version)
if __name__ == '__main__':
+34
View File
@@ -0,0 +1,34 @@
"""Check release assembly and manifest versions without invoking NativeAOT."""
import contextlib
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import xml.etree.ElementTree as ET
import publish
class PublishTests(unittest.TestCase):
def test_published_manifest_uses_shared_version(self):
def fake_publish(command, **kwargs):
stage = Path(command[command.index('-o') + 1])
stage.mkdir(parents=True)
(stage / (stage.name + '.exe')).write_bytes(b'synthetic executable')
with tempfile.TemporaryDirectory(prefix='finaltoken-publish-test-') as temporary:
output = Path(temporary) / 'package'
with patch('sys.argv', ['publish.py', 'win-x64', '--out', str(output)]), \
patch.object(publish.subprocess, 'run', side_effect=fake_publish), \
contextlib.redirect_stdout(io.StringIO()):
publish.main()
version = ET.parse(Path(publish.__file__).resolve().parent.parent / 'Directory.Build.props').findtext('.//Version')
self.assertIsNotNone(version)
manifest = json.loads((output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/manifest.json').read_text(encoding='utf-8'))
self.assertEqual(version + '.0', manifest['Version'])
if __name__ == '__main__':
unittest.main()