From a3b6c16736fda61e0120657a9a0a3b5f9cf28ee8 Mon Sep 17 00:00:00 2001 From: DevMando Date: Thu, 3 Dec 2026 23:51:57 -0800 Subject: [PATCH 1/4] Feature: discover ACP sessions and prefer bounded conversation history loading Discover saved sessions through a trusted, read-only adapter connection without creating a conversation. Filter by project folder, remove duplicate or invalid IDs, follow bounded pagination, stop repeated cursors, and offer up to 100 sessions ordered by update time. Keep opaque IDs separate from readable titles and local date captions, with remembered-session fallback for agents that cannot list sessions. Prefer session/load when available so resumed conversations replay earlier messages; retain session/resume behavior for adapters without loading support. Collect a bounded display of recent user and assistant messages, completed tool results, and plans. Merge tool updates within their turn, preserve reused IDs across different turns, and omit unfinished activity and private thoughts. Reject permission prompts during history replay and keep replay outside the active prompt loop. Add mock-adapter and protocol regressions for read-only discovery, load preference, resume-only fallback, pagination, local dates, selection cancellation, opaque IDs, and history size limits. --- src/MandoCode.Acp/Client/AcpClient.cs | 8 +- src/MandoCode/Services/Acp/AcpAgentRuntime.cs | 6 +- src/MandoCode/Services/Acp/AcpHistory.cs | 124 ++++++++++++++---- src/MandoCode/Services/Acp/AcpPaneCommands.cs | 4 +- .../Services/Acp/AcpSessionPicker.cs | 91 +++++++++++++ .../Input/ApprovalSelectCoordinator.cs | 6 +- tests/MandoCode.Acp.MockAgent/Program.cs | 4 +- tests/MandoCode.Tests/Acp/AcpClientTests.cs | 41 ++++++ tests/MandoCode.Tests/Acp/AcpHistoryTests.cs | 71 ++++++++++ .../Acp/AcpSessionPickerTests.cs | 94 +++++++++++++ tests/MandoCode.Tests/Acp/AcpSessionTests.cs | 53 +++++++- 11 files changed, 464 insertions(+), 38 deletions(-) create mode 100644 src/MandoCode/Services/Acp/AcpSessionPicker.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpHistoryTests.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpSessionPickerTests.cs diff --git a/src/MandoCode.Acp/Client/AcpClient.cs b/src/MandoCode.Acp/Client/AcpClient.cs index 0a10270..7ce6909 100644 --- a/src/MandoCode.Acp/Client/AcpClient.cs +++ b/src/MandoCode.Acp/Client/AcpClient.cs @@ -212,6 +212,7 @@ public async Task> ListSessionsAsync( var result = new List(); string? cursor = null; + var seen = new HashSet(StringComparer.Ordinal); for (var page = 0; page < maxPages; page++) { var response = await WithTimeoutAsync("session/list", cancellationToken, token => @@ -220,9 +221,9 @@ public async Task> ListSessionsAsync( AcpJsonContext.Default.ListSessionsRequest, AcpJsonContext.Default.ListSessionsResponse, token)) .ConfigureAwait(false); - result.AddRange(response.Sessions); + result.AddRange(response.Sessions.Take(1000 - result.Count)); cursor = response.NextCursor; - if (string.IsNullOrEmpty(cursor)) + if (result.Count >= 1000 || string.IsNullOrEmpty(cursor) || !seen.Add(cursor)) break; } @@ -347,7 +348,8 @@ private async ValueTask HandlePermissionAsync(Request { var cancelled = new RequestPermissionResponse { Outcome = new CancelledPermissionOutcome() }; - if (!_sessions.TryGetValue(request.SessionId, out var session)) + // Loading an earlier conversation is display-only: never interrupt replay with an approval prompt. + if (!_sessions.TryGetValue(request.SessionId, out var session) || session.HistorySink is not null) return cancelled; // A cancel is already under way: do not bother the user with a prompt for a turn being abandoned. diff --git a/src/MandoCode/Services/Acp/AcpAgentRuntime.cs b/src/MandoCode/Services/Acp/AcpAgentRuntime.cs index 90b019f..9a1c4b7 100644 --- a/src/MandoCode/Services/Acp/AcpAgentRuntime.cs +++ b/src/MandoCode/Services/Acp/AcpAgentRuntime.cs @@ -294,12 +294,12 @@ public async Task ConnectAsync(CancellationToken cancellationToken) var capabilities = client.Initialized!.AgentCapabilities; try { - if (capabilities.SessionCapabilities.CanResume()) - return (await client.ResumeSessionAsync(resume.SessionId, _workingDirectory, cancellationToken, _mcpServers).ConfigureAwait(false), AcpSessionOrigin.Resumed); - if (capabilities.LoadSession) return (await client.LoadSessionAsync(resume.SessionId, _workingDirectory, _history ?? (_ => { }), cancellationToken, _mcpServers).ConfigureAwait(false), AcpSessionOrigin.Loaded); + if (capabilities.SessionCapabilities.CanResume()) + return (await client.ResumeSessionAsync(resume.SessionId, _workingDirectory, cancellationToken, _mcpServers).ConfigureAwait(false), AcpSessionOrigin.Resumed); + AddWarning("The agent can neither resume nor load sessions, so a new session was started."); } catch (Exception ex) when (ex is JsonRpcException or AcpTimeoutException) diff --git a/src/MandoCode/Services/Acp/AcpHistory.cs b/src/MandoCode/Services/Acp/AcpHistory.cs index c46768c..8b1a406 100644 --- a/src/MandoCode/Services/Acp/AcpHistory.cs +++ b/src/MandoCode/Services/Acp/AcpHistory.cs @@ -1,57 +1,135 @@ +using System.Text.Json; using System.Text; using MandoCode.Acp.Protocol; using MandoCode.Models; namespace MandoCode.Services.Acp; -/// -/// Collects what an agent replays during session/load into plain messages: consecutive chunks of the same -/// speaker become one message. Only user and assistant text is kept; tool calls, thoughts, plans and the rest of the -/// replay are not shown again. -/// +public sealed record AcpHistoryItem(string? Role = null, string Text = "", ToolCall? Tool = null, Plan? Plan = null); + +/// Bounded, display-only replay. Never invokes tools, permissions, or the prompt loop. public sealed class AcpHistoryCollector { + public const int TurnLimit = 40; + public const int ItemLimit = 240; + public const int TextLimit = 12000; private readonly object _gate = new(); - private readonly List _messages = []; + private readonly List _items = []; private string? _role; private readonly StringBuilder _text = new(); + public bool Truncated { get; private set; } - /// Called for every replayed update, in order (it may run on the connection's notification thread). public void Add(SessionUpdate update) { - var (role, text) = update switch - { - UserMessageChunk { Content: TextContent user } => ("user", user.Text), - AgentMessageChunk { Content: TextContent agent } => ("assistant", agent.Text), - _ => (null, null), - }; - - if (role is null || text is null) - return; - lock (_gate) { - if (_role != role) + var (role, text) = update switch + { + UserMessageChunk { Content: TextContent user } => ("user", user.Text), + AgentMessageChunk { Content: TextContent agent } => ("assistant", agent.Text), + _ => (null, null) + }; + if (role is not null && text is not null) + { + if (_role != role) Flush(); + _role = role; + var remaining = TextLimit - _text.Length; + _text.Append(text.AsSpan(0, Math.Min(text.Length, remaining))); + if (text.Length > remaining) Truncated = true; + return; + } + if (update is ToolCallBase tool) + { + if (!AcpSessionPicker.ValidId(tool.ToolCallId)) return; + Flush(); + var index = -1; + for (var i = _items.Count - 1; i >= 0 && _items[i].Role != "user"; i--) + if (_items[i].Tool?.ToolCallId == tool.ToolCallId) { index = i; break; } + var previous = index >= 0 ? _items[index].Tool : null; + var merged = new ToolCall + { + ToolCallId = tool.ToolCallId, Title = Cut(tool.Title ?? previous?.Title), + Kind = Cut(tool.Kind ?? previous?.Kind), + Status = Cut(tool.Status ?? previous?.Status) ?? ToolCallStatuses.Pending, + RawInput = BoundedJson(tool.RawInput) ?? previous?.RawInput, + RawOutput = BoundedJson(tool.RawOutput) ?? previous?.RawOutput, + Content = tool.Content is null ? previous?.Content : tool.Content.Take(8).Select(c => c switch + { + ContentToolCallContent { Content: TextContent t } => (ToolCallContent)new ContentToolCallContent { Content = new TextContent(Cut(t.Text) ?? "") }, + DiffToolCallContent d => new DiffToolCallContent { Path = Cut(d.Path) ?? "", OldText = Cut(d.OldText), NewText = Cut(d.NewText) ?? "" }, + _ => null + }).OfType().ToArray() + }; + var item = new AcpHistoryItem(Tool: merged); + if (index >= 0) _items[index] = item; else _items.Add(item); + Trim(); + } + else if (update is Plan plan) + { Flush(); - _role = role; - _text.Append(text); + _items.Add(new(Plan: new Plan { Entries = plan.Entries.Take(30).Select(e => e with { Content = Cut(e.Content) ?? "" }).ToArray() })); + Trim(); + } } } - public IReadOnlyList Messages() + public IReadOnlyList Items() { lock (_gate) { Flush(); - return _messages.ToArray(); + return _items.Where(i => i.Tool is null || i.Tool.Status is ToolCallStatuses.Completed or ToolCallStatuses.Failed).ToArray(); } } + public IReadOnlyList Messages() => Items().Where(i => i.Role is not null) + .Select(i => new ChatMsg { Role = i.Role!, Text = i.Text }).ToArray(); + + private JsonElement? BoundedJson(JsonElement? value) + { + if (value is not { } element) return null; + var text = element.GetRawText(); + return text.Length <= TextLimit ? element.Clone() : JsonSerializer.SerializeToElement(Cut(text)); + } + + private string? Cut(string? text) + { + if (text is null || text.Length <= TextLimit) return text; + Truncated = true; + return text[..TextLimit] + "…"; + } + private void Flush() { if (_role is not null && _text.ToString().Trim() is { Length: > 0 } text) - _messages.Add(new ChatMsg { Role = _role, Text = text }); + { + _items.Add(new(_role, text)); + Trim(); + } _role = null; _text.Clear(); } + + private static int Size(AcpHistoryItem item) => item.Text.Length + + (item.Tool?.Title?.Length ?? 0) + (item.Tool?.RawInput?.GetRawText().Length ?? 0) + (item.Tool?.RawOutput?.GetRawText().Length ?? 0) + + (item.Plan?.Entries.Sum(e => e.Content.Length) ?? 0) + + (item.Tool?.Content?.Sum(c => c switch + { + ContentToolCallContent { Content: TextContent t } => t.Text.Length, + DiffToolCallContent d => d.Path.Length + (d.OldText?.Length ?? 0) + d.NewText.Length, + _ => 0 + }) ?? 0); + + private void Trim() + { + var removed = false; + while (_items.Count > ItemLimit || _items.Count(i => i.Role == "user") > TurnLimit || _items.Sum(Size) > 256000) + { + _items.RemoveAt(0); + removed = Truncated = true; + } + // Avoid starting the visible tail halfway through an older user turn. + if (removed && _items.Any(i => i.Role == "user")) + while (_items.Count > 0 && _items[0].Role != "user") _items.RemoveAt(0); + } } diff --git a/src/MandoCode/Services/Acp/AcpPaneCommands.cs b/src/MandoCode/Services/Acp/AcpPaneCommands.cs index 8002156..54f1c4b 100644 --- a/src/MandoCode/Services/Acp/AcpPaneCommands.cs +++ b/src/MandoCode/Services/Acp/AcpPaneCommands.cs @@ -4,8 +4,8 @@ namespace MandoCode.Services.Acp; -/// One entry of a question asked in the pane. -public sealed record AcpChoice(string Label, Color Color); +/// One choice. Label is returned by the prompt; session panels use Caption and Description for display. +public sealed record AcpChoice(string Label, Color Color, string? Caption = null, string? Description = null); /// Asks the user to pick one entry; null when they dismissed the question. public interface IAcpChoicePrompt diff --git a/src/MandoCode/Services/Acp/AcpSessionPicker.cs b/src/MandoCode/Services/Acp/AcpSessionPicker.cs new file mode 100644 index 0000000..6cc788d --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpSessionPicker.cs @@ -0,0 +1,91 @@ +using System.Globalization; +using MandoCode.Acp.Client; +using MandoCode.Acp.Protocol; +using MandoCode.Acp.Transport; +using MandoCode.Models; +using Spectre.Console; + +namespace MandoCode.Services.Acp; + +public sealed record AcpSessionSelection(bool Proceed, string? SessionId = null, string? Error = null); + +/// Read-only discovery and selection before the current pane is changed. +public static class AcpSessionPicker +{ + public const int Limit = 100; + public static bool ValidId(string? id) => !string.IsNullOrWhiteSpace(id) && id.Length <= 1024 && !id.Any(char.IsControl); + + public static async Task?> DiscoverAsync(string name, AcpAgentConfig config, string folder, + AcpAgentLauncher launcher, Func> confirm, CancellationToken cancellationToken) + { + var plan = launcher.Prepare(name, config, folder); + if (!await launcher.EnsureTrustedAsync(plan, confirm).ConfigureAwait(false)) + throw new OperationCanceledException("Agent launch declined."); + var stderr = new StderrLog(); + var transport = AcpProcessTransport.Start(plan.Spec, plan.Resolved, stderr); + await using var client = new AcpClient(transport, new DenyAllClientHandler(), new AcpClientOptions + { + ClientName = "MandoCode-session-picker", StartupTimeout = TimeSpan.FromSeconds(config.StartupTimeoutSeconds) + }); + await client.ConnectAsync(cancellationToken).ConfigureAwait(false); + if (!client.Initialized!.AgentCapabilities.SessionCapabilities.CanList()) return null; + return await client.ListSessionsAsync(folder, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + public static async Task ChooseAsync(IReadOnlyList? sessions, string folder, + string? remembered, IAcpChoicePrompt prompt, Action notice) + { + if (sessions is null) + { + notice("This agent does not support choosing sessions. Using its last remembered session for this folder."); + return new(true, ValidId(remembered) ? remembered : null); + } + var matching = sessions.Where(s => AcpPaths.SameFolder(s.Cwd, folder) && ValidId(s.SessionId)) + .DistinctBy(s => s.SessionId).OrderByDescending(s => s.UpdatedAt, StringComparer.Ordinal).Take(Limit).ToArray(); + if (matching.Length == 0) + { + notice("No sessions found for this folder. Starting a new conversation."); + return new(true); + } + if (matching.Length == 1) return new(true, matching[0].SessionId); + // The opaque id is only the selection value; titles and dates are separate display fields. + var choices = matching.Select(s => new AcpChoice(s.SessionId, Color.Grey, + Clean(s.Title, 120, "Untitled conversation"), FormatDate(s.UpdatedAt))).ToArray(); + var selected = await prompt.ChooseAsync("Continue an ACP session in this folder:", choices, + Math.Max(0, Array.FindIndex(matching, s => s.SessionId == remembered))).ConfigureAwait(false); + var index = Array.FindIndex(choices, c => c.Label == selected); + return index < 0 ? new(false) : new(true, matching[index].SessionId); + } + + public static string FormatDate(string? value, TimeZoneInfo? timeZone = null) + { + if (!DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + return "Date unavailable"; + return TimeZoneInfo.ConvertTime(date, timeZone ?? TimeZoneInfo.Local).ToString("MMM d · h:mm tt", CultureInfo.InvariantCulture); + } + + private static string Clean(string? value, int limit, string fallback) + { + if (string.IsNullOrWhiteSpace(value)) return fallback; + var text = new string(value.Where(c => !char.IsControl(c)).ToArray()); + return text.Length > limit ? text[..limit] + "…" : text; + } +} + +/// Metadata for the dedicated session panel; ids remain in choice values, never its visible rows. +public sealed record AcpSessionPickerState(string AgentName, string Folder, IReadOnlyList Choices); + +public sealed class AcpSessionChoicePrompt(ApprovalPromptGate gate, ApprovalSelectCoordinator menu, + Func suppressKeys, string agentName, string folder) : IAcpChoicePrompt +{ + public async Task ChooseAsync(string heading, IReadOnlyList choices, int initialIndex = 0) + { + using var hold = await gate.AcquireAsync(); + using (suppressKeys()) + { + var answer = await menu.RequestAsync(choices.Select(c => new ApprovalSelectCoordinator.Option(c.Label, c.Color)).ToArray(), + cancelOnEscape: true, initialIndex: initialIndex, sessionPicker: new(agentName, folder, choices)); + return string.IsNullOrEmpty(answer) ? null : answer; + } + } +} diff --git a/src/MandoCode/Services/Input/ApprovalSelectCoordinator.cs b/src/MandoCode/Services/Input/ApprovalSelectCoordinator.cs index 076bd3f..9babb10 100644 --- a/src/MandoCode/Services/Input/ApprovalSelectCoordinator.cs +++ b/src/MandoCode/Services/Input/ApprovalSelectCoordinator.cs @@ -32,6 +32,7 @@ public sealed record PreviewLine(string Text, Color Color, Decoration Decoration private readonly object _gate = new(); public bool IsActive { get; private set; } + public Acp.AcpSessionPickerState? SessionPicker { get; private set; } public IReadOnlyList