Files
ExecuteR/src/Shared.Banner/ScreenBannerProtocol.cs
Alphaeus Mote b3716e3f38 perf(banner): plain Win32 and Native AOT, 47 MB to 1.6 MB
The Being Viewed banner was WinForms published as a self-contained single
file (49.3 MB, ~320 ms just to start and exit). It is now plain Win32 through
source-generated LibraryImport (runtime marshalling disabled, no reflection)
published with Native AOT: 1.6 MB for win-x64 and win-arm64, ~33 ms to start
and exit (the OS process floor), on screen in ~0.1 s.

- BannerWindow: a WS_EX_TOPMOST | TOOLWINDOW | NOACTIVATE popup, a STATIC per
  caption (read by screen readers, clicks fall through to drag) and an
  owner-drawn BUTTON per Stop, named for its session; the mouse is handled in
  a subclass and BM_CLICK invokes directly, so clicking or assistive-tech
  invoke never activates the banner. GDI drawing, comctl32 6 tooltips,
  PerMonitorV2 manifest with WM_DPICHANGED, AppsUseLightTheme and high
  contrast on WM_SETTINGCHANGE, DWM rounded corners and dark frame.
- Same metrics, colours and wording as the WinForms banner (checked against
  screenshots at 125%), now in window-free Logic/ (layout, palette, rows)
  that Agent.Tests compiles and tests.
- The protocol moves to src/Shared.Banner (compiled into agent and banner),
  with the exit codes; DLL hardening, pipe checks and protocol unchanged.
- Package-Agent publishes the banner with AOT when vswhere finds the MSVC
  tools for the RID (and puts vswhere on PATH for newer VS vcvarsall),
  otherwise warns and publishes a trimmed single file (~11 MB).
- README: Build Tools "Desktop development with C++" (plus ARM64 tools) as a
  prerequisite, also for the CI windows-host runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 16:33:17 -05:00

278 lines
10 KiB
C#

using System.Globalization;
using System.Text;
using System.Text.Json;
namespace Agent.Screen;
/// <summary>One Remote View session as the Being Viewed banner shows it.</summary>
/// <param name="SessionId">The Remote View session (the only thing Stop can name).</param>
/// <param name="Operator">Who is viewing (display name), already cleaned for display.</param>
/// <param name="ViewOnly">View Only, otherwise Control.</param>
public sealed record ScreenBannerItem(Guid SessionId, string Operator, bool ViewOnly);
/// <summary>
/// The wire between the agent service and the banner (<c>ExecuteR-Banner.exe</c>) on a
/// named pipe, one UTF-8 line per message. This folder (src/Shared.Banner) is compiled
/// into both the agent and the banner, so it has no dependencies beyond the BCL, uses
/// no reflection (the banner is Native AOT) and never pulls the agent into the banner.
/// <list type="bullet">
/// <item>Pipe: <c>\\.\pipe\ExecuteR-Banner-&lt;32 hex&gt;</c>; the nonce is new for every launch
/// and reaches the banner on its command line (<c>--pipe &lt;name&gt;</c>).</item>
/// <item>Service to banner: <c>{"sessions":[{"sessionId":"…","operator":"…","mode":"control|view-only"}]}</c>,
/// display data only. An empty list hides the banner.</item>
/// <item>Banner to service: <c>stop &lt;session id&gt;</c>, nothing else. Anything else ends the banner.</item>
/// </list>
/// </summary>
public static class ScreenBannerProtocol
{
public const string PipePrefix = "ExecuteR-Banner-";
public const string PipeArgument = "--pipe";
/// <summary>The longest line the banner may send (<c>stop</c>, a space and a GUID, with room to spare).</summary>
public const int MaxBannerLineBytes = 64;
/// <summary>The longest line the service sends.</summary>
public const int MaxServiceLineBytes = 4096;
/// <summary>The most characters of an operator's name shown.</summary>
public const int MaxOperatorLength = 64;
/// <summary>The most sessions one line carries (a device runs at most two).</summary>
public const int MaxItems = 4;
public const string ModeControl = "control";
public const string ModeViewOnly = "view-only";
/// <summary>The banner's exit code when its command line is not <c>--pipe &lt;name&gt;</c>.</summary>
public const int ExitBadArguments = 2;
/// <summary>The banner's exit code when the pipe is not there in time or is not the service's.</summary>
public const int ExitNoService = 3;
private const string StopVerb = "stop ";
public static string PipeName(string nonce) => PipePrefix + nonce;
/// <summary>A pipe name the service makes: the prefix and 32 lowercase hex digits.</summary>
public static bool IsPipeName(string? name)
{
if (name is null || name.Length != PipePrefix.Length + 32 || !name.StartsWith(PipePrefix, StringComparison.Ordinal))
{
return false;
}
foreach (var c in name.AsSpan(PipePrefix.Length))
{
if (!char.IsAsciiHexDigitLower(c) && !char.IsAsciiDigit(c))
{
return false;
}
}
return true;
}
/// <summary>The banner's message asking to end a session.</summary>
public static string StopLine(Guid sessionId) => StopVerb + sessionId.ToString("D", CultureInfo.InvariantCulture);
/// <summary>
/// The only message the service accepts from the banner: exactly <c>stop </c> and a
/// lowercase GUID in its D form. Anything else (another verb, padding, a second
/// argument, another GUID format) is not a stop.
/// </summary>
public static bool TryParseStop(string? line, out Guid sessionId)
{
sessionId = Guid.Empty;
if (line is null || line.Length != StopVerb.Length + 36 || !line.StartsWith(StopVerb, StringComparison.Ordinal))
{
return false;
}
var id = line.AsSpan(StopVerb.Length);
foreach (var c in id)
{
if (c != '-' && !char.IsAsciiDigit(c) && !char.IsAsciiHexDigitLower(c))
{
return false;
}
}
return Guid.TryParseExact(id, "D", out sessionId) && sessionId != Guid.Empty;
}
/// <summary>The service's display line for <paramref name="items"/>.</summary>
public static string ShowLine(IReadOnlyList<ScreenBannerItem> items)
{
using var buffer = new MemoryStream();
using (var writer = new Utf8JsonWriter(buffer))
{
writer.WriteStartObject();
writer.WriteStartArray("sessions");
foreach (var item in items.Take(MaxItems))
{
writer.WriteStartObject();
writer.WriteString("sessionId", item.SessionId.ToString("D", CultureInfo.InvariantCulture));
writer.WriteString("operator", CleanOperator(item.Operator));
writer.WriteString("mode", item.ViewOnly ? ModeViewOnly : ModeControl);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
}
return Encoding.UTF8.GetString(buffer.ToArray());
}
/// <summary>The banner's reading of a display line; false for anything malformed.</summary>
public static bool TryParseShow(string? line, out IReadOnlyList<ScreenBannerItem> items)
{
items = [];
if (string.IsNullOrEmpty(line) || Encoding.UTF8.GetByteCount(line) > MaxServiceLineBytes)
{
return false;
}
try
{
using var document = JsonDocument.Parse(line);
if (document.RootElement.ValueKind != JsonValueKind.Object
|| !document.RootElement.TryGetProperty("sessions", out var sessions)
|| sessions.ValueKind != JsonValueKind.Array
|| sessions.GetArrayLength() > MaxItems)
{
return false;
}
var parsed = new List<ScreenBannerItem>();
foreach (var session in sessions.EnumerateArray())
{
if (session.ValueKind != JsonValueKind.Object
|| !session.TryGetProperty("sessionId", out var id) || id.ValueKind != JsonValueKind.String
|| !Guid.TryParseExact(id.GetString(), "D", out var sessionId)
|| !session.TryGetProperty("operator", out var name) || name.ValueKind != JsonValueKind.String
|| !session.TryGetProperty("mode", out var mode) || mode.ValueKind != JsonValueKind.String)
{
return false;
}
var modeText = mode.GetString();
if (modeText is not (ModeControl or ModeViewOnly))
{
return false;
}
parsed.Add(new ScreenBannerItem(sessionId, CleanOperator(name.GetString()), modeText == ModeViewOnly));
}
items = parsed;
return true;
}
catch (JsonException)
{
return false;
}
}
/// <summary>
/// A name safe to show: no control or bidirectional-override characters (which could
/// make the banner read differently from what was sent), trimmed and capped.
/// </summary>
public static string CleanOperator(string? name)
{
var builder = new StringBuilder();
foreach (var c in name ?? string.Empty)
{
var category = char.GetUnicodeCategory(c);
if (category is UnicodeCategory.Control or UnicodeCategory.Format or UnicodeCategory.LineSeparator
or UnicodeCategory.ParagraphSeparator or UnicodeCategory.Surrogate or UnicodeCategory.PrivateUse
or UnicodeCategory.OtherNotAssigned)
{
continue;
}
builder.Append(c);
}
var text = builder.ToString().Trim();
if (text.Length > MaxOperatorLength)
{
text = text[..MaxOperatorLength].TrimEnd() + "…";
}
return text.Length == 0 ? "An administrator" : text;
}
}
/// <summary>
/// Reads newline-terminated UTF-8 lines of at most a fixed size from a stream: a peer
/// that sends a longer line, or invalid UTF-8, breaks the protocol
/// (<see cref="InvalidDataException"/>) instead of growing a buffer.
/// </summary>
public sealed class ScreenBannerLineReader(Stream stream, int maxLineBytes)
{
private static readonly UTF8Encoding Strict = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
private readonly byte[] buffer = new byte[Math.Max(256, maxLineBytes + 1)];
private int start;
private int end;
/// <summary>The next line without its terminator (a trailing CR is dropped), or null at the end of the stream.</summary>
public async Task<string?> ReadLineAsync(CancellationToken cancellationToken)
{
while (true)
{
var newline = Array.IndexOf(buffer, (byte)'\n', start, end - start);
if (newline >= 0)
{
var length = newline - start;
if (length > maxLineBytes)
{
throw new InvalidDataException("The line is too long.");
}
var line = Decode(buffer.AsSpan(start, length));
start = newline + 1;
return line;
}
if (end - start > maxLineBytes)
{
throw new InvalidDataException("The line is too long.");
}
if (start > 0)
{
Array.Copy(buffer, start, buffer, 0, end - start);
end -= start;
start = 0;
}
var read = await stream.ReadAsync(buffer.AsMemory(end), cancellationToken).ConfigureAwait(false);
if (read == 0)
{
return null;
}
end += read;
}
}
private static string Decode(ReadOnlySpan<byte> bytes)
{
if (bytes.Length > 0 && bytes[^1] == (byte)'\r')
{
bytes = bytes[..^1];
}
try
{
return Strict.GetString(bytes);
}
catch (DecoderFallbackException exception)
{
throw new InvalidDataException("The line is not UTF-8.", exception);
}
}
}