diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8f79438..5ac7293 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,13 +4,14 @@ All notable changes to MandoCode will be documented in this file. ## [Unreleased] -**External agents with clearer session controls and tool activity.** Run coding agents through ACP, including Codex through its tested adapter. See the connected agent, model, and mode at startup, change the session mode with `/agent-acp-mode`, and expand individual tool calls to inspect their details. The CLI also includes RazorConsole 0.7.0's upstream focus fix and retains MandoCode's startup rendering safeguard. +**External agents, clearer session controls, and smoother workspace switching.** Run coding agents through ACP, including Codex through its tested adapter. See the connected agent, model, and mode at startup, change the session mode with `/agent-acp-mode`, and expand individual tool calls to inspect their details. Reduce visible top-to-bottom repainting when switching workspaces, including from multiple agent panes to a blank conversation. The CLI also includes RazorConsole 0.7.0's upstream focus fix and retains MandoCode's startup rendering safeguard. **Highlights** - Run Codex through the existing ACP client, with documented setup and authentication handled by Codex. - Choose the external agent's permission and behavior mode without starting another conversation. - Follow ACP tool calls through compact, expandable rows that update in place. +- Switch agents and workspaces with fewer unnecessary redraws and completed terminal frames delivered together. - Upgrade the terminal UI framework while preserving the startup rendering fix. - Keep transcript formatting, hyperlinks, and emoji shortcuts compatible with the updated rendering dependencies. - Clear the clipboard attachment message reliably after sending a prompt. @@ -38,15 +39,22 @@ All notable changes to MandoCode will be documented in this file. ### Fixed +- Batch synchronized terminal frames into one output write, reducing fragmented row-by-row delivery during large workspace transitions. Preserve terminal size and encoding, pass non-frame output through, bound buffering, and release interrupted frames at shutdown. +- Enable synchronized terminal frames to reduce visible top-to-bottom repainting on terminals supporting synchronized output. Publish one completed workspace-switch notification instead of three intermediate redraw requests, preserving pane focus and background sessions. +- Reuse unchanged conversation snapshots and transcript groups during focus, scrolling, and status updates. Avoid copying and regrouping the full history on these refreshes while keeping streamed output, tool expansion, late agent replies, and cleared conversations current. +- Reduce unnecessary multi-agent redraws: selecting an agent no longer re-focuses the previous pane when the workspace picker is already closed. Poll top-level status only when visible indicators or tips change, let the root forward workspace and resize updates once, and avoid rebuilding pane content for unchanged Git status. Preserve background streaming, focus safeguards, and inactive-pane dimming. - Refresh the prompt after submission so the clipboard attachment message clears reliably. ### Test coverage +- Verify frame batching through the actual RazorConsole live canvas: a large-to-blank transition produces identical ANSI output in one underlying writer call. Cover fragmented frame markers, interrupted-frame shutdown, bounded buffering, and output restoration. All 59 selected rendering, workspace, and routing checks pass on both net8.0 and net10.0. +- Cover reuse of long conversation snapshots, updated streaming status, cleared history, retained expansion, and late agent replies. During this rendering work, a full-suite run passed 1,924 tests with one skip on net10.0; net8.0 passed 1,923 with one skip and hit the previously observed ACP command-notification timeout. The final frame-batching change was validated with the targeted checks above. The user also confirmed that batching resolved the visible workspace repaint sweep in their terminal. +- Add rendering regressions for no-op picker closure, one focus transition per agent-tab selection, quiet idle polling, one body repaint per pane on focus changes, and continued awaiting-input updates. A two-pane test that previously rebuilt agent bodies six extra times over 750 ms now performs no extra idle rebuilds. - Explicitly enable hyperlink support in Markdown rendering tests so their clickable-link assertions run consistently in local terminals and CI. - Add a component check that focusing and redrawing the prompt repeatedly leaves one prompt in the render tree and keeps keyboard focus on it. - The RazorConsole upgrade passed its then-current suite of 1,248 tests on net10.0 and net8.0, plus startup, typing, resizing, and CLI packaging checks. - Add coverage for ACP mode selection, sparse and interleaved tool updates, permission decisions, cancellation and interruption, reused call ids, bounded output, attached diffs, and expansion that stays open during updates. The 95 targeted activity, permission, transcript, and export checks pass on both supported frameworks. -- Final full-suite validation passes on net10.0 and net8.0: 1,919 tests passed and one existing symlink-creation test skipped on each framework. Verify Codex adapter initialization, session creation, a streamed reply, and a session-scoped mode change on Windows. +- The earlier Codex ACP full-suite validation passed on net10.0 and net8.0: 1,919 tests passed and one existing symlink-creation test skipped on each framework. Verify Codex adapter initialization, session creation, a streamed reply, and a session-scoped mode change on Windows. ## [0.16.2] - 2026-11-11 diff --git a/src/MandoCode/Components/Conversation/ConversationView.razor b/src/MandoCode/Components/Conversation/ConversationView.razor index 749076d..f43ea78 100644 --- a/src/MandoCode/Components/Conversation/ConversationView.razor +++ b/src/MandoCode/Components/Conversation/ConversationView.razor @@ -20,9 +20,14 @@ private int _offset; private bool _following = true; private TuiEntry[] _visibleEntries = []; + private IReadOnlyList? _partitionedEntries; private IReadOnlyDictionary _details = new Dictionary(); protected override void OnParametersSet() { + // Session snapshots reuse their entries until an entry is added or cleared. + // Focus, scrolling, and live activity still render, without regrouping history. + if (ReferenceEquals(_partitionedEntries, Entries)) return; + _partitionedEntries = Entries; _visibleEntries = Entries.Where(e => e.AgentOutput is null).ToArray(); _details = Entries.Where(e => e.AgentOutput is not null).GroupBy(e => e.AgentOutput!).ToDictionary(g => g.Key, g => g.ToArray()); } diff --git a/src/MandoCode/Components/Workspaces/AgentPaneContent.razor b/src/MandoCode/Components/Workspaces/AgentPaneContent.razor index b57b056..003ba16 100644 --- a/src/MandoCode/Components/Workspaces/AgentPaneContent.razor +++ b/src/MandoCode/Components/Workspaces/AgentPaneContent.razor @@ -86,7 +86,9 @@ if (_shutdown.IsCancellationRequested) break; await InvokeAsync(() => { - _git = root == rootAccessor.ProjectRoot ? status : null; + var next = root == rootAccessor.ProjectRoot ? status : null; + if (_git == next) return; + _git = next; StateHasChanged(); }); } while (await timer.WaitForNextTickAsync(_shutdown.Token)); diff --git a/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor b/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor index 041f6a5..669dce7 100644 --- a/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor +++ b/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor @@ -14,6 +14,8 @@ [Parameter] public RenderFragment? AgentBody { get; set; } [Parameter] public AgentWorkspace Workspace { get; set; } = default!; [Parameter] public int ReservedHeight { get; set; } + // TerminalWorkspaceView already forwards registry and resize changes through parameters. + [Parameter] public bool ObserveChanges { get; set; } = true; private int AvailableHeight => Math.Max(1, Viewport.Height - ReservedHeight); private int RowWidth => SplitRowsSideBySide ? Viewport.Width : PaneWidth; private long _lastFocusVersion = -1; @@ -24,8 +26,11 @@ protected override void OnInitialized() { Workspace ??= DefaultWorkspace; - Workspace.Changed += Changed; - Viewport.OnResized += Changed; + if (ObserveChanges) + { + Workspace.Changed += Changed; + Viewport.OnResized += Changed; + } if (Workspace.Panes.Count == 0) Workspace.Add(); UpdateSizes(); } diff --git a/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor b/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor index 161af07..afec45f 100644 --- a/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor +++ b/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor @@ -80,6 +80,7 @@ private readonly WorkspaceTabWindow _tabs = new(); private AgentWorkspace[] _openWorkspaces = []; private bool _pickerWasOpen; + private (int Awaiting, bool Explorer, bool AgentTips, string Tip) _lastStatus; private string ExplorerTip => Registry.Active.SelectedPane?.IsHistoryOpen?.Invoke() == true ? "Tab switches list/conversation · Up/Down or Page Up/Page Down navigates · Home/End jumps · Type to search the list · Left/Right selects actions · Enter activates · Esc closes." : Registry.Active.SelectedPane?.IsGitChangesOpen?.Invoke() == true @@ -109,6 +110,7 @@ Viewport.OnResized += Changed; if (Registry.Active.Panes.Count == 0) Registry.Active.Add(); UpdateTabs(); + _lastStatus = CaptureStatus(); _ = RefreshStatusAsync(); } private void UpdateTabs() @@ -118,7 +120,20 @@ _openWorkspaces = Registry.Workspaces.ToArray(); _tabs.Update(_openWorkspaces, Registry.Active, Viewport.Width - LabelWidth - ArrowWidth - ActionsWidth); } - private void Changed() => _ = InvokeAsync(() => { UpdateTabs(); _revision++; StateHasChanged(); }); + private void Changed() => _ = InvokeAsync(() => { UpdateTabs(); _lastStatus = CaptureStatus(); _revision++; StateHasChanged(); }); + private (int Awaiting, bool Explorer, bool AgentTips, string Tip) CaptureStatus() + { + var awaiting = 0; + var panes = Registry.Active.Panes; + for (var index = 0; index < panes.Count; index++) + if (panes[index].IsAwaitingInput?.Invoke() == true) awaiting |= 1 << index; + var explorer = ShowExplorerTip; + return (awaiting, explorer, ShowAgentTips, explorer ? ExplorerTip : ""); + } + private void PollStatus() + { + if (CaptureStatus() != _lastStatus) Changed(); + } private void ScrollTabs(int direction) { _tabs.Scroll(direction, _openWorkspaces.Length); Changed(); } private void ClosePicker() { @@ -129,7 +144,7 @@ private async Task RefreshStatusAsync() { using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(300)); - try { while (await timer.WaitForNextTickAsync(_shutdown.Token)) Changed(); } + try { while (await timer.WaitForNextTickAsync(_shutdown.Token)) await InvokeAsync(PollStatus); } catch (OperationCanceledException) when (_shutdown.IsCancellationRequested) { } } public void Dispose() { Registry.Changed -= Changed; Viewport.OnResized -= Changed; Registry.IsWorkspacePickerOpen = false; _shutdown.Cancel(); _shutdown.Dispose(); } diff --git a/src/MandoCode/Components/Workspaces/WorkspaceSurface.razor b/src/MandoCode/Components/Workspaces/WorkspaceSurface.razor index b9d425b..c5112e4 100644 --- a/src/MandoCode/Components/Workspaces/WorkspaceSurface.razor +++ b/src/MandoCode/Components/Workspaces/WorkspaceSurface.razor @@ -3,7 +3,7 @@ { @* grid selects the renderer's Spectre fallback, which emits zero cells when hidden. *@
- +
} @code { diff --git a/src/MandoCode/Program.cs b/src/MandoCode/Program.cs index d1b1d90..2a0fa94 100644 --- a/src/MandoCode/Program.cs +++ b/src/MandoCode/Program.cs @@ -74,6 +74,8 @@ static async Task Main(string[] args) options.RenderingPipeline = RazorConsoleRenderingPipeline.WidgetLayout; options.ConsoleLiveDisplayOptions.UseAlternateScreenBuffer = true; options.ConsoleLiveDisplayOptions.EnableMouseEvents = true; + // Present a complete frame together on terminals supporting mode 2026. + options.ConsoleLiveDisplayOptions.EnableSynchronizedUpdates = true; options.EnableTerminalResizing = true; }); @@ -104,6 +106,7 @@ static async Task Main(string[] args) using (var host = hostBuilder.Build()) using (var outputScope = host.Services.CreateScope()) + using (var frames = FrameBufferedOutput.Attach(Spectre.Console.AnsiConsole.Console)) using (var tuiOutput = TuiConsole.Begin(outputScope.ServiceProvider.GetRequiredService())) await host.RunAsync(); try { toolUpdate.Launch(); } diff --git a/src/MandoCode/Services/Rendering/FrameBufferedOutput.cs b/src/MandoCode/Services/Rendering/FrameBufferedOutput.cs new file mode 100644 index 0000000..fa08a64 --- /dev/null +++ b/src/MandoCode/Services/Rendering/FrameBufferedOutput.cs @@ -0,0 +1,121 @@ +using System.Text; +using Spectre.Console; + +namespace MandoCode.Services; + +/// Delivers synchronized frames in one write while retaining terminal capabilities. +internal sealed class FrameBufferedOutput(IAnsiConsoleOutput inner) : IAnsiConsoleOutput, IDisposable +{ + private readonly FrameWriter _writer = new(inner.Writer); + public TextWriter Writer => _writer; + public bool IsTerminal => inner.IsTerminal; + public int Width => inner.Width; + public int Height => inner.Height; + public void SetEncoding(Encoding encoding) => inner.SetEncoding(encoding); + public void Dispose() => _writer.Dispose(); + + internal sealed class FrameWriter(TextWriter inner) : TextWriter + { + internal const string Begin = "\u001b[?2026h"; + internal const string End = "\u001b[?2026l"; + private const int MaximumBufferedCharacters = 1024 * 1024; + private readonly object _sync = new(); + private readonly StringBuilder _frame = new(); + private string _pending = ""; + private bool _inFrame; + public override Encoding Encoding => inner.Encoding; + public override void Write(char value) => Write(value.ToString()); + public override void Write(char[] buffer, int index, int count) => Write(new string(buffer, index, count)); + public override void Write(ReadOnlySpan buffer) => Write(buffer.ToString()); + public override void Write(string? value) + { + if (string.IsNullOrEmpty(value)) return; + lock (_sync) + { + _pending += value; + while (_pending.Length > 0) + { + var marker = _inFrame ? End : Begin; + var index = _pending.IndexOf(marker, StringComparison.Ordinal); + if (index >= 0) + { + Emit(_pending[..index]); + _pending = _pending[(index + marker.Length)..]; + if (_inFrame) + { + _frame.Append(End); + DeliverFrame(); + _inFrame = false; + } + else + { + _inFrame = true; + _frame.Append(Begin); + } + continue; + } + // A marker can be split across Spectre writes, including char writes. + var keep = Math.Min(marker.Length - 1, _pending.Length); + while (keep > 0 && !_pending.EndsWith(marker[..keep], StringComparison.Ordinal)) keep--; + Emit(_pending[..(_pending.Length - keep)]); + _pending = keep == 0 ? "" : _pending[^keep..]; + break; + } + } + } + private void Emit(string text) + { + if (text.Length == 0) return; + if (!_inFrame) inner.Write(text); + else + { + _frame.Append(text); + // Bound memory even if a producer fails to finish its frame. + if (_frame.Length >= MaximumBufferedCharacters) DeliverFrame(); + } + } + private void DeliverFrame() + { + if (_frame.Length == 0) return; + inner.Write(_frame.ToString()); + _frame.Clear(); + inner.Flush(); + } + public override void Flush() + { + lock (_sync) { if (!_inFrame) inner.Flush(); } + } + protected override void Dispose(bool disposing) + { + if (disposing) + { + lock (_sync) + { + Emit(_pending); + _pending = ""; + if (_inFrame) _frame.Append(End); + DeliverFrame(); + _inFrame = false; + inner.Flush(); + } + } + base.Dispose(disposing); + } + } + + public static IDisposable Attach(IAnsiConsole console) + { + var original = console.Profile.Out; + var buffered = new FrameBufferedOutput(original); + console.Profile.Out = buffered; + return new OutputScope(() => + { + try { buffered.Dispose(); } + finally { console.Profile.Out = original; } + }); + } + private sealed class OutputScope(Action restore) : IDisposable + { + public void Dispose() => restore(); + } +} diff --git a/src/MandoCode/Services/Rendering/TuiSession.cs b/src/MandoCode/Services/Rendering/TuiSession.cs index 8d17834..2957408 100644 --- a/src/MandoCode/Services/Rendering/TuiSession.cs +++ b/src/MandoCode/Services/Rendering/TuiSession.cs @@ -10,6 +10,7 @@ public sealed class TuiSession(TimeProvider? timeProvider = null) { private readonly object _sync = new(); private readonly List _entries = new(); + private TuiEntry[]? _entrySnapshot; private readonly Dictionary _entryContent = new(); private readonly Dictionary _registered = new(); private static long _nextId; @@ -100,7 +101,7 @@ private sealed class OutputScope(Action close) : IDisposable { public void Dispo public long Revision => Interlocked.Read(ref _revision); public TuiSnapshot Snapshot() { - lock (_sync) return new(_entries.ToArray(), _running, _activity, _preview) { Spinner = _spinner, LoadingMessage = _loadingMessage, Elapsed = _elapsed }; + lock (_sync) return new(_entrySnapshot ??= _entries.ToArray(), _running, _activity, _preview) { Spinner = _spinner, LoadingMessage = _loadingMessage, Elapsed = _elapsed }; } public void Append(IRenderable content) { @@ -156,6 +157,7 @@ public void AppendRestored(IRenderable content, string? userPrompt, bool spaceAf private void AddEntry(TuiEntry entry) { _entries.Add(entry); + _entrySnapshot = null; _entryContent[entry.Id] = entry.Content; } public long Register(IRenderable content) @@ -165,7 +167,7 @@ public long Register(IRenderable content) public void Unregister(long id) { lock (_sync) _registered.Remove(id); } public void Clear() { - lock (_sync) { _entries.Clear(); _entryContent.Clear(); _exchanges.Clear(); Interlocked.Increment(ref _revision); } + lock (_sync) { _entries.Clear(); _entrySnapshot = null; _entryContent.Clear(); _exchanges.Clear(); Interlocked.Increment(ref _revision); } } private bool _fixedLoadingMessage; public void SetRunning(bool running, string? activity = null, string? message = null) diff --git a/src/MandoCode/Services/Rendering/WorkspaceRegistry.cs b/src/MandoCode/Services/Rendering/WorkspaceRegistry.cs index efafa12..7e2b086 100644 --- a/src/MandoCode/Services/Rendering/WorkspaceRegistry.cs +++ b/src/MandoCode/Services/Rendering/WorkspaceRegistry.cs @@ -60,12 +60,21 @@ public AgentWorkspace Add(string? name = null) public void Switch(AgentWorkspace workspace) { if (workspace.IsClosed || !_entries.Contains(workspace)) return; - IsWorkspacePickerOpen = false; - var previous = Active; - Active = workspace; - previous.Refresh(); - if (workspace.SelectedPane is { } pane) workspace.Focus(pane); - Notify(); + var alreadyChanging = _changing; + _changing = true; + try + { + IsWorkspacePickerOpen = false; + var previous = Active; + Active = workspace; + previous.Refresh(); + if (workspace.SelectedPane is { } pane) workspace.Focus(pane); + } + finally + { + _changing = alreadyChanging; + Notify(); + } } public void Cycle(int direction) { @@ -86,6 +95,7 @@ public void OpenPicker() } public void ClosePicker() { + if (!IsWorkspacePickerOpen) return; IsWorkspacePickerOpen = false; if (Active.SelectedPane is { } pane) Active.Focus(pane); else Notify(); diff --git a/tests/MandoCode.Tests/FrameBufferedOutputTests.cs b/tests/MandoCode.Tests/FrameBufferedOutputTests.cs new file mode 100644 index 0000000..1111c00 --- /dev/null +++ b/tests/MandoCode.Tests/FrameBufferedOutputTests.cs @@ -0,0 +1,95 @@ +using System.Text; +using MandoCode.Services; +using RazorConsole.Core; +using RazorConsole.Core.Rendering; +using Spectre.Console; +using Xunit; + +namespace MandoCode.Tests; + +public sealed class FrameBufferedOutputTests +{ + [Fact] + public void FragmentedFrameIsDeliveredTogetherDespiteIntermediateFlushes() + { + var terminal = new CountingWriter(); + using var writer = new FrameBufferedOutput.FrameWriter(terminal); + var frame = FrameBufferedOutput.FrameWriter.Begin + "\u001b[Hrow one\u001b[2;1Hrow two" + FrameBufferedOutput.FrameWriter.End; + foreach (var ch in frame[..^1]) { writer.Write(ch); writer.Flush(); } + Assert.Empty(terminal.Writes); + writer.Write(frame[^1]); + Assert.Equal(frame, Assert.Single(terminal.Writes)); + writer.Write("outside frame"); + Assert.Equal("outside frame", terminal.Writes[1]); + } + + [Fact] + public void ShutdownCompletesAnInterruptedFrameWithoutClosingTerminal() + { + var terminal = new CountingWriter(); + using (var writer = new FrameBufferedOutput.FrameWriter(terminal)) + writer.Write(FrameBufferedOutput.FrameWriter.Begin + "partial content"); + Assert.Equal(FrameBufferedOutput.FrameWriter.Begin + "partial content" + FrameBufferedOutput.FrameWriter.End, Assert.Single(terminal.Writes)); + terminal.Write("still usable"); + Assert.Equal(2, terminal.Writes.Count); + } + + [Fact] + public void LargeFramesDoNotBufferWithoutLimit() + { + var terminal = new CountingWriter(); + using var writer = new FrameBufferedOutput.FrameWriter(terminal); + writer.Write(FrameBufferedOutput.FrameWriter.Begin); + writer.Write(new string('x', 1024 * 1024)); + Assert.Single(terminal.Writes); + writer.Write(FrameBufferedOutput.FrameWriter.End); + Assert.Equal(FrameBufferedOutput.FrameWriter.Begin + new string('x', 1024 * 1024) + FrameBufferedOutput.FrameWriter.End, string.Concat(terminal.Writes)); + } + + [Fact] + public void ActualLiveCanvasDeliversLargeToBlankTransitionInOneWrite() + { + var terminal = new CountingWriter(); + var console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(terminal), Ansi = AnsiSupport.Yes }); + console.Profile.Width = 100; + console.Profile.Height = 40; + console.Profile.Capabilities.Ansi = true; + var original = console.Profile.Out; + var canvasType = typeof(ConsoleAppOptions).Assembly.GetType("RazorConsole.Core.LiveDisplayCanvas")!; + using var canvas = (IDisposable)Activator.CreateInstance(canvasType, new ConsoleLiveDisplayOptions + { + EnableSynchronizedUpdates = true, + UseAlternateScreenBuffer = true + }, console)!; + var update = canvasType.GetMethod("UpdateTarget")!; + var occupied = new Text(string.Join('\n', Enumerable.Range(0, 38).Select(i => $"Occupied pane row {i}"))); + update.Invoke(canvas, [occupied]); + terminal.Writes.Clear(); + update.Invoke(canvas, [new Text("")]); + Assert.True(terminal.Writes.Count > 1); + var unbufferedFrame = string.Concat(terminal.Writes); + update.Invoke(canvas, [occupied]); + using (FrameBufferedOutput.Attach(console)) + { + terminal.Writes.Clear(); + update.Invoke(canvas, [new Text("")]); + var frame = Assert.Single(terminal.Writes); + Assert.StartsWith(FrameBufferedOutput.FrameWriter.Begin, frame); + Assert.EndsWith(FrameBufferedOutput.FrameWriter.End, frame); + Assert.Contains("\u001b[", frame); + Assert.Equal(unbufferedFrame, frame); + } + Assert.Same(original, console.Profile.Out); + } + + private sealed class CountingWriter : StringWriter + { + public List Writes { get; } = []; + public override void Write(string? value) + { + if (!string.IsNullOrEmpty(value)) Writes.Add(value); + base.Write(value); + } + public override Encoding Encoding => Encoding.UTF8; + } +} diff --git a/tests/MandoCode.Tests/TranscriptSnapshotPerformanceTests.cs b/tests/MandoCode.Tests/TranscriptSnapshotPerformanceTests.cs new file mode 100644 index 0000000..96f221a --- /dev/null +++ b/tests/MandoCode.Tests/TranscriptSnapshotPerformanceTests.cs @@ -0,0 +1,62 @@ +using System.Reflection; +using MandoCode.Components; +using MandoCode.Services; +using Spectre.Console; +using Xunit; + +namespace MandoCode.Tests; + +public sealed class TranscriptSnapshotPerformanceTests +{ + [Fact] + public void StatusUpdatesReuseHistoryWhileNewOutputAndClearInvalidateIt() + { + var session = new TuiSession(); + for (var i = 0; i < 1000; i++) session.Append(new Text($"History {i}")); + var before = session.Snapshot(); + session.SetRunning(true, "Working"); + session.SetPreview("New streaming preview"); + var during = session.Snapshot(); + Assert.Same(before.Entries, during.Entries); + Assert.True(during.Running); + Assert.Equal("New streaming preview", during.Preview); + session.AppendUserPrompt("Next question"); + var appended = session.Snapshot(); + Assert.NotSame(before.Entries, appended.Entries); + Assert.Equal(1000, before.Entries.Count); + Assert.Equal("Next question", appended.Entries[^1].UserPrompt); + session.Clear(); + Assert.Empty(session.Snapshot().Entries); + Assert.Equal(1001, appended.Entries.Count); + session.Append(new Text("Fresh conversation")); + Assert.Single(session.Snapshot().Entries); + } + + [Fact] + public void UnchangedHistoryKeepsGroupsWhileLateAgentDetailsRemainVisible() + { + var session = new TuiSession(); + session.AppendAgentDetail("peer", "Other agent", new Text("First detail"), "Working"); + var view = new ConversationView(); + void Apply() + { + typeof(ConversationView).GetProperty(nameof(ConversationView.Entries))!.SetValue(view, session.Snapshot().Entries); + typeof(ConversationView).GetMethod("OnParametersSet", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(view, null); + } + var detailsField = typeof(ConversationView).GetField("_details", BindingFlags.Instance | BindingFlags.NonPublic)!; + Apply(); + var before = (IReadOnlyDictionary)detailsField.GetValue(view)!; + var exchange = Assert.Single(before.Keys); + exchange.Expanded = true; + session.SetActivity("Waiting"); + Apply(); + Assert.Same(before, detailsField.GetValue(view)); + Assert.True(exchange.Expanded); + session.AppendAgentDetail("peer", "Other agent", new Text("Late reply"), "Completed"); + Apply(); + var after = (IReadOnlyDictionary)detailsField.GetValue(view)!; + Assert.NotSame(before, after); + Assert.Equal(2, after[exchange].Length); + Assert.Equal("Completed", exchange.Status); + } +} diff --git a/tests/MandoCode.Tests/WorkspaceRenderingPerformanceTests.cs b/tests/MandoCode.Tests/WorkspaceRenderingPerformanceTests.cs new file mode 100644 index 0000000..eb1c300 --- /dev/null +++ b/tests/MandoCode.Tests/WorkspaceRenderingPerformanceTests.cs @@ -0,0 +1,142 @@ +using System.Reflection; +using MandoCode.Components; +using MandoCode.Services; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Rendering; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace MandoCode.Tests; + +[Collection("TUI console routing")] +[Trait("Category", "Component")] +public class WorkspaceRenderingPerformanceTests +{ + [Fact] + public async Task WorkspaceSwitchPublishesOneCompletedTransition() + { + await using var services = Acp.AcpTestHost.Services(); + var registry = services.GetRequiredService(); + var first = registry.Active; + first.Add(); + var second = registry.Add(); + var version = first.FocusVersion; + var notifications = 0; + registry.Changed += () => + { + notifications++; + Assert.Same(first, registry.Active); + Assert.True(first.IsVisible); + Assert.False(second.IsVisible); + Assert.Equal(version + 1, first.FocusVersion); + }; + registry.Switch(first); + Assert.Equal(1, notifications); + Assert.True(first.SelectedPane!.Active); + } + + [Fact] + public async Task ClosingAnAlreadyClosedPickerDoesNotRefocusOrRedraw() + { + await using var services = Acp.AcpTestHost.Services(); + var registry = services.GetRequiredService(); + registry.Active.Add(); + var version = registry.Active.FocusVersion; + var notifications = 0; + registry.Changed += () => notifications++; + registry.ClosePicker(); + Assert.Equal(version, registry.Active.FocusVersion); + Assert.Equal(0, notifications); + } + + [Fact] + public async Task SelectingAnAgentTabHasOneFocusTransition() + { + await using var services = Acp.AcpTestHost.Services(); + var registry = services.GetRequiredService(); + var first = registry.Active.Add(); + registry.Active.Add(); + var navigation = new AgentNavigationBar(); + typeof(AgentNavigationBar).GetProperty(nameof(AgentNavigationBar.Workspace))!.SetValue(navigation, registry.Active); + typeof(AgentNavigationBar).GetProperty("Registry", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)!.SetValue(navigation, registry); + var version = registry.Active.FocusVersion; + var notifications = 0; + registry.Changed += () => notifications++; + typeof(AgentNavigationBar).GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(navigation, [first]); + Assert.Same(first, registry.Active.SelectedPane); + Assert.Equal(version + 1, registry.Active.FocusVersion); + Assert.Equal(1, notifications); + } + + [Fact] + public async Task IdlePollingIsQuietWhileFocusAndStatusChangesStillRender() + { + await using var services = Acp.AcpTestHost.Services(); + var registry = services.GetRequiredService(); + var first = registry.Active.Add(); + registry.Active.Add(); + var awaiting = false; + first.IsAwaitingInput = () => awaiting; + var renders = 0; + RenderFragment body = pane => builder => + { + builder.OpenComponent(0); + builder.AddAttribute(1, "Count", (Action)(() => renders++)); + builder.CloseComponent(); + }; + await using var renderer = new HtmlRenderer(services, services.GetRequiredService()); + var before = 0; + TerminalWorkspaceView view = null!; + await renderer.Dispatcher.InvokeAsync(async () => + { + await renderer.RenderComponentAsync(ParameterView.FromDictionary(new Dictionary + { + ["AgentBody"] = body, + ["Capture"] = (Action)(value => view = value) + })); + before = renders; + }); + // Observe more than two actual 300ms status-poll intervals, without model/network activity. + await Task.Delay(750); + await renderer.Dispatcher.InvokeAsync(() => + { + Assert.Equal(before, renders); + registry.Active.Focus(first); + Assert.Equal(before + 2, renders); // Exactly one repaint per agent, through the root. + var focused = renders; + awaiting = true; + var poll = typeof(TerminalWorkspaceView).GetMethod("PollStatus", BindingFlags.Instance | BindingFlags.NonPublic)!; + poll.Invoke(view, null); + Assert.Equal(focused + 2, renders); + poll.Invoke(view, null); + Assert.Equal(focused + 2, renders); // The same status must not repaint again. + }); + } + + public sealed class RootHost : ComponentBase + { + [Parameter] public RenderFragment AgentBody { get; set; } = default!; + [Parameter] public Action Capture { get; set; } = default!; + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + builder.OpenComponent(0); + builder.AddAttribute(1, "AgentBody", AgentBody); + builder.AddComponentReferenceCapture(2, value => Capture((TerminalWorkspaceView)value)); + builder.CloseComponent(); + } + } + + public sealed class CountBody : ComponentBase + { + [Parameter] public Action Count { get; set; } = default!; + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + Count(); + builder.OpenElement(0, "div"); + builder.AddContent(1, "Agent content"); + builder.CloseElement(); + } + } +}