From 27ddb2b9dbe3b3c7369746314c3989104a8ba2dd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:44:37 +0000 Subject: [PATCH 1/7] Update TelnetNegotiationCore to 4.13.2 and the Microsoft packages TelnetNegotiationCore 4.13.2 on net10.0 depends on Microsoft.Extensions.Logging.Abstractions 11.0.0, so that moves with it. Microsoft.CodeAnalysis.BannedApiAnalyzers goes from 3.3.4 to 5.6.0; a banned call in the Tui still fails the build with RS0030. No source change was needed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- CHANGELOG.md | 4 ++++ Directory.Packages.props | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd0c12f1..6602139a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,10 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`] ### Changed +- Updated TelnetNegotiationCore to 4.13.2 and Microsoft.Extensions.Logging.Abstractions to 11.0.0 (which 4.13.2 + needs). Nothing a player does changes: the new library releases add WebSocket transports and connection hooks this + client does not use yet. + - The quick bar lists every key you have bound, not only function keys. Keypad and letter-chord bindings (`Num8`, `Ctrl+E`) used to be left off it. Function keys come first, then other chords, then the keypad in the pad's own order. When the bar is short of room it says `nw` for `northwest` and `Num 7 nw 8 n` for the keypad before it diff --git a/Directory.Packages.props b/Directory.Packages.props index 4b4a1142..0776a2f6 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -19,7 +19,7 @@ - + @@ -58,7 +58,7 @@ - + - + From 507d454db42d691f87852f5b3e2aabfb15c94735 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:52:37 +0000 Subject: [PATCH 2/7] Update MarkupString to 2.31.3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- CHANGELOG.md | 2 +- Directory.Packages.props | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6602139a..79de5a69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,7 +54,7 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`] ### Changed -- Updated TelnetNegotiationCore to 4.13.2 and Microsoft.Extensions.Logging.Abstractions to 11.0.0 (which 4.13.2 +- Updated TelnetNegotiationCore to 4.13.2, MarkupString to 2.31.3 and Microsoft.Extensions.Logging.Abstractions to 11.0.0 (which 4.13.2 needs). Nothing a player does changes: the new library releases add WebSocket transports and connection hooks this client does not use yet. diff --git a/Directory.Packages.props b/Directory.Packages.props index 0776a2f6..1c04c074 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,10 +13,10 @@ Reading server output: ANSI/VT, MXP and Pueblo into MarkupText, which Core folds into StyledLine (Text/MarkupLineParser). One version for the family. --> - - - - + + + + From 50e5d8a2a8eecf57a08cb200d30ddf1642445d88 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 19:01:46 +0000 Subject: [PATCH 3/7] Run the telnet read loop through the library's StartAsync TelnetSession ran its own loop around InterpretByteArrayAsync. It now hands our transport to TelnetNegotiationCore (TransportBridge) and starts the connection with StartAsync: OnStarting sets and seeds the interpreter before anything is read, OnInputProcessed raises ReceiveBatchEnded, and WrapOutput watches for IAC DO MSDP where the negotiation callback used to. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- src/SharpMUTerm.Core/Telnet/TelnetSession.cs | 91 ++++++++++++------- .../Telnet/TransportBridge.cs | 35 +++++++ 2 files changed, 92 insertions(+), 34 deletions(-) create mode 100644 src/SharpMUTerm.Core/Telnet/TransportBridge.cs diff --git a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs index cec9f179..5e0814ea 100644 --- a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs +++ b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs @@ -325,7 +325,8 @@ public sealed class TelnetSession : ITelnetSession private SessionEncoding _lastReported; - private TelnetInterpreter? _interpreter; + private volatile TelnetInterpreter? _interpreter; + private TelnetNegotiationCore.Connections.TelnetConnection? _connection; private CancellationTokenSource? _loopCts; private Task? _readLoop; private int _disconnected; @@ -441,9 +442,15 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) try { - _interpreter = await BuildInterpreterAsync().ConfigureAwait(false); - SeedInterpreterEncoding(_interpreter); - WireCharsetCallback(_interpreter); + // The read loop is the library's (StartAsync), on our transport. OnStarting sets the fields every + // callback reads before a byte is read, and Task.Run keeps the loop off the caller's context: the + // library awaits without ConfigureAwait, and the caller is often the UI thread. + _loopCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var builder = ConfigureInterpreter(); + var loopToken = _loopCts.Token; + _connection = await Task.Run( + () => builder.StartAsync(new TransportBridge(_transport, _options.ReceiveBufferSize), loopToken), + CancellationToken.None).ConfigureAwait(false); } catch { @@ -452,6 +459,9 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) var stopping = _cellQueries?.OnDisabledAsync() ?? ValueTask.CompletedTask; _cellQueries = null; _interpreter = null; + _connection = null; + _loopCts?.Dispose(); + _loopCts = null; _seeded = null; _negotiated = null; await _transport.CloseAsync().ConfigureAwait(false); @@ -459,16 +469,14 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) throw; } - _lastReported = CurrentEncoding; - _loopCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - _readLoop = Task.Run(() => ReadLoopAsync(_loopCts.Token), CancellationToken.None); + _readLoop = WatchReadLoopAsync(_connection); // Nothing else goes out from here. The interpreter's own opening WILL NAWS offers an option of // ours; what this client never sends is an IAC DO the server has not offered — see // UnsolicitedNegotiationTests for the login that paid for the rule. } - private Task BuildInterpreterAsync() + private TelnetInterpreterBuilder ConfigureInterpreter() { _cellQueries = new TerminalQueryProtocol().WithCellSizeProvider(() => TerminalCellSizeProvider?.Invoke() is { IsValid: true } size @@ -477,7 +485,9 @@ private Task BuildInterpreterAsync() TelnetInterpreterBuilder builder = new TelnetInterpreterBuilder() .UseMode(TelnetInterpreter.TelnetMode.Client) .UseLogger(_logger) - .OnNegotiation(WriteToTransportAsync) + .WrapOutput(write => data => ObserveOutput(data, write)) + .OnStarting(OnStartingAsync) + .OnInputProcessed(OnInputProcessedAsync) .OnSubmit(OnSubmitAsync) .AddPlugin(_cellQueries) // Who this client is, for every protocol in the library that names it. @@ -529,7 +539,32 @@ private Task BuildInterpreterAsync() builder = builder.WithKeepAlive(interval); } - return builder.BuildAsync(); + return builder; + } + + /// + /// The library's start hook: runs after the opening negotiation is written and before anything is read, so no + /// callback ever finds the interpreter unset or unseeded. + /// + private ValueTask OnStartingAsync(TelnetNegotiationCore.Connections.TelnetConnection connection) + { + _interpreter = connection.Interpreter; + SeedInterpreterEncoding(connection.Interpreter); + WireCharsetCallback(connection.Interpreter); + _lastReported = CurrentEncoding; + return ValueTask.CompletedTask; + } + + /// After each read has been handled, its callbacks included. + private ValueTask OnInputProcessedAsync(TelnetInterpreter interpreter) + { + ReceiveBatchEnded?.Invoke(this, EventArgs.Empty); + + // The second arm of charset observation: the direction whose callback the library + // does not raise (see WireCharsetCallback). Cheap — a reference comparison — and + // idempotent, so the arm that already fired mid-batch makes this a no-op. + ReportEncodingIfChanged(); + return ValueTask.CompletedTask; } /// @@ -645,18 +680,18 @@ private void ReportEncodingIfChanged() /// WILL is the moment it is. Only negotiation passes through here, never data, so the three bytes /// cannot be a literal in someone's text. /// - private ValueTask WriteToTransportAsync(ReadOnlyMemory data) + private ValueTask ObserveOutput(ReadOnlyMemory data, Func, ValueTask> write) { if (!_msdpAgreed && Contains(data.Span, [Iac, DoCommand, MsdpOption])) { _msdpAgreed = true; _logger.LogInformation("MSDP negotiated."); - var transportWrite = _transport.SendAsync(data); + var transportWrite = write(data); MsdpEnabled?.Invoke(this, EventArgs.Empty); return transportWrite; } - return _transport.SendAsync(data); + return write(data); } private const byte Iac = 255; @@ -944,28 +979,14 @@ private ValueTask OnMspChangedAsync(bool active) return ValueTask.CompletedTask; } - private async Task ReadLoopAsync(CancellationToken cancellationToken) + private async Task WatchReadLoopAsync(TelnetNegotiationCore.Connections.TelnetConnection connection) { - var buffer = new byte[_options.ReceiveBufferSize]; Exception? error = null; try { - while (!cancellationToken.IsCancellationRequested) - { - var read = await _transport.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); - if (read == 0) - { - break; // clean end of stream - } - - await _interpreter!.InterpretByteArrayAsync(buffer.AsMemory(0, read)).ConfigureAwait(false); - ReceiveBatchEnded?.Invoke(this, EventArgs.Empty); - - // The second arm of charset observation: the direction whose callback the library - // does not raise (see WireCharsetCallback). Cheap — a reference comparison — and - // idempotent, so the arm that already fired mid-batch makes this a no-op. - ReportEncodingIfChanged(); - } + // Completes when the server closes or the loop is cancelled; faults when the transport or a + // callback fails. + await connection.Completion.ConfigureAwait(false); } catch (OperationCanceledException) { @@ -1072,13 +1093,15 @@ public async Task DisconnectAsync() // Dispose and clear the interpreter here (not in DisposeAsync, which calls this first // and would then see it already null) so no interpreter leaks per disconnect/reconnect, // and so the "not connected" send guards observe the disconnected state. - var interpreter = _interpreter; + // The connection owns the interpreter and disposes it. + var connection = _connection; + _connection = null; _interpreter = null; _seeded = null; _negotiated = null; - if (interpreter is not null) + if (connection is not null) { - await interpreter.DisposeAsync().ConfigureAwait(false); + await connection.DisposeAsync().ConfigureAwait(false); } RaiseDisconnected(null); diff --git a/src/SharpMUTerm.Core/Telnet/TransportBridge.cs b/src/SharpMUTerm.Core/Telnet/TransportBridge.cs new file mode 100644 index 00000000..dbb44f69 --- /dev/null +++ b/src/SharpMUTerm.Core/Telnet/TransportBridge.cs @@ -0,0 +1,35 @@ +using SharpMUTerm.Core.Transport; + +namespace SharpMUTerm.Core.Telnet; + +/// +/// Hands one of our s to TelnetNegotiationCore as the transport its read loop runs on +/// (TelnetInterpreterBuilder.StartAsync). The read loop is the library's, so its input hooks +/// (OnInputProcessed) and its start hook (OnStarting) apply; the socket, TLS and the test fakes stay ours. +/// +internal sealed class TransportBridge(ITransport transport, int receiveBufferSize) + : TelnetNegotiationCore.Connections.ITelnetTransport +{ + public async Task ReadAsync(Func, ValueTask> onData, CancellationToken cancellationToken) + { + var buffer = new byte[receiveBufferSize]; + while (!cancellationToken.IsCancellationRequested) + { + var read = await transport.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); + if (read == 0) + { + return; // the peer closed + } + + await onData(buffer.AsMemory(0, read)).ConfigureAwait(false); + } + } + + public ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken) => + // Not the token: the library passes its start token, which a disconnect cancels before the socket closes, + // and a write already under way should finish as it did when this loop was ours. + transport.SendAsync(data, CancellationToken.None); + + public async ValueTask CloseAsync(CancellationToken cancellationToken) => + await transport.CloseAsync().ConfigureAwait(false); +} From b3715ad1fec8a1d5311a77a474404f6ac5c05cbe Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 19:18:52 +0000 Subject: [PATCH 4/7] Add WebSocket worlds A world with a WebSocket path is dialled through TNC's TelnetWebSocketClient (telnet.mudstandards.org, then telnet) and runs the same telnet session inside binary frames. Browse worlds lists mu*index's websocket endpoints (wss where TLS was measured, the endpoint's path or /), /connect reads ws:// and wss:// addresses, and F5 has a websocket path field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- CHANGELOG.md | 5 + CLAUDE.md | 14 ++ src/SharpMUTerm.Client/Help/SlashCommands.cs | 2 +- src/SharpMUTerm.Client/Modals/WelcomeModel.cs | 8 +- .../Modals/WorldBrowseModel.cs | 8 +- .../Settings/BuiltInSettings.cs | 3 + src/SharpMUTerm.Client/Settings/TextRules.cs | 8 + .../Configuration/WorldDefinition.cs | 9 + src/SharpMUTerm.Core/Session/WorldSession.cs | 2 +- src/SharpMUTerm.Core/Telnet/TelnetSession.cs | 12 +- .../Transport/ConnectionOptions.cs | 10 +- src/SharpMUTerm.Core/Transport/ITransport.cs | 8 + .../Transport/WebSocketAddress.cs | 101 ++++++++ .../Transport/WebSocketTransport.cs | 109 +++++++++ .../WorldIndex/WorldDirectory.cs | 28 ++- src/SharpMUTerm.Tui/DeclaredFields.cs | 3 +- src/SharpMUTerm.Tui/DemoWorldDirectory.cs | 4 +- src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs | 22 +- src/SharpMUTerm.Tui/SharpMUTermApp.Welcome.cs | 6 + .../SharpMUTermApp.WorldBrowse.cs | 10 +- src/SharpMUTerm.Tui/WelcomeSurface.cs | 17 +- src/SharpMUTerm.Tui/WorldsScreenRenderer.cs | 54 +++-- .../WorldBrowseModelTests.cs | 2 + .../Transport/WebSocketWorldTests.cs | 226 ++++++++++++++++++ .../WorldIndex/WorldDirectoryTests.cs | 6 +- .../ConnectCommandTests.cs | 29 +++ .../ScreenFieldRenderingTests.cs | 2 +- .../SettingsSessionEditTests.cs | 11 +- .../SharpMUTerm.Tui.Tests/WorldBrowseTests.cs | 11 +- 29 files changed, 665 insertions(+), 65 deletions(-) create mode 100644 src/SharpMUTerm.Core/Transport/WebSocketAddress.cs create mode 100644 src/SharpMUTerm.Core/Transport/WebSocketTransport.cs create mode 100644 tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 79de5a69..7505ec54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`] ### Added +- Worlds can be reached over a WebSocket, as a browser client would. Browse worlds now lists a game's WebSocket + addresses and can connect to them, `/connect ws://host/path` (or `wss://` for an encrypted one) adds and dials one, + and F5 has a *websocket path* field: blank keeps the world on plain telnet. Everything else (triggers, GMCP, MXP, + logging) works the same over either. + - *Open log folder* shows the folder a character's logs are written to in your file manager (Explorer, Finder, or whatever your desktop opens folders with). It is on the command palette (⌃P) for the character in front, on a character's page in the desktop window's Worlds & Characters settings, and on F5 in the terminal (`o` on a diff --git a/CLAUDE.md b/CLAUDE.md index 86953626..765c0225 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3567,6 +3567,20 @@ markup (`[bold #rrggbb on #rrggbb]…[/]`, `[[`/`]]` escaping, `[link=url]…[/] What the jump *makes available* and is not yet used: a GMCP `Core` client session (`UseGmcpClientSession`, `TelnetNegotiationCore.Gmcp`), typed GMCP packages, MSDP over GMCP, `PuebloProtocol`, and MCP 2.1 (`MudClientProtocol`, now used — see below). + - **The read loop is the library's** (4.12+: `TelnetInterpreterBuilder.StartAsync(ITelnetTransport)` → + `TelnetConnection`). `TelnetSession` hands it `ITransport.ForTelnet(bufferSize)`: a `TransportBridge` over + `TcpTransport` (socket, TLS and the test fakes stay ours), or the library's own `TelnetTransport.WebSocket` + for `WebSocketTransport`. Seeding the encoding and wiring CHARSET is `OnStarting` (before the first read); + `ReceiveBatchEnded` and the encoding report are `OnInputProcessed`; the MSDP `DO` spotting is `WrapOutput`. + The bridge writes with `CancellationToken.None`, because the library passes its start token, which a + disconnect cancels before the socket closes. Disposing the connection disposes the interpreter, never the + transport. A read that faults after this side began stopping is a close, not a failure (`WatchReadLoopAsync`). + - **WebSocket worlds** (`WorldDefinition.WebSocketPath`, null = telnet; `WebSocketTransport`, `WebSocketAddress`, + Core; F5 ▸ `websocket path`; `/connect ws://…|wss://…`; Browse lists mu*index's `websocket` endpoints, `wss` where + TLS was measured, at the endpoint's optional `path`, else `/`). Dialled through `TelnetWebSocketClient` + (subprotocols `telnet.mudstandards.org`, then `telnet`), binary frames, telnet inside unchanged. A path is + refused, not tidied (`IsPath`: starts with `/`, ASCII address characters, 256 at most); an address with user + information or a fragment is refused. A `telnet://` link never matches a WebSocket world. - **Never pin a version that is not on nuget.org, and never work around it with a local feed.** A pin that only resolves from a local `nuget.config` builds here and fails `NU1101` everywhere else; if a locally-built nupkg of that version is already in `~/.nuget/packages/`, the real package diff --git a/src/SharpMUTerm.Client/Help/SlashCommands.cs b/src/SharpMUTerm.Client/Help/SlashCommands.cs index 8df5baa6..fa68c6d3 100644 --- a/src/SharpMUTerm.Client/Help/SlashCommands.cs +++ b/src/SharpMUTerm.Client/Help/SlashCommands.cs @@ -17,7 +17,7 @@ public static class SlashCommands [ new("/help", "/help [words]", "This help: keys, slash commands and short how-tos, searched for the words", "/help "), new("/connect", "/connect ", "Open a configured world by name", "/connect "), - new("/connect", "/connect [port] [tls]", "Add a world for a host and connect to it (port 4000 by default)", "/connect "), + new("/connect", "/connect [port] [tls]", "Add a world for a host, or a ws:// or wss:// address, and connect to it (port 4000 by default)", "/connect "), new("/welcome", "/welcome", "Show the first-run welcome again", "/welcome"), new("/welcome", "/welcome layout roleplay|combat|suggested", "Choose the starting layout the welcome offers", "/welcome layout "), new("/browse", "/browse [words]", "Browse worlds listed on mu*index, searched for the words; a pick fills in the connect form", "/browse "), diff --git a/src/SharpMUTerm.Client/Modals/WelcomeModel.cs b/src/SharpMUTerm.Client/Modals/WelcomeModel.cs index 7425becd..e0e4ea24 100644 --- a/src/SharpMUTerm.Client/Modals/WelcomeModel.cs +++ b/src/SharpMUTerm.Client/Modals/WelcomeModel.cs @@ -57,7 +57,8 @@ public sealed record WelcomeModel( string? Problem, string? IndexProblem, string? WorldName = null, - string? Encoding = null) + string? Encoding = null, + string? WebSocketPath = null) { /// The example the surface names, a host nobody owns (RFC 2606). public const string ExampleCommand = "/connect mud.example.org 4201 tls"; @@ -95,9 +96,8 @@ public sealed record WelcomeModel( /// public string FormIntroLine => WorldName is null ? FormIntro - : Encoding is { } encoding - ? $"{WorldName}, as listed on mu*index, saved with encoding {encoding}. Check it and press ⏎ to save and connect." - : $"{WorldName}, as listed on mu*index. Check it and press ⏎ to save and connect."; + : $"{WorldName}, as listed on mu*index{(WebSocketPath is null ? string.Empty : ", over a WebSocket")}" + + $"{(Encoding is { } encoding ? $", saved with encoding {encoding}" : string.Empty)}. Check it and press ⏎ to save and connect."; /// The TLS row's words when on; the window's check box carries these words. public const string TlsOn = "On, encrypted"; diff --git a/src/SharpMUTerm.Client/Modals/WorldBrowseModel.cs b/src/SharpMUTerm.Client/Modals/WorldBrowseModel.cs index 614c35dd..ac7a8a4f 100644 --- a/src/SharpMUTerm.Client/Modals/WorldBrowseModel.cs +++ b/src/SharpMUTerm.Client/Modals/WorldBrowseModel.cs @@ -131,7 +131,13 @@ public static (string Address, string Security, string State) Endpoint(WorldEndp { ArgumentNullException.ThrowIfNull(endpoint); var state = endpoint.Stale ? "stale · not reached lately" : "active"; - return (endpoint.Address, endpoint.Tls ? "TLS" : "plain", endpoint.Connectable ? state : $"{state} · not connectable"); + return (endpoint.Address, (endpoint.WebSocket, endpoint.Tls) switch + { + (true, true) => "WebSocket, TLS", + (true, false) => "WebSocket", + (false, true) => "TLS", + _ => "plain", + }, endpoint.Connectable ? state : $"{state} · not connectable"); } /// An address as one line (--plain, a tooltip). diff --git a/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs b/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs index 6f9ccb34..eedd26d7 100644 --- a/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs +++ b/src/SharpMUTerm.Client/Settings/BuiltInSettings.cs @@ -324,6 +324,9 @@ public static WindowMode WindowStartFor(string? words) Group = ConnectionGroup, Binding = SettingBinding.ForWorld((_, w) => w.Port, (_, w, v) => w.Port = v, resettable: false), }, + WorldText("websocket", "websocket path", TextRule.WebSocketPath, ConnectionGroup, + (_, w) => w.WebSocketPath, (_, w, v) => w.WebSocketPath = v, + "blank dials telnet; a path such as / dials a WebSocket there (wss:// with TLS)", "ws wss web socket browser"), WorldFlag("tls", "TLS", ConnectionGroup, w => w.UseTls, (w, v) => w.UseTls = v, "connect over an encrypted connection", "ssl secure encrypted"), WorldFlag("invalid-certificates", "accept invalid certificates", ConnectionGroup, diff --git a/src/SharpMUTerm.Client/Settings/TextRules.cs b/src/SharpMUTerm.Client/Settings/TextRules.cs index 6fb4de75..6489db84 100644 --- a/src/SharpMUTerm.Client/Settings/TextRules.cs +++ b/src/SharpMUTerm.Client/Settings/TextRules.cs @@ -55,6 +55,12 @@ public enum TextRule /// Image, + /// + /// A world's WebSocket path (): blank for telnet, stored as null; + /// else starting with /; trimmed. + /// + WebSocketPath, + /// A split pane's live tail (): rows, or a share such as 25%. ScrollTail, } @@ -92,6 +98,8 @@ TextRule.Name or TextRule.Secret or TextRule.Defaulted when text.Any(char.IsCont TextRule.Pattern when !string.IsNullOrWhiteSpace(text) => PatternError(text), TextRule.Image => Core.Avatars.AvatarSource.Problem(text), TextRule.ScrollTail => Core.Configuration.ScrollTail.Problem(text), + TextRule.WebSocketPath when !string.IsNullOrWhiteSpace(text) && !Core.Transport.WebSocketAddress.IsPath(text.Trim()) => + $"{field.Label} starts with / and holds no spaces or characters past ASCII", TextRule.NameHighlights => Core.Automation.NameHighlights.Parse( text, colour => HighlightColours.Palette.Contains(colour) && colour != HighlightColours.None).Error, _ => null, diff --git a/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs b/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs index 81f4b304..d8c912f4 100644 --- a/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs +++ b/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs @@ -119,6 +119,13 @@ public sealed class WorldDefinition public bool AllowInvalidCertificates { get; set; } + /// + /// Null (the default) dials telnet over TCP. A path such as / or /ws dials a WebSocket at + /// ws://host:port/path instead (wss:// with ), speaking telnet inside it as the + /// mudstandards.org proposal writes it. Checked by . + /// + public string? WebSocketPath { get; set; } + /// Echo typed commands locally into the output window. public bool LocalEcho { get; set; } = true; @@ -305,6 +312,7 @@ public sealed class WorldDefinition Port = Port, UseTls = UseTls, AllowInvalidCertificates = AllowInvalidCertificates, + WebSocketPath = WebSocketPath, LocalEcho = LocalEcho, Encoding = Encoding, KeepaliveSeconds = KeepaliveSeconds, @@ -344,5 +352,6 @@ public sealed class WorldDefinition Port = Port, UseTls = UseTls, AllowInvalidCertificates = AllowInvalidCertificates, + WebSocketPath = WebSocketPath, }; } diff --git a/src/SharpMUTerm.Core/Session/WorldSession.cs b/src/SharpMUTerm.Core/Session/WorldSession.cs index 06d0d217..f3827a46 100644 --- a/src/SharpMUTerm.Core/Session/WorldSession.cs +++ b/src/SharpMUTerm.Core/Session/WorldSession.cs @@ -1688,7 +1688,7 @@ private ITelnetSession DefaultSessionFactory(ConnectionOptions options) TelnetSessionOptions.ResolveWorldEncoding(World.Encoding, _charsetOrder); return new TelnetSession( - new TcpTransport(options), + options.WebSocketPath is null ? new TcpTransport(options) : new WebSocketTransport(options), Logger, options: new TelnetSessionOptions { diff --git a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs index 5e0814ea..ecdf290f 100644 --- a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs +++ b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs @@ -449,7 +449,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) var builder = ConfigureInterpreter(); var loopToken = _loopCts.Token; _connection = await Task.Run( - () => builder.StartAsync(new TransportBridge(_transport, _options.ReceiveBufferSize), loopToken), + () => builder.StartAsync(_transport.ForTelnet(_options.ReceiveBufferSize), loopToken), CancellationToken.None).ConfigureAwait(false); } catch @@ -469,7 +469,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) throw; } - _readLoop = WatchReadLoopAsync(_connection); + _readLoop = WatchReadLoopAsync(_connection, _loopCts.Token); // Nothing else goes out from here. The interpreter's own opening WILL NAWS offers an option of // ours; what this client never sends is an IAC DO the server has not offered — see @@ -979,7 +979,8 @@ private ValueTask OnMspChangedAsync(bool active) return ValueTask.CompletedTask; } - private async Task WatchReadLoopAsync(TelnetNegotiationCore.Connections.TelnetConnection connection) + private async Task WatchReadLoopAsync( + TelnetNegotiationCore.Connections.TelnetConnection connection, CancellationToken stopping) { Exception? error = null; try @@ -992,6 +993,11 @@ private async Task WatchReadLoopAsync(TelnetNegotiationCore.Connections.TelnetCo { // graceful shutdown } + catch (Exception) when (stopping.IsCancellationRequested) + { + // This side is disconnecting: closing a WebSocket under a read fails that read, which is the close + // asked for and not a fault. + } catch (Exception ex) { error = ex; diff --git a/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs b/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs index 3e5181b3..741f98a3 100644 --- a/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs +++ b/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs @@ -18,11 +18,19 @@ public sealed class ConnectionOptions /// public bool AllowInvalidCertificates { get; init; } + /// + /// Null for telnet over TCP; a path for a WebSocket at that path on and + /// (). + /// + public string? WebSocketPath { get; init; } + /// SNI / certificate target host. Defaults to when null. public string? TlsTargetHost { get; init; } /// Socket connect timeout. Defaults to 30 seconds. public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(30); - public override string ToString() => $"{(UseTls ? "telnets" : "telnet")}://{Host}:{Port}"; + public override string ToString() => WebSocketPath is { } path + ? WebSocketAddress.Format(Host, Port, UseTls, path) + : $"{(UseTls ? "telnets" : "telnet")}://{Host}:{Port}"; } diff --git a/src/SharpMUTerm.Core/Transport/ITransport.cs b/src/SharpMUTerm.Core/Transport/ITransport.cs index a8ac445d..17c2b359 100644 --- a/src/SharpMUTerm.Core/Transport/ITransport.cs +++ b/src/SharpMUTerm.Core/Transport/ITransport.cs @@ -26,4 +26,12 @@ public interface ITransport : IAsyncDisposable /// Closes the connection. Task CloseAsync(); + + /// + /// What TelnetNegotiationCore's read loop runs on once this transport is open. By default a bridge that reads + /// through and writes through ; a WebSocket hands over the + /// library's own, which knows the framing. + /// + TelnetNegotiationCore.Connections.ITelnetTransport ForTelnet(int receiveBufferSize) => + new Telnet.TransportBridge(this, receiveBufferSize); } diff --git a/src/SharpMUTerm.Core/Transport/WebSocketAddress.cs b/src/SharpMUTerm.Core/Transport/WebSocketAddress.cs new file mode 100644 index 00000000..f30069d1 --- /dev/null +++ b/src/SharpMUTerm.Core/Transport/WebSocketAddress.cs @@ -0,0 +1,101 @@ +using System.Globalization; + +namespace SharpMUTerm.Core.Transport; + +/// +/// A world reached over a WebSocket: what a path may hold, how the address is written, and how a ws:// or +/// wss:// address typed on the command line is read. The address is the player's or a directory's text, so it is +/// refused rather than tidied, as refuses a link. +/// +public static class WebSocketAddress +{ + /// The longest path kept. + public const int MaxPathLength = 256; + + /// + /// Whether is a path a world may dial: it starts with /, is at most + /// characters, and holds only the characters an address's path and query may (no + /// spaces, no control characters, no #, nothing past ASCII). + /// + public static bool IsPath(string? path) => + path is { Length: > 0 and <= MaxPathLength } && path[0] == '/' && path.All(IsPathCharacter); + + private static bool IsPathCharacter(char c) => + c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' + or '-' or '.' or '_' or '~' or '!' or '$' or '&' or '\'' or '(' or ')' or '*' or '+' or ',' or ';' or '=' + or ':' or '@' or '/' or '?' or '%'; + + /// The address dialled: ws://host:port/path, wss:// with TLS, an IPv6 host bracketed. + public static string Format(string host, int port, bool tls, string path) + { + var shownHost = host.Contains(':') ? $"[{host}]" : host; + return string.Create(CultureInfo.InvariantCulture, $"{(tls ? "wss" : "ws")}://{shownHost}:{port}{path}"); + } + + /// Whether starts with ws:// or wss://, in any case. + public static bool LooksLikeOne(string text) => + text.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("wss://", StringComparison.OrdinalIgnoreCase); + + /// + /// Reads a ws:// or wss:// address into a host, port (80 or 443 when none is given), TLS and path + /// (/ when none is given), or null with the reason in . Refused: user information, + /// a fragment, a port outside 1–65535, a path refuses, and anything over 512 characters. + /// + public static (string Host, int Port, bool Tls, string Path)? TryParse(string text, out string? refusal) + { + refusal = null; + if (text.Length > 512) + { + refusal = "the address is too long"; + return null; + } + + if (!LooksLikeOne(text)) + { + refusal = "it is not a ws:// or wss:// address"; + return null; + } + + if (text.Any(c => char.IsControl(c) || char.IsWhiteSpace(c) || c > '~' || c == '\\')) + { + refusal = "the address holds a character an address cannot"; + return null; + } + + if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || uri.HostNameType is UriHostNameType.Unknown) + { + refusal = "the address does not read"; + return null; + } + + if (uri.UserInfo.Length > 0) + { + refusal = "the address carries a user name"; + return null; + } + + if (uri.Fragment.Length > 0 || text.Contains('#')) + { + refusal = "the address carries a fragment"; + return null; + } + + var path = uri.PathAndQuery; + if (!IsPath(path)) + { + refusal = "the address's path holds characters this client does not send"; + return null; + } + + var tls = uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase); + var port = uri.IsDefaultPort ? (tls ? 443 : 80) : uri.Port; + if (port is <= 0 or > 65535) + { + refusal = "the port is out of range"; + return null; + } + + return (uri.IdnHost.Trim('[', ']'), port, tls, path); + } +} diff --git a/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs b/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs new file mode 100644 index 00000000..f200a3c4 --- /dev/null +++ b/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs @@ -0,0 +1,109 @@ +using System.Net.WebSockets; +using TelnetNegotiationCore.Connections; +using TelnetNegotiationCore.WebSockets; + +namespace SharpMUTerm.Core.Transport; + +/// +/// A world reached over a WebSocket (). TelnetNegotiationCore connects the +/// socket, offering telnet.mudstandards.org and then telnet, and its own transport runs the session over +/// it (), so the framing — one BINARY message per write, frames fed as they arrive, and the +/// Base64 variant — is the library's. +/// +public sealed class WebSocketTransport(ConnectionOptions options) : ITransport +{ + private static readonly TimeSpan CloseWait = TimeSpan.FromSeconds(2); + + private readonly ConnectionOptions _options = options ?? throw new ArgumentNullException(nameof(options)); + private ClientWebSocket? _socket; + + public bool IsConnected => _socket?.State == WebSocketState.Open; + + public string? RemoteDescription { get; private set; } + + public async Task ConnectAsync(CancellationToken cancellationToken = default) + { + if (_socket is not null) + { + throw new InvalidOperationException("Transport is already connected."); + } + + if (!WebSocketAddress.IsPath(_options.WebSocketPath)) + { + throw new InvalidOperationException("The world's WebSocket path is not one this client dials."); + } + + var address = new Uri(WebSocketAddress.Format(_options.Host, _options.Port, _options.UseTls, _options.WebSocketPath!)); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_options.ConnectTimeout); + _socket = await TelnetWebSocketClient.ConnectAsync( + address, + socket => + { + // A quiet connection behind a proxy is kept open, and one that stops answering is noticed. + socket.KeepAliveInterval = TimeSpan.FromSeconds(30); + socket.KeepAliveTimeout = TimeSpan.FromSeconds(30); + if (_options.AllowInvalidCertificates) + { + socket.RemoteCertificateValidationCallback = static (_, _, _, _) => true; + } + }, + timeout.Token).ConfigureAwait(false); + RemoteDescription = address.ToString(); + } + + public ITelnetTransport ForTelnet(int receiveBufferSize) => + TelnetTransport.WebSocket(_socket ?? throw new InvalidOperationException("Transport is not connected.")); + + public async ValueTask SendAsync(ReadOnlyMemory data, CancellationToken cancellationToken = default) + { + var socket = _socket ?? throw new InvalidOperationException("Transport is not connected."); + await socket.SendAsync(data, WebSocketMessageType.Binary, endOfMessage: true, cancellationToken).ConfigureAwait(false); + } + + public async ValueTask ReceiveAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var socket = _socket ?? throw new InvalidOperationException("Transport is not connected."); + try + { + var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); + return result.MessageType == WebSocketMessageType.Close ? 0 : result.Count; + } + catch (WebSocketException) + { + return 0; + } + } + + public async Task CloseAsync() + { + if (_socket is not { } socket) + { + return; + } + + try + { + if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived) + { + using var wait = new CancellationTokenSource(CloseWait); + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, wait.Token).ConfigureAwait(false); + } + } + catch + { + // Best-effort close. + } + finally + { + socket.Abort(); + } + } + + public async ValueTask DisposeAsync() + { + await CloseAsync().ConfigureAwait(false); + _socket?.Dispose(); + _socket = null; + } +} diff --git a/src/SharpMUTerm.Core/WorldIndex/WorldDirectory.cs b/src/SharpMUTerm.Core/WorldIndex/WorldDirectory.cs index a1cbd562..7fdb9686 100644 --- a/src/SharpMUTerm.Core/WorldIndex/WorldDirectory.cs +++ b/src/SharpMUTerm.Core/WorldIndex/WorldDirectory.cs @@ -58,7 +58,7 @@ public bool Equals(WorldListPage? other) => /// The encoding a world added from here is set to (one of F5's names), or null to leave it auto: set only when the /// directory names a charset that is not UTF-8 and not ASCII (). /// -public sealed record WorldAddress(string Name, string Host, int Port, bool Tls, string? Encoding = null); +public sealed record WorldAddress(string Name, string Host, int Port, bool Tls, string? Encoding = null, string? WebSocketPath = null); /// /// One address a game answers at, as the directory lists it: a telnet or tls endpoint it does not call gone. @@ -71,7 +71,15 @@ public sealed record WorldAddress(string Name, string Host, int Port, bool Tls, /// Whether — the reader /connect uses — takes it. One it refuses is still listed, /// marked not connectable, and is never put in the connect form. /// -public sealed record WorldEndpoint(string Host, int Port, bool Tls, bool Stale, bool Connectable = true) +/// +/// Whether it is the directory's websocket kind: telnet inside a WebSocket on that host and port, wss:// +/// when TLS was measured there. +/// +/// +/// The endpoint's path when the directory gives one that takes; +/// otherwise null, and the address is dialled at . +/// +public sealed record WorldEndpoint(string Host, int Port, bool Tls, bool Stale, bool Connectable = true, bool WebSocket = false, string? WebSocketPath = null) { /// host:port, an IPv6 host in brackets. public string Address => $"{(Host.Contains(':') ? $"[{Host}]" : Host)}:{Port.ToString(CultureInfo.InvariantCulture)}"; @@ -106,11 +114,14 @@ public int FirstConnectable /// The encoding a world added from this game is set to, or null to leave it auto. public string? Encoding => WorldDirectory.EncodingFor(Charset); + /// The path a directory's websocket address is dialled at when it gives none. + public const string WebSocketRoot = "/"; + /// Endpoint as the address the connect form is filled in with. public WorldAddress Address(int index) { var endpoint = Endpoints[index]; - return new WorldAddress(Name, endpoint.Host, endpoint.Port, endpoint.Tls, Encoding); + return new WorldAddress(Name, endpoint.Host, endpoint.Port, endpoint.Tls, Encoding, endpoint.WebSocket ? endpoint.WebSocketPath ?? WebSocketRoot : null); } public bool Equals(WorldGame? other) => @@ -268,7 +279,7 @@ private static WorldListing ReadListing(JsonElement game) /// /// Reads a GET /games/{id} answer (GameView) down to its addresses, in the order the directory lists - /// them: telnet and tls endpoints (a websocket or http one is not a telnet address) that it does not call + /// them: telnet, tls and websocket endpoints (an http one is not a telnet address) that it does not call /// gone, at most . An address refuses is listed and /// marked not connectable. The charset is the game's fields.CHARSET value — the directory's one charset field, /// which names no address. @@ -305,7 +316,7 @@ public static (WorldGame? Game, string? Problem) ParseGame(ReadOnlySpan js var kind = Text(endpoint, "kind"); var state = Text(endpoint, "state"); - if (endpoint.ValueKind != JsonValueKind.Object || kind is not ("telnet" or "tls") || state == "gone") + if (endpoint.ValueKind != JsonValueKind.Object || kind is not ("telnet" or "tls" or "websocket") || state == "gone") { continue; } @@ -317,9 +328,12 @@ public static (WorldGame? Game, string? Problem) ParseGame(ReadOnlySpan js var parsed = host.Length is > 0 and <= 253 && !host.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)) && port is > 0 and <= 65535 ? ConnectEndpoint.Parse([host, port.ToString(CultureInfo.InvariantCulture)]) : null; + var path = kind == "websocket" && Text(endpoint, "path") is { } given && Transport.WebSocketAddress.IsPath(given) + ? given + : null; listed.Add(parsed is { } ok - ? new WorldEndpoint(ok.Host, ok.Port, tls, state == "stale") - : new WorldEndpoint(Clean(host, MaxHostShown), Math.Clamp(port, 0, 65535), tls, state == "stale", Connectable: false)); + ? new WorldEndpoint(ok.Host, ok.Port, tls, state == "stale", WebSocket: kind == "websocket", WebSocketPath: path) + : new WorldEndpoint(Clean(host, MaxHostShown), Math.Clamp(port, 0, 65535), tls, state == "stale", Connectable: false, WebSocket: kind == "websocket")); } if (listed.Count == 0) diff --git a/src/SharpMUTerm.Tui/DeclaredFields.cs b/src/SharpMUTerm.Tui/DeclaredFields.cs index b486130d..9c790764 100644 --- a/src/SharpMUTerm.Tui/DeclaredFields.cs +++ b/src/SharpMUTerm.Tui/DeclaredFields.cs @@ -49,7 +49,8 @@ internal static ScreenField Screen(SettingsField field, SettingTarget target) TextRule.Pattern => ScreenField.OptionalPattern(field.Label, Get, Set), TextRule.Secret => ScreenField.Password(field.Label, Get, Set), TextRule.Defaulted => ScreenField.Defaulted(field.Label, Get, Set, text.Fallback ?? string.Empty), - TextRule.Image => ScreenField.Optional(field.Label, Get, Set) with { Validate = v => TextRules.Check(text, v) }, + TextRule.Image or TextRule.WebSocketPath => + ScreenField.Optional(field.Label, Get, Set) with { Validate = v => TextRules.Check(text, v) }, _ => ScreenField.Optional(field.Label, Get, Set), }; } diff --git a/src/SharpMUTerm.Tui/DemoWorldDirectory.cs b/src/SharpMUTerm.Tui/DemoWorldDirectory.cs index fab87144..cf8bd99a 100644 --- a/src/SharpMUTerm.Tui/DemoWorldDirectory.cs +++ b/src/SharpMUTerm.Tui/DemoWorldDirectory.cs @@ -55,8 +55,8 @@ private static string Endpoint(string host, int port, string kind, string state, private static string Page(Game g) { - // Aetherfall, listed TLS first as the directory might: TLS and plain both active, an old port the directory has not reached lately, a gone one and a - // websocket (neither offered), and a charset — the address choice. Everything else: one usable address. + // Aetherfall, listed TLS first as the directory might: TLS and plain both active, an old port the directory has not reached lately, a gone one (not offered), + // a WebSocket, and a charset — the address choice. Everything else: one usable address. var endpoints = g.Name == "Aetherfall" ? string.Join(",", Endpoint(g.Host, g.Port + 1, "tls", "active"), diff --git a/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs b/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs index 182dd7f8..162b4216 100644 --- a/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs +++ b/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs @@ -22,7 +22,7 @@ internal sealed partial class SharpMUTermApp internal const int DefaultConnectPort = ConnectEndpoint.DefaultPort; /// What /connect with nothing after it says. - internal const string ConnectUsage = "/connect , or /connect [port] [tls] to add one"; + internal const string ConnectUsage = "/connect , or /connect [port] [tls] or a ws:// address to add one"; /// /// Finishes a world this adds before it is saved — the welcome's form adds the character it named. Not @@ -54,6 +54,23 @@ private void ConnectCommand(string windowId, string arguments, Action + { + added.WebSocketPath = socket.Path; + shape?.Invoke(added); + }); + return; + } + if (ParseEndpoint(words) is not { } endpoint) { RefuseCommand($"no world called {Snippet(string.Join(' ', words))}, and that is not a host — {ConnectUsage}"); @@ -88,7 +105,8 @@ internal void OpenLink(TelnetLink link) var world = _config.Worlds.FirstOrDefault(known => string.Equals(known.Host, link.Host, StringComparison.OrdinalIgnoreCase) && known.Port == link.Port - && known.UseTls == link.Tls); + && known.UseTls == link.Tls + && known.WebSocketPath is null); if (world is not null) { DialWorld(world); diff --git a/src/SharpMUTerm.Tui/SharpMUTermApp.Welcome.cs b/src/SharpMUTerm.Tui/SharpMUTermApp.Welcome.cs index 632df366..9a708226 100644 --- a/src/SharpMUTerm.Tui/SharpMUTermApp.Welcome.cs +++ b/src/SharpMUTerm.Tui/SharpMUTermApp.Welcome.cs @@ -246,6 +246,12 @@ private void ConnectFromWelcome(WelcomeConnect request) world.Encoding = encoding; } + // A WebSocket address Browse worlds picked: the world dials it rather than plain telnet. + if (Core.Transport.WebSocketAddress.IsPath(request.WebSocketPath)) + { + world.WebSocketPath = request.WebSocketPath; + } + if (request.Character is { } name) { world.Characters.Add(new CharacterDefinition { Name = name }); diff --git a/src/SharpMUTerm.Tui/SharpMUTermApp.WorldBrowse.cs b/src/SharpMUTerm.Tui/SharpMUTermApp.WorldBrowse.cs index cbe03fca..798e8b7f 100644 --- a/src/SharpMUTerm.Tui/SharpMUTermApp.WorldBrowse.cs +++ b/src/SharpMUTerm.Tui/SharpMUTermApp.WorldBrowse.cs @@ -411,7 +411,7 @@ private void OpenWorldForm(WorldAddress address) { _formFromBrowse = false; PublishWorldModel(_worldModel); - current.Prefill(address.Name, address.Host, address.Port, address.Tls, address.Encoding); + current.Prefill(address.Name, address.Host, address.Port, address.Tls, address.Encoding, address.WebSocketPath); page.Publish(current.Model); return; } @@ -419,7 +419,7 @@ private void OpenWorldForm(WorldAddress address) _formFromBrowse = CellWorldBrowse is not null || NativeWorldBrowse is not null; CloseWorldBrowse(); var welcome = new WelcomeSurface(WorldDirectoryProblem()) { Layout = _welcomeLayout }; - welcome.Prefill(address.Name, address.Host, address.Port, address.Tls, address.Encoding); + welcome.Prefill(address.Name, address.Host, address.Port, address.Tls, address.Encoding, address.WebSocketPath); if (WelcomeIsOpen) { CloseWelcome(); @@ -726,7 +726,9 @@ game.Charset is { } charset var address = game.Address(index); var host = address.Host.Contains(':') ? $"[{address.Host}]" : address.Host; - var command = $"/connect {host} {address.Port}" + (address.Tls ? " tls" : string.Empty); + var command = address.WebSocketPath is { } path + ? "/connect " + Core.Transport.WebSocketAddress.Format(address.Host, address.Port, address.Tls, path) + : $"/connect {host} {address.Port}" + (address.Tls ? " tls" : string.Empty); if (Host.ScreenIsSeen) { OpenWorldForm(address); @@ -735,7 +737,7 @@ game.Charset is { } charset var said = new List { - $"{row.Name} is at {address.Host} port {address.Port}{(address.Tls ? ", encrypted" : string.Empty)}, as listed on mu*index.", + $"{row.Name} is at {address.Host} port {address.Port}{(address.WebSocketPath is null ? "" : " over a WebSocket")}{(address.Tls ? ", encrypted" : string.Empty)}, as listed on mu*index.", $"To add it and connect, type: {command}", }; if (address.Encoding is { } encoding) diff --git a/src/SharpMUTerm.Tui/WelcomeSurface.cs b/src/SharpMUTerm.Tui/WelcomeSurface.cs index cd2ad2fc..cd608e1f 100644 --- a/src/SharpMUTerm.Tui/WelcomeSurface.cs +++ b/src/SharpMUTerm.Tui/WelcomeSurface.cs @@ -24,7 +24,7 @@ internal enum WelcomeAction } /// What the connect form asks for, read once ⏎ has checked it. -internal sealed record WelcomeConnect(string Host, int Port, bool Tls, string? Character, bool PasswordLater, string? WorldName = null, string? Encoding = null); +internal sealed record WelcomeConnect(string Host, int Port, bool Tls, string? Character, bool PasswordLater, string? WorldName = null, string? Encoding = null, string? WebSocketPath = null); /// /// The first-run welcome: what it says and what a key on it means, with no window in it — the @@ -88,18 +88,24 @@ internal sealed class WelcomeSurface /// public string? Encoding { get; private set; } + /// + /// The WebSocket path when Browse worlds picked a WebSocket address (null: telnet); dropped with + /// once the host is changed. + /// + public string? WebSocketPath { get; private set; } + /// The host Browse worlds filled in, so a changed host drops the name that went with it. private string? _prefilledHost; /// Everything the surface says now: what the cells draw and the window's native welcome draws. public WelcomeModel Model => - new(InForm, Selected, Layout, Field, Host, Port, Tls, Character, PasswordLater, Problem, _indexProblem, WorldName, Encoding); + new(InForm, Selected, Layout, Field, Host, Port, Tls, Character, PasswordLater, Problem, _indexProblem, WorldName, Encoding, WebSocketPath); /// /// The form, filled in from a world Browse worlds picked: its host, port and TLS, and its name for the world it will /// be saved as. Only fills it in — the player's own ⏎ there is what saves and dials, through /connect's path. /// - public void Prefill(string worldName, string host, int port, bool tls, string? encoding = null) + public void Prefill(string worldName, string host, int port, bool tls, string? encoding = null, string? webSocketPath = null) { InForm = true; Field = WelcomeField.Character; @@ -108,6 +114,7 @@ public void Prefill(string worldName, string host, int port, bool tls, string? e Tls = tls; WorldName = worldName; Encoding = encoding; + WebSocketPath = webSocketPath; _prefilledHost = Host; Problem = null; Request = null; @@ -195,6 +202,7 @@ public bool ForgetPick() PasswordLater = false; WorldName = null; Encoding = null; + WebSocketPath = null; _prefilledHost = null; Problem = null; Request = null; @@ -361,9 +369,10 @@ private WelcomeAction Submit(Func, (string Host, int Port) { WorldName = null; Encoding = null; + WebSocketPath = null; } - Request = new WelcomeConnect(endpoint.Host, endpoint.Port, Tls, character.Length == 0 ? null : character, PasswordLater, WorldName, Encoding); + Request = new WelcomeConnect(endpoint.Host, endpoint.Port, Tls, character.Length == 0 ? null : character, PasswordLater, WorldName, Encoding, WebSocketPath); return WelcomeAction.Connect; } diff --git a/src/SharpMUTerm.Tui/WorldsScreenRenderer.cs b/src/SharpMUTerm.Tui/WorldsScreenRenderer.cs index d734c93c..16c46f33 100644 --- a/src/SharpMUTerm.Tui/WorldsScreenRenderer.cs +++ b/src/SharpMUTerm.Tui/WorldsScreenRenderer.cs @@ -61,69 +61,72 @@ internal static class WorldsScreenRenderer internal const int PortField = 2; - internal const int EncodingField = 3; + /// : telnet over TCP when blank, else a WebSocket at that path. + internal const int WebSocketField = 3; - internal const int KeepaliveField = 4; + internal const int EncodingField = 4; + + internal const int KeepaliveField = 5; /// /// : the GMCP modules asked for beyond the client's own, as a /// comma-separated list of Name Version. /// - internal const int GmcpModulesField = 7; + internal const int GmcpModulesField = 8; /// , as . - internal const int ContentField = 6; + internal const int ContentField = 7; /// 's three switches, as one of . - internal const int EmojiField = 10; + internal const int EmojiField = 11; /// : the line naming a room, for a game that sends no GMCP room. - internal const int MapRoomField = 18; + internal const int MapRoomField = 19; /// : the line listing a room's exits. - internal const int MapExitsField = 19; + internal const int MapExitsField = 20; /// : a line that stops a speedwalk. - internal const int WalkFailField = 20; + internal const int WalkFailField = 21; /// , as one of . - internal const int SoundsField = 21; + internal const int SoundsField = 22; /// : the line prefix a MUSH hands text back to edit with. - internal const int GrabField = 14; + internal const int GrabField = 15; /// , as one of . - internal const int GmcpLoginField = 8; + internal const int GmcpLoginField = 9; /// , as one of . - internal const int DiscordField = 9; + internal const int DiscordField = 10; /// : the layout this world's characters use, or the suggestion. - internal const int WorldLayoutField = 22; + internal const int WorldLayoutField = 23; /// : the world's picture for the sidebar, which its characters fall back to. - internal const int WorldAvatarField = 23; + internal const int WorldAvatarField = 24; /// , as one of . - internal const int JoinWrapsField = 11; + internal const int JoinWrapsField = 12; /// : the column output wraps at and NAWS reports, or 0 for the pane. - internal const int WrapColumnField = 12; + internal const int WrapColumnField = 13; /// , as one of . - internal const int ReconnectField = 5; + internal const int ReconnectField = 6; /// , as one of . - internal const int StackingField = 13; + internal const int StackingField = 14; /// and , as one of . - internal const int AlertOnField = 15; + internal const int AlertOnField = 16; /// , as one of . - internal const int CaptureChannelsField = 16; + internal const int CaptureChannelsField = 17; /// : Name=colour, …. - internal const int HighlightNamesField = 17; + internal const int HighlightNamesField = 18; /// F5's words for . internal static readonly IReadOnlyList ChannelCaptureChoices = WorldFieldValues.ChannelCaptureChoices; @@ -788,7 +791,7 @@ .. SecurityFieldOrder.Select(id => ScreenRow.Of(DeclaredFields.Toggle(DeclaredFi /// internal static readonly IReadOnlyList WorldFieldOrder = [ - "name", "host", "port", "encoding", "keepalive", "reconnect", + "name", "host", "port", "websocket", "encoding", "keepalive", "reconnect", "content", "gmcp-modules", "gmcp-login", "discord", "emoji", "join-wraps", "wrap-at", "stacking", "edit-grab", "alert-on", "capture-channels", "highlight-names", @@ -1028,6 +1031,13 @@ internal static List DetailColumn( cursor, selectedWorld, PortField), + ["websocket"] = Field( + world.WebSocketPath is { } socketPath + ? $"[{Value}]{Escape(socketPath)}[/] [{Label}]· {(world.UseTls ? "wss" : "ws")}://[/]" + : $"[{Label}]off · telnet[/]", + cursor, + selectedWorld, + WebSocketField), ["encoding"] = Field( EncodingDetail(world.Encoding), cursor, selectedWorld, EncodingField), ["keepalive"] = Field( diff --git a/tests/SharpMUTerm.Client.Tests/WorldBrowseModelTests.cs b/tests/SharpMUTerm.Client.Tests/WorldBrowseModelTests.cs index debbe4c9..943eb8d1 100644 --- a/tests/SharpMUTerm.Client.Tests/WorldBrowseModelTests.cs +++ b/tests/SharpMUTerm.Client.Tests/WorldBrowseModelTests.cs @@ -118,6 +118,8 @@ public async Task TheAddressChoiceSaysEachAddressItsSecurityItsStateAndTheGamesC await Assert.That((Ready() with { Choosing = Game(null) }).CharsetLine).IsEqualTo("mu*index names no charset for it; the world's encoding stays auto"); await Assert.That(WorldBrowseModel.Endpoint(model.Choosing!.Endpoints[0])).IsEqualTo(("a.example:4202", "TLS", "active")); await Assert.That(WorldBrowseModel.Endpoint(model.Choosing.Endpoints[2])).IsEqualTo(("a.example:4000", "plain", "stale · not reached lately")); + await Assert.That(WorldBrowseModel.Endpoint(new WorldEndpoint("a.example", 443, true, false, WebSocket: true)).Security).IsEqualTo("WebSocket, TLS"); + await Assert.That(WorldBrowseModel.Endpoint(new WorldEndpoint("a.example", 80, false, false, WebSocket: true)).Security).IsEqualTo("WebSocket"); await Assert.That(WorldBrowseModel.Endpoint(new WorldEndpoint("2001:db8::1", 23, false, false)).Address).IsEqualTo("[2001:db8::1]:23"); await Assert.That(WorldBrowseModel.Endpoint(new WorldEndpoint("bad host", 4000, false, false, Connectable: false)).State).IsEqualTo("active · not connectable"); await Assert.That(model).IsEqualTo(Ready() with { Choosing = Game("ISO-8859-1") }); diff --git a/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs b/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs new file mode 100644 index 00000000..e4d893f1 --- /dev/null +++ b/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs @@ -0,0 +1,226 @@ +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Text; +using SharpMUTerm.Core.Configuration; +using SharpMUTerm.Core.Session; +using SharpMUTerm.Core.Text; +using SharpMUTerm.Core.Transport; + +namespace SharpMUTerm.Core.Tests.Transport; + +/// +/// A world with a WebSocket path is dialled over a WebSocket, end to end: the real session factory, the real +/// , and a loopback server that speaks telnet in binary frames. +/// +public class WebSocketWorldTests +{ + [Test] + public async Task AWorldWithAPathReadsAndWritesTelnetInsideAWebSocket() + { + await using var server = await WebSocketServer.StartAsync(); + var world = new WorldDefinition { Name = "Lanternport", Host = "127.0.0.1", Port = server.Port, WebSocketPath = "/telnet" }; + await using var session = new WorldSession(world, null); + var lines = new List(); + session.LinePrinted += (_, line) => + { + lock (lines) + { + lines.Add(line.Text); + } + }; + + await session.ConnectAsync(); + await server.SendAsync("Welcome to Lanternport.\r\n"); + await Until(() => { lock (lines) { return lines.Contains("Welcome to Lanternport."); } }); + + await session.SendCommandAsync("look"); + await Until(() => Encoding.ASCII.GetString(server.Received).Contains("look\r\n", StringComparison.Ordinal)); + + await Assert.That(server.Path).IsEqualTo("/telnet"); + await Assert.That(server.SubProtocol).IsEqualTo("telnet.mudstandards.org"); + } + + [Test] + public async Task AServerThatClosesTheSocketEndsTheConnection() + { + await using var server = await WebSocketServer.StartAsync(); + var world = new WorldDefinition { Name = "Lanternport", Host = "127.0.0.1", Port = server.Port, WebSocketPath = "/" }; + await using var session = new WorldSession(world, null); + var states = new List(); + session.StateChanged += (_, e) => + { + lock (states) + { + states.Add(e.State); + } + }; + + await session.ConnectAsync(); + await server.CloseAsync(); + + await Until(() => { lock (states) { return states.Contains(ConnectionState.Disconnected); } }); + } + + [Test] + [Arguments("ws://example.org", "example.org", 80, false, "/")] + [Arguments("wss://example.org", "example.org", 443, true, "/")] + [Arguments("WSS://example.org:8443/mud?v=1", "example.org", 8443, true, "/mud?v=1")] + [Arguments("ws://[2001:db8::1]:4000/", "2001:db8::1", 4000, false, "/")] + public async Task AnAddressReadsAsItsHostPortTlsAndPath(string text, string host, int port, bool tls, string path) + { + var parsed = WebSocketAddress.TryParse(text, out var refusal); + + await Assert.That(refusal).IsNull(); + await Assert.That(parsed).IsEqualTo((host, port, tls, path)); + } + + [Test] + [Arguments("ws://user:pw@example.org/")] + [Arguments("ws://example.org/#top")] + [Arguments("ws://example.org/a b")] + [Arguments("ws://example.org/café")] + [Arguments("ws://example.org:99999/")] + [Arguments("http://example.org/")] + [Arguments("ws:///")] + public async Task AnAddressThatCarriesMoreThanAPlaceToDialIsRefused(string text) + { + var parsed = WebSocketAddress.TryParse(text, out var refusal); + + await Assert.That(parsed).IsNull(); + await Assert.That(refusal).IsNotNull(); + } + + [Test] + public async Task APathStartsWithASlashAndHoldsOnlyAddressCharacters() + { + await Assert.That(WebSocketAddress.IsPath("/")).IsTrue(); + await Assert.That(WebSocketAddress.IsPath("/ws/telnet?game=1")).IsTrue(); + await Assert.That(WebSocketAddress.IsPath("ws")).IsFalse(); + await Assert.That(WebSocketAddress.IsPath("/a\r\nHost: x")).IsFalse(); + await Assert.That(WebSocketAddress.IsPath("/" + new string('a', WebSocketAddress.MaxPathLength))).IsFalse(); + await Assert.That(WebSocketAddress.Format("2001:db8::1", 443, true, "/m")).IsEqualTo("wss://[2001:db8::1]:443/m"); + } + + [Test] + public async Task AWorldWithNoPathIsTelnetAndOneWithAPathSaysItsAddress() + { + var telnet = new WorldDefinition { Name = "W", Host = "example.org", Port = 4000 }; + var socket = new WorldDefinition { Name = "W", Host = "example.org", Port = 443, UseTls = true, WebSocketPath = "/ws" }; + + await Assert.That(telnet.ToConnectionOptions().WebSocketPath).IsNull(); + await Assert.That(socket.ToConnectionOptions().ToString()).IsEqualTo("wss://example.org:443/ws"); + await Assert.That(socket.Clone().WebSocketPath).IsEqualTo("/ws"); + } + + private static async Task Until(Func predicate) + { + for (var i = 0; i < 200 && !predicate(); i++) + { + await Task.Delay(20); + } + + await Assert.That(predicate()).IsTrue(); + } + + /// One WebSocket connection on loopback, recording what the client sends. + private sealed class WebSocketServer : IAsyncDisposable + { + private readonly HttpListener _listener = new(); + private readonly TaskCompletionSource _socket = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Lock _gate = new(); + private readonly List _received = []; + private readonly CancellationTokenSource _cts = new(); + + private WebSocketServer(int port) + { + Port = port; + _listener.Prefixes.Add($"http://127.0.0.1:{port}/"); + } + + public int Port { get; } + + public string? Path { get; private set; } + + public string? SubProtocol { get; private set; } + + public byte[] Received + { + get + { + lock (_gate) + { + return [.. _received]; + } + } + } + + public static Task StartAsync() + { + var probe = new TcpListener(IPAddress.Loopback, 0); + probe.Start(); + var port = ((IPEndPoint)probe.LocalEndpoint).Port; + probe.Stop(); + + var server = new WebSocketServer(port); + server._listener.Start(); + _ = Task.Run(server.AcceptAsync); + return Task.FromResult(server); + } + + public async Task SendAsync(string text) + { + var socket = await _socket.Task.WaitAsync(TimeSpan.FromSeconds(10)); + await socket.SendAsync(Encoding.ASCII.GetBytes(text), WebSocketMessageType.Binary, true, CancellationToken.None); + } + + public async Task CloseAsync() + { + var socket = await _socket.Task.WaitAsync(TimeSpan.FromSeconds(10)); + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "bye", CancellationToken.None); + } + + private async Task AcceptAsync() + { + try + { + var context = await _listener.GetContextAsync(); + Path = context.Request.Url?.PathAndQuery; + var offered = context.Request.Headers["Sec-WebSocket-Protocol"] ?? string.Empty; + SubProtocol = offered.Split(',', StringSplitOptions.TrimEntries).FirstOrDefault(); + var accepted = await context.AcceptWebSocketAsync(SubProtocol); + _socket.SetResult(accepted.WebSocket); + var buffer = new byte[4096]; + while (!_cts.IsCancellationRequested) + { + var result = await accepted.WebSocket.ReceiveAsync(buffer, _cts.Token); + if (result.MessageType == WebSocketMessageType.Close) + { + return; + } + + lock (_gate) + { + _received.AddRange(buffer.AsSpan(0, result.Count)); + } + } + } + catch (Exception) + { + // The test is over, or the client went away. + } + } + + public async ValueTask DisposeAsync() + { + await _cts.CancelAsync(); + if (_socket.Task.IsCompletedSuccessfully) + { + _socket.Task.Result.Abort(); + } + + _listener.Close(); + _cts.Dispose(); + } + } +} diff --git a/tests/SharpMUTerm.Core.Tests/WorldIndex/WorldDirectoryTests.cs b/tests/SharpMUTerm.Core.Tests/WorldIndex/WorldDirectoryTests.cs index 75fe75cb..19d211cd 100644 --- a/tests/SharpMUTerm.Core.Tests/WorldIndex/WorldDirectoryTests.cs +++ b/tests/SharpMUTerm.Core.Tests/WorldIndex/WorldDirectoryTests.cs @@ -102,10 +102,12 @@ public async Task AddressesAreListedInTheDirectorysOrderLeavingOutOnlyGoneAndUnd await Assert.That(problem).IsNull(); await Assert.That(string.Join(",", parsed!.Endpoints.Select(e => $"{e.Address}:{(e.Tls ? "tls" : "plain")}:{(e.Stale ? "stale" : "active")}"))) - .IsEqualTo("stale.example:4000:plain:stale,a.example:4201:plain:active,b.example:4202:tls:active,a.example:4201:plain:active") + .IsEqualTo("ws.example:443:plain:active,stale.example:4000:plain:stale,a.example:4201:plain:active,b.example:4202:tls:active,a.example:4201:plain:active") .Because("the client neither re-ranks nor de-duplicates what the directory lists"); await Assert.That(parsed.FirstConnectable).IsEqualTo(0); - await Assert.That(parsed.Address(2)).IsEqualTo(new WorldAddress("Aetherfall", "b.example", 4202, true)); + await Assert.That(parsed.Endpoints[0].WebSocket).IsTrue(); + await Assert.That(parsed.Address(0).WebSocketPath).IsEqualTo("/").Because("mu*index gives no path yet, so the root is dialled"); + await Assert.That(parsed.Address(3)).IsEqualTo(new WorldAddress("Aetherfall", "b.example", 4202, true)); await Assert.That(parsed.Charset).IsNull(); } diff --git a/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs b/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs index 4a9c574b..993e3eb7 100644 --- a/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs @@ -55,6 +55,35 @@ await Assert.That(app.FindSession("mud.example.org")!.State) .IsEqualTo(ConnectionState.Connected); } + [Test] + public async Task AWebSocketAddressAddsAWorldThatDialsIt() + { + var (app, _, config) = Open(); + await using var _app = app; + + Type(app, "/connect wss://mud.example.org/telnet"); + await app.LastCommand; + + var world = config.Worlds.Single(); + await Assert.That(world.Host).IsEqualTo("mud.example.org"); + await Assert.That(world.Port).IsEqualTo(443); + await Assert.That(world.UseTls).IsTrue(); + await Assert.That(world.WebSocketPath).IsEqualTo("/telnet"); + } + + [Test] + public async Task AWebSocketAddressCarryingAUserIsRefused() + { + var (app, wire, config) = Open(); + await using var _app = app; + + Type(app, "/connect ws://me:pw@mud.example.org/"); + + await Assert.That(config.Worlds).IsEmpty(); + await Assert.That(wire.Lines).IsEmpty(); + await Assert.That(app.LastNotice).Contains("user name"); + } + [Test] public async Task AConfiguredWorldIsReachedByNameAndNotAddedAgain() { diff --git a/tests/SharpMUTerm.Tui.Tests/ScreenFieldRenderingTests.cs b/tests/SharpMUTerm.Tui.Tests/ScreenFieldRenderingTests.cs index 8a3c5221..98e55395 100644 --- a/tests/SharpMUTerm.Tui.Tests/ScreenFieldRenderingTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/ScreenFieldRenderingTests.cs @@ -88,7 +88,7 @@ public async Task Worlds_PortAndKeepaliveGetTheirOwnCarets() await Assert.That(port).Contains("port"); var keepalive = WorldsScreenRenderer.DetailColumn( - worlds, Sets(), 0, 0, ScreenPalette.Accent, Edit(0, 0, 4, "30")).Single(HasCaret); + worlds, Sets(), 0, 0, ScreenPalette.Accent, Edit(0, 0, WorldsScreenRenderer.KeepaliveField, "30")).Single(HasCaret); await Assert.That(keepalive).Contains("keepalive"); } diff --git a/tests/SharpMUTerm.Tui.Tests/SettingsSessionEditTests.cs b/tests/SharpMUTerm.Tui.Tests/SettingsSessionEditTests.cs index d7abe0f7..09822c6e 100644 --- a/tests/SharpMUTerm.Tui.Tests/SettingsSessionEditTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/SettingsSessionEditTests.cs @@ -351,11 +351,12 @@ public async Task TheRealScreensBindTheirFieldsInTheOrderTheyAreDrawn() await Assert.That(model.FieldAt(0, 0, 0)!.Value.Get()).IsEqualTo("Aardwolf"); await Assert.That(model.FieldAt(0, 0, 1)!.Value.Get()).IsEqualTo("aardmud.org"); await Assert.That(model.FieldAt(0, 0, 2)!.Value.Get()).IsEqualTo("4000"); - // "auto" rather than "UTF-8": a world's encoding now defaults to following CHARSET negotiation, - // and naming one is an override. The claim here is unchanged — ordinal 3 is the encoding field - // and reads the world's own property — it is the property's default that moved. - await Assert.That(model.FieldAt(0, 0, 3)!.Value.Get()).IsEqualTo("auto"); - await Assert.That(model.FieldAt(0, 0, 4)!.Value.Get()).IsEqualTo("0"); + // Blank: a world dials telnet until it is given a WebSocket path. + await Assert.That(model.FieldAt(0, 0, 3)!.Value.Get()).IsEqualTo(""); + // "auto" rather than "UTF-8": a world's encoding defaults to following CHARSET negotiation, + // and naming one is an override. + await Assert.That(model.FieldAt(0, 0, 4)!.Value.Get()).IsEqualTo("auto"); + await Assert.That(model.FieldAt(0, 0, 5)!.Value.Get()).IsEqualTo("0"); new ScreenEdits().Apply(model.FieldAt(0, 0, 1)!.Value, "example.net"); await Assert.That(world.Host).IsEqualTo("example.net"); diff --git a/tests/SharpMUTerm.Tui.Tests/WorldBrowseTests.cs b/tests/SharpMUTerm.Tui.Tests/WorldBrowseTests.cs index 913c157a..55f6b8f6 100644 --- a/tests/SharpMUTerm.Tui.Tests/WorldBrowseTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/WorldBrowseTests.cs @@ -169,10 +169,10 @@ public async Task APickWithSeveralAddressesIsChosenFromAndTheChoiceFillsInTheFor await Assert.That(run.App.WorldBrowseOpen).IsTrue(); var game = run.App.WorldBrowseModelNow.Choosing!; await Assert.That(string.Join(",", game.Endpoints.Select(WorldBrowseModel.EndpointText))) - .IsEqualTo("aetherfall.example:4202 — TLS — active,aetherfall.example:4201 — plain — active,aetherfall.example:4000 — plain — stale · not reached lately"); + .IsEqualTo("aetherfall.example:4202 — TLS — active,aetherfall.example:4201 — plain — active,aetherfall.example:4000 — plain — stale · not reached lately,aetherfall.example:4280 — WebSocket — active"); await Assert.That(game.Charset).IsEqualTo("ISO-8859-1"); var drawn = string.Join('\n', run.App.CellWorldBrowse!.Render(run.App.WorldBrowseModelNow, 96, 20).Select(MarkupText.Plain)); - await Assert.That(drawn).Contains("Aetherfall answers at 3 addresses").And.Contains("▸ aetherfall.example:4202").And.Contains("charset ISO-8859-1"); + await Assert.That(drawn).Contains("Aetherfall answers at 4 addresses").And.Contains("▸ aetherfall.example:4202").And.Contains("charset ISO-8859-1"); run.App.SimulateWorldBrowseKey(Key(ConsoleKey.DownArrow)); run.App.SimulateWorldBrowseKey(Key(ConsoleKey.Enter, '\r')); @@ -340,7 +340,7 @@ public async Task WhereTheScreenIsNotSeenSeveralAddressesAreNumberedAndASecondNu TypeCommand(run.App, "/browse 1"); - await Assert.That(heard.Heard).Contains("Aetherfall answers at 3 addresses — choose one:"); + await Assert.That(heard.Heard).Contains("Aetherfall answers at 4 addresses — choose one:"); await Assert.That(heard.Heard).Contains("1. aetherfall.example:4202 — TLS — active"); await Assert.That(heard.Heard).Contains("3. aetherfall.example:4000 — plain — stale · not reached lately"); await Assert.That(heard.Heard).Contains("mu*index names its charset ISO-8859-1, for the whole game rather than per address."); @@ -352,8 +352,11 @@ public async Task WhereTheScreenIsNotSeenSeveralAddressesAreNumberedAndASecondNu await Assert.That(heard.Heard).Contains("To add it and connect, type: /connect aetherfall.example 4201"); await Assert.That(heard.Heard).Contains(line => line.Contains("set the world's encoding to ISO-8859-1", StringComparison.Ordinal)); + TypeCommand(run.App, "/browse 1 4"); + await Assert.That(heard.Heard).Contains("To add it and connect, type: /connect ws://aetherfall.example:4280/"); + TypeCommand(run.App, "/browse 1 7"); - await Assert.That(run.App.LastNotice).Contains("Aetherfall has 3 addresses"); + await Assert.That(run.App.LastNotice).Contains("Aetherfall has 4 addresses"); await Assert.That(run.Config.Worlds.Count).IsEqualTo(0); } From 5dee832dc7948d0fb9f9d46c0dba7b177f879502 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:33:42 +0000 Subject: [PATCH 5/7] Report each read without the library's polling wait; review fixes OnInputProcessed makes every read wait on a Task.Delay(1) poll of the interpreter's queue, ~15 ms a read on Windows, which timed out the fragmented telnet tests there. AfterEachRead runs the batch-end work straight after the interpreter takes each read, as the old loop did. Also: refuse --tls beside a ws:// address, keep a WebSocket path in the welcome's /connect line, and treat a WebSocketException on leaving as a closed connection. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- CLAUDE.md | 2 +- src/SharpMUTerm.Avalonia/WelcomeView.cs | 5 +++- src/SharpMUTerm.Client/Modals/WelcomeModel.cs | 10 +++++-- src/SharpMUTerm.Core/Session/WorldSession.cs | 4 ++- src/SharpMUTerm.Core/Telnet/AfterEachRead.cs | 30 +++++++++++++++++++ src/SharpMUTerm.Core/Telnet/TelnetSession.cs | 8 ++--- .../Telnet/TransportBridge.cs | 4 +-- src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs | 7 +++++ .../PanelHeadingTests.cs | 2 ++ .../ConnectCommandTests.cs | 13 ++++++++ 10 files changed, 73 insertions(+), 12 deletions(-) create mode 100644 src/SharpMUTerm.Core/Telnet/AfterEachRead.cs diff --git a/CLAUDE.md b/CLAUDE.md index 765c0225..3d8d0ffb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3571,7 +3571,7 @@ markup (`[bold #rrggbb on #rrggbb]…[/]`, `[[`/`]]` escaping, `[link=url]…[/] `TelnetConnection`). `TelnetSession` hands it `ITransport.ForTelnet(bufferSize)`: a `TransportBridge` over `TcpTransport` (socket, TLS and the test fakes stay ours), or the library's own `TelnetTransport.WebSocket` for `WebSocketTransport`. Seeding the encoding and wiring CHARSET is `OnStarting` (before the first read); - `ReceiveBatchEnded` and the encoding report are `OnInputProcessed`; the MSDP `DO` spotting is `WrapOutput`. + `ReceiveBatchEnded` and the encoding report run after each read through `AfterEachRead` (not `OnInputProcessed`, which polls the interpreter's queue with `Task.Delay(1)` per read: ~15 ms a read on Windows); the MSDP `DO` spotting is `WrapOutput`. The bridge writes with `CancellationToken.None`, because the library passes its start token, which a disconnect cancels before the socket closes. Disposing the connection disposes the interpreter, never the transport. A read that faults after this side began stopping is a close, not a failure (`WatchReadLoopAsync`). diff --git a/src/SharpMUTerm.Avalonia/WelcomeView.cs b/src/SharpMUTerm.Avalonia/WelcomeView.cs index 605c444f..664ccdb3 100644 --- a/src/SharpMUTerm.Avalonia/WelcomeView.cs +++ b/src/SharpMUTerm.Avalonia/WelcomeView.cs @@ -654,7 +654,10 @@ private void DrawCommand() var (lead, tail) = WelcomeModel.CommandWords; _command.Inlines!.Clear(); _command.Inlines.Add(new Run(lead + " ")); - _command.Inlines.Add(new Run(WelcomeModel.CommandFor(_host.Text ?? string.Empty, _port.Text ?? string.Empty, _tls.IsChecked == true)) + // The path goes with the host Browse worlds filled in; a host typed over it is a telnet world, as the form saves it. + var host = _host.Text ?? string.Empty; + var path = string.Equals(host.Trim(), _model.Host, StringComparison.OrdinalIgnoreCase) ? _model.WebSocketPath : null; + _command.Inlines.Add(new Run(WelcomeModel.CommandFor(host, _port.Text ?? string.Empty, _tls.IsChecked == true, path)) { FontFamily = Mono, Foreground = _colours.Brush(_colours.Text), diff --git a/src/SharpMUTerm.Client/Modals/WelcomeModel.cs b/src/SharpMUTerm.Client/Modals/WelcomeModel.cs index e0e4ea24..ba48478b 100644 --- a/src/SharpMUTerm.Client/Modals/WelcomeModel.cs +++ b/src/SharpMUTerm.Client/Modals/WelcomeModel.cs @@ -209,14 +209,20 @@ public sealed record WelcomeModel( /// /// The command line that does what the form would with these fields: /connect mud.example.org 4201 tls. An /// empty host or port reads as its placeholder, so the line always shows the shape; an IPv6 host is bracketed, as - /// /connect wants it. + /// /connect wants it. With a WebSocket (a world Browse worlds picked at a WebSocket + /// address) it is the ws:// or wss:// address instead, which is the only way /connect takes one. /// - public static string CommandFor(string host, string port, bool tls) + public static string CommandFor(string host, string port, bool tls, string? path = null) { ArgumentNullException.ThrowIfNull(host); ArgumentNullException.ThrowIfNull(port); host = host.Trim(); port = port.Trim(); + if (path is not null && host.Length > 0 && int.TryParse(port, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var number)) + { + return "/connect " + Core.Transport.WebSocketAddress.Format(host.Trim('[', ']'), number, tls, path); + } + host = host.Length == 0 ? HostPlaceholder : host.Contains(':', StringComparison.Ordinal) && !host.StartsWith('[') ? $"[{host}]" : host; port = port.Length == 0 ? "4000" : port; return $"/connect {host} {port}" + (tls ? " tls" : string.Empty); diff --git a/src/SharpMUTerm.Core/Session/WorldSession.cs b/src/SharpMUTerm.Core/Session/WorldSession.cs index f3827a46..56edb724 100644 --- a/src/SharpMUTerm.Core/Session/WorldSession.cs +++ b/src/SharpMUTerm.Core/Session/WorldSession.cs @@ -1637,8 +1637,10 @@ private async Task SendLeavingAsync() await SendRawAsync(command, timeout.Token).ConfigureAwait(false); } } - catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException) + catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException + or System.Net.WebSockets.WebSocketException) { + // A WebSocket world's write fails with its own exception, not an IOException; either way the close goes on. Logger.LogDebug(ex, "{World}: the on-disconnect commands were not all sent", World.Name); } } diff --git a/src/SharpMUTerm.Core/Telnet/AfterEachRead.cs b/src/SharpMUTerm.Core/Telnet/AfterEachRead.cs new file mode 100644 index 00000000..fb42e3d2 --- /dev/null +++ b/src/SharpMUTerm.Core/Telnet/AfterEachRead.cs @@ -0,0 +1,30 @@ +namespace SharpMUTerm.Core.Telnet; + +/// +/// Runs once the interpreter has taken each read, on the read loop, before the next read. +/// +/// +/// This is the batch boundary reports, and it is taken here rather than +/// from the library's OnInputProcessed hook on purpose. That hook waits for the interpreter's queue by polling +/// with Task.Delay(1) after every read: about a millisecond a read on Linux and the timer's 15.6 ms on Windows, +/// so a server writing a byte at a time (or a busy one) is delayed by that per read, and the fragmented telnet tests +/// ran out of time on Windows. The read loop this replaced called the same callbacks straight after +/// InterpretByteArrayAsync with no wait, and this keeps that. +/// +internal sealed class AfterEachRead(TelnetNegotiationCore.Connections.ITelnetTransport inner, Action afterRead) + : TelnetNegotiationCore.Connections.ITelnetTransport +{ + public Task ReadAsync(Func, ValueTask> onData, CancellationToken cancellationToken) => + inner.ReadAsync( + async data => + { + await onData(data).ConfigureAwait(false); + afterRead(); + }, + cancellationToken); + + public ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken) => + inner.WriteAsync(data, cancellationToken); + + public ValueTask CloseAsync(CancellationToken cancellationToken) => inner.CloseAsync(cancellationToken); +} diff --git a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs index ecdf290f..67549069 100644 --- a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs +++ b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs @@ -449,7 +449,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) var builder = ConfigureInterpreter(); var loopToken = _loopCts.Token; _connection = await Task.Run( - () => builder.StartAsync(_transport.ForTelnet(_options.ReceiveBufferSize), loopToken), + () => builder.StartAsync(new AfterEachRead(_transport.ForTelnet(_options.ReceiveBufferSize), OnReadProcessed), loopToken), CancellationToken.None).ConfigureAwait(false); } catch @@ -487,7 +487,6 @@ private TelnetInterpreterBuilder ConfigureInterpreter() .UseLogger(_logger) .WrapOutput(write => data => ObserveOutput(data, write)) .OnStarting(OnStartingAsync) - .OnInputProcessed(OnInputProcessedAsync) .OnSubmit(OnSubmitAsync) .AddPlugin(_cellQueries) // Who this client is, for every protocol in the library that names it. @@ -555,8 +554,8 @@ private ValueTask OnStartingAsync(TelnetNegotiationCore.Connections.TelnetConnec return ValueTask.CompletedTask; } - /// After each read has been handled, its callbacks included. - private ValueTask OnInputProcessedAsync(TelnetInterpreter interpreter) + /// After the interpreter has taken each read (). + private void OnReadProcessed() { ReceiveBatchEnded?.Invoke(this, EventArgs.Empty); @@ -564,7 +563,6 @@ private ValueTask OnInputProcessedAsync(TelnetInterpreter interpreter) // does not raise (see WireCharsetCallback). Cheap — a reference comparison — and // idempotent, so the arm that already fired mid-batch makes this a no-op. ReportEncodingIfChanged(); - return ValueTask.CompletedTask; } /// diff --git a/src/SharpMUTerm.Core/Telnet/TransportBridge.cs b/src/SharpMUTerm.Core/Telnet/TransportBridge.cs index dbb44f69..a584dc44 100644 --- a/src/SharpMUTerm.Core/Telnet/TransportBridge.cs +++ b/src/SharpMUTerm.Core/Telnet/TransportBridge.cs @@ -4,8 +4,8 @@ namespace SharpMUTerm.Core.Telnet; /// /// Hands one of our s to TelnetNegotiationCore as the transport its read loop runs on -/// (TelnetInterpreterBuilder.StartAsync). The read loop is the library's, so its input hooks -/// (OnInputProcessed) and its start hook (OnStarting) apply; the socket, TLS and the test fakes stay ours. +/// (TelnetInterpreterBuilder.StartAsync). The read loop is the library's, so its start hook +/// (OnStarting) applies, and wraps it for the per-read work; the socket, TLS and the test fakes stay ours. /// internal sealed class TransportBridge(ITransport transport, int receiveBufferSize) : TelnetNegotiationCore.Connections.ITelnetTransport diff --git a/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs b/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs index 162b4216..448c2e85 100644 --- a/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs +++ b/src/SharpMUTerm.Tui/SharpMUTermApp.Connect.cs @@ -63,6 +63,13 @@ private void ConnectCommand(string windowId, string arguments, Action { added.WebSocketPath = socket.Path; diff --git a/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs b/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs index fad7296c..79c11f59 100644 --- a/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs +++ b/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs @@ -54,5 +54,7 @@ public async Task TheWelcomesConnectLineIsTheCommandTheFormRunsThrough() await Assert.That(WelcomeModel.CommandFor("", "", false)).IsEqualTo($"/connect {WelcomeModel.HostPlaceholder} 4000"); await Assert.That(WelcomeModel.CommandFor(" mud.example.org ", "4201", true)).IsEqualTo("/connect mud.example.org 4201 tls"); await Assert.That(WelcomeModel.CommandFor("::1", "23", false)).IsEqualTo("/connect [::1] 23"); + // A WebSocket world Browse worlds picked is typed as its address, the only way /connect takes one. + await Assert.That(WelcomeModel.CommandFor("mume.org", "443", true, "/ws-play/")).IsEqualTo("/connect wss://mume.org:443/ws-play/"); } } diff --git a/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs b/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs index 993e3eb7..12180900 100644 --- a/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs +++ b/tests/SharpMUTerm.Tui.Tests/ConnectCommandTests.cs @@ -84,6 +84,19 @@ public async Task AWebSocketAddressCarryingAUserIsRefused() await Assert.That(app.LastNotice).Contains("user name"); } + [Test] + public async Task TlsBesideAPlainWebSocketAddressIsRefusedRatherThanDroppedSilently() + { + var (app, wire, config) = Open(); + await using var _app = app; + + Type(app, "/connect ws://mud.example.org:4000/telnet tls"); + + await Assert.That(config.Worlds).IsEmpty(); + await Assert.That(wire.Lines).IsEmpty(); + await Assert.That(app.LastNotice).Contains("wss://"); + } + [Test] public async Task AConfiguredWorldIsReachedByNameAndNotAddedAgain() { From 21129974669c988f8340883c3848e5ee11ee4adc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 21:07:49 +0000 Subject: [PATCH 6/7] Take TelnetNegotiationCore 4.13.3; report each read through OnInputProcessed 4.13.3 waits for the interpreter's queue on a signal rather than a Task.Delay(1) poll, so the library's per-read hook costs nothing and the AfterEachRead decorator that stood in for it goes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- CHANGELOG.md | 2 +- CLAUDE.md | 2 +- Directory.Packages.props | 2 +- src/SharpMUTerm.Core/Telnet/AfterEachRead.cs | 30 ------------------- src/SharpMUTerm.Core/Telnet/TelnetSession.cs | 8 +++-- .../Telnet/TransportBridge.cs | 2 +- 6 files changed, 9 insertions(+), 37 deletions(-) delete mode 100644 src/SharpMUTerm.Core/Telnet/AfterEachRead.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7505ec54..de2a6ac3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,7 +59,7 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`] ### Changed -- Updated TelnetNegotiationCore to 4.13.2, MarkupString to 2.31.3 and Microsoft.Extensions.Logging.Abstractions to 11.0.0 (which 4.13.2 +- Updated TelnetNegotiationCore to 4.13.3, MarkupString to 2.31.3 and Microsoft.Extensions.Logging.Abstractions to 11.0.0 (which 4.13.3 needs). Nothing a player does changes: the new library releases add WebSocket transports and connection hooks this client does not use yet. diff --git a/CLAUDE.md b/CLAUDE.md index 3d8d0ffb..202c8223 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3571,7 +3571,7 @@ markup (`[bold #rrggbb on #rrggbb]…[/]`, `[[`/`]]` escaping, `[link=url]…[/] `TelnetConnection`). `TelnetSession` hands it `ITransport.ForTelnet(bufferSize)`: a `TransportBridge` over `TcpTransport` (socket, TLS and the test fakes stay ours), or the library's own `TelnetTransport.WebSocket` for `WebSocketTransport`. Seeding the encoding and wiring CHARSET is `OnStarting` (before the first read); - `ReceiveBatchEnded` and the encoding report run after each read through `AfterEachRead` (not `OnInputProcessed`, which polls the interpreter's queue with `Task.Delay(1)` per read: ~15 ms a read on Windows); the MSDP `DO` spotting is `WrapOutput`. + `ReceiveBatchEnded` and the encoding report run after each read through `OnInputProcessed` (4.13.3+: it awaits a signal; before that it polled with `Task.Delay(1)`, ~15 ms a read on Windows); the MSDP `DO` spotting is `WrapOutput`. The bridge writes with `CancellationToken.None`, because the library passes its start token, which a disconnect cancels before the socket closes. Disposing the connection disposes the interpreter, never the transport. A read that faults after this side began stopping is a close, not a failure (`WatchReadLoopAsync`). diff --git a/Directory.Packages.props b/Directory.Packages.props index 1c04c074..7271e221 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -19,7 +19,7 @@ - + diff --git a/src/SharpMUTerm.Core/Telnet/AfterEachRead.cs b/src/SharpMUTerm.Core/Telnet/AfterEachRead.cs deleted file mode 100644 index fb42e3d2..00000000 --- a/src/SharpMUTerm.Core/Telnet/AfterEachRead.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace SharpMUTerm.Core.Telnet; - -/// -/// Runs once the interpreter has taken each read, on the read loop, before the next read. -/// -/// -/// This is the batch boundary reports, and it is taken here rather than -/// from the library's OnInputProcessed hook on purpose. That hook waits for the interpreter's queue by polling -/// with Task.Delay(1) after every read: about a millisecond a read on Linux and the timer's 15.6 ms on Windows, -/// so a server writing a byte at a time (or a busy one) is delayed by that per read, and the fragmented telnet tests -/// ran out of time on Windows. The read loop this replaced called the same callbacks straight after -/// InterpretByteArrayAsync with no wait, and this keeps that. -/// -internal sealed class AfterEachRead(TelnetNegotiationCore.Connections.ITelnetTransport inner, Action afterRead) - : TelnetNegotiationCore.Connections.ITelnetTransport -{ - public Task ReadAsync(Func, ValueTask> onData, CancellationToken cancellationToken) => - inner.ReadAsync( - async data => - { - await onData(data).ConfigureAwait(false); - afterRead(); - }, - cancellationToken); - - public ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken) => - inner.WriteAsync(data, cancellationToken); - - public ValueTask CloseAsync(CancellationToken cancellationToken) => inner.CloseAsync(cancellationToken); -} diff --git a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs index 67549069..ecdf290f 100644 --- a/src/SharpMUTerm.Core/Telnet/TelnetSession.cs +++ b/src/SharpMUTerm.Core/Telnet/TelnetSession.cs @@ -449,7 +449,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) var builder = ConfigureInterpreter(); var loopToken = _loopCts.Token; _connection = await Task.Run( - () => builder.StartAsync(new AfterEachRead(_transport.ForTelnet(_options.ReceiveBufferSize), OnReadProcessed), loopToken), + () => builder.StartAsync(_transport.ForTelnet(_options.ReceiveBufferSize), loopToken), CancellationToken.None).ConfigureAwait(false); } catch @@ -487,6 +487,7 @@ private TelnetInterpreterBuilder ConfigureInterpreter() .UseLogger(_logger) .WrapOutput(write => data => ObserveOutput(data, write)) .OnStarting(OnStartingAsync) + .OnInputProcessed(OnInputProcessedAsync) .OnSubmit(OnSubmitAsync) .AddPlugin(_cellQueries) // Who this client is, for every protocol in the library that names it. @@ -554,8 +555,8 @@ private ValueTask OnStartingAsync(TelnetNegotiationCore.Connections.TelnetConnec return ValueTask.CompletedTask; } - /// After the interpreter has taken each read (). - private void OnReadProcessed() + /// After each read has been handled, its callbacks included. + private ValueTask OnInputProcessedAsync(TelnetInterpreter interpreter) { ReceiveBatchEnded?.Invoke(this, EventArgs.Empty); @@ -563,6 +564,7 @@ private void OnReadProcessed() // does not raise (see WireCharsetCallback). Cheap — a reference comparison — and // idempotent, so the arm that already fired mid-batch makes this a no-op. ReportEncodingIfChanged(); + return ValueTask.CompletedTask; } /// diff --git a/src/SharpMUTerm.Core/Telnet/TransportBridge.cs b/src/SharpMUTerm.Core/Telnet/TransportBridge.cs index a584dc44..ba071629 100644 --- a/src/SharpMUTerm.Core/Telnet/TransportBridge.cs +++ b/src/SharpMUTerm.Core/Telnet/TransportBridge.cs @@ -5,7 +5,7 @@ namespace SharpMUTerm.Core.Telnet; /// /// Hands one of our s to TelnetNegotiationCore as the transport its read loop runs on /// (TelnetInterpreterBuilder.StartAsync). The read loop is the library's, so its start hook -/// (OnStarting) applies, and wraps it for the per-read work; the socket, TLS and the test fakes stay ours. +/// (OnStarting) applies; the socket, TLS and the test fakes stay ours. /// internal sealed class TransportBridge(ITransport transport, int receiveBufferSize) : TelnetNegotiationCore.Connections.ITelnetTransport From 7f9d44014d43310c46443a2575029519e3270894 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 21:19:40 +0000 Subject: [PATCH 7/7] Welcome form drops a stale WebSocket path first; preview keeps ws with a blank port; bound the leaving send Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- src/SharpMUTerm.Client/Modals/WelcomeModel.cs | 5 +++++ src/SharpMUTerm.Core/Session/WorldSession.cs | 2 +- src/SharpMUTerm.Tui/WelcomeSurface.cs | 15 ++++++++------- .../SharpMUTerm.Client.Tests/PanelHeadingTests.cs | 1 + 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/SharpMUTerm.Client/Modals/WelcomeModel.cs b/src/SharpMUTerm.Client/Modals/WelcomeModel.cs index ba48478b..05d17c86 100644 --- a/src/SharpMUTerm.Client/Modals/WelcomeModel.cs +++ b/src/SharpMUTerm.Client/Modals/WelcomeModel.cs @@ -218,6 +218,11 @@ public static string CommandFor(string host, string port, bool tls, string? path ArgumentNullException.ThrowIfNull(port); host = host.Trim(); port = port.Trim(); + if (path is not null && port.Length == 0) + { + port = "4000"; + } + if (path is not null && host.Length > 0 && int.TryParse(port, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var number)) { return "/connect " + Core.Transport.WebSocketAddress.Format(host.Trim('[', ']'), number, tls, path); diff --git a/src/SharpMUTerm.Core/Session/WorldSession.cs b/src/SharpMUTerm.Core/Session/WorldSession.cs index 56edb724..ff0ec3ab 100644 --- a/src/SharpMUTerm.Core/Session/WorldSession.cs +++ b/src/SharpMUTerm.Core/Session/WorldSession.cs @@ -1634,7 +1634,7 @@ private async Task SendLeavingAsync() { foreach (var command in SplitCommands(character.OnDisconnect)) { - await SendRawAsync(command, timeout.Token).ConfigureAwait(false); + await SendRawAsync(command, timeout.Token).WaitAsync(timeout.Token).ConfigureAwait(false); } } catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException diff --git a/src/SharpMUTerm.Tui/WelcomeSurface.cs b/src/SharpMUTerm.Tui/WelcomeSurface.cs index cd608e1f..e22b5404 100644 --- a/src/SharpMUTerm.Tui/WelcomeSurface.cs +++ b/src/SharpMUTerm.Tui/WelcomeSurface.cs @@ -355,6 +355,14 @@ private WelcomeAction Submit(Func, (string Host, int Port) return WelcomeAction.Redraw; } + // Before the endpoint is read, so a changed host with a bad port does not keep the pick's path. + if (WorldName is not null && !string.Equals(Host, _prefilledHost, StringComparison.OrdinalIgnoreCase)) + { + WorldName = null; + Encoding = null; + WebSocketPath = null; + } + if (parse(Port.Length == 0 ? [Host] : [Host, Port]) is not { } endpoint) { Problem = Port.Length > 0 && !(int.TryParse(Port, out var port) && port is > 0 and <= 65535) @@ -365,13 +373,6 @@ private WelcomeAction Submit(Func, (string Host, int Port) } var character = Character.Trim(); - if (WorldName is not null && !string.Equals(Host, _prefilledHost, StringComparison.OrdinalIgnoreCase)) - { - WorldName = null; - Encoding = null; - WebSocketPath = null; - } - Request = new WelcomeConnect(endpoint.Host, endpoint.Port, Tls, character.Length == 0 ? null : character, PasswordLater, WorldName, Encoding, WebSocketPath); return WelcomeAction.Connect; } diff --git a/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs b/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs index 79c11f59..e256a01f 100644 --- a/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs +++ b/tests/SharpMUTerm.Client.Tests/PanelHeadingTests.cs @@ -56,5 +56,6 @@ public async Task TheWelcomesConnectLineIsTheCommandTheFormRunsThrough() await Assert.That(WelcomeModel.CommandFor("::1", "23", false)).IsEqualTo("/connect [::1] 23"); // A WebSocket world Browse worlds picked is typed as its address, the only way /connect takes one. await Assert.That(WelcomeModel.CommandFor("mume.org", "443", true, "/ws-play/")).IsEqualTo("/connect wss://mume.org:443/ws-play/"); + await Assert.That(WelcomeModel.CommandFor("mume.org", "", false, "/")).IsEqualTo("/connect ws://mume.org:4000/"); } }