Blocking findings: 1. A Codex RPC error or early exit threw past LimitProbe and stopped the refresh loop, so Claude stopped updating too (D2). Every probe failure is now a failed probe result, the loop records an unexpected tick failure and keeps ticking, shutdown cancellation still propagates, the app reports failed operations, and the CLI exits 1 instead of crashing. Fake app-server modes in the GUI process host test errors, EOF and garbage. 2. Totals converted local midnight directly and threw where midnight does not exist (Cairo, Santiago, Beirut). Today and the week start through CalendarDays now. 3. Daily chart labels used UTC dates for local-day buckets; labels and tooltips now share the local date. Review notes fixed as well: Claude Code installed with npm on Windows is found through its native binary or cli.js; the plugin ends cleanly on a bad host frame; Linux autostart honours XDG_CONFIG_HOME; the unused stub installer and the worker names in docs are gone. Refs #1
This commit is contained in:
@@ -68,7 +68,7 @@ public sealed class UsageChart : Control
|
|||||||
context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
|
context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
|
||||||
}
|
}
|
||||||
context.DrawEllipse(Palette[0], null, point, 3, 3);
|
context.DrawEllipse(Palette[0], null, point, 3, 3);
|
||||||
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{value.Time.LocalDateTime:g} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}"));
|
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}"));
|
||||||
previous = value;
|
previous = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -85,14 +85,13 @@ public sealed class UsageChart : Control
|
|||||||
var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width;
|
var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width;
|
||||||
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height);
|
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height);
|
||||||
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect);
|
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect);
|
||||||
hits.Add((rect, $"{value.Time.LocalDateTime:g} · {value.Series}: {value.Value:N0} tokens"));
|
hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens"));
|
||||||
bottom -= height;
|
bottom -= height;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
string DateLabel(DateTimeOffset time) => Interval >= TimeSpan.FromDays(1) ? time.UtcDateTime.ToString("MM-dd") : time.LocalDateTime.ToString("MM-dd HH:mm");
|
Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink);
|
||||||
Text(context, DateLabel(groups[0].Key), new(plot.Left, plot.Bottom + 8), ink);
|
Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink);
|
||||||
Text(context, DateLabel(groups[^1].Key), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink);
|
|
||||||
ToolTip.SetShowDelay(this, 0);
|
ToolTip.SetShowDelay(this, 0);
|
||||||
}
|
}
|
||||||
private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
|
private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
|
||||||
|
|||||||
@@ -178,7 +178,10 @@ public sealed class DesktopApp : Application
|
|||||||
{
|
{
|
||||||
try { await work(); }
|
try { await work(); }
|
||||||
catch (OperationCanceledException) { }
|
catch (OperationCanceledException) { }
|
||||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
catch (Exception)
|
||||||
{ model.Message = "Operation failed: " + e.Message; }
|
{
|
||||||
|
engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed.");
|
||||||
|
model.Message = "Operation failed. See diagnostics.";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,15 @@ namespace FinalToken.App;
|
|||||||
|
|
||||||
public static class OsStartup
|
public static class OsStartup
|
||||||
{
|
{
|
||||||
|
public static string LinuxAutostartPath(string? configHome, string userHome)
|
||||||
|
=> Path.Combine(string.IsNullOrEmpty(configHome) ? Path.Combine(userHome, ".config") : configHome, "autostart", "finaltoken.desktop");
|
||||||
public static async Task ApplyAsync(bool enabled, string? executable = null)
|
public static async Task ApplyAsync(bool enabled, string? executable = null)
|
||||||
{
|
{
|
||||||
executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable.");
|
executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable.");
|
||||||
if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; }
|
if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; }
|
||||||
if (!OperatingSystem.IsLinux()) return;
|
if (!OperatingSystem.IsLinux()) return;
|
||||||
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "autostart", "finaltoken.desktop");
|
var path = LinuxAutostartPath(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"),
|
||||||
|
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
|
||||||
if (!enabled) { if (File.Exists(path)) File.Delete(path); return; }
|
if (!enabled) { if (File.Exists(path)) File.Delete(path); return; }
|
||||||
await AtomicFile.WriteAsync(path, DesktopEntry(executable));
|
await AtomicFile.WriteAsync(path, DesktopEntry(executable));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,6 +66,12 @@ public partial class PanelViewModel : ObservableObject
|
|||||||
|
|
||||||
public static class Display
|
public static class Display
|
||||||
{
|
{
|
||||||
|
public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval)
|
||||||
|
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
|
||||||
|
public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval)
|
||||||
|
=> ChartTime(time, interval).ToString("g");
|
||||||
|
private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval)
|
||||||
|
=> interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime;
|
||||||
public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null)
|
public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null)
|
||||||
{
|
{
|
||||||
clock ??= TimeProvider.System;
|
clock ??= TimeProvider.System;
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public static class CliApplication
|
|||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or OperationCanceledException)
|
catch (Exception)
|
||||||
{ await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; }
|
{ await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
|
|||||||
`ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously.
|
`ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously.
|
||||||
The desktop host passes `appPath: Environment.ProcessPath`. Other hosts omit it to keep the
|
The desktop host passes `appPath: Environment.ProcessPath`. Other hosts omit it to keep the
|
||||||
previous snapshot's desktop path. A missing path stays null in readers and writers (D9).
|
previous snapshot's desktop path. A missing path stays null in readers and writers (D9).
|
||||||
|
- Probes return a failed `ProbeResult` for process or protocol failures; shutdown cancellation
|
||||||
|
propagates. The background engine records other tick failures and retries without faulting its loop.
|
||||||
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
|
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
|
||||||
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
|
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
|
||||||
- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the
|
- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the
|
||||||
@@ -22,7 +24,7 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
|
|||||||
Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
|
Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
|
||||||
- `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with
|
- `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with
|
||||||
`CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7.
|
`CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7.
|
||||||
- W3 owns `StreamDeck/`: `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and its stub.
|
- `StreamDeck/` contains `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and platform deployment.
|
||||||
No shipped production dependency is needed in Core. Source parsers use temporary memory for one
|
No shipped production dependency is needed in Core. Source parsers use temporary memory for one
|
||||||
complete line; memory usage therefore scales with the largest transcript entry.
|
complete line; memory usage therefore scales with the largest transcript entry.
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ namespace FinalToken.Core;
|
|||||||
/// the earlier instant; midnight gaps start at the first valid local minute.</summary>
|
/// the earlier instant; midnight gaps start at the first valid local minute.</summary>
|
||||||
public static class CalendarDays
|
public static class CalendarDays
|
||||||
{
|
{
|
||||||
|
/// <summary>Start of a specified local calendar date; midnight gaps and overlaps follow the same policy as Start(instant).</summary>
|
||||||
|
public static DateTimeOffset Start(DateTime date, TimeZoneInfo? zone = null)
|
||||||
|
=> AtStart(DateTime.SpecifyKind(date.Date, DateTimeKind.Unspecified), zone ?? TimeZoneInfo.Local);
|
||||||
public static DateTimeOffset Start(DateTimeOffset instant, TimeZoneInfo? zone = null)
|
public static DateTimeOffset Start(DateTimeOffset instant, TimeZoneInfo? zone = null)
|
||||||
{
|
{
|
||||||
zone ??= TimeZoneInfo.Local;
|
zone ??= TimeZoneInfo.Local;
|
||||||
|
|||||||
@@ -24,7 +24,11 @@ public sealed class LimitProbe(IProcessRunner runner, DiagnosticLog diagnostics,
|
|||||||
diagnostics.Add(provider, "probe-no-limits", "No usable limit windows returned; CLI may be logged out.");
|
diagnostics.Add(provider, "probe-no-limits", "No usable limit windows returned; CLI may be logged out.");
|
||||||
return new(false, [], "No usable limits returned; CLI may be logged out.");
|
return new(false, [], "No usable limits returned; CLI may be logged out.");
|
||||||
}
|
}
|
||||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or InvalidOperationException)
|
catch (Exception) when (cancellationToken.IsCancellationRequested)
|
||||||
{ diagnostics.Add(provider, "probe-start", "CLI probe could not run."); return new(false, [], "CLI probe could not run."); }
|
{ throw new OperationCanceledException(cancellationToken); }
|
||||||
|
// D2: a provider's process/protocol failure must not interrupt the other provider.
|
||||||
|
// Exception messages can contain child output; expose only fixed metadata.
|
||||||
|
catch (Exception)
|
||||||
|
{ diagnostics.Add(provider, "probe-failed", "CLI probe could not complete."); return new(false, [], "CLI probe could not complete."); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -242,8 +242,8 @@ public sealed class HistoryStore
|
|||||||
var local = TimeZoneInfo.ConvertTime(now, zone);
|
var local = TimeZoneInfo.ConvertTime(now, zone);
|
||||||
var today = local.Date;
|
var today = local.Date;
|
||||||
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
|
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
|
||||||
var todayUtc = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(today, zone));
|
var todayUtc = CalendarDays.Start(today, zone);
|
||||||
var weekUtc = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(week, zone));
|
var weekUtc = CalendarDays.Start(week, zone);
|
||||||
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
|
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
|
||||||
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now));
|
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,15 @@ public static class CliDiscovery
|
|||||||
if (!File.Exists(path)) return new(null, "Configured CLI does not exist.");
|
if (!File.Exists(path)) return new(null, "Configured CLI does not exist.");
|
||||||
var directory = Path.GetDirectoryName(path)!;
|
var directory = Path.GetDirectoryName(path)!;
|
||||||
if (windows && Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) return new(new(path, []), null);
|
if (windows && Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) return new(new(path, []), null);
|
||||||
|
if (provider == Provider.Claude && windows)
|
||||||
|
{
|
||||||
|
var package = Path.Combine(directory, "node_modules", "@anthropic-ai", "claude-code");
|
||||||
|
// Current npm installs copy the platform binary here; older releases use cli.js.
|
||||||
|
var binary = Path.Combine(package, "bin", "claude.exe");
|
||||||
|
if (File.Exists(binary)) return new(new(binary, []), null);
|
||||||
|
var script = Path.Combine(package, "cli.js");
|
||||||
|
if (File.Exists(script) && FindNode(directory, searchPath, true) is { } node) return new(new(node, [script]), null);
|
||||||
|
}
|
||||||
if (provider == Provider.Codex)
|
if (provider == Provider.Codex)
|
||||||
{
|
{
|
||||||
var package = Path.Combine(directory, "node_modules", "@openai", "codex");
|
var package = Path.Combine(directory, "node_modules", "@openai", "codex");
|
||||||
|
|||||||
@@ -145,8 +145,10 @@ public sealed class RefreshEngine : IAsyncDisposable
|
|||||||
do
|
do
|
||||||
{
|
{
|
||||||
try { await TickAsync(token); }
|
try { await TickAsync(token); }
|
||||||
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||||
{ Diagnostics.Add(null, "refresh-write", "Refresh could not persist files."); }
|
// D6: isolate a failed tick, including a malformed stored partition, and retry.
|
||||||
|
catch (Exception)
|
||||||
|
{ Diagnostics.Add(null, "refresh-failed", "Refresh failed; the scheduler will retry."); }
|
||||||
} while (await timer.WaitForNextTickAsync(token));
|
} while (await timer.WaitForNextTickAsync(token));
|
||||||
}
|
}
|
||||||
private async Task<Snapshot> RefreshAsync(bool noProbe, CancellationToken token)
|
private async Task<Snapshot> RefreshAsync(bool noProbe, CancellationToken token)
|
||||||
|
|||||||
@@ -7,14 +7,6 @@ public interface IPluginInstaller
|
|||||||
Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default);
|
Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default);
|
||||||
Task InstallOrUpdateAsync(CancellationToken cancellationToken = default);
|
Task InstallOrUpdateAsync(CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
/// <summary>W3 replaces this with platform host detection and atomic plugin deployment (D11).</summary>
|
|
||||||
public sealed class StubPluginInstaller : IPluginInstaller
|
|
||||||
{
|
|
||||||
public Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default) =>
|
|
||||||
Task.FromResult(new PluginInstallStatus(PluginInstallState.NoHostFound));
|
|
||||||
public Task InstallOrUpdateAsync(CancellationToken cancellationToken = default) =>
|
|
||||||
Task.FromException(new InvalidOperationException("No Stream Deck host found."));
|
|
||||||
}
|
|
||||||
public enum InstallAction { Nothing, Ask, Install }
|
public enum InstallAction { Nothing, Ask, Install }
|
||||||
public static class InstallPolicy
|
public static class InstallPolicy
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ try
|
|||||||
do { updates.Writer.TryWrite(SnapshotFile.Read(DataPaths.DataDirectory)); }
|
do { updates.Writer.TryWrite(SnapshotFile.Read(DataPaths.DataDirectory)); }
|
||||||
while (await timer.WaitForNextTickAsync(stop.Token));
|
while (await timer.WaitForNextTickAsync(stop.Token));
|
||||||
});
|
});
|
||||||
var incoming = transport.ReceiveAsync(stop.Token);
|
var incoming = session.ReceiveAsync(stop.Token);
|
||||||
var update = updates.Reader.ReadAsync(stop.Token).AsTask();
|
var update = updates.Reader.ReadAsync(stop.Token).AsTask();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -34,7 +34,7 @@ try
|
|||||||
var json = await incoming;
|
var json = await incoming;
|
||||||
if (json is null) break;
|
if (json is null) break;
|
||||||
await session.HandleAsync(json, DateTimeOffset.UtcNow, stop.Token);
|
await session.HandleAsync(json, DateTimeOffset.UtcNow, stop.Token);
|
||||||
incoming = transport.ReceiveAsync(stop.Token);
|
incoming = session.ReceiveAsync(stop.Token);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -51,7 +51,7 @@ try
|
|||||||
}
|
}
|
||||||
if (socket.State == WebSocketState.CloseReceived)
|
if (socket.State == WebSocketState.CloseReceived)
|
||||||
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
|
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
|
||||||
await RollingLog.WriteAsync("host-closed");
|
await RollingLog.WriteAsync(session.ConnectionEndCode);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
catch (Exception e) when (e is WebSocketException or IOException or OperationCanceledException or UnauthorizedAccessException)
|
catch (Exception e) when (e is WebSocketException or IOException or OperationCanceledException or UnauthorizedAccessException)
|
||||||
|
|||||||
@@ -58,6 +58,12 @@ public sealed class PluginSocket(ClientWebSocket socket) : IPluginSocket
|
|||||||
|
|
||||||
public sealed class PluginSession(IPluginSocket socket, Func<string?, Task<bool>> launch)
|
public sealed class PluginSession(IPluginSocket socket, Func<string?, Task<bool>> launch)
|
||||||
{
|
{
|
||||||
|
public string ConnectionEndCode { get; private set; } = "host-closed";
|
||||||
|
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try { return await socket.ReceiveAsync(cancellationToken); }
|
||||||
|
catch (InvalidDataException) { ConnectionEndCode = "connection-ended"; return null; }
|
||||||
|
}
|
||||||
public const string Action = "de.finalfactory.finaltoken.stat";
|
public const string Action = "de.finalfactory.finaltoken.stat";
|
||||||
private readonly Dictionary<string, StatSettings> keys = [];
|
private readonly Dictionary<string, StatSettings> keys = [];
|
||||||
private readonly Dictionary<string, string> images = [];
|
private readonly Dictionary<string, string> images = [];
|
||||||
|
|||||||
@@ -2,6 +2,6 @@
|
|||||||
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||||
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
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
|
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
|
Skia and HarfBuzz, exercise settings and popup actions, and save PNG screenshots outside
|
||||||
the repo at ../runs/shots/w2. FINALTOKEN_SCREENSHOT_DIR overrides that path.
|
the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path.
|
||||||
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
|
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
|
||||||
|
|||||||
@@ -5,6 +5,24 @@ namespace FinalToken.App.Tests;
|
|||||||
|
|
||||||
public sealed class FormattingTests
|
public sealed class FormattingTests
|
||||||
{
|
{
|
||||||
|
[Fact]
|
||||||
|
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
|
||||||
|
{
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
|
||||||
|
var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone);
|
||||||
|
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
|
||||||
|
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("custom-config")]
|
||||||
|
public void LinuxAutostartHonorsConfigHome(string? configHome)
|
||||||
|
{
|
||||||
|
var home = Path.Combine(Path.GetTempPath(), "fixture-home");
|
||||||
|
var config = string.IsNullOrEmpty(configHome) ? null : Path.Combine(Path.GetTempPath(), configHome);
|
||||||
|
Assert.Equal(Path.Combine(config ?? Path.Combine(home, ".config"), "autostart", "finaltoken.desktop"), OsStartup.LinuxAutostartPath(config, home));
|
||||||
|
}
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("de-DE")]
|
[InlineData("de-DE")]
|
||||||
[InlineData("en-US")]
|
[InlineData("en-US")]
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public sealed class HeadlessTests
|
|||||||
AppBuilder.Configure<TestApplication>().UseSkia().UseHarfBuzz().UseHeadless(new() { UseHeadlessDrawing = false }).SetupWithoutStarting();
|
AppBuilder.Configure<TestApplication>().UseSkia().UseHarfBuzz().UseHeadless(new() { UseHeadlessDrawing = false }).SetupWithoutStarting();
|
||||||
var root = new DirectoryInfo(AppContext.BaseDirectory);
|
var root = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
while (root.Parent is not null && !File.Exists(Path.Combine(root.FullName, "FinalToken.slnx"))) root = root.Parent;
|
while (root.Parent is not null && !File.Exists(Path.Combine(root.FullName, "FinalToken.slnx"))) root = root.Parent;
|
||||||
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "w2");
|
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
|
||||||
Directory.CreateDirectory(shots);
|
Directory.CreateDirectory(shots);
|
||||||
var model = FakeData.Model();
|
var model = FakeData.Model();
|
||||||
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
|
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
|
||||||
@@ -86,7 +86,7 @@ public sealed class HeadlessTests
|
|||||||
using (chartWindow.CaptureRenderedFrame()) { }
|
using (chartWindow.CaptureRenderedFrame()) { }
|
||||||
chartWindow.MouseMove(new Point(65, 80));
|
chartWindow.MouseMove(new Point(65, 80));
|
||||||
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
|
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
|
||||||
var polishShots = Path.Combine(root.Parent!.FullName, "runs", "shots", "w1");
|
var polishShots = shots;
|
||||||
Directory.CreateDirectory(polishShots);
|
Directory.CreateDirectory(polishShots);
|
||||||
var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260,
|
var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260,
|
||||||
RequestedThemeVariant = ThemeVariant.Light };
|
RequestedThemeVariant = ThemeVariant.Light };
|
||||||
@@ -96,6 +96,13 @@ public sealed class HeadlessTests
|
|||||||
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
|
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
|
||||||
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
|
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
|
||||||
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
|
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
|
||||||
|
var day = new DateTimeOffset(2026, 10, 14, 0, 0, 0, TimeSpan.FromHours(2));
|
||||||
|
var daily = new UsageChart { Interval = TimeSpan.FromDays(1), Values = [new(day, "Claude", 3), new(day.AddDays(1), "Claude", 2)] };
|
||||||
|
var dailyWindow = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), daily)),
|
||||||
|
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
|
||||||
|
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
|
||||||
|
dailyWindow.MouseMove(new Point(90, 150));
|
||||||
|
Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
|
||||||
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
|
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
|
||||||
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
|
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
|
||||||
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
|
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
|
||||||
|
|||||||
@@ -6,6 +6,19 @@ namespace FinalToken.Cli.Tests;
|
|||||||
|
|
||||||
public class CliTests
|
public class CliTests
|
||||||
{
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task UnexpectedRefreshFailureReturnsOneWithoutExceptionText()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var output = new StringWriter(); using var error = new StringWriter();
|
||||||
|
Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory,
|
||||||
|
_ => throw new System.Text.Json.JsonException("synthetic private input"), TestContext.Current.CancellationToken));
|
||||||
|
Assert.Contains("could not complete", error.ToString()); Assert.DoesNotContain("synthetic private", error.ToString());
|
||||||
|
}
|
||||||
|
finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("")]
|
[InlineData("")]
|
||||||
[InlineData("unknown")]
|
[InlineData("unknown")]
|
||||||
|
|||||||
@@ -6,6 +6,22 @@ namespace FinalToken.Core.Tests;
|
|||||||
|
|
||||||
public class DiscoveryAndPolicyTests
|
public class DiscoveryAndPolicyTests
|
||||||
{
|
{
|
||||||
|
[Fact]
|
||||||
|
public void WindowsClaudeNpmShimResolvesInstalledNativeBinary()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture");
|
||||||
|
var binary = directory.Write("node_modules/@anthropic-ai/claude-code/bin/claude.exe", "fixture native");
|
||||||
|
Assert.Equal(binary, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command?.FileName);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void WindowsClaudeNpmShimFallsBackToLegacyCliScriptWithoutShell()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture");
|
||||||
|
var script = directory.Write("node_modules/@anthropic-ai/claude-code/cli.js", "fixture script");
|
||||||
|
var node = directory.Write("node.exe", "fixture node");
|
||||||
|
var command = CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command;
|
||||||
|
Assert.NotNull(command); Assert.Equal(node, command.FileName); Assert.Equal([script], command.PrefixArguments);
|
||||||
|
}
|
||||||
[Fact]
|
[Fact]
|
||||||
public void FindsNativeWindowsAndHonorsOverride()
|
public void FindsNativeWindowsAndHonorsOverride()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading.Channels;
|
||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using FinalToken.Core.Processes;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public sealed class ReviewRegressionTests
|
||||||
|
{
|
||||||
|
private static CliCommand Child(string mode) => new(Path.Combine(AppContext.BaseDirectory, "ProcessHost",
|
||||||
|
OperatingSystem.IsWindows() ? "FinalToken.ProcessHost.exe" : "FinalToken.ProcessHost"), [mode]);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--rpc-success", true)]
|
||||||
|
[InlineData("--rpc-error", false)]
|
||||||
|
[InlineData("--rpc-init-error", false)]
|
||||||
|
[InlineData("--rpc-eof", false)]
|
||||||
|
[InlineData("--rpc-garbage", false)]
|
||||||
|
[InlineData("--rpc-shape", false)]
|
||||||
|
[InlineData("--rpc-bound", false)]
|
||||||
|
public async Task RpcChildFailuresBecomeFailedProbes(string mode, bool success)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
var probe = new LimitProbe(new ProcessRunner(), log, directory.Path);
|
||||||
|
var result = await probe.RunAsync(Provider.Codex, Child(mode), new TestClock().GetUtcNow(), TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(success, result.Success);
|
||||||
|
if (!success) { Assert.Empty(result.Windows); Assert.NotNull(result.Reason); Assert.NotEmpty(log.Recent); }
|
||||||
|
else Assert.Single(result.Windows);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--rpc-error", false)]
|
||||||
|
[InlineData("--rpc-eof", false)]
|
||||||
|
[InlineData("--rpc-garbage", false)]
|
||||||
|
[InlineData("--rpc-error", true)]
|
||||||
|
public async Task EngineKeepsUpdatingClaudeWhenCodexFails(string mode, bool fallback)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner { Handler = (request, token) => request.CodexRpc
|
||||||
|
? new ProcessRunner().RunAsync(request, token) : Task.FromResult(new ProcessResult(0, Fixtures.ClaudeEnvelope)) };
|
||||||
|
if (fallback) directory.Write("codex/sessions/rollout-fixture.jsonl", Fixtures.Meta + Fixtures.Codex(10));
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, clock, runner, Path.Combine(directory.Path, "claude"),
|
||||||
|
Path.Combine(directory.Path, "codex"), (provider, _) => new(provider == Provider.Codex ? Child(mode) : new("fixture", []), null));
|
||||||
|
var snapshots = Channel.CreateUnbounded<Snapshot>(); engine.SnapshotChanged += value => snapshots.Writer.TryWrite(value);
|
||||||
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||||
|
deadline.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
await engine.StartAsync(deadline.Token);
|
||||||
|
var initial = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
var first = initial.Providers.Single(p => p.Provider == Provider.Claude).Windows[0].Window.SampleTime;
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
var snapshot = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
var claude = snapshot.Providers.Single(p => p.Provider == Provider.Claude);
|
||||||
|
Assert.Equal(ProviderStatus.Available, claude.Status); Assert.True(claude.Windows[0].Window.SampleTime > first);
|
||||||
|
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
|
||||||
|
Assert.Equal(fallback ? ProviderStatus.Available : ProviderStatus.Unavailable, codex.Status);
|
||||||
|
if (fallback) Assert.Contains("rollout", codex.Reason); else Assert.Empty(codex.Windows);
|
||||||
|
await engine.StopAsync();
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task BackgroundLoopRecoversAfterCorruptMonthAndStopsCleanly()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var bad = directory.Write("history/2026-10.json", "{");
|
||||||
|
var clock = new TestClock();
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, clock, new FakeRunner(), directory.Path, directory.Path, (_, _) => new(new("fixture", []), null));
|
||||||
|
var snapshots = Channel.CreateUnbounded<Snapshot>();
|
||||||
|
engine.SnapshotChanged += value => snapshots.Writer.TryWrite(value);
|
||||||
|
await engine.StartAsync(TestContext.Current.CancellationToken);
|
||||||
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||||
|
deadline.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
while (!engine.RecentDiagnostics.Any(d => d.Code == "refresh-failed")) await Task.Delay(10, deadline.Token);
|
||||||
|
await File.WriteAllTextAsync(bad, "{\"v\":1,\"buckets\":[],\"limits\":[]}", deadline.Token);
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(1));
|
||||||
|
var first = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
var second = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
Assert.True(second.MadeAt > first.MadeAt);
|
||||||
|
await engine.StopAsync();
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ProbeDoesNotSwallowShutdownCancellation()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
using var stop = new CancellationTokenSource(); stop.Cancel();
|
||||||
|
var runner = new FakeRunner { Handler = (_, token) => Task.FromCanceled<ProcessResult>(token) };
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new LimitProbe(runner, new(), directory.Path)
|
||||||
|
.RunAsync(Provider.Codex, Child("--rpc-error"), DateTimeOffset.UtcNow, stop.Token));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ShutdownWinsWhenAProcessFailureRacesCancellation()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
using var stop = new CancellationTokenSource();
|
||||||
|
var runner = new FakeRunner { Handler = (_, _) => { stop.Cancel(); throw new InvalidDataException("synthetic failure during shutdown"); } };
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new LimitProbe(runner, new(), directory.Path)
|
||||||
|
.RunAsync(Provider.Codex, Child("--rpc-error"), DateTimeOffset.UtcNow, stop.Token));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Africa/Cairo", "2026-04-24")]
|
||||||
|
[InlineData("America/Santiago", "2026-09-06")]
|
||||||
|
[InlineData("Asia/Beirut", "2026-03-29")]
|
||||||
|
public void TotalsSurviveMissingLocalMidnight(string zoneId, string dateText)
|
||||||
|
{
|
||||||
|
var zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
|
||||||
|
var date = DateTime.ParseExact(dateText, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
Assert.True(zone.IsInvalidTime(date));
|
||||||
|
VerifyTotals(zone, date);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void WeekCanStartOnAMondayWithNoMidnight()
|
||||||
|
{
|
||||||
|
var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new(2026, 1, 1), new(2026, 12, 31), TimeSpan.FromHours(1),
|
||||||
|
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new(1, 1, 1), 3, 30),
|
||||||
|
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new(1, 1, 1), 10, 1));
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("Monday gap", TimeSpan.Zero, "Monday gap", "standard", "summer", [rule]);
|
||||||
|
VerifyTotals(zone, new(2026, 3, 30));
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var monday = new DateTimeOffset(2026, 3, 30, 1, 0, 0, TimeSpan.FromHours(1));
|
||||||
|
store.Add(new(Provider.Codex, monday.AddHours(-1), null, null, new(Total: 7), "before-week"));
|
||||||
|
store.Add(new(Provider.Codex, monday, null, null, new(Total: 11), "in-week"));
|
||||||
|
var wednesday = new DateTimeOffset(2026, 4, 1, 12, 0, 0, TimeSpan.FromHours(1));
|
||||||
|
store.Add(new(Provider.Codex, wednesday.AddHours(-1), null, null, new(Total: 13), "today"));
|
||||||
|
var totals = store.Totals(Provider.Codex, wednesday, null, zone);
|
||||||
|
Assert.Equal(13, totals.Today.Total); Assert.Equal(24, totals.Week.Total);
|
||||||
|
}
|
||||||
|
private static void VerifyTotals(TimeZoneInfo zone, DateTime date)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var first = new DateTimeOffset(date.AddHours(1), zone.GetUtcOffset(date.AddHours(1)));
|
||||||
|
var now = first.AddHours(10);
|
||||||
|
store.Add(new(Provider.Codex, first.AddHours(-1), null, null, new(Total: 7), "before"));
|
||||||
|
store.Add(new(Provider.Codex, first, null, null, new(Total: 11), "inside"));
|
||||||
|
var totals = store.Totals(Provider.Codex, now, null, zone);
|
||||||
|
Assert.Equal(11, totals.Today.Total);
|
||||||
|
Assert.Equal(date.DayOfWeek == DayOfWeek.Monday ? 11 : 18, totals.Week.Total);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,3 +4,5 @@ handles, then runs Core's ProcessRunner. Child modes check handles and synthetic
|
|||||||
live Claude mode keeps provider output in memory and writes only diagnostic metadata.
|
live Claude mode keeps provider output in memory and writes only diagnostic metadata.
|
||||||
No provider text or real transcript fixtures belong here. JSON uses source generation.
|
No provider text or real transcript fixtures belong here. JSON uses source generation.
|
||||||
Built with Core tests; run `dotnet test --project tests/FinalToken.Core.Tests -c Release`.
|
Built with Core tests; run `dotnet test --project tests/FinalToken.Core.Tests -c Release`.
|
||||||
|
Portable `--rpc-*` modes provide synthetic app-server exchanges, errors, EOF and malformed output.
|
||||||
|
The `app-server` mode returns an RPC error for published-CLI checks; it never contacts a provider.
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ public static class Program
|
|||||||
{
|
{
|
||||||
public static async Task<int> Main(string[] args)
|
public static async Task<int> Main(string[] args)
|
||||||
{
|
{
|
||||||
|
if (args.FirstOrDefault() is { } mode && (mode.StartsWith("--rpc-", StringComparison.Ordinal) || mode == "app-server"))
|
||||||
|
return await RpcAsync(mode == "app-server" ? "--rpc-error" : mode);
|
||||||
if (!OperatingSystem.IsWindows()) return 0;
|
if (!OperatingSystem.IsWindows()) return 0;
|
||||||
if (args is ["--handles"])
|
if (args is ["--handles"])
|
||||||
return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17;
|
return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17;
|
||||||
@@ -42,6 +44,32 @@ public static class Program
|
|||||||
await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport));
|
await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport));
|
||||||
return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode;
|
return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode;
|
||||||
}
|
}
|
||||||
|
private static async Task<int> RpcAsync(string mode)
|
||||||
|
{
|
||||||
|
Console.InputEncoding = System.Text.Encoding.UTF8;
|
||||||
|
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
|
||||||
|
if (mode == "--rpc-eof") return 0;
|
||||||
|
var initialize = await Console.In.ReadLineAsync();
|
||||||
|
using var first = JsonDocument.Parse(initialize ?? "null");
|
||||||
|
if (first.RootElement.GetProperty("method").GetString() != "initialize") return 20;
|
||||||
|
if (mode == "--rpc-init-error") { await Console.Out.WriteLineAsync("{\"id\":1,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}"); return 0; }
|
||||||
|
await Console.Out.WriteLineAsync("{\"id\":1,\"result\":{}}");
|
||||||
|
using var initialized = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
|
||||||
|
using var request = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
|
||||||
|
if (initialized.RootElement.GetProperty("method").GetString() != "initialized" ||
|
||||||
|
request.RootElement.GetProperty("method").GetString() != "account/rateLimits/read") return 21;
|
||||||
|
await Console.Out.WriteLineAsync("{\"method\":\"syntheticNotification\"}");
|
||||||
|
var response = mode switch
|
||||||
|
{
|
||||||
|
"--rpc-error" => "{\"id\":2,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}",
|
||||||
|
"--rpc-garbage" => "not JSON",
|
||||||
|
"--rpc-shape" => "[]",
|
||||||
|
"--rpc-bound" => new string('x', 1024 * 1024 + 1),
|
||||||
|
_ => "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531}}}}"
|
||||||
|
};
|
||||||
|
await Console.Out.WriteLineAsync(response);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed record ProbeReport
|
public sealed record ProbeReport
|
||||||
|
|||||||
@@ -7,6 +7,14 @@ namespace FinalToken.StreamDeck.Tests;
|
|||||||
|
|
||||||
public sealed class PluginTests
|
public sealed class PluginTests
|
||||||
{
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task InvalidHostFrameEndsConnectionWithoutLoggingFrameText()
|
||||||
|
{
|
||||||
|
var socket = new FakeSocket { ReceiveFailure = new InvalidDataException("synthetic private frame") };
|
||||||
|
var session = new PluginSession(socket, _ => Task.FromResult(false));
|
||||||
|
Assert.Null(await session.ReceiveAsync(TestContext.Current.CancellationToken));
|
||||||
|
Assert.Equal("connection-ended", session.ConnectionEndCode);
|
||||||
|
}
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("{}", "Claude", "SessionPercent", "")]
|
[InlineData("{}", "Claude", "SessionPercent", "")]
|
||||||
[InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")]
|
[InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")]
|
||||||
@@ -146,9 +154,11 @@ public sealed class PluginTests
|
|||||||
}
|
}
|
||||||
private sealed class FakeSocket : IPluginSocket
|
private sealed class FakeSocket : IPluginSocket
|
||||||
{
|
{
|
||||||
|
public Exception? ReceiveFailure { get; init; }
|
||||||
public List<string> Sent { get; } = [];
|
public List<string> Sent { get; } = [];
|
||||||
public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; }
|
public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; }
|
||||||
public Task<string?> ReceiveAsync(CancellationToken cancellationToken) => Task.FromResult<string?>(null);
|
public Task<string?> ReceiveAsync(CancellationToken cancellationToken) => ReceiveFailure is { } error
|
||||||
|
? Task.FromException<string?>(error) : Task.FromResult<string?>(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user