
Building a Custom Dashboard Plugin for the Mars Gaming MSD-ONE
Build an MSD-ONE dashboard for Codex usage limits, dev-server ports and disk space, with C# source, Windows setup and troubleshooting.
I bought a Mars Gaming MSD-ONE for its customizable LCD keys. Its side monitoring screen became the more useful part: a dashboard for remaining Codex allowance, running development servers and free disk space.
I built Vercetti HUD, one Windows plugin with three actions. It collects the readings, draws them over animated artwork and sends the images to the deck. The MSD desktop application holds the details: allowance windows, reset dates and clickable server addresses. Below are the source, setup steps and the decisions behind the three widgets.
- Requirements and installation
- How the widgets collect and display data
- Customization and source
- Troubleshooting and validation
Three readings I wanted to trust
A number beside your keyboard becomes easy to trust. That makes its meaning and age part of the interface: a quota needs an identified window, an old reading needs to look old, and a server returning an error still exists. Most of the implementation work is deciding what an unavailable, old or ambiguous reading should mean.
Codex allowance is the check I want to make without leaving my task. Development servers are the things I forget: an agent starts a preview for a test, finishes its work and leaves the process running. Closing its browser tab does not stop it. The count gives me a reason to inspect the address list, a practical consequence of giving coding agents shell tools.
Disk space is the other constraint I keep encountering. Dependencies, build outputs, browser tooling and session data compete for the same drive. The widget makes the remaining capacity visible; investigating which shared resource is becoming the bottleneck is the next step when that number falls.
Requirements and installation
The MSD-ONE has 15 LCD keys and an extended side monitoring screen. Mars supplies the application that drives them; it needs to remain running in the background. Product and software downloads, manufacturer’s manual.
Here is the environment used for the October 27 checks:
| Component | Tested environment |
|---|---|
| Windows | Windows 11 Pro 25H2, x64; build 26200.9711 |
| Codex selected by the quota reader | codex-cli 0.160.0 |
| MARS GAMING MSD | 3.10.192.0530 |
| Vercetti HUD | Installed/screenshots: 1.0.3; downloadable source/build: 1.0.4 |
| .NET Framework | Installed: 4.8.1; plugin target: 4.8; compiler: 4.8.9221.0 |
The manifest requires Windows 10 or later and MSD software 3.10.188.226 or later. For the quota action, Codex must already be signed in. The executable locator prefers a running same-user Codex process, so the version selected can differ from the one bundled with the desktop application.
1. Download and build
Download the complete source ZIP · SHA-256 checksum
The archive includes the C# implementation, manifest, HTML inspector, artwork, build script and tests. Release changes and packaging details are in the README.
Install the MSD-ONE software, connect the deck directly by USB as the manual recommends, and confirm that it appears in the application. Extract the source into a writable folder such as C:\dev\vercetti-hud. From that folder, using PowerShell 5.1 or later:
.\build.ps1 -Destination '.\build\com.criticaldeveloper.vercetti-hud.sdPlugin'
& '.\build\com.criticaldeveloper.vercetti-hud.sdPlugin\CriticalHud-1.0.4.exe' --self-test |
Out-String
The script uses %SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\csc.exe, then assembles the complete .sdPlugin folder. The self-test should report ok: true and frames: 24, confirming that the packaged drawings load and the display rules pass.
If PowerShell blocks build.ps1, check Get-ExecutionPolicy -List. Restricted prevents scripts; RemoteSigned can block an unsigned downloaded script carrying an internet mark. After reviewing the extracted script, Unblock-File -LiteralPath .\build.ps1 removes that file’s mark without changing policy. Under Restricted or an organizational policy, follow the administrator’s approved script-running procedure. Execution policies, Unblock-File.
2. Install the complete plugin folder
Quit MSD fully, including its tray process. Its user plugin directory on this setup is %APPDATA%\HotSpot\StreamDock\plugins. Copy the build there with an existing-installation guard:
$pluginRoot = Join-Path $env:APPDATA 'HotSpot\StreamDock\plugins'
$pluginName = 'com.criticaldeveloper.vercetti-hud.sdPlugin'
$pluginTarget = Join-Path $pluginRoot $pluginName
if (Test-Path -LiteralPath $pluginTarget) {
throw 'Vercetti HUD already exists. Back up and review that installation first.'
}
New-Item -ItemType Directory -Path $pluginRoot -Force | Out-Null
Copy-Item -LiteralPath (Join-Path '.\build' $pluginName) -Destination $pluginRoot -Recurse
Keep all generated files together, including the versioned executable named by the manifest. For an update, back up the existing plugin outside the scanned directory and replace it while MSD is stopped. SDK installation guide.
3. Assign the three widgets
Reopen MSD, choose Panel in the right-hand action library, expand Vercetti HUD, then drag Codex quota, Live dev servers and C: free space into the top, middle and bottom side slots.
Select a placed widget to open its inspector. Scroll inside the pane to reach Animate artwork, Refresh now and the quota widget’s Rotate quota windows. Disabling animation leaves the readings updating. The side slots are display-only; assigning an action to a regular key also lets its release request a refresh.
Compare the quota window with Codex, start one known development server and check its port, then stop it from its terminal and watch the count fall. Compare disk space against the same drive in Windows.
How the plugin collects and displays data
The implementation builds with the .NET Framework C# compiler and framework assemblies, without a package restore. Keeping collection and drawing in one Windows executable avoids a separate collector service. The tradeoff is a Windows-specific implementation using WMI, TCP tables and System.Drawing.
The host follows the StreamDock SDK conventions: a .sdPlugin folder, a manifest defining three action UUIDs and an HTML property inspector. Each action supports Information for the side slots and Keypad for regular keys. SDK repository, manifest reference.
The core flow is collector → snapshot/status → rendered PNG → action context:
| Source file | Responsibility |
|---|---|
PluginHost.cs | SDK connection, visible contexts, scheduling and image delivery |
CodexQuota.cs | Codex discovery and allowance queries |
LocalMetrics.cs | Development endpoints and drive space |
WidgetRenderer.cs | Artwork, values, countdowns and warning/stale presentation |
MSD launches the executable with a local WebSocket port and registration identifiers. After registration at ws://127.0.0.1:<provided-port>, each willAppear event supplies an action context. The plugin addresses subsequent images to that context. The HTML inspector registers independently through connectElgatoStreamDeckSocket. Registration procedure.
An image update has this shape:
{
"event": "setImage",
"context": "host-supplied-action-context",
"payload": {
"image": "data:image/png;base64,<rendered-image>",
"target": 0
}
}
target: 0 updates both the software preview and hardware. The plugin composes the reading into a 144×144 PNG before sending it. Image update reference.
| Collector | Refresh while visible and connected |
|---|---|
| Codex allowance | 120 seconds |
| Development endpoints | 5 seconds |
| C: available space | 15 seconds |
Animation advances separately at four frames per second, and unchanged images are cached. Failed collection preserves the last successful value with a stale state; a missing reading gets UNKNOWN. The renderer also checks the snapshot’s age.
Reconnect handling belongs to the same problem. On deviceDidDisconnect, the plugin retains and pauses the known contexts. On a matching reconnect, it refreshes collection and invalidates cached images, so the device repaints even without another willAppear. A normal profile/page disappearance removes its hidden actions.
Codex usage: identify the allowance window
The reader locates a running same-user codex process, falling back to %LOCALAPPDATA%\OpenAI\Codex\bin and its immediate version directories. It starts an owned temporary process:
codex.exe app-server --listen stdio://
It initializes the connection, calls account/read with refreshToken: false, then account/rateLimits/read. Codex handles the existing sign-in; the HUD queries allowance and cleans up its own reader process.
The response describes usage through usedPercent, the window length through windowDurationMins, and reset time through Unix-second resetsAt. rateLimitsByLimitId can contain several buckets, identified by limitId, with an optional limitName. Official rate-limit documentation.
remainingPercent = 100 - clamp(usedPercent, 0, 100)
The default selector compares valid primary/secondary windows across all returned buckets, choosing the highest used percentage; a tie favors the shorter duration. The 1.0.4 inspector labels each window with its bucket ID, such as codex · Weekly. The LCD keeps its short duration label, so use the inspector’s ID when several buckets are returned. Rotate quota windows cycles through the available windows every five seconds.
On the LCD, 7D · RESET 3D means a seven-day allowance window resetting in three days, rounded upward. This is usage allowance rather than subscription renewal or a prediction of remaining prompts. The inspector holds the exact local reset date.
Missing sign-in produces LOGIN. A failed refresh or an expired nonzero usage window is marked stale, so yesterday’s percentage cannot silently present itself as today’s allowance.
Dev servers: a live endpoint can still return an error
The detector joins Windows TCP listeners from GetExtendedTcpTable to WMI process information. Runtime/framework commands, project paths and supported Docker/WSL forwarders identify candidates; helper services and debugger ports are excluded. It confirms candidates with credential-free loopback HTTP/HTTPS HEAD / requests.
The count represents PID/port endpoints. One process listening on two ports can count twice; duplicate IPv4/IPv6 entries for the same PID/port count once. Any HTTP response, including 405 or 500, means the endpoint exists. That distinction matters when looking for a forgotten server.
Detection remains heuristic: custom services may be missed, and another matching service may appear. The project-name rule recognizes C:\dev\<project>; adapt it in LocalMetrics.cs for another root. Probes stop at response headers, do not follow redirects, and accept self-signed HTTPS only for their individual literal-loopback checks.
While preparing this guide, I started the blog preview and watched the inspector add criticaldeveloper-blog · :4321. That established the useful path from a running process to a visible endpoint. The widget cannot identify whether an AI or I started it.
The inspector lists and opens servers; it has no Stop control. Use Ctrl+C in the originating terminal. If that terminal is unavailable, identify the current port owner before ending the intended process in Task Manager:
$listeners = Get-NetTCPConnection -State Listen -LocalPort 4321 -ErrorAction SilentlyContinue
$listeners.OwningProcess | Sort-Object -Unique | ForEach-Object {
Get-Process -Id $_ -ErrorAction SilentlyContinue |
Select-Object Id, ProcessName, Path
}
Free disk space and low-space warnings
The disk action reads DriveInfo.AvailableFreeSpace and TotalSize for C:\. Available space is quota-aware: it represents what the current user can use. Microsoft API reference.
Version 1.0.4 labels the display GiB, matching its division by 1,073,741,824 bytes. The photograph’s earlier GB label used the same calculation.
Amber means below 20 GiB or 10% free; red means below 5 GiB or 5% free, taking priority. Defaults live in WidgetSettings. To monitor another volume, change the drive in LocalMetrics.cs and update its labels. The inspector currently exposes refresh and animation settings.
Customize the artwork or add a metric
Each action has eight 144×144 PNG frames, frame-00.png through frame-07.png, under assets/quota, assets/servers or assets/disk. Playback runs forward and back:
0 1 2 3 4 5 6 7 6 5 4 3 2 1
At 250 milliseconds per frame, the loop lasts 3.5 seconds. The prepared images come from cropped and scaled Vercetti’s Tales artwork. System.Drawing adds the current title, value and detail line. Keep the lower area dark so the reading survives your choice of theme.
Replace the frames and library icons, preserve their dimensions/paths, rebuild and restart MSD. The manufacturer’s 126×126 recommendation concerns ordinary imported key pictures; these renderer assets use 144×144.
For another metric, add its collector and snapshot state, map a unique action UUID in the manifest/host/inspector, then implement the renderer description. Decide how it presents missing and stale data before styling the successful value.
Browse the implementation below or use the complete ZIP:
Source files
5 filesCodexQuota.cs
Codex discovery and account allowance reader
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace CriticalHud
{
public sealed class QuotaSnapshot
{
public string Status { get; set; }
public DateTime UpdatedAt { get; set; }
public List<QuotaWindow> Windows { get; set; }
public QuotaSnapshot()
{
Status = "unavailable";
UpdatedAt = DateTime.UtcNow;
Windows = new List<QuotaWindow>();
}
}
public sealed class QuotaWindow
{
public string Bucket { get; set; }
public string Label { get; set; }
public double UsedPercent { get; set; }
public int WindowMinutes { get; set; }
public DateTime ResetsAt { get; set; }
}
// The owned stdio server is used only for account reads. Raw protocol and
// account responses never leave this class or enter application logs.
public sealed class CodexQuotaReader : IDisposable
{
private const int TimeoutMilliseconds = 18000;
private const int MaximumMessageCharacters = 1024 * 1024;
private readonly string executableOverride;
private readonly SemaphoreSlim gate = new SemaphoreSlim(1, 1);
private readonly CancellationTokenSource lifetime = new CancellationTokenSource();
private int disposed;
public CodexQuotaReader() : this(null) { }
public CodexQuotaReader(string executablePath)
{
executableOverride = executablePath == null ? null : ValidateExecutable(executablePath);
}
public async Task<QuotaSnapshot> ReadAsync(CancellationToken cancellationToken)
{
if (Volatile.Read(ref disposed) != 0)
return Unavailable();
using (CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lifetime.Token))
{
deadline.CancelAfter(TimeoutMilliseconds);
bool entered = false;
try
{
await gate.WaitAsync(deadline.Token).ConfigureAwait(false);
entered = true;
return await ReadOwnedServerAsync(deadline.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) { return Unavailable(); }
catch (Exception) { return Unavailable(); }
finally { if (entered) gate.Release(); }
}
}
private async Task<QuotaSnapshot> ReadOwnedServerAsync(CancellationToken cancellationToken)
{
string executable = executableOverride ?? FindExecutable();
if (executable == null) return Unavailable();
ProcessStartInfo start = new ProcessStartInfo(executable, "app-server --listen stdio://");
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.WindowStyle = ProcessWindowStyle.Hidden;
start.RedirectStandardInput = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.StandardOutputEncoding = Encoding.UTF8;
start.StandardErrorEncoding = Encoding.UTF8;
start.WorkingDirectory = Path.GetDirectoryName(executable);
using (Process process = new Process())
using (OwnedJob job = new OwnedJob())
{
process.StartInfo = start;
if (!process.Start()) return Unavailable();
Task stderrDrain = DiscardStderrAsync(process.StandardError);
try
{
// Fail closed if Windows cannot contain this newly owned server.
if (!job.Assign(process)) return Unavailable();
JavaScriptSerializer serializer = NewSerializer();
await SendAsync(process, serializer, new Dictionary<string, object> {
{ "id", 1 }, { "method", "initialize" },
{ "params", new Dictionary<string, object> {
{ "clientInfo", new Dictionary<string, object> {
{ "name", "critical_hud" }, { "title", "Critical HUD" }, { "version", "1.0.0" }
} }
} }
}, cancellationToken).ConfigureAwait(false);
await ReceiveResultAsync(process.StandardOutput, serializer, 1, cancellationToken).ConfigureAwait(false);
await SendAsync(process, serializer, new Dictionary<string, object> {
{ "method", "initialized" }, { "params", new Dictionary<string, object>() }
}, cancellationToken).ConfigureAwait(false);
await SendAsync(process, serializer, new Dictionary<string, object> {
{ "id", 2 }, { "method", "account/read" },
{ "params", new Dictionary<string, object> { { "refreshToken", false } } }
}, cancellationToken).ConfigureAwait(false);
Dictionary<string, object> accountResult = await ReceiveResultAsync(process.StandardOutput, serializer, 2, cancellationToken).ConfigureAwait(false);
Dictionary<string, object> account = ObjectAt(accountResult, "account");
if (account == null) return Unavailable("login-required");
string accountType = StringAt(account, "type");
if (accountType != "chatgpt" && accountType != "chatgptAuthTokens") return Unavailable();
await SendAsync(process, serializer, new Dictionary<string, object> {
{ "id", 3 }, { "method", "account/rateLimits/read" }, { "params", new Dictionary<string, object>() }
}, cancellationToken).ConfigureAwait(false);
Dictionary<string, object> quota = await ReceiveResultAsync(process.StandardOutput, serializer, 3, cancellationToken).ConfigureAwait(false);
return ParseRateLimits(quota, DateTime.UtcNow);
}
finally
{
try { process.StandardInput.Close(); } catch (Exception) { }
try { if (!process.WaitForExit(300)) process.Kill(); } catch (Exception) { }
// Closing the job also stops only children created by this query.
job.Dispose();
try { stderrDrain.Wait(200); } catch (Exception) { }
}
}
}
private static async Task SendAsync(Process process, JavaScriptSerializer serializer, Dictionary<string, object> message, CancellationToken token)
{
token.ThrowIfCancellationRequested();
await WithCancellation(process.StandardInput.WriteLineAsync(serializer.Serialize(message)), token).ConfigureAwait(false);
await WithCancellation(process.StandardInput.FlushAsync(), token).ConfigureAwait(false);
}
private static async Task<Dictionary<string, object>> ReceiveResultAsync(StreamReader reader, JavaScriptSerializer serializer, int expectedId, CancellationToken token)
{
for (int messages = 0; messages < 128; messages++)
{
string line = await WithCancellation(ReadBoundedLineAsync(reader), token).ConfigureAwait(false);
if (line == null) throw new IOException();
Dictionary<string, object> response = serializer.DeserializeObject(line) as Dictionary<string, object>;
if (response == null) continue;
object id;
double numericId;
if (!response.TryGetValue("id", out id) || !TryNumber(id, out numericId) || numericId != expectedId) continue;
if (response.ContainsKey("error")) throw new IOException();
Dictionary<string, object> result = ObjectAt(response, "result");
if (result == null) throw new IOException();
return result;
}
throw new IOException();
}
private static async Task<string> ReadBoundedLineAsync(StreamReader reader)
{
StringBuilder line = new StringBuilder();
char[] character = new char[1];
while (line.Length <= MaximumMessageCharacters)
{
int count = await reader.ReadAsync(character, 0, 1).ConfigureAwait(false);
if (count == 0) return line.Length == 0 ? null : line.ToString();
if (character[0] == '\n') return line.ToString();
if (character[0] != '\r') line.Append(character[0]);
}
throw new IOException();
}
private static async Task DiscardStderrAsync(StreamReader reader)
{
char[] buffer = new char[4096];
try { while (await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false) != 0) { } }
catch (Exception) { }
}
private static async Task WithCancellation(Task task, CancellationToken token)
{
TaskCompletionSource<bool> cancelled = new TaskCompletionSource<bool>();
using (token.Register(delegate { cancelled.TrySetResult(true); }))
{
if (await Task.WhenAny(task, cancelled.Task).ConfigureAwait(false) != task)
{
ObserveAbandonedTask(task);
throw new OperationCanceledException(token);
}
await task.ConfigureAwait(false);
}
}
private static async Task<T> WithCancellation<T>(Task<T> task, CancellationToken token)
{
TaskCompletionSource<bool> cancelled = new TaskCompletionSource<bool>();
using (token.Register(delegate { cancelled.TrySetResult(true); }))
{
if (await Task.WhenAny(task, cancelled.Task).ConfigureAwait(false) != task)
{
ObserveAbandonedTask(task);
throw new OperationCanceledException(token);
}
return await task.ConfigureAwait(false);
}
}
private static void ObserveAbandonedTask(Task task)
{
task.ContinueWith(delegate(Task failed) { var ignored = failed.Exception; },
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
internal static QuotaSnapshot ParseRateLimitsJson(string json)
{
try
{
Dictionary<string, object> parsed = NewSerializer().DeserializeObject(json) as Dictionary<string, object>;
if (parsed == null || parsed.ContainsKey("error")) return Unavailable();
Dictionary<string, object> result = ObjectAt(parsed, "result") ?? parsed;
return ParseRateLimits(result, DateTime.UtcNow);
}
catch (Exception) { return Unavailable(); }
}
private static QuotaSnapshot ParseRateLimits(Dictionary<string, object> result, DateTime updatedAt)
{
QuotaSnapshot snapshot = new QuotaSnapshot { UpdatedAt = updatedAt };
Dictionary<string, object> buckets = ObjectAt(result, "rateLimitsByLimitId");
if (buckets != null && buckets.Count > 0)
{
foreach (string key in buckets.Keys.OrderBy(x => x, StringComparer.Ordinal).Take(32))
{
Dictionary<string, object> bucket = buckets[key] as Dictionary<string, object>;
if (bucket != null) AddBucket(snapshot.Windows, bucket, key);
}
}
else
{
Dictionary<string, object> bucket = ObjectAt(result, "rateLimits");
if (bucket != null) AddBucket(snapshot.Windows, bucket, "codex");
}
snapshot.Status = snapshot.Windows.Count > 0 ? "ready" : "unavailable";
return snapshot;
}
private static void AddBucket(List<QuotaWindow> windows, Dictionary<string, object> bucket, string fallback)
{
string id = StringAt(bucket, "limitId") ?? fallback;
if (!Regex.IsMatch(id, "^[a-zA-Z0-9_-]{1,80}$")) return;
foreach (string name in new[] { "primary", "secondary" })
{
Dictionary<string, object> window = ObjectAt(bucket, name);
if (window == null) continue;
double used, minutes, resets;
if (!NumberAt(window, "usedPercent", out used) || used < 0 || used > 100 ||
!NumberAt(window, "windowDurationMins", out minutes) || minutes < 1 || minutes > 5256000 || minutes != Math.Floor(minutes) ||
!NumberAt(window, "resetsAt", out resets) || resets < 0 || resets > 253402300799 || resets != Math.Floor(resets)) continue;
DateTime reset = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(resets);
QuotaWindow existing = windows.FirstOrDefault(x => x.Bucket == id && x.WindowMinutes == (int)minutes && x.ResetsAt == reset);
if (existing != null) { existing.UsedPercent = Math.Max(existing.UsedPercent, used); continue; }
windows.Add(new QuotaWindow { Bucket = id, Label = WindowLabel((int)minutes), UsedPercent = used, WindowMinutes = (int)minutes, ResetsAt = reset });
}
}
private static string WindowLabel(int minutes)
{
if (minutes == 10080) return "Weekly";
if (minutes == 1440) return "Daily";
if (minutes % 60 == 0) return (minutes / 60).ToString(CultureInfo.InvariantCulture) + "-hour";
return minutes.ToString(CultureInfo.InvariantCulture) + "-minute";
}
private static bool NumberAt(Dictionary<string, object> value, string key, out double number)
{
object raw;
if (!value.TryGetValue(key, out raw)) { number = 0; return false; }
return TryNumber(raw, out number);
}
private static bool TryNumber(object value, out double number)
{
number = 0;
if (!(value is int || value is long || value is double || value is decimal || value is float)) return false;
try { number = Convert.ToDouble(value, CultureInfo.InvariantCulture); }
catch (Exception) { return false; }
return !Double.IsNaN(number) && !Double.IsInfinity(number);
}
private static Dictionary<string, object> ObjectAt(Dictionary<string, object> value, string key)
{
object raw;
return value.TryGetValue(key, out raw) ? raw as Dictionary<string, object> : null;
}
private static string StringAt(Dictionary<string, object> value, string key)
{
object raw;
return value.TryGetValue(key, out raw) ? raw as string : null;
}
private static JavaScriptSerializer NewSerializer()
{
return new JavaScriptSerializer { MaxJsonLength = MaximumMessageCharacters, RecursionLimit = 24 };
}
private static QuotaSnapshot Unavailable(string status = "unavailable")
{
return new QuotaSnapshot { Status = status };
}
private static string ValidateExecutable(string path)
{
if (String.IsNullOrWhiteSpace(path) || path.IndexOf('"') >= 0 || !Regex.IsMatch(path, "^[a-zA-Z]:[\\\\/]") || !String.Equals(Path.GetFileName(path), "codex.exe", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("A full path to an existing codex.exe is required.", "executablePath");
string fullPath = Path.GetFullPath(path);
if (!File.Exists(fullPath)) throw new ArgumentException("A full path to an existing codex.exe is required.", "executablePath");
return fullPath;
}
private static string FindExecutable()
{
foreach (Process candidate in Process.GetProcessesByName("codex"))
{
using (candidate)
{
try
{
if (!IsSameUser(candidate)) continue;
string executable = candidate.MainModule.FileName;
return ValidateExecutable(executable);
}
catch (Exception) { }
}
}
try
{
string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OpenAI", "Codex", "bin");
if (!Directory.Exists(root)) return null;
string direct = Path.Combine(root, "codex.exe");
if (File.Exists(direct)) return ValidateExecutable(direct);
foreach (DirectoryInfo folder in new DirectoryInfo(root).GetDirectories().OrderByDescending(x => x.LastWriteTimeUtc))
{
string executable = Path.Combine(folder.FullName, "codex.exe");
if (File.Exists(executable)) return ValidateExecutable(executable);
}
}
catch (Exception) { }
return null;
}
private static bool IsSameUser(Process process)
{
IntPtr token;
if (!OpenProcessToken(process.Handle, 8, out token)) return false;
try
{
using (WindowsIdentity identity = new WindowsIdentity(token))
using (WindowsIdentity current = WindowsIdentity.GetCurrent())
return identity.User != null && current.User != null && identity.User.Equals(current.User);
}
finally { CloseHandle(token); }
}
public void Dispose()
{
if (Interlocked.Exchange(ref disposed, 1) == 0) lifetime.Cancel();
// Synchronization primitives stay valid while an in-flight read unwinds.
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
private sealed class OwnedJob : IDisposable
{
private IntPtr handle;
public OwnedJob()
{
handle = CreateJobObject(IntPtr.Zero, null);
if (handle == IntPtr.Zero) return;
JobExtendedLimitInformation information = new JobExtendedLimitInformation();
information.BasicLimitInformation.LimitFlags = 0x2000; // KILL_ON_JOB_CLOSE
int length = Marshal.SizeOf(typeof(JobExtendedLimitInformation));
IntPtr pointer = Marshal.AllocHGlobal(length);
try
{
Marshal.StructureToPtr(information, pointer, false);
if (!SetInformationJobObject(handle, 9, pointer, (uint)length)) Dispose();
}
finally { Marshal.FreeHGlobal(pointer); }
}
public bool Assign(Process process) { return handle != IntPtr.Zero && AssignProcessToJobObject(handle, process.Handle); }
public void Dispose() { if (handle != IntPtr.Zero) { CloseHandle(handle); handle = IntPtr.Zero; } }
}
[StructLayout(LayoutKind.Sequential)]
private struct JobBasicLimitInformation
{
public long PerProcessUserTimeLimit, PerJobUserTimeLimit;
public uint LimitFlags;
public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public UIntPtr Affinity;
public uint PriorityClass, SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
private struct IoCounters
{
public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount, ReadTransferCount, WriteTransferCount, OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct JobExtendedLimitInformation
{
public JobBasicLimitInformation BasicLimitInformation;
public IoCounters IoInfo;
public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateJobObject(IntPtr attributes, string name);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetInformationJobObject(IntPtr job, int informationClass, IntPtr information, uint informationLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
}
}
LocalMetrics.cs
Endpoint heuristics, probes and drive readings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace CriticalHud
{
public sealed class DiskSnapshot
{
public string Status { get; set; }
public DateTime UpdatedAt { get; set; }
public long FreeBytes { get; set; }
public long TotalBytes { get; set; }
}
public sealed class DevServer
{
public int Port { get; set; }
public int ProcessId { get; set; }
public string Label { get; set; }
public string Url { get; set; }
public bool Reachable { get; set; }
public int HttpStatus { get; set; }
public string ProcessName { get; set; }
}
public sealed class ServerSnapshot
{
public string Status { get; set; }
public DateTime UpdatedAt { get; set; }
public List<DevServer> Servers { get; set; }
public ServerSnapshot()
{
Servers = new List<DevServer>();
}
}
public static class LocalMetrics
{
private const int ScanMilliseconds = 5000;
private const int ProbeMilliseconds = 800;
private const int MaxConcurrentProbes = 6;
private static readonly SemaphoreSlim DiscoveryGate = new SemaphoreSlim(1, 1);
private static readonly Regex RuntimeName = new Regex(
@"^(node|bun|deno|python(?:w|\d+(?:\.\d+)?)?|dotnet|php|ruby|javaw?)$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex ForwarderName = new Regex(
@"^(?:com\.docker\.backend|com\.docker\.proxy|docker-proxy|wslrelay|wslhost|wslservice)$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex ProjectPath = new Regex(
@"(?<![a-z0-9_.-])c:[\\/]dev[\\/]([a-z0-9_.-]{1,64})(?=[\\/\s""']|$)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex FrameworkSignal = new Regex(
@"(?:^|[\\/\s""'])((?:@astrojs[\\/])?astro|vite|next|nuxt|webpack-dev-server|http-server|uvicorn|gunicorn|flask|django|rails)(?:[\\/\s""'.]|$)|\bartisan\s+serve\b|\bdotnet\s+(?:watch|run)\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex KnownHelper = new Regex(
@"(?:[\\/]\.codex[\\/](?:plugins|bin|tools|vendor)[\\/])|(?:[\\/](?:codex-primary-runtime|codex-app-server|node_repl|cua_repl)[\\/])|(?:[\\/]@modelcontextprotocol[\\/])|(?:[\\/](?:mcp-server-[a-z0-9_-]+|playwright-mcp|n8n-mcp|chrome-devtools-mcp)[\\/])|(?:^|\s)--(?:remote-debugging-port|remote-debugging-pipe)(?:=|\s|$)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex BcoServiceEntrypoint = new Regex(
@"(?:^|[\s""'])c:[\\/]program files[\\/]better codex orchestrator[\\/]app[\\/]services[\\/]orchestrator[\\/]dist[\\/](?:gateway-runtime-main|background-host-main)\.js(?=[\s""']|$)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex OpenClawEntrypoint = new Regex(
"^" + Regex.Escape(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
@"Documents\CriticalDeveloper\OpenClaw\app\node_modules\openclaw\openclaw.mjs")).Replace(@"\\", @"[\\/]") + "$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
public static DiskSnapshot ReadDisk()
{
DiskSnapshot result = new DiskSnapshot { Status = "unavailable", UpdatedAt = DateTime.UtcNow };
try
{
DriveInfo drive = new DriveInfo(@"C:\");
if (drive.IsReady && drive.TotalSize > 0)
{
result.FreeBytes = drive.AvailableFreeSpace;
result.TotalBytes = drive.TotalSize;
result.Status = "ready";
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
catch (System.Security.SecurityException) { }
return result;
}
public static async Task<ServerSnapshot> ReadServersAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!await DiscoveryGate.WaitAsync(0, cancellationToken).ConfigureAwait(false))
return Unavailable();
CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(ScanMilliseconds);
Task<ServerSnapshot> worker = Task.Run(() => DiscoverAsync(deadline.Token));
// A timed-out WMI provider must not accumulate background scans on every refresh.
Task cleanup = worker.ContinueWith(t =>
{
if (t.IsFaulted) { AggregateException ignored = t.Exception; }
deadline.Dispose();
DiscoveryGate.Release();
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Task completed = await Task.WhenAny(worker, Task.Delay(ScanMilliseconds, cancellationToken)).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
if (completed != worker) return Unavailable();
try { return await worker.ConfigureAwait(false); }
catch (OperationCanceledException) { return Unavailable(); }
catch (Exception) { return Unavailable(); }
}
private static ServerSnapshot Unavailable()
{
return new ServerSnapshot { Status = "unavailable", UpdatedAt = DateTime.UtcNow };
}
private static async Task<ServerSnapshot> DiscoverAsync(CancellationToken cancellationToken)
{
List<Listener> listeners = ReadListeners();
cancellationToken.ThrowIfCancellationRequested();
if (listeners.Count == 0)
return new ServerSnapshot { Status = "ready", UpdatedAt = DateTime.UtcNow };
Dictionary<int, ProcessRecord> processes = ReadProcesses(cancellationToken);
List<Candidate> candidates = BuildCandidates(listeners, processes);
using (SemaphoreSlim probes = new SemaphoreSlim(MaxConcurrentProbes, MaxConcurrentProbes))
{
Task<DevServer>[] tasks = candidates.Select(async candidate =>
{
await probes.WaitAsync(cancellationToken).ConfigureAwait(false);
try { return await ProbeAsync(candidate, cancellationToken).ConfigureAwait(false); }
finally { probes.Release(); }
}).ToArray();
DevServer[] results = await Task.WhenAll(tasks).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
return new ServerSnapshot
{
Status = "ready",
UpdatedAt = DateTime.UtcNow,
Servers = results.Where(server => server != null)
.OrderBy(server => server.Port).ThenBy(server => server.ProcessId).ToList()
};
}
}
private static Dictionary<int, ProcessRecord> ReadProcesses(CancellationToken cancellationToken)
{
Dictionary<int, ProcessRecord> result = new Dictionary<int, ProcessRecord>();
EnumerationOptions options = new EnumerationOptions
{
ReturnImmediately = true,
Rewindable = false,
Timeout = TimeSpan.FromMilliseconds(1500)
};
// Command lines are used transiently for classification; never exported or logged.
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(
new ManagementScope(@"\\.\root\cimv2"),
new ObjectQuery("SELECT ProcessId, ParentProcessId, Name, CommandLine, ExecutablePath FROM Win32_Process"), options))
using (ManagementObjectCollection collection = searcher.Get())
{
foreach (ManagementObject process in collection)
using (process)
{
cancellationToken.ThrowIfCancellationRequested();
int id = Convert.ToInt32(process["ProcessId"]);
result[id] = new ProcessRecord
{
ProcessId = id,
ParentProcessId = Convert.ToInt32(process["ParentProcessId"]),
Name = Path.GetFileNameWithoutExtension(Convert.ToString(process["Name"])) ?? "",
CommandLine = Convert.ToString(process["CommandLine"]) ?? "",
ExecutablePath = Convert.ToString(process["ExecutablePath"]) ?? ""
};
}
}
return result;
}
internal static List<Candidate> BuildCandidates(IEnumerable<Listener> listeners, IDictionary<int, ProcessRecord> processes)
{
List<Candidate> candidates = new List<Candidate>();
foreach (IGrouping<string, Listener> group in listeners.GroupBy(row => row.ProcessId + ":" + row.Port))
{
Listener first = group.First();
ProcessRecord process;
if (!processes.TryGetValue(first.ProcessId, out process)) continue; // Exited between snapshots.
string ownContext = process.CommandLine + " " + process.ExecutablePath;
if (IsKnownHelper(process, ownContext)) continue;
if (process.Name.Equals("node", StringComparison.OrdinalIgnoreCase) && GetInspectorPorts(process.CommandLine).Contains(first.Port)) continue;
string context = ownContext;
ProcessRecord ancestor = process;
HashSet<int> visited = new HashSet<int> { process.ProcessId };
for (int depth = 0; depth < 3; depth++)
{
ProcessRecord parent;
if (!processes.TryGetValue(ancestor.ParentProcessId, out parent) || !visited.Add(parent.ProcessId)) break;
context += " " + parent.CommandLine;
ancestor = parent;
}
Match project = ProjectPath.Match(context);
Match framework = FrameworkSignal.Match(context);
bool forwarding = ForwarderName.IsMatch(process.Name);
if (!RuntimeName.IsMatch(process.Name) && !forwarding && !project.Success && !framework.Success) continue;
List<IPAddress> addresses = group.Select(row => row.Address).Distinct().OrderBy(address =>
address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 0 : 1).ToList();
if (addresses.Count == 0) continue;
string label = project.Success ? project.Groups[1].Value : forwarding
? (process.Name.StartsWith("wsl", StringComparison.OrdinalIgnoreCase) ? "WSL preview" : "Docker preview")
: FrameworkLabel(framework, process.Name);
candidates.Add(new Candidate
{
ProcessId = first.ProcessId,
Port = first.Port,
ProcessName = process.Name,
Label = label,
Addresses = addresses
});
}
return candidates;
}
private static bool IsKnownHelper(ProcessRecord process, string ownContext)
{
// Assistant Node runtimes also launch project previews; identify the service entry point and command.
return KnownHelper.IsMatch(ownContext) || BcoServiceEntrypoint.IsMatch(process.CommandLine) ||
IsOpenClawGateway(process.CommandLine);
}
private static bool IsOpenClawGateway(string commandLine)
{
List<string> arguments = SplitCommandLine(commandLine);
for (int index = 1; index + 2 < arguments.Count; index++)
if (OpenClawEntrypoint.IsMatch(arguments[index]) &&
arguments[index + 1].Equals("gateway", StringComparison.OrdinalIgnoreCase) &&
arguments[index + 2].Equals("run", StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private static string FrameworkLabel(Match framework, string processName)
{
if (!framework.Success) return processName;
string value = framework.Groups[1].Value;
if (value.IndexOf("astro", StringComparison.OrdinalIgnoreCase) >= 0) return "Astro";
if (String.IsNullOrEmpty(value)) return processName;
return Char.ToUpperInvariant(value[0]) + value.Substring(1);
}
internal static HashSet<int> GetInspectorPorts(string commandLine)
{
HashSet<int> ports = new HashSet<int>();
List<string> arguments = SplitCommandLine(commandLine);
bool enabled = false;
int port = 9229;
for (int index = 1; index < arguments.Count; index++)
{
string argument = arguments[index];
if (argument == "--" || !argument.StartsWith("-", StringComparison.Ordinal)) break;
int equals = argument.IndexOf('=');
string option = equals < 0 ? argument : argument.Substring(0, equals);
string value = equals < 0 ? "" : argument.Substring(equals + 1);
if (option == "--inspect" || option == "--inspect-brk" || option == "--inspect-wait" || option == "--inspect-port")
{
if (option != "--inspect-port") enabled = true;
if (option == "--inspect-port" && equals < 0 && index + 1 < arguments.Count)
value = arguments[++index];
int separator = value.LastIndexOf(':');
int parsed;
if (Int32.TryParse(separator >= 0 ? value.Substring(separator + 1) : value, out parsed) && parsed >= 0 && parsed <= 65535)
port = parsed;
}
else if (equals < 0 && Regex.IsMatch(option,
@"^(?:-r|-e|-p|-C|--require|--eval|--print|--import|--loader|--experimental-loader|--conditions|--env-file|--env-file-if-exists|--openssl-config|--icu-data-dir|--trace-event-categories|--trace-event-file-pattern|--redirect-warnings|--title|--watch-path|--input-type|--experimental-config-file|--dns-result-order)$"))
index++; // A preload/eval value is not the script entry point.
}
if (enabled && port > 0) ports.Add(port); // Port zero is dynamically assigned, not the default port.
return ports;
}
private static List<string> SplitCommandLine(string commandLine)
{
List<string> arguments = new List<string>();
if (String.IsNullOrWhiteSpace(commandLine)) return arguments;
int count;
IntPtr values = CommandLineToArgvW(commandLine, out count);
if (values == IntPtr.Zero) return arguments;
try
{
for (int index = 0; index < count; index++)
arguments.Add(Marshal.PtrToStringUni(Marshal.ReadIntPtr(values, index * IntPtr.Size)) ?? "");
}
finally { LocalFree(values); }
return arguments;
}
internal static async Task<DevServer> ProbeAsync(Candidate candidate, CancellationToken cancellationToken)
{
using (CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
deadline.CancelAfter(ProbeMilliseconds);
foreach (IPAddress address in candidate.Addresses)
{
if (!IPAddress.IsLoopback(address)) continue;
string host = address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6
? "[" + address.ToString() + "]" : address.ToString();
foreach (string scheme in new[] { "http", "https" })
{
if (deadline.IsCancellationRequested) break;
string url = scheme + "://" + host + ":" + candidate.Port + "/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Proxy = null;
request.AllowAutoRedirect = false;
request.UseDefaultCredentials = false;
request.Credentials = null;
request.PreAuthenticate = false;
request.KeepAlive = false;
request.UserAgent = "CriticalHud/1.0";
request.Timeout = ProbeMilliseconds / 2;
request.ReadWriteTimeout = ProbeMilliseconds / 2;
request.MaximumResponseHeadersLength = 8;
if (scheme == "https")
{
// Local development certificates are accepted for this credential-free HEAD only.
// No global callback, certificate trust change, redirects, proxy, or body access.
request.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
certificate != null && IsLiteralLoopback(request.RequestUri);
}
using (CancellationTokenSource requestDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token))
{
requestDeadline.CancelAfter(ProbeMilliseconds / 2);
using (requestDeadline.Token.Register(request.Abort))
{
try
{
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync().ConfigureAwait(false))
return Confirmed(candidate, url, (int)response.StatusCode);
}
catch (WebException exception)
{
using (HttpWebResponse response = exception.Response as HttpWebResponse)
{
if (response != null) return Confirmed(candidate, url, (int)response.StatusCode);
}
}
}
}
}
if (deadline.IsCancellationRequested) break;
}
}
cancellationToken.ThrowIfCancellationRequested();
return null;
}
internal static bool IsLiteralLoopback(Uri uri)
{
IPAddress address;
if (uri == null || uri.Scheme != "https" || !String.IsNullOrEmpty(uri.UserInfo) ||
!IPAddress.TryParse(uri.Host.Trim('[', ']'), out address)) return false;
if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4();
return IPAddress.IsLoopback(address);
}
private static DevServer Confirmed(Candidate candidate, string url, int status)
{
return new DevServer
{
Port = candidate.Port, ProcessId = candidate.ProcessId, Label = candidate.Label,
Url = url, Reachable = true, HttpStatus = status, ProcessName = candidate.ProcessName
};
}
private static List<Listener> ReadListeners()
{
List<Listener> rows = new List<Listener>();
rows.AddRange(ReadListenerTable(2, false));
rows.AddRange(ReadListenerTable(23, true));
return rows;
}
private static List<Listener> ReadListenerTable(int family, bool ipv6)
{
const uint InsufficientBuffer = 122;
int bytes = 0;
uint error = GetExtendedTcpTable(IntPtr.Zero, ref bytes, false, family, 3, 0);
if (error != 0 && error != InsufficientBuffer) throw new Win32Exception((int)error);
for (int attempt = 0; attempt < 4; attempt++)
{
if (bytes < 4 || bytes > 16 * 1024 * 1024) throw new InvalidDataException("Invalid TCP table size.");
IntPtr buffer = Marshal.AllocHGlobal(bytes);
try
{
int capacity = bytes;
error = GetExtendedTcpTable(buffer, ref bytes, false, family, 3, 0);
if (error == InsufficientBuffer) continue;
if (error != 0) throw new Win32Exception((int)error);
int count = Marshal.ReadInt32(buffer);
int rowSize = ipv6 ? 56 : 24;
if (count < 0 || count > (capacity - 4) / rowSize) throw new InvalidDataException("Invalid TCP table rows.");
List<Listener> rows = new List<Listener>();
for (int index = 0; index < count; index++)
{
IntPtr row = IntPtr.Add(buffer, 4 + index * rowSize);
int state = Marshal.ReadInt32(row, ipv6 ? 48 : 0);
if (state != 2) continue;
byte[] addressBytes = new byte[ipv6 ? 16 : 4];
Marshal.Copy(IntPtr.Add(row, ipv6 ? 0 : 4), addressBytes, 0, addressBytes.Length);
IPAddress address = new IPAddress(addressBytes);
if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4();
if (address.Equals(IPAddress.Any)) address = IPAddress.Loopback;
else if (address.Equals(IPAddress.IPv6Any)) address = IPAddress.IPv6Loopback;
else if (!IPAddress.IsLoopback(address)) continue;
int portValue = Marshal.ReadInt32(row, ipv6 ? 20 : 8);
int port = ((portValue & 0xff) << 8) | ((portValue >> 8) & 0xff);
int pid = Marshal.ReadInt32(row, ipv6 ? 52 : 20);
if (port > 0 && pid > 0) rows.Add(new Listener { Address = address, Port = port, ProcessId = pid });
}
return rows;
}
finally { Marshal.FreeHGlobal(buffer); }
}
throw new IOException("TCP listeners changed repeatedly during discovery.");
}
[DllImport("iphlpapi.dll", SetLastError = true)]
private static extern uint GetExtendedTcpTable(IntPtr table, ref int size, [MarshalAs(UnmanagedType.Bool)] bool order,
int family, int tableClass, uint reserved);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CommandLineToArgvW(string commandLine, out int count);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr memory);
internal sealed class Listener
{
public int ProcessId;
public int Port;
public IPAddress Address;
}
internal sealed class ProcessRecord
{
public int ProcessId;
public int ParentProcessId;
public string Name = "";
public string CommandLine = "";
public string ExecutablePath = "";
}
internal sealed class Candidate
{
public int ProcessId;
public int Port;
public string Label;
public string ProcessName;
public List<IPAddress> Addresses;
}
}
}
PluginHost.cs
SDK lifecycle, snapshots and image delivery
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace CriticalHud
{
internal sealed class LaunchOptions
{
public int Port;
public string PluginUuid;
public string RegisterEvent;
public bool SelfTest;
public bool Diagnostics;
public string PreviewDirectory;
public static LaunchOptions Parse(string[] args)
{
LaunchOptions options = new LaunchOptions();
HashSet<string> seen = new HashSet<string>(StringComparer.Ordinal);
for (int index = 0; index < args.Length; index++)
{
string key = args[index];
if (!seen.Add(key)) throw new ArgumentException("Duplicate launch option.");
if (key == "--self-test") { options.SelfTest = true; continue; }
if (key == "--diagnostics") { options.Diagnostics = true; continue; }
if (key != "-port" && key != "-pluginUUID" && key != "-registerEvent" && key != "-info" && key != "--preview-dir")
throw new ArgumentException("Unknown launch option.");
if (++index >= args.Length) throw new ArgumentException("Missing launch option value.");
string value = args[index];
if (key == "-port")
{
if (!Int32.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out options.Port) || options.Port < 1 || options.Port > 65535)
throw new ArgumentException("Invalid SDK port.");
}
else if (key == "-pluginUUID")
{
if (!SafeIdentifier(value, 256)) throw new ArgumentException("Invalid plugin identifier.");
options.PluginUuid = value;
}
else if (key == "-registerEvent")
{
if (value != "registerPlugin") throw new ArgumentException("Invalid plugin registration event.");
options.RegisterEvent = value;
}
else if (key == "-info")
{
if (value.Length > 512 * 1024 || !(Json.Parse(value) is Dictionary<string, object>))
throw new ArgumentException("Invalid SDK metadata.");
}
else options.PreviewDirectory = Path.GetFullPath(value);
}
if (!options.SelfTest && !options.Diagnostics && options.PreviewDirectory == null &&
(options.Port == 0 || options.PluginUuid == null || options.RegisterEvent == null))
throw new ArgumentException("SDK connection arguments are required.");
if ((options.SelfTest || options.Diagnostics || options.PreviewDirectory != null) && options.Port != 0)
throw new ArgumentException("Diagnostics cannot share an SDK connection.");
return options;
}
public static bool SafeIdentifier(string value, int length)
{
return !String.IsNullOrWhiteSpace(value) && value.Length <= length && !value.Any(Char.IsControl);
}
}
internal static class Json
{
private static JavaScriptSerializer Serializer()
{
return new JavaScriptSerializer { MaxJsonLength = 512 * 1024, RecursionLimit = 32 };
}
public static object Parse(string text) { return Serializer().DeserializeObject(text); }
public static string Stringify(object value) { return Serializer().Serialize(value); }
public static Dictionary<string, object> Object(object value) { return value as Dictionary<string, object>; }
public static object Get(Dictionary<string, object> value, string key)
{
object result;
return value != null && value.TryGetValue(key, out result) ? result : null;
}
public static string Text(Dictionary<string, object> value, string key) { return Get(value, key) as string; }
}
internal sealed class VisibleWidget
{
public string Context;
public string Action;
public string Kind;
public string Device;
public WidgetSettings Settings;
public bool DeviceDisconnected;
public bool InspectorVisible;
public string LastImageKey;
}
internal sealed class InspectorSession
{
public string Context;
public string Action;
public string Kind;
public DateTime LastSeen;
}
internal sealed class PluginHost : IDisposable
{
private const string ActionPrefix = "com.criticaldeveloper.vercetti-hud.";
private const int MaximumMessageBytes = 512 * 1024;
private const int MaximumContexts = 128;
private readonly ClientWebSocket socket = new ClientWebSocket();
private readonly CancellationTokenSource lifetime = new CancellationTokenSource();
private readonly SemaphoreSlim sends = new SemaphoreSlim(1, 1);
private readonly object stateGate = new object();
private readonly Dictionary<string, VisibleWidget> widgets = new Dictionary<string, VisibleWidget>(StringComparer.Ordinal);
private readonly Dictionary<string, InspectorSession> inspectors = new Dictionary<string, InspectorSession>(StringComparer.Ordinal);
private readonly WidgetRenderer renderer;
private readonly CodexQuotaReader quotaReader = new CodexQuotaReader();
private readonly Stopwatch clock = Stopwatch.StartNew();
private QuotaSnapshot quota;
private ServerSnapshot servers;
private DiskSnapshot disk;
private DateTime nextQuota = DateTime.MinValue;
private DateTime nextServers = DateTime.MinValue;
private DateTime nextDisk = DateTime.MinValue;
private int disposed;
public PluginHost(string assetsDirectory) { renderer = new WidgetRenderer(assetsDirectory); }
public async Task<int> RunAsync(LaunchOptions options)
{
CancellationToken cancellation = lifetime.Token;
Task[] running = new Task[0];
int result = 0;
try
{
socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
using (CancellationTokenSource connectionDeadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation))
{
connectionDeadline.CancelAfter(TimeSpan.FromSeconds(10));
await socket.ConnectAsync(new Uri("ws://127.0.0.1:" + options.Port.ToString(CultureInfo.InvariantCulture)), connectionDeadline.Token).ConfigureAwait(false);
}
await SendAsync(new { @event = options.RegisterEvent, uuid = options.PluginUuid }, cancellation).ConfigureAwait(false);
running = new[] { ReceiveLoopAsync(cancellation), RenderLoopAsync(cancellation), QuotaLoopAsync(cancellation), ServerLoopAsync(cancellation), DiskLoopAsync(cancellation) };
await Task.WhenAny(running).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
catch (Exception exception)
{
Console.Error.WriteLine("Widget host stopped: " + exception.GetType().Name + ".");
result = 1;
}
lifetime.Cancel();
socket.Abort();
try { await Task.WhenAll(running).ConfigureAwait(false); }
catch (OperationCanceledException) { }
catch (Exception exception)
{
Console.Error.WriteLine("Widget connection stopped: " + exception.GetType().Name + ".");
result = 1;
}
return result;
}
private async Task ReceiveLoopAsync(CancellationToken cancellation)
{
byte[] buffer = new byte[8192];
while (!cancellation.IsCancellationRequested && socket.State == WebSocketState.Open)
{
using (MemoryStream message = new MemoryStream())
{
WebSocketReceiveResult received;
do
{
received = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cancellation).ConfigureAwait(false);
if (received.MessageType == WebSocketMessageType.Close) return;
if (received.MessageType != WebSocketMessageType.Text || message.Length + received.Count > MaximumMessageBytes)
throw new InvalidDataException("SDK message is outside supported bounds.");
message.Write(buffer, 0, received.Count);
} while (!received.EndOfMessage);
Dictionary<string, object> parsed;
try { parsed = Json.Object(Json.Parse(new UTF8Encoding(false, true).GetString(message.ToArray()))); }
catch (ArgumentException) { continue; }
catch (InvalidOperationException) { continue; }
if (parsed != null) await HandleEventAsync(parsed, cancellation).ConfigureAwait(false);
}
}
}
private async Task HandleEventAsync(Dictionary<string, object> message, CancellationToken cancellation)
{
string eventName = Json.Text(message, "event");
string context = Json.Text(message, "context");
string action = Json.Text(message, "action");
Dictionary<string, object> payload = Json.Object(Json.Get(message, "payload"));
if (eventName == "deviceDidDisconnect" || eventName == "deviceDidConnect")
{
string device = Json.Text(message, "device");
if (LaunchOptions.SafeIdentifier(device, 512))
lock (stateGate)
foreach (VisibleWidget deviceWidget in widgets.Values.Where(delegate(VisibleWidget value) { return value.Device == device; }))
{
if (eventName == "deviceDidDisconnect") deviceWidget.DeviceDisconnected = true;
else if (deviceWidget.DeviceDisconnected)
{
// MSD can reconnect the same profile without replaying willAppear.
deviceWidget.DeviceDisconnected = false;
deviceWidget.LastImageKey = null;
ScheduleRefresh(deviceWidget.Kind);
}
}
return;
}
if (!LaunchOptions.SafeIdentifier(context, 512)) return;
if (eventName == "propertyInspectorDidDisappear")
{
lock (stateGate) inspectors.Remove(context);
}
if (eventName == "sendToPlugin" && KindForAction(action) != null)
{
string command = Json.Text(payload, "command");
bool separateInspector;
lock (stateGate) separateInspector = !widgets.ContainsKey(context);
if (separateInspector)
{
if (command != "refresh" && command != "status") return;
string kind = KindForAction(action);
lock (stateGate)
{
foreach (string expired in inspectors.Where(delegate(KeyValuePair<string, InspectorSession> pair) { return DateTime.UtcNow - pair.Value.LastSeen > TimeSpan.FromMinutes(10); }).Select(delegate(KeyValuePair<string, InspectorSession> pair) { return pair.Key; }).ToArray())
inspectors.Remove(expired);
if (inspectors.Count >= 32 && !inspectors.ContainsKey(context)) return;
inspectors[context] = new InspectorSession { Context = context, Action = action, Kind = kind, LastSeen = DateTime.UtcNow };
if (command == "refresh") ScheduleRefresh(kind);
}
await SendInspectorByKindAsync(context, action, kind, cancellation).ConfigureAwait(false);
return;
}
}
if (eventName == "willAppear")
{
string kind = KindForAction(action);
if (kind == null) return;
lock (stateGate)
{
if (widgets.Count >= MaximumContexts && !widgets.ContainsKey(context)) return;
widgets[context] = new VisibleWidget
{
Context = context, Action = action, Kind = kind, Device = Json.Text(message, "device"),
Settings = ReadSettings(Json.Object(Json.Get(payload, "settings")))
};
ScheduleRefresh(kind);
}
return;
}
VisibleWidget widget;
lock (stateGate)
{
if (!widgets.TryGetValue(context, out widget)) return;
if (action != null && action != widget.Action) return;
if (eventName == "willDisappear") { widgets.Remove(context); return; }
if (eventName == "didReceiveSettings")
{
widget.Settings = ReadSettings(Json.Object(Json.Get(payload, "settings")));
widget.LastImageKey = null;
}
else if (eventName == "propertyInspectorDidAppear") widget.InspectorVisible = true;
else if (eventName == "propertyInspectorDidDisappear") { widget.InspectorVisible = false; return; }
else if (eventName == "keyUp") ScheduleRefresh(widget.Kind);
else if (eventName == "sendToPlugin")
{
string command = Json.Text(payload, "command");
if (command != "refresh" && command != "status") return;
widget.InspectorVisible = true;
if (command == "refresh") ScheduleRefresh(widget.Kind);
}
else if (eventName != "didReceiveSettings") return;
}
if (widget.InspectorVisible) await SendInspectorAsync(widget.Context, cancellation).ConfigureAwait(false);
}
private static string KindForAction(string action)
{
if (action == ActionPrefix + "quota") return "quota";
if (action == ActionPrefix + "servers") return "servers";
if (action == ActionPrefix + "disk") return "disk";
return null;
}
private static WidgetSettings ReadSettings(Dictionary<string, object> values)
{
WidgetSettings settings = new WidgetSettings();
object animation = Json.Get(values, "animationEnabled");
object cycle = Json.Get(values, "quotaCycle");
if (animation is bool) settings.AnimationEnabled = (bool)animation;
if (cycle is bool) settings.QuotaCycle = (bool)cycle;
settings.DiskWarningGb = SettingNumber(values, "diskWarningGb", 20, 1, 2048);
settings.DiskCriticalGb = SettingNumber(values, "diskCriticalGb", 5, 0.1, settings.DiskWarningGb);
settings.DiskWarningPercent = SettingNumber(values, "diskWarningPercent", 10, 1, 50);
settings.DiskCriticalPercent = SettingNumber(values, "diskCriticalPercent", 5, 0.1, settings.DiskWarningPercent);
return settings;
}
private static double SettingNumber(Dictionary<string, object> values, string key, double fallback, double minimum, double maximum)
{
object value = Json.Get(values, key);
if (!(value is int || value is long || value is double || value is decimal)) return Math.Max(minimum, Math.Min(maximum, fallback));
double number;
try { number = Convert.ToDouble(value, CultureInfo.InvariantCulture); }
catch (Exception) { return Math.Max(minimum, Math.Min(maximum, fallback)); }
return Double.IsNaN(number) || Double.IsInfinity(number) ? Math.Max(minimum, Math.Min(maximum, fallback)) : Math.Max(minimum, Math.Min(maximum, number));
}
private void ScheduleRefresh(string kind)
{
if (kind == "quota") nextQuota = DateTime.MinValue;
else if (kind == "servers") nextServers = DateTime.MinValue;
else if (kind == "disk") nextDisk = DateTime.MinValue;
}
private bool CollectDue(string kind, ref DateTime next, int seconds)
{
lock (stateGate)
{
if (!widgets.Values.Any(delegate(VisibleWidget widget) { return widget.Kind == kind && !widget.DeviceDisconnected; }) || DateTime.UtcNow < next) return false;
next = DateTime.UtcNow.AddSeconds(seconds);
return true;
}
}
private async Task QuotaLoopAsync(CancellationToken cancellation)
{
try
{
while (!cancellation.IsCancellationRequested)
{
if (CollectDue("quota", ref nextQuota, 120))
{
QuotaSnapshot result = await quotaReader.ReadAsync(cancellation).ConfigureAwait(false);
lock (stateGate)
{
if (result != null && (result.Status == "ready" || result.Status == "login-required")) quota = result;
else if (quota != null && quota.Windows != null && quota.Windows.Count > 0)
quota = new QuotaSnapshot { Status = "stale", UpdatedAt = quota.UpdatedAt, Windows = quota.Windows };
else quota = result ?? new QuotaSnapshot();
}
await SendInspectorsForKindAsync("quota", cancellation).ConfigureAwait(false);
}
await Task.Delay(500, cancellation).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
catch (WebSocketException) { lifetime.Cancel(); }
catch (ObjectDisposedException) { }
}
private async Task ServerLoopAsync(CancellationToken cancellation)
{
try
{
while (!cancellation.IsCancellationRequested)
{
if (CollectDue("servers", ref nextServers, 5))
{
ServerSnapshot result;
try { result = await LocalMetrics.ReadServersAsync(cancellation).ConfigureAwait(false); }
catch (OperationCanceledException) { throw; }
catch (Exception) { result = new ServerSnapshot { Status = "unavailable", UpdatedAt = DateTime.UtcNow, Servers = new List<DevServer>() }; }
lock (stateGate)
{
if (result != null && result.Status == "ready") servers = result;
else if (servers != null && servers.Status != "unavailable")
servers = new ServerSnapshot { Status = "stale", UpdatedAt = servers.UpdatedAt, Servers = servers.Servers };
else servers = result;
}
await SendInspectorsForKindAsync("servers", cancellation).ConfigureAwait(false);
}
await Task.Delay(500, cancellation).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
catch (WebSocketException) { lifetime.Cancel(); }
catch (ObjectDisposedException) { }
}
private async Task DiskLoopAsync(CancellationToken cancellation)
{
try
{
while (!cancellation.IsCancellationRequested)
{
if (CollectDue("disk", ref nextDisk, 15))
{
DiskSnapshot result;
try { result = await Task.Run(delegate { return LocalMetrics.ReadDisk(); }, cancellation).ConfigureAwait(false); }
catch (OperationCanceledException) { throw; }
catch (Exception) { result = new DiskSnapshot { Status = "unavailable", UpdatedAt = DateTime.UtcNow }; }
lock (stateGate)
{
if (result != null && result.Status == "ready") disk = result;
else if (disk != null && disk.Status != "unavailable")
disk = new DiskSnapshot { Status = "stale", UpdatedAt = disk.UpdatedAt, FreeBytes = disk.FreeBytes, TotalBytes = disk.TotalBytes };
else disk = result;
}
await SendInspectorsForKindAsync("disk", cancellation).ConfigureAwait(false);
}
await Task.Delay(500, cancellation).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
catch (WebSocketException) { lifetime.Cancel(); }
catch (ObjectDisposedException) { }
}
private async Task RenderLoopAsync(CancellationToken cancellation)
{
try
{
while (!cancellation.IsCancellationRequested)
{
VisibleWidget[] current;
QuotaSnapshot currentQuota;
ServerSnapshot currentServers;
DiskSnapshot currentDisk;
lock (stateGate)
{
current = widgets.Values.Where(delegate(VisibleWidget widget) { return !widget.DeviceDisconnected; }).Select(delegate(VisibleWidget widget)
{
return new VisibleWidget { Context = widget.Context, Kind = widget.Kind, Settings = widget.Settings, LastImageKey = widget.LastImageKey };
}).ToArray();
currentQuota = quota; currentServers = servers; currentDisk = disk;
}
long tick = clock.ElapsedMilliseconds / 250;
int phase = (int)(tick % 14);
int frame = phase <= 7 ? phase : 14 - phase;
DateTime now = DateTime.UtcNow;
Dictionary<string, string> images = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (VisibleWidget widget in current)
{
WidgetText text = WidgetRenderer.Describe(widget.Kind, widget.Settings, currentQuota, currentServers, currentDisk, now);
string imageKey = widget.Kind + "|" + (widget.Settings.AnimationEnabled ? frame : 0).ToString(CultureInfo.InvariantCulture) + "|" + text.Value + "|" + text.Secondary + "|" + text.Accent.ToArgb().ToString(CultureInfo.InvariantCulture);
if (imageKey == widget.LastImageKey) continue;
string image;
if (!images.TryGetValue(imageKey, out image))
{
image = "data:image/png;base64," + Convert.ToBase64String(renderer.Render(widget.Kind, frame, widget.Settings, currentQuota, currentServers, currentDisk, now));
images.Add(imageKey, image);
}
lock (stateGate)
{
VisibleWidget active;
if (!widgets.TryGetValue(widget.Context, out active) || active.DeviceDisconnected) continue;
active.LastImageKey = imageKey;
}
await SendAsync(new { @event = "setImage", context = widget.Context, payload = new { image = image, target = 0 } }, cancellation).ConfigureAwait(false);
}
await Task.Delay(250, cancellation).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
catch (WebSocketException) { lifetime.Cancel(); }
catch (ObjectDisposedException) { }
}
private async Task SendAsync(object message, CancellationToken cancellation)
{
byte[] bytes = Encoding.UTF8.GetBytes(Json.Stringify(message));
using (CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation))
{
deadline.CancelAfter(TimeSpan.FromSeconds(5));
await sends.WaitAsync(deadline.Token).ConfigureAwait(false);
try
{
if (socket.State != WebSocketState.Open) throw new OperationCanceledException();
await socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, deadline.Token).ConfigureAwait(false);
}
finally { sends.Release(); }
}
}
private async Task SendInspectorsForKindAsync(string kind, CancellationToken cancellation)
{
string[] contexts;
InspectorSession[] sessions;
lock (stateGate)
{
contexts = widgets.Values.Where(delegate(VisibleWidget widget) { return widget.Kind == kind && !widget.DeviceDisconnected && widget.InspectorVisible; }).Select(delegate(VisibleWidget widget) { return widget.Context; }).ToArray();
sessions = inspectors.Values.Where(delegate(InspectorSession inspector) { return inspector.Kind == kind && DateTime.UtcNow - inspector.LastSeen <= TimeSpan.FromMinutes(10); }).ToArray();
}
foreach (string context in contexts) await SendInspectorAsync(context, cancellation).ConfigureAwait(false);
foreach (InspectorSession session in sessions) await SendInspectorByKindAsync(session.Context, session.Action, kind, cancellation).ConfigureAwait(false);
}
private async Task SendInspectorAsync(string context, CancellationToken cancellation)
{
string action;
string kind;
object snapshot;
lock (stateGate)
{
VisibleWidget widget;
if (!widgets.TryGetValue(context, out widget)) return;
action = widget.Action; kind = widget.Kind;
snapshot = SanitizedSnapshot(kind, quota, servers, disk);
}
await SendAsync(new { @event = "sendToPropertyInspector", action = action, context = context, payload = new { kind = kind, snapshot = snapshot } }, cancellation).ConfigureAwait(false);
}
private async Task SendInspectorByKindAsync(string context, string action, string kind, CancellationToken cancellation)
{
object snapshot;
lock (stateGate) snapshot = SanitizedSnapshot(kind, quota, servers, disk);
await SendAsync(new { @event = "sendToPropertyInspector", action = action, context = context, payload = new { kind = kind, snapshot = snapshot } }, cancellation).ConfigureAwait(false);
}
public static object SanitizedSnapshot(string kind, QuotaSnapshot quota, ServerSnapshot servers, DiskSnapshot disk)
{
if (kind == "quota")
{
QuotaSnapshot value = quota ?? new QuotaSnapshot();
return new
{
Status = value.Status, UpdatedAt = IsoDate(value.UpdatedAt),
Windows = (value.Windows ?? new List<QuotaWindow>()).Where(delegate(QuotaWindow window) { return window != null && !Double.IsNaN(window.UsedPercent) && !Double.IsInfinity(window.UsedPercent); }).Select(delegate(QuotaWindow window)
{
return new { Bucket = SafeBucket(window.Bucket), Label = WidgetRenderer.CleanText(window.Label, 48), UsedPercent = Math.Max(0, Math.Min(100, window.UsedPercent)), WindowMinutes = window.WindowMinutes, ResetsAt = IsoDate(window.ResetsAt) };
}).ToArray()
};
}
if (kind == "servers")
{
ServerSnapshot value = servers ?? new ServerSnapshot { Status = "unavailable", UpdatedAt = DateTime.UtcNow, Servers = new List<DevServer>() };
return new
{
Status = value.Status, UpdatedAt = IsoDate(value.UpdatedAt),
Servers = (value.Servers ?? new List<DevServer>()).Where(delegate(DevServer server) { return server != null; }).Select(delegate(DevServer server)
{
return new { Port = server.Port, ProcessId = server.ProcessId, Label = WidgetRenderer.CleanText(server.Label, 80), Url = LocalUrl(server.Url), Reachable = server.Reachable, HttpStatus = server.HttpStatus, ProcessName = WidgetRenderer.CleanText(server.ProcessName, 40) };
}).ToArray()
};
}
DiskSnapshot drive = disk ?? new DiskSnapshot { Status = "unavailable", UpdatedAt = DateTime.UtcNow };
return new { Status = drive.Status, UpdatedAt = IsoDate(drive.UpdatedAt), FreeBytes = drive.FreeBytes, TotalBytes = drive.TotalBytes };
}
private static string IsoDate(DateTime value) { return value == DateTime.MinValue ? null : value.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture); }
private static string SafeBucket(string value) { return value != null && System.Text.RegularExpressions.Regex.IsMatch(value, "^[a-zA-Z0-9_-]{1,80}$") ? value : null; }
private static string LocalUrl(string value)
{
Uri uri;
if (!Uri.TryCreate(value, UriKind.Absolute, out uri) || (uri.Scheme != "http" && uri.Scheme != "https") || !uri.IsLoopback || !String.IsNullOrEmpty(uri.UserInfo)) return null;
return uri.GetLeftPart(UriPartial.Authority) + "/";
}
public void Dispose()
{
if (Interlocked.Exchange(ref disposed, 1) != 0) return;
lifetime.Cancel();
socket.Abort();
quotaReader.Dispose();
socket.Dispose();
sends.Dispose();
lifetime.Dispose();
renderer.Dispose();
}
}
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
try
{
LaunchOptions options = LaunchOptions.Parse(args);
string assets = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets");
if (options.SelfTest || options.PreviewDirectory != null)
{
using (WidgetRenderer renderer = new WidgetRenderer(assets))
RenderFixtures(renderer, options.PreviewDirectory, options.SelfTest);
}
if (options.Diagnostics) DiagnosticsAsync().GetAwaiter().GetResult();
if (options.SelfTest || options.Diagnostics || options.PreviewDirectory != null) return 0;
using (PluginHost host = new PluginHost(assets)) return host.RunAsync(options).GetAwaiter().GetResult();
}
catch (Exception exception)
{
Console.Error.WriteLine("Widget host could not start: " + exception.GetType().Name + ".");
return 1;
}
}
private static void RenderFixtures(WidgetRenderer renderer, string previewDirectory, bool selfTest)
{
DateTime now = DateTime.UtcNow;
QuotaSnapshot quota = new QuotaSnapshot { Status = "ready", UpdatedAt = now, Windows = new List<QuotaWindow>
{
new QuotaWindow { Bucket = "codex", Label = "Weekly", UsedPercent = 1, WindowMinutes = 10080, ResetsAt = now.AddDays(3) },
new QuotaWindow { Bucket = "codex", Label = "5 hour", UsedPercent = 15, WindowMinutes = 300, ResetsAt = now.AddHours(2) }
} };
ServerSnapshot servers = new ServerSnapshot { Status = "ready", UpdatedAt = now, Servers = new List<DevServer>
{
new DevServer { Port = 4321, ProcessId = 1, Label = "ASTRO", ProcessName = "node", Reachable = true, HttpStatus = 200, Url = "http://localhost:4321/" },
new DevServer { Port = 5173, ProcessId = 2, Label = "VITE", ProcessName = "node", Reachable = true, HttpStatus = 200, Url = "http://localhost:5173/" },
new DevServer { Port = 3000, ProcessId = 3, Label = "NODE", ProcessName = "node", Reachable = true, HttpStatus = 200, Url = "http://localhost:3000/" }
} };
DiskSnapshot disk = new DiskSnapshot { Status = "ready", UpdatedAt = now, FreeBytes = 68L * 1073741824, TotalBytes = 500L * 1073741824 };
WidgetSettings settings = new WidgetSettings();
if (selfTest)
{
if (renderer.LoadedFrames != 24) throw new InvalidDataException("Missing packaged artwork.");
Assert(WidgetRenderer.Describe("quota", settings, quota, servers, disk, now).Value == "85%", "Quota must choose limiting window.");
Assert(WidgetRenderer.Describe("servers", settings, quota, servers, disk, now).Value == "3 LIVE", "All reachable servers must count.");
Assert(WidgetRenderer.Describe("disk", settings, quota, servers, disk, now).Value == "68 GiB", "Disk value must label binary free-space units.");
Assert(WidgetRenderer.Describe("quota", settings, new QuotaSnapshot { Status = "login-required" }, servers, disk, now).Value == "LOGIN", "Login status must remain distinct.");
Assert(WidgetRenderer.Describe("disk", settings, quota, servers, null, now).Value == "UNKNOWN", "Missing data must not become zero.");
Assert(WidgetRenderer.Describe("quota", settings, new QuotaSnapshot { Status = "stale", UpdatedAt = now, Windows = quota.Windows }, servers, disk, now).Secondary.StartsWith("STALE", StringComparison.Ordinal), "Stale quota must be visible.");
Assert(WidgetRenderer.Describe("servers", settings, quota, new ServerSnapshot { Status = "ready", UpdatedAt = now, Servers = new List<DevServer>() }, disk, now).Secondary == "NO DEV SERVERS", "No servers must remain distinct.");
Assert(WidgetRenderer.Describe("quota", settings, new QuotaSnapshot { Status = "ready", UpdatedAt = now, Windows = new List<QuotaWindow> { new QuotaWindow { UsedPercent = 200 } } }, servers, disk, now).Value == "0%", "Quota must clamp percentage.");
Assert(WidgetRenderer.Describe("quota", settings, new QuotaSnapshot { Status = "ready", UpdatedAt = now, Windows = new List<QuotaWindow> { new QuotaWindow { UsedPercent = Double.NaN } } }, servers, disk, now).Value == "UNKNOWN", "Invalid quota must be unknown.");
QuotaSnapshot mixedBuckets = new QuotaSnapshot { Status = "ready", UpdatedAt = now, Windows = new List<QuotaWindow>
{
new QuotaWindow { Bucket = "codex", Label = "5-hour", UsedPercent = 15, WindowMinutes = 300, ResetsAt = now.AddHours(2) },
new QuotaWindow { Bucket = "codex_other", Label = "Weekly", UsedPercent = 45, WindowMinutes = 10080, ResetsAt = now.AddDays(3) }
} };
Assert(WidgetRenderer.Describe("quota", settings, mixedBuckets, servers, disk, now).Value == "55%", "Selection compares windows across returned buckets.");
Assert(Json.Stringify(PluginHost.SanitizedSnapshot("quota", mixedBuckets, null, null)).Contains("\"Bucket\":\"codex_other\""), "Inspector data preserves the bucket identity.");
mixedBuckets.Windows[1].Bucket = "private@example.com";
Assert(!Json.Stringify(PluginHost.SanitizedSnapshot("quota", mixedBuckets, null, null)).Contains("private@example.com"), "Invalid bucket identifiers must not enter inspector data.");
try { LaunchOptions.Parse(new[] { "-port", "65536", "-pluginUUID", "a", "-registerEvent", "registerPlugin" }); throw new InvalidOperationException("Invalid port accepted."); }
catch (ArgumentException) { }
}
if (previewDirectory != null) Directory.CreateDirectory(previewDirectory);
foreach (string kind in new[] { "quota", "servers", "disk" })
{
byte[] png = renderer.Render(kind, 0, settings, quota, servers, disk, now);
using (MemoryStream stream = new MemoryStream(png))
using (Image image = Image.FromStream(stream)) Assert(image.Width == 144 && image.Height == 144, "PNG dimensions must match hardware.");
if (previewDirectory != null) File.WriteAllBytes(Path.Combine(previewDirectory, kind + "-ready.png"), png);
}
if (previewDirectory != null)
{
File.WriteAllBytes(Path.Combine(previewDirectory, "quota-login.png"), renderer.Render("quota", 0, settings, new QuotaSnapshot { Status = "login-required" }, servers, disk, now));
File.WriteAllBytes(Path.Combine(previewDirectory, "quota-stale.png"), renderer.Render("quota", 0, settings, new QuotaSnapshot { Status = "stale", UpdatedAt = now.AddMinutes(-10), Windows = quota.Windows }, servers, disk, now));
File.WriteAllBytes(Path.Combine(previewDirectory, "servers-empty.png"), renderer.Render("servers", 0, settings, quota, new ServerSnapshot { Status = "ready", UpdatedAt = now, Servers = new List<DevServer>() }, disk, now));
File.WriteAllBytes(Path.Combine(previewDirectory, "disk-low.png"), renderer.Render("disk", 0, settings, quota, servers, new DiskSnapshot { Status = "ready", UpdatedAt = now, FreeBytes = 3L * 1073741824, TotalBytes = 500L * 1073741824 }, now));
}
Console.WriteLine(Json.Stringify(new { ok = true, frames = renderer.LoadedFrames, checks = selfTest ? 16 : 3, previews = previewDirectory }));
}
private static async Task DiagnosticsAsync()
{
using (CancellationTokenSource deadline = new CancellationTokenSource(TimeSpan.FromSeconds(25)))
using (CodexQuotaReader reader = new CodexQuotaReader())
{
Task<QuotaSnapshot> quota = reader.ReadAsync(deadline.Token);
Task<ServerSnapshot> servers = LocalMetrics.ReadServersAsync(deadline.Token);
DiskSnapshot disk = LocalMetrics.ReadDisk();
await Task.WhenAll(quota, servers).ConfigureAwait(false);
Console.WriteLine(Json.Stringify(new
{
quota = PluginHost.SanitizedSnapshot("quota", quota.Result, null, null),
servers = PluginHost.SanitizedSnapshot("servers", null, servers.Result, null),
disk = PluginHost.SanitizedSnapshot("disk", null, null, disk)
}));
}
}
private static void Assert(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
}
}
WidgetRenderer.cs
Animation, values and stale states
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Linq;
namespace CriticalHud
{
public sealed class WidgetSettings
{
public bool AnimationEnabled { get; set; }
public bool QuotaCycle { get; set; }
public double DiskWarningGb { get; set; }
public double DiskCriticalGb { get; set; }
public double DiskWarningPercent { get; set; }
public double DiskCriticalPercent { get; set; }
public WidgetSettings()
{
AnimationEnabled = true;
DiskWarningGb = 20;
DiskCriticalGb = 5;
DiskWarningPercent = 10;
DiskCriticalPercent = 5;
}
}
public sealed class WidgetText
{
public string Title { get; set; }
public string Value { get; set; }
public string Secondary { get; set; }
public Color Accent { get; set; }
}
public sealed class WidgetRenderer : IDisposable
{
public const int ImageSize = 144;
private static readonly Color Green = Color.FromArgb(188, 245, 93);
private static readonly Color Amber = Color.FromArgb(255, 196, 80);
private static readonly Color Red = Color.FromArgb(255, 112, 105);
private static readonly Color Gray = Color.FromArgb(166, 170, 170);
private readonly Dictionary<string, Bitmap[]> artwork = new Dictionary<string, Bitmap[]>(StringComparer.Ordinal);
private readonly Font valueFont = new Font("Segoe UI", 24, FontStyle.Bold, GraphicsUnit.Pixel);
private readonly Font detailFont = new Font("Segoe UI", 10, FontStyle.Regular, GraphicsUnit.Pixel);
private readonly Font titleFont = new Font("Segoe UI", 10, FontStyle.Bold, GraphicsUnit.Pixel);
public int LoadedFrames { get; private set; }
public WidgetRenderer(string assetsDirectory)
{
foreach (string kind in new[] { "quota", "servers", "disk" })
{
Bitmap[] frames = new Bitmap[8];
for (int frame = 0; frame < frames.Length; frame++)
{
string path = Path.Combine(assetsDirectory, kind, "frame-" + frame.ToString("00", CultureInfo.InvariantCulture) + ".png");
try
{
using (FileStream stream = File.OpenRead(path))
using (Image source = Image.FromStream(stream))
{
if (source.Width != ImageSize || source.Height != ImageSize)
throw new InvalidDataException("Artwork size is invalid.");
frames[frame] = new Bitmap(source);
LoadedFrames++;
}
}
catch (IOException) { frames[frame] = EmptyFrame(); }
catch (UnauthorizedAccessException) { frames[frame] = EmptyFrame(); }
catch (ArgumentException) { frames[frame] = EmptyFrame(); }
}
artwork.Add(kind, frames);
}
}
private static Bitmap EmptyFrame()
{
Bitmap image = new Bitmap(ImageSize, ImageSize, PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(image))
graphics.Clear(Color.FromArgb(17, 21, 20));
return image;
}
public byte[] Render(string kind, int frame, WidgetSettings settings, QuotaSnapshot quota, ServerSnapshot servers, DiskSnapshot disk, DateTime utcNow)
{
Bitmap[] frames;
if (!artwork.TryGetValue(kind, out frames))
throw new ArgumentException("Unknown widget kind.", "kind");
settings = settings ?? new WidgetSettings();
frame = settings.AnimationEnabled ? Math.Max(0, Math.Min(7, frame)) : 0;
WidgetText text = Describe(kind, settings, quota, servers, disk, utcNow);
using (Bitmap image = new Bitmap(frames[frame]))
using (Graphics graphics = Graphics.FromImage(image))
using (MemoryStream output = new MemoryStream())
{
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
using (Brush shadow = new SolidBrush(Color.FromArgb(190, 0, 0, 0)))
using (Brush title = new SolidBrush(Color.FromArgb(225, 228, 220)))
using (Brush accent = new SolidBrush(text.Accent))
using (Brush secondary = new SolidBrush(Color.FromArgb(210, 211, 205)))
using (StringFormat center = new StringFormat())
{
center.Alignment = StringAlignment.Center;
center.LineAlignment = StringAlignment.Center;
center.Trimming = StringTrimming.EllipsisCharacter;
center.FormatFlags = StringFormatFlags.NoWrap;
graphics.DrawString(text.Title, titleFont, shadow, new RectangleF(5, 5, 136, 15), center);
graphics.DrawString(text.Title, titleFont, title, new RectangleF(4, 4, 136, 15), center);
graphics.DrawString(text.Value, valueFont, accent, new RectangleF(2, 96, 140, 32), center);
graphics.DrawString(text.Secondary, detailFont, secondary, new RectangleF(4, 126, 136, 16), center);
}
image.Save(output, ImageFormat.Png);
return output.ToArray();
}
}
public static WidgetText Describe(string kind, WidgetSettings settings, QuotaSnapshot quota, ServerSnapshot servers, DiskSnapshot disk, DateTime utcNow)
{
settings = settings ?? new WidgetSettings();
if (kind == "quota") return DescribeQuota(settings, quota, utcNow);
if (kind == "servers") return DescribeServers(servers, utcNow);
if (kind == "disk") return DescribeDisk(settings, disk, utcNow);
throw new ArgumentException("Unknown widget kind.", "kind");
}
private static WidgetText DescribeQuota(WidgetSettings settings, QuotaSnapshot snapshot, DateTime now)
{
WidgetText result = new WidgetText { Title = "CODEX LEFT", Value = "UNKNOWN", Secondary = "QUOTA UNAVAILABLE", Accent = Gray };
if (snapshot == null) return result;
if (snapshot.Status == "login-required")
{
result.Value = "LOGIN";
result.Secondary = "SIGN IN TO CODEX";
return result;
}
List<QuotaWindow> windows = (snapshot.Windows ?? new List<QuotaWindow>())
.Where(delegate(QuotaWindow window) { return window != null && !Double.IsNaN(window.UsedPercent) && !Double.IsInfinity(window.UsedPercent); })
.OrderByDescending(delegate(QuotaWindow window) { return Clamp(window.UsedPercent, 0, 100); })
.ThenBy(delegate(QuotaWindow window) { return window.WindowMinutes; }).ToList();
if (windows.Count == 0 || (snapshot.Status != "ready" && snapshot.Status != "stale")) return result;
int selected = settings.QuotaCycle ? (int)(now.Ticks / TimeSpan.FromSeconds(5).Ticks % windows.Count) : 0;
QuotaWindow chosen = windows[selected];
double remaining = 100 - Clamp(chosen.UsedPercent, 0, 100);
bool stale = IsStale(snapshot.Status, snapshot.UpdatedAt, now, TimeSpan.FromMinutes(6)) ||
(chosen.ResetsAt != DateTime.MinValue && chosen.ResetsAt <= now && chosen.UsedPercent > 0);
result.Value = remaining.ToString("0", CultureInfo.InvariantCulture) + "%";
result.Secondary = stale ? "STALE · " + WindowLabel(chosen.WindowMinutes) : WindowLabel(chosen.WindowMinutes) + " · " + ResetLabel(chosen.ResetsAt, now);
result.Accent = stale ? Gray : remaining <= 10 ? Red : remaining <= 25 ? Amber : Green;
return result;
}
private static WidgetText DescribeServers(ServerSnapshot snapshot, DateTime now)
{
WidgetText result = new WidgetText { Title = "LIVE", Value = "UNKNOWN", Secondary = "SERVERS UNAVAILABLE", Accent = Gray };
if (snapshot == null || (snapshot.Status != "ready" && snapshot.Status != "stale")) return result;
List<DevServer> live = (snapshot.Servers ?? new List<DevServer>()).Where(delegate(DevServer server) { return server != null && server.Reachable; })
.OrderBy(delegate(DevServer server) { return server.Port; }).ThenBy(delegate(DevServer server) { return server.ProcessId; }).ToList();
bool stale = IsStale(snapshot.Status, snapshot.UpdatedAt, now, TimeSpan.FromSeconds(30));
if (live.Count == 0)
{
result.Value = stale ? "UNKNOWN" : "0 LIVE";
result.Secondary = stale ? "LAST CHECK FAILED" : "NO DEV SERVERS";
result.Accent = Gray;
return result;
}
DevServer selected = live[(int)(now.Ticks / TimeSpan.FromSeconds(3).Ticks % live.Count)];
result.Value = live.Count.ToString(CultureInfo.InvariantCulture) + " LIVE";
result.Secondary = stale ? "STALE · :" + selected.Port.ToString(CultureInfo.InvariantCulture) : ":" + selected.Port.ToString(CultureInfo.InvariantCulture) + " " + CleanText(selected.Label, 20);
result.Accent = stale ? Gray : Green;
return result;
}
private static WidgetText DescribeDisk(WidgetSettings settings, DiskSnapshot snapshot, DateTime now)
{
WidgetText result = new WidgetText { Title = "C:", Value = "UNKNOWN", Secondary = "DISK UNAVAILABLE", Accent = Gray };
if (snapshot == null || (snapshot.Status != "ready" && snapshot.Status != "stale") || snapshot.TotalBytes <= 0 || snapshot.FreeBytes < 0 || snapshot.FreeBytes > snapshot.TotalBytes)
return result;
double gb = snapshot.FreeBytes / 1073741824.0;
double percent = 100.0 * snapshot.FreeBytes / snapshot.TotalBytes;
bool stale = IsStale(snapshot.Status, snapshot.UpdatedAt, now, TimeSpan.FromSeconds(60));
result.Value = gb.ToString(gb < 10 ? "0.0" : "0", CultureInfo.InvariantCulture) + " GiB";
result.Secondary = stale ? "STALE · C: FREE" : percent.ToString("0", CultureInfo.InvariantCulture) + "% FREE · C:";
result.Accent = stale ? Gray : gb < settings.DiskCriticalGb || percent < settings.DiskCriticalPercent ? Red :
gb < settings.DiskWarningGb || percent < settings.DiskWarningPercent ? Amber : Green;
return result;
}
private static bool IsStale(string status, DateTime updated, DateTime now, TimeSpan lifetime)
{
return status == "stale" || updated == DateTime.MinValue || updated > now.AddMinutes(1) || now - updated > lifetime;
}
private static string WindowLabel(int minutes)
{
if (minutes >= 1440) return (minutes / 1440.0).ToString("0.#", CultureInfo.InvariantCulture) + "D";
if (minutes >= 60) return (minutes / 60.0).ToString("0.#", CultureInfo.InvariantCulture) + "H";
return minutes > 0 ? minutes.ToString(CultureInfo.InvariantCulture) + "M" : "QUOTA";
}
private static string ResetLabel(DateTime reset, DateTime now)
{
if (reset == DateTime.MinValue) return "REMAINING";
TimeSpan left = reset - now;
if (left <= TimeSpan.Zero) return "REFRESHING";
if (left.TotalDays >= 1) return "RESET " + Math.Ceiling(left.TotalDays).ToString("0", CultureInfo.InvariantCulture) + "D";
if (left.TotalHours >= 1) return "RESET " + Math.Ceiling(left.TotalHours).ToString("0", CultureInfo.InvariantCulture) + "H";
return "RESET " + Math.Max(1, Math.Ceiling(left.TotalMinutes)).ToString("0", CultureInfo.InvariantCulture) + "M";
}
public static string CleanText(string value, int maximumLength)
{
if (String.IsNullOrWhiteSpace(value)) return "DEV";
string cleaned = new string(value.Where(delegate(char character) { return !Char.IsControl(character); }).ToArray()).Trim();
return cleaned.Length > maximumLength ? cleaned.Substring(0, maximumLength) : cleaned;
}
private static double Clamp(double value, double minimum, double maximum) { return Math.Max(minimum, Math.Min(maximum, value)); }
public void Dispose()
{
foreach (Bitmap[] frames in artwork.Values)
foreach (Bitmap frame in frames) frame.Dispose();
valueFont.Dispose();
detailFont.Dispose();
titleFont.Dispose();
}
}
}
AssemblyInfo.cs
Release metadata
using System.Reflection;
using System.Runtime.Versioning;
[assembly: AssemblyTitle("Vercetti HUD")]
[assembly: AssemblyProduct("Vercetti HUD for MARS Gaming MSD")]
[assembly: AssemblyCompany("Critical Developer")]
[assembly: AssemblyVersion("1.0.4.0")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
Source files
2 filesbuild.ps1
Build the complete plugin folder
#requires -Version 5.1
[CmdletBinding()]
param([string]$Destination = (Join-Path $PSScriptRoot 'build\com.criticaldeveloper.vercetti-hud.sdPlugin'))
$ErrorActionPreference = 'Stop'
$destinationPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)
$compiler = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
if (-not (Test-Path -LiteralPath $compiler -PathType Leaf)) { throw '.NET Framework compiler unavailable.' }
$sources = @('AssemblyInfo.cs', 'CodexQuota.cs', 'LocalMetrics.cs', 'PluginHost.cs', 'WidgetRenderer.cs') | ForEach-Object { Join-Path $PSScriptRoot ('src\' + $_) }
foreach ($source in $sources) { if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw ('Missing source: ' + $source) } }
New-Item -ItemType Directory -Path $destinationPath -Force | Out-Null
$compilerArgs = @('/nologo', '/target:winexe', '/platform:anycpu', '/optimize+', '/warn:4', '/langversion:5',
'/r:System.Drawing.dll', '/r:System.Web.Extensions.dll', '/r:System.Net.Http.dll', '/r:System.Management.dll',
('/out:' + (Join-Path $destinationPath 'CriticalHud.exe'))) + $sources
& $compiler @compilerArgs
if ($LASTEXITCODE -ne 0) { throw 'Plugin compilation failed.' }
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'plugin\manifest.json') -Destination (Join-Path $destinationPath 'manifest.json') -Force
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'plugin\inspector.html') -Destination (Join-Path $destinationPath 'inspector.html') -Force
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'plugin\CriticalHud.exe.config') -Destination (Join-Path $destinationPath 'CriticalHud.exe.config') -Force
$manifestData = Get-Content -LiteralPath (Join-Path $destinationPath 'manifest.json') -Raw | ConvertFrom-Json
if ($manifestData.CodePathWin -ne 'CriticalHud.exe') {
if ($manifestData.CodePathWin -notmatch '^CriticalHud-[0-9.]+\.exe$') { throw 'Unexpected executable filename in manifest.' }
Copy-Item -LiteralPath (Join-Path $destinationPath 'CriticalHud.exe') -Destination (Join-Path $destinationPath $manifestData.CodePathWin) -Force
Copy-Item -LiteralPath (Join-Path $destinationPath 'CriticalHud.exe.config') -Destination (Join-Path $destinationPath ($manifestData.CodePathWin + '.config')) -Force
}
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets') -Destination $destinationPath -Recurse -Force
Add-Type -AssemblyName System.Drawing
$categorySource = [Drawing.Image]::FromFile((Join-Path $destinationPath 'assets\quota\icon.png'))
$categoryImage = [Drawing.Bitmap]::new(48, 48)
$categoryGraphics = [Drawing.Graphics]::FromImage($categoryImage)
try {
$categoryGraphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$categoryGraphics.DrawImage($categorySource, 0, 0, 48, 48)
$categoryImage.Save((Join-Path $destinationPath 'assets\category.png'), [Drawing.Imaging.ImageFormat]::Png)
} finally { $categoryGraphics.Dispose(); $categoryImage.Dispose(); $categorySource.Dispose() }
'Built: ' + (Join-Path $destinationPath 'CriticalHud.exe')
README.md
Release changes, diagnostics and detailed test commands
# Vercetti HUD: source edition for the MSD-ONE walkthrough
Source edition 1.0.4, reviewed 27 October 2026. One C# Windows plugin exposes three
actions: Codex quota, Live dev servers, and C: free space.
## Requirements
- Windows 10 or later with .NET Framework 4.8 and its C# compiler.
- MARS GAMING MSD. The manifest minimum is 3.10.188.226; the author's installed
host is 3.10.192.0530. Other hosts and devices were not tested.
- For the quota action, a signed-in Codex executable found among the current
user's running processes or in the supported desktop layout. Executable
discovery is in `src/CodexQuota.cs`; a deployment
with a different executable layout can require an adaptation there.
The plugin needs no Node, Python, npm packages, API key, background web service,
or administrator privileges. Node is needed only for the optional inspector tests.
### Tested environment
| Component | Observed on 27 October 2026 |
| --- | --- |
| Windows | Windows 11 Pro 25H2, x64, build 26200.9711 |
| Codex selected by the quota reader | `codex-cli 0.160.0` |
| MARS GAMING MSD | 3.10.192.0530 |
| Installed HUD in the device photograph and desktop captures | 1.0.3; executable 1.0.3.0 |
| This source edition | 1.0.4; executable 1.0.4.0 |
| Installed .NET Framework | 4.8.1, Release 533509; compiler 4.8.9221.0 |
| Plugin target | .NET Framework 4.8, C# 5, AnyCPU |
The locator selects the first qualifying running `codex.exe` belonging to the
current Windows user. It does not choose the newest version. The resolved
executable in this check was an existing local npm installation; the separate
desktop-bundled executable reported `0.164.0-alpha.11.1`. The installed locator
was invoked directly to verify which one it selected. With no qualifying running
process, the fallback checks `%LOCALAPPDATA%\OpenAI\Codex\bin`, then its immediate
version directories. A Codex command available only in an unrelated PATH folder
is not discovered automatically.
## Build
Extract the entire archive into a writable folder. Open PowerShell in the folder
containing this README and `build.ps1`. Review the source and script first.
```powershell
.\build.ps1 -Destination '.\build\com.criticaldeveloper.vercetti-hud.sdPlugin'
& '.\build\com.criticaldeveloper.vercetti-hud.sdPlugin\CriticalHud-1.0.4.exe' --self-test | Out-String
```
The build uses the Windows .NET Framework compiler with C# 5, and references
System.Drawing, System.Web.Extensions, System.Net.Http and System.Management.
It creates `CriticalHud.exe`, the versioned executable named in the manifest,
their runtime configuration files, the inspector, manifest and artwork assets.
No dependency download occurs. The self-test uses synthetic readings and should
report `ok: true`, `frames: 24`, and `checks: 16`.
### If PowerShell blocks build.ps1
Run `Get-ExecutionPolicy -List` to see the policy at each scope. `Restricted`
prevents script execution. `RemoteSigned` can block an unsigned script marked as
downloaded from the internet even when local scripts are allowed. These are
different causes: removing a downloaded-file mark does not override `Restricted`
or an organization policy. Follow the approved policy on a managed machine.
After inspecting the downloaded source, `Unblock-File -LiteralPath .\build.ps1`
can remove that file's internet-zone mark when `RemoteSigned` is the relevant
restriction. It does not change execution policy. Review the named file before
unblocking it. See Microsoft's [execution-policy explanation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1)
and [Unblock-File reference](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/unblock-file?view=powershell-5.1).
## Install
Quit MARS GAMING MSD completely before copying. The following commands refuse
to replace an existing installation:
```powershell
$pluginName = 'com.criticaldeveloper.vercetti-hud.sdPlugin'
$pluginRoot = Join-Path $env:APPDATA 'HotSpot\StreamDock\plugins'
$pluginTarget = Join-Path $pluginRoot $pluginName
if (Test-Path -LiteralPath $pluginTarget) {
throw 'Plugin already exists. Back it up and review an update separately.'
}
New-Item -ItemType Directory -Path $pluginRoot -Force | Out-Null
Copy-Item -LiteralPath (Join-Path '.\build' $pluginName) -Destination $pluginRoot -Recurse
```
Reopen MARS GAMING MSD. In the `Panel` tab, expand `Vercetti HUD` and drag each
action into one of the three information slots on the side display. Select a
slot to inspect its readings, request a refresh, or disable animation. The quota
action can rotate through windows. Regular pad keys can refresh an indicator;
the information slots are display-only.
The server inspector lists and opens detected local URLs. It does **not** stop
processes. Stop a server from its owning terminal or another process-management
tool after identifying it.
## What is included
- `src/`: five C# source files for collectors, SDK transport, lifecycle and rendering.
- `plugin/`: manifest, property inspector and .NET runtime configuration.
- `assets/`: eight 144x144 frames and one icon per action, plus crop/hash provenance.
- `tests/`: fake Codex process, quota checks, inspector checks, metrics fixtures,
and the SDK protocol test source. These are source files, not test results.
- `build.ps1`: compiler and package assembly script.
The drawings come from Critical Developer's Vercetti's Tales artwork project.
`assets/artwork-provenance.json` records relative source-art paths, original
SHA-256 hashes, crop rectangles, fixed scaling, output hashes and playback order.
Original large sheets are not needed to build this plugin. Replacing the frames
and icons lets you use your own visual theme; preserve their dimensions and the
manifest paths. Artwork attribution is Critical Developer, Vercetti's Tales.
The original package did not include a separate license file.
## Differences from the installed package
The original installed package is 1.0.3. Source edition 1.0.4 changes the LCD disk
suffix from `GB` to `GiB` and includes the quota bucket identifier in the desktop
inspector and diagnostic JSON. Selection still compares all valid returned
windows across buckets; it chooses the highest used percentage, then the shortest
duration for equal percentages. The inspector labels each window with its
validated `limitId` (for example, `codex · Weekly`). It does not use `limitName`
or offer a per-bucket selector. Optional rotation cycles the returned windows.
The public source also derives a narrow OpenClaw gateway exclusion from the current user's profile instead of
embedding the author's Windows username. It still assumes the same
`Documents\CriticalDeveloper\OpenClaw` installation layout. This is an optional
assistant-service exclusion, not a general OpenClaw detector. The BCO exclusion
and `C:\dev\` project heuristic also reflect the author's setup; inspect
`src/LocalMetrics.cs` before adapting them.
For portability, `build.ps1` defaults to `build/` within this folder. An explicit
relative `-Destination` resolves against the current PowerShell location,
including after `Set-Location`; an absolute destination is preserved. The
metrics test uses the same per-user path and adds a `--pure` mode that runs no
live discovery. Artwork provenance paths are relative. No installed plugin,
desktop profile, credential file, runtime log or original source was modified
when preparing this archive.
## Optional checks
Run these in an extracted working copy. They create test executables there.
```powershell
.\tests\quota-tests.ps1
node --test .\tests\inspector.test.mjs
$compiler = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
& $compiler /nologo /warnaserror /target:exe /out:tests\local-tests.exe /r:System.Management.dll .\src\LocalMetrics.cs .\tests\local-tests.cs
& '.\tests\local-tests.exe' --pure
```
The quota checks use a local fake `codex.exe`, not the signed-in account. The
inspector checks run in a simulated DOM/WebSocket. Pure metrics checks classify
synthetic process/listener records. Expected results are 29 quota assertions,
6 inspector tests and 44 pure classification assertions. The self-test covers
16 display/packaging checks, including binary disk units, signed-out/missing/stale
states, cross-bucket selection and bucket identity sanitization. The inspector
tests include equal-duration windows with different bucket identifiers.
The additional `local-run-tests.ps1` creates temporary TLS certificates through
Git for Windows' `openssl.exe` and launches owned HTTP/TLS fixtures; it also runs
the real local discovery collector. It is optional and was not rerun for this
source edition. `host-protocol.cs` is the fixture for the SDK lifecycle and
reconnect behavior; the 14-check reconnect result belongs to the original
development record, not a new physical-device test of this source edition.
## Diagnose an unavailable reading
The plugin does not maintain a log file. Its diagnostic mode writes sanitized
JSON to standard output, independently of the MSD socket and physical display:
```powershell
$hud = '.\build\com.criticaldeveloper.vercetti-hud.sdPlugin\CriticalHud-1.0.4.exe'
$report = (& $hud --diagnostics | Out-String) | ConvertFrom-Json
$report.quota.Status
$report.servers.Status
$report.disk.Status
```
This performs account-limit reads, local endpoint probes and the C: drive query.
It starts its own temporary Codex app-server process, submits no model prompt,
and does not stop a development server. Allow up to 25 seconds. The executable
can exit successfully even if a collector is unavailable, so inspect each
`Status`, rather than relying on the exit code alone.
A working collection reports `ready`. `quota.Windows` contains `Bucket`, `Label`,
`UsedPercent`, `WindowMinutes` and `ResetsAt`; `servers.Servers` contains detected
endpoints and can legitimately be empty; `disk.TotalBytes` should be positive.
The October 27 check returned `ready` for all three collectors, one quota window
in the `codex` bucket and zero detected development endpoints.
- `quota.Status = login-required`: sign in to Codex with ChatGPT, then refresh.
- `quota.Status = unavailable`: check the resolved executable/version and its
sign-in. For another installation layout, inspect or adapt `FindExecutable`
in `src/CodexQuota.cs` and rebuild.
- `servers.Status = unavailable`: Windows listener/process discovery or probes
failed. A `ready` result with an empty list instead means no matching endpoint
responded. For a missing known server, inspect the runtime, framework and
path heuristics in `src/LocalMetrics.cs`.
- `disk.Status = unavailable`: check that C: exists, is ready and is accessible
to the current Windows user. The collector is fixed to C: in `LocalMetrics.cs`.
- Collectors report `ready`, but the deck stays stale: check the installed
manifest's `CodePathWin`, folder nesting, MSD restart and whether the widget
is visible. Diagnostics tests the readings, not the host's image delivery.
During normal operation, `STALE` preserves a previous successful reading after
a failed refresh. A new diagnostics invocation has no previous reading to retain.
Diagnostic JSON includes local project labels, ports and usage readings; keep
that output local when it contains information you do not want to share.
## Reading semantics
- Quota refresh: 120 seconds while visible. Default display is the highest-used
valid window across returned buckets, not the subscription billing period or
a token estimate. Bucket identity is included in the inspector.
- Server refresh: 5 seconds while visible. Counts confirmed candidate HTTP/HTTPS
endpoints after process heuristics, not every process or listener on the machine.
- Disk refresh: 15 seconds while visible. Uses `DriveInfo.AvailableFreeSpace`
for `C:`; both LCD and inspector label 1,073,741,824-byte units as `GiB`.
- Rendering: one PNG per displayed action, 144x144, four animation frames per
second. `LOGIN`, `UNKNOWN` and `STALE` are distinct from successful zero values.
For the full explanation, screenshots and validation limits, read the accompanying
Critical Developer article. No tokens, account identifiers, diagnostic output,
compiled binaries, certificate keys or dependencies are included in this archive.
Source files
3 filesmanifest.json
Actions and host requirements
{
"Name": "Vercetti HUD",
"Description": "Animated Vercetti's Tales indicators for Codex quota, live local dev servers and C: free space.",
"Author": "Critical Developer",
"Version": "1.0.4",
"SDKVersion": 1,
"Category": "Vercetti HUD",
"Icon": "assets/quota/icon.png",
"CategoryIcon": "assets/category.png",
"CodePath": "CriticalHud-1.0.4.exe",
"CodePathWin": "CriticalHud-1.0.4.exe",
"RunAsAdministrator": false,
"OS": [{ "Platform": "windows", "MinimumVersion": "10" }],
"Software": { "MinimumVersion": "3.10.188.226" },
"Actions": [
{
"UUID": "com.criticaldeveloper.vercetti-hud.quota",
"Name": "Codex quota",
"Tooltip": "Remaining Codex allowance and reset countdown using your existing ChatGPT login.",
"Icon": "assets/quota/icon.png",
"Controllers": ["Keypad", "Information"],
"PropertyInspectorPath": "inspector.html",
"UserTitleEnabled": false,
"SupportedInMultiActions": false,
"Settings": { "animationEnabled": true, "quotaCycle": false },
"States": [{ "Image": "assets/quota/frame-00.png", "ShowTitle": false, "Title": "" }]
},
{
"UUID": "com.criticaldeveloper.vercetti-hud.servers",
"Name": "Live dev servers",
"Tooltip": "Discover live development HTTP servers on this computer; rotate through every detected server.",
"Icon": "assets/servers/icon.png",
"Controllers": ["Keypad", "Information"],
"PropertyInspectorPath": "inspector.html",
"UserTitleEnabled": false,
"SupportedInMultiActions": false,
"Settings": { "animationEnabled": true },
"States": [{ "Image": "assets/servers/frame-00.png", "ShowTitle": false, "Title": "" }]
},
{
"UUID": "com.criticaldeveloper.vercetti-hud.disk",
"Name": "C: free space",
"Tooltip": "Available storage on C: with low-space warnings.",
"Icon": "assets/disk/icon.png",
"Controllers": ["Keypad", "Information"],
"PropertyInspectorPath": "inspector.html",
"UserTitleEnabled": false,
"SupportedInMultiActions": false,
"Settings": { "animationEnabled": true },
"States": [{ "Image": "assets/disk/frame-00.png", "ShowTitle": false, "Title": "" }]
}
]
}
inspector.html
Settings, allowance windows and endpoint list
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vercetti HUD</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body { margin: 0; padding: 18px; background: #151719; color: #e9e7df; font: 13px/1.5 "Segoe UI", sans-serif; }
.brand { color: #d9b46a; font-size: 10px; font-weight: 700; letter-spacing: 2px; text-transform: uppercase; }
h1 { margin: 5px 0 12px; font-size: 21px; line-height: 1.2; }
.description, .note { color: #a4aaa9; }
.description { margin: 0 0 17px; }
.card { padding: 13px; border: 1px solid #383a32; border-radius: 9px; background: #1c201e; }
.status { margin: 0 0 8px; color: #d9b46a; font-size: 11px; font-weight: 700; letter-spacing: .6px; }
.row { display: flex; justify-content: space-between; gap: 12px; padding: 7px 0; border-bottom: 1px solid #343731; }
.row:last-child { border-bottom: 0; }
.label { color: #b1b8b4; overflow-wrap: anywhere; }
.value { text-align: right; font-variant-numeric: tabular-nums; }
.server { padding: 9px 0; border-bottom: 1px solid #343731; }
.server:last-child { border-bottom: 0; }
.server-name { font-weight: 600; overflow-wrap: anywhere; }
.link { padding: 0; border: 0; background: transparent; color: #b3d6aa; cursor: pointer; font: inherit; text-align: left; }
.controls { display: flex; flex-wrap: wrap; gap: 12px; margin: 16px 0 9px; }
label { cursor: pointer; }
input { accent-color: #b5c58b; vertical-align: middle; }
button.refresh { margin-top: 8px; padding: 9px 16px; border: 1px solid #bc9f62; border-radius: 6px; background: #302b20; color: #f2e4c5; font: 600 13px "Segoe UI", sans-serif; cursor: pointer; }
button:focus-visible, input:focus-visible { outline: 2px solid #f2ca73; outline-offset: 3px; }
button:disabled { opacity: .6; cursor: wait; }
.note { margin: 13px 0 0; font-size: 11px; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<div class="brand">Vercetti's Tales</div>
<h1 id="heading">Vercetti HUD</h1>
<p class="description" id="description">Live information, original artwork.</p>
<div class="card" aria-live="polite">
<p class="status" id="status">CONNECTING</p>
<div id="details">Waiting for the widget.</div>
</div>
<div class="controls">
<label><input id="animation" type="checkbox" checked> Animate artwork</label>
<label id="cycle-label" hidden><input id="cycle" type="checkbox"> Rotate quota windows</label>
</div>
<button class="refresh" id="refresh" type="button" disabled>Refresh now</button>
<p class="note" id="note">The sidebar displays information. A regular pad key refreshes its indicator.</p>
<script>
(function () {
'use strict';
var socket, actionContext, actionUuid, inspectorId, settings = {}, kind = '';
var headings = { quota: 'Codex quota', servers: 'Live dev servers', disk: 'C: free space' };
var descriptions = {
quota: 'Remaining account allowance and reset time. Uses your existing Codex / ChatGPT sign-in.',
servers: 'All detected development HTTP servers. The pad rotates through the list automatically.',
disk: 'Available space on C:, with amber and red low-space warnings.'
};
function field(object, name) {
if (!object) return undefined;
return object[name] !== undefined ? object[name] : object[name.charAt(0).toLowerCase() + name.slice(1)];
}
function send(event, context, payload) {
if (!socket || socket.readyState !== 1) return;
var message = { event: event, context: context, payload: payload };
if (event === 'sendToPlugin') message.action = actionUuid;
socket.send(JSON.stringify(message));
}
function command(name) { send('sendToPlugin', inspectorId, { command: name }); }
function syncSettings(next) {
settings = next && typeof next === 'object' ? next : {};
document.getElementById('animation').checked = settings.animationEnabled !== false;
document.getElementById('cycle').checked = settings.quotaCycle === true;
}
function saveSettings() {
settings.animationEnabled = document.getElementById('animation').checked;
settings.quotaCycle = document.getElementById('cycle').checked;
send('setSettings', inspectorId, settings);
}
function row(label, value) {
var node = document.createElement('div'); node.className = 'row';
var left = document.createElement('span'); left.className = 'label'; left.textContent = label;
var right = document.createElement('span'); right.className = 'value'; right.textContent = value;
node.appendChild(left); node.appendChild(right); return node;
}
function date(value) {
if (typeof value === 'string' && /^\/Date\(/.test(value)) return new Date(Number(value.slice(6).split(/[+-]/)[0]));
return new Date(value);
}
function updatedLabel(value) {
var parsed = date(value);
return isNaN(parsed.getTime()) ? 'Update time unavailable' : 'Updated ' + parsed.toLocaleTimeString();
}
function localPreviewUrl(value) {
if (typeof value !== 'string') return false;
try {
var parsed = new URL(value);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
if (parsed.username || parsed.password || parsed.search || parsed.hash || parsed.pathname !== '/') return false;
if (parsed.port && (!/^\d+$/.test(parsed.port) || Number(parsed.port) < 1 || Number(parsed.port) > 65535)) return false;
var host = parsed.hostname.toLowerCase();
if (host === 'localhost' || host === '[::1]') return true;
return /^127(?:\.\d{1,3}){3}$/.test(host) && host.split('.').every(function (part) { return Number(part) <= 255; });
} catch (_) { return false; }
}
function render(message) {
var snapshot = message.snapshot || message.data;
if (!snapshot || typeof snapshot !== 'object') return;
var status = String(field(snapshot, 'Status') || 'unavailable');
document.getElementById('status').textContent = status === 'ready' ? 'LIVE' : status.toUpperCase().replace(/-/g, ' ');
var details = document.getElementById('details');
while (details.firstChild) details.removeChild(details.firstChild);
if (kind === 'quota') {
var windows = field(snapshot, 'Windows') || [];
if (!windows.length) details.textContent = status === 'login-required' ? 'Sign in to Codex with ChatGPT to display your allowance.' : 'Quota data is currently unavailable.';
windows.forEach(function (window) {
var used = field(window, 'UsedPercent');
var remaining = typeof used === 'number' && isFinite(used) ? Math.max(0, Math.min(100, 100 - used)) : null;
var label = field(window, 'Label') || 'Allowance';
var bucket = field(window, 'Bucket');
details.appendChild(row(bucket ? bucket + ' · ' + label : label, remaining === null ? 'Unknown' : Math.round(remaining) + '% remaining'));
var reset = date(field(window, 'ResetsAt'));
if (!isNaN(reset.getTime())) details.appendChild(row('Resets', reset.toLocaleString()));
});
} else if (kind === 'servers') {
var servers = field(snapshot, 'Servers') || [];
if (!servers.length) details.textContent = status === 'ready' ? 'No live development HTTP servers detected.' : 'Local server discovery is currently unavailable.';
servers.forEach(function (server) {
var item = document.createElement('div'); item.className = 'server';
var name = document.createElement('div'); name.className = 'server-name';
name.textContent = (field(server, 'Label') || field(server, 'ProcessName') || 'Dev server') + ' · :' + field(server, 'Port');
item.appendChild(name);
var url = field(server, 'Url');
if (localPreviewUrl(url)) {
var link = document.createElement('button'); link.className = 'link'; link.type = 'button'; link.textContent = url;
link.addEventListener('click', function () { send('openUrl', inspectorId, { url: url }); });
item.appendChild(link);
}
details.appendChild(item);
});
} else if (kind === 'disk') {
var free = field(snapshot, 'FreeBytes'), total = field(snapshot, 'TotalBytes');
if (status !== 'ready' || !(total > 0)) details.textContent = 'Disk information is currently unavailable.';
else {
details.appendChild(row('Available', (free / 1073741824).toFixed(1) + ' GiB'));
details.appendChild(row('Total', (total / 1073741824).toFixed(1) + ' GiB'));
details.appendChild(row('Free', (100 * free / total).toFixed(1) + '%'));
}
}
document.getElementById('note').textContent = updatedLabel(field(snapshot, 'UpdatedAt')) + (status === 'stale' ? ' · Showing the last successful reading.' : '');
}
window.connectElgatoStreamDeckSocket = function (port, uuid, registerEvent, info, actionInfo) {
var action;
try { action = JSON.parse(actionInfo); } catch (_) { return; }
inspectorId = uuid; actionContext = action.context; actionUuid = action.action;
kind = String(action.action || '').split('.').pop();
document.getElementById('heading').textContent = headings[kind] || 'Vercetti HUD';
document.getElementById('description').textContent = descriptions[kind] || '';
document.getElementById('cycle-label').hidden = kind !== 'quota';
syncSettings(action.payload && action.payload.settings);
if (!/^\d+$/.test(String(port)) || Number(port) < 1 || Number(port) > 65535) return;
socket = new WebSocket('ws://127.0.0.1:' + port);
socket.onopen = function () {
socket.send(JSON.stringify({ event: registerEvent, uuid: uuid }));
document.getElementById('refresh').disabled = false; command('status');
};
socket.onmessage = function (event) {
var message; try { message = JSON.parse(event.data); } catch (_) { return; }
if (message.event === 'sendToPropertyInspector') render(message.payload || {});
if (message.event === 'didReceiveSettings') syncSettings(message.payload && message.payload.settings);
};
socket.onclose = function () {
document.getElementById('status').textContent = 'DISCONNECTED';
document.getElementById('refresh').disabled = true;
};
socket.onerror = function () { document.getElementById('status').textContent = 'CONNECTION UNAVAILABLE'; };
};
document.getElementById('animation').addEventListener('change', saveSettings);
document.getElementById('cycle').addEventListener('change', saveSettings);
document.getElementById('refresh').addEventListener('click', function () {
command('refresh');
var button = this; button.disabled = true;
window.setTimeout(function () { if (socket && socket.readyState === 1) button.disabled = false; }, 2000);
});
}());
</script>
</body>
</html>
CriticalHud.exe.config
.NET Framework target
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
Troubleshooting and validation
From the extracted source root, query the collectors directly:
$hud = '.\build\com.criticaldeveloper.vercetti-hud.sdPlugin\CriticalHud-1.0.4.exe'
$diagnostics = (& $hud --diagnostics | Out-String) | ConvertFrom-Json
$diagnostics | ConvertTo-Json -Depth 6
Successful collection returns Status: ready for quota, servers and disk, with allowance windows, detected endpoints and disk byte counts. An empty ready server list means no matching live endpoint was found. This command writes to the console; the plugin has no persistent log file.
- Category missing in MSD: confirm one
.sdPluginfolder level, the manifest’s executable exists, and MSD was fully restarted. - Quota
login-required: sign in through Codex, rerun diagnostics, then refresh the widget. - Quota unavailable: check the executable locator in
CodexQuota.cs; adapt it for an unsupported installation path. - Server missing: check its runtime/framework/path classification in
LocalMetrics.csand whether it responds to the probe. - LCD stays
STALE: compare diagnostics and the inspector timestamp; if fresh collection succeeds, refresh or reconnect the widget in MSD.
My photograph shows the physical setup, and the desktop captures show the installed plugin detecting the blog preview. The downloadable release was built and exercised separately:
| Check | Behavior exercised |
|---|---|
| Display fixtures | Missing, login and stale states; empty server lists; bounded percentages and GiB units |
| Quota fixtures | Multiple windows/buckets, invalid data, reader failures and process cleanup |
| Inspector/classification fixtures | Bucket labels and settings messages; candidate inclusion, helper/debugger exclusions and deduplication |
| Extracted source and install copy | Complete build assets and refusal to overwrite an existing target |
The README records exact commands and results. Physical testing used the installed 1.0.3 release on this Windows PC; 1.0.4’s changes were checked through the build and fixtures. Other hosts and macOS remain untested.
I used AI assistance for implementation review, this walkthrough and reproduction checks. The result is a dashboard I can glance at, with enough context in the inspector to decide what needs attention.
