diff --git a/README.md b/README.md index d3d495d..e57c1d8 100644 --- a/README.md +++ b/README.md @@ -523,8 +523,20 @@ slash commands appear with the connected agent's name. Alt+V attaches an image w Changing folders restarts only that ACP pane and keeps the transcript. MandoCode attempts to continue its session; if the adapter starts fresh, choose whether to carry recent text context. A project-change note tells the agent to re-read files before the next request. `/clear` starts a fresh ACP conversation and discards pending context. -`/agent-acp --resume` requests the remembered session for this folder; `/agent-acp sessions` lists available -sessions when supported. Agent memory and session continuation depend on the adapter. +`/acp-agent --resume` lists this folder's sessions and lets you choose which conversation to continue. +One session is selected directly; Escape cancels without replacing the current agent. A dedicated panel shows up to +100 sessions with readable titles and local update times. Use arrows or Page Up/Down to browse and Enter to continue; +IDs stay out of the picker. Workspace and agent bars are hidden while choosing; navigation controls sit at the lower +right. Use `/acp-agent --resume ` to continue an explicit id, optionally with `--new-panel`; quote +ids containing spaces. `/acp-agent sessions` remains a plain list +with full ids. The `/agent-acp` spelling also works. + +When supported, MandoCode loads the session and restores user/agent messages, completed tool activity, and plans +between history separators. The display keeps up to 40 recent turns and 240 entries, with long text shortened and +an overall text budget; this does not trim the agent's own memory. Replay does not run tools or ask for permissions, +and prompts typed while history loads wait for it to finish. Agents without history loading can resume their context +without displaying earlier messages. Agents without session listing use the last remembered id for this folder; +when no session is available, a new conversation starts. Agent memory and continuation depend on the adapter. ACP agents receive a built-in `mandocode` MCP server for the open-agent directory, collaboration, and saved conversation snapshots. Type `@`, then Tab to select another agent. Try `Ask @Ares what it found and let me know diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8ac30df..2cdd47b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,8 @@ All notable changes to MandoCode will be documented in this file. **Highlights** +- Choose an earlier ACP conversation with `--resume`, or continue a specific session id, and restore its recent messages and completed activity when the adapter supports history loading. + - Run ACP builds, tests, and scripts through MandoCode-managed terminals, with live output and lifecycle cleanup via ACP v1 or the built-in MCP bridge. - Collaborate between ACP and native Ollama agents with agent mentions, questions, background tasks, messages, and progress tracking. @@ -25,6 +27,8 @@ All notable changes to MandoCode will be documented in this file. ### Added +- Add a folder-scoped ACP session picker before switching agents, with direct session IDs and `--new-panel` support. Show choices in a dedicated panel with readable titles, local update times, keyboard paging, and clear continue/cancel controls at the lower right. Hide workspace/agent chrome while the picker is open and restore it without remounting the conversation; keep full IDs in the plain session list. Keep the current pane on cancellation, follow bounded session-list pagination, and fall back to the last remembered session for agents without listing support. Prefer history loading over resume, restore bounded messages, completed tool calls and plans, suppress replay-time permission prompts, and queue new input until loading finishes. + - Run non-interactive commands in host-managed ACP terminals through the five ACP v1 `terminal/*` methods or the built-in MCP terminal tools. Stream bounded stdout/stderr into persistent command rows, report exit status, preserve displayed output after release, and isolate IDs by session. Cancel command trees on Escape and clean up on session clear, crash, restart, folder change, and closure. Apply configured ACP environment rules, validate working directories, and cap command duration, output, and terminal counts. Disable both routes per agent with `clientTerminals: false`; the reusable process backend does not require ACP v2. - Offer a source-agent recap when switching between native and ACP agents, with opt-out and cancellation before changing runtimes. @@ -80,6 +84,8 @@ All notable changes to MandoCode will be documented in this file. ### Test coverage +- The ACP session picker/history update passed 2,069 tests with one existing skip on .NET 10 Release. Coverage includes read-only discovery against the mock adapter, folder filtering and duplicate IDs, picker cancellation for current/new panes, direct IDs without local persistence, history-load preference and resume-only fallback, bounded text/tool/plan replay, repeated pagination cursors, suppression of replay permissions, reused tool IDs across turns, queued input delivered once after history, local date conversion, panel placement, hidden IDs, and keyboard selection/paging at narrow sizes. A further 71 focused workspace and layout checks passed after the fullscreen refinement, including real terminal footer placement and chrome restoration without disposing the conversation. + - The ACP terminal update passed 2,038 tests with one existing skip on .NET 10 Release. Coverage includes all five ACP terminal methods, real MCP terminal calls, capability opt-out, active-session validation, literal arguments/environment, stdout/stderr and non-newline streaming, bounded UTF-8 tail output under a large flood, exit status, cancellation with child processes, per-pane isolation, and cleanup on clear, crash, and disposal. Terminal DTOs are checked against the vendored official v1 schema. - The final ACP collaboration update passed 1,990 tests with one existing skip on .NET 10 Release. Real stdio MCP checks cover tool discovery, owning-pane identity, active-turn restrictions, call-loop prevention, cancellation, snapshot operations, skill precedence/disabled files, resource boundaries, and connection revocation. Component checks cover snapshots without Ollama, import retries and images, optional source-agent handoffs, compatible command spellings, and compact exchange rendering. A regression deliberately announces a command before the session/new response. Final focused checks and user testing also passed. 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/Components/Sessions/AcpSessionPickerPanel.razor b/src/MandoCode/Components/Sessions/AcpSessionPickerPanel.razor new file mode 100644 index 0000000..e3cba4d --- /dev/null +++ b/src/MandoCode/Components/Sessions/AcpSessionPickerPanel.razor @@ -0,0 +1,119 @@ +@namespace MandoCode.Components +@using MandoCode.Services.Acp +@using Microsoft.AspNetCore.Components.Web +@using RazorConsole.Core.Renderables +@using Spectre.Console +@inject RazorConsole.Core.Rendering.ITerminalViewport Viewport +@inject RazorConsole.Core.Focus.FocusManager Focus +@implements IDisposable + + + + +
+ + @if (ShowContext) { } + @if (ShowSeparator) { } + @for (var i = _start; i < Math.Min(State.Choices.Count, _start + PageSize); i++) + { + var index = i; var choice = State.Choices[index]; var selected = index == _selected; +
+ + + @if (ShowDates) { } + +
+ } +
+
+
+
+ + + + + +
+ +@code { + [CascadingParameter] public AgentPane? Pane { get; set; } + [Parameter, EditorRequired] public AcpSessionPickerState State { get; set; } = default!; + [Parameter] public int InitialIndex { get; set; } + [Parameter] public int? Width { get; set; } + [Parameter] public int? Height { get; set; } + [Parameter] public EventCallback OnSelect { get; set; } + [Parameter] public EventCallback OnClose { get; set; } + private readonly string _focusKey = "acp-sessions-" + Guid.NewGuid().ToString("N"); + private AcpSessionPickerState? _previous; + private int _selected, _start; + private bool _requestFocus = true; + private sealed record Draft(AcpSessionPickerState State, int Selected); + private int AvailableWidth => Math.Max(12, Width ?? Pane?.Width ?? Viewport.Width); + private int PanelWidth => Math.Min(AvailableWidth, 96); + private int PanelHeight => Math.Max(5, Height ?? Pane?.Height ?? Viewport.Height); + private int BoxHeight => Math.Min(PanelHeight - 1, State.Choices.Count * 2 + 5); + private int RowWidth => Math.Max(1, PanelWidth - 4); + private bool ShowDates => BoxHeight >= 7; + private bool ShowContext => BoxHeight >= 6; + private bool ShowSeparator => BoxHeight >= 8; + private int PageSize => Math.Max(1, (BoxHeight - 2 - (ShowContext ? 1 : 0) - (ShowSeparator ? 1 : 0)) / (ShowDates ? 2 : 1)); + private string Title => Spectre.Console.Markup.Escape("Continue with " + (State.AgentName.Length > 0 ? char.ToUpperInvariant(State.AgentName[0]) + State.AgentName[1..] : "ACP agent")); + private string ProjectName => Path.GetFileName(Path.TrimEndingDirectorySeparator(State.Folder)) is { Length: > 0 } name ? name : State.Folder; + private string Context => ProjectName + " · " + State.Choices.Count + " conversations · Local time"; + private string Footer => AvailableWidth >= 60 + ? $"↑↓ Select · Enter Continue · Esc Cancel {_selected + 1}/{State.Choices.Count}" + : AvailableWidth >= 35 ? $"↑↓ Select · Enter Open · Esc Cancel" : "↑↓ · Enter · Esc"; + private string Escape(string text) => Spectre.Console.Markup.Escape(WorkspaceTabWindow.Fit(text, RowWidth)); + protected override void OnParametersSet() + { + if (!ReferenceEquals(State, _previous)) + { + _previous = State; + var saved = Pane?.PresentationState.GetValueOrDefault("acp-session-selection") as Draft; + _selected = Math.Clamp(saved is not null && ReferenceEquals(saved.State, State) ? saved.Selected : InitialIndex, 0, Math.Max(0, State.Choices.Count - 1)); + Reveal(); _requestFocus = true; + } + Reveal(); + } + private void Reveal() => _start = Math.Clamp(_selected - PageSize + 1, 0, Math.Max(0, State.Choices.Count - PageSize)); + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (Pane is not null && !Pane.Active) return; + if (Pane is not null) Pane.FocusKey = _focusKey; + if (firstRender || _requestFocus || !Focus.IsFocused(_focusKey)) + { + await Focus.FocusDeferredAsync(_focusKey); + _requestFocus = !Focus.IsFocused(_focusKey); + } + } + private async Task Select(int index) + { + _selected = index; Reveal(); _requestFocus = true; + await Focus.FocusDeferredAsync(_focusKey); + } + private async Task Key(KeyboardEventArgs key) + { + if (Pane is not null && !Pane.Active) return; + if (Pane?.Workspace.Key(Pane, key) == true) return; + switch (key.Key) + { + case "Escape": await OnClose.InvokeAsync(); return; + case "Enter": case "Return": + if (State.Choices.Count > 0) await OnSelect.InvokeAsync(State.Choices[_selected].Label); + return; + case "ArrowUp": case "UpArrow": _selected--; break; + case "ArrowDown": case "DownArrow": _selected++; break; + case "PageUp": _selected -= PageSize; break; + case "PageDown": _selected += PageSize; break; + case "Home": _selected = 0; break; + case "End": _selected = State.Choices.Count - 1; break; + } + _selected = Math.Clamp(_selected, 0, Math.Max(0, State.Choices.Count - 1)); Reveal(); + } + public void Dispose() + { + if (Pane is not null) Pane.PresentationState["acp-session-selection"] = new Draft(State, _selected); + } +} diff --git a/src/MandoCode/Components/Shell/App.Acp.cs b/src/MandoCode/Components/Shell/App.Acp.cs index 9b7ba60..57f1179 100644 --- a/src/MandoCode/Components/Shell/App.Acp.cs +++ b/src/MandoCode/Components/Shell/App.Acp.cs @@ -20,6 +20,7 @@ public partial class App private AcpTranscriptAdapter? _acpTranscript; private AcpToolActivityStore? _acpTools; private CancellationTokenSource? _acpStartCts; + private CancellationTokenSource? _acpSessionSelectionCts; private AcpFolderChangeContext? _acpFolderChange; private string? _pendingAcpProjectNotice; @@ -225,7 +226,7 @@ private void UpdateAcpHeader() /// Something of this pane is running or waiting for the user; a mode switch must not cut it off. private bool HasActiveWork => - _requestCts is not null || _runningPeerRequest is not null || _planSelectActive || ApprovalMenu.IsActive; + _acpSessionSelectionCts is not null || _requestCts is not null || _runningPeerRequest is not null || _planSelectActive || ApprovalMenu.IsActive; private const string BusyMessage = "This agent is busy. Wait for it to finish (Escape cancels it), or use --new-panel to open the agent in another pane."; @@ -248,21 +249,32 @@ private async Task TearDownAcpAsync() /// /agent-acp <name>: this pane runs the external agent from now on. The native session stays alive /// underneath; the user may explicitly carry a source-generated recap to the new agent. /// - private async Task SwitchToAcpAsync(string agentName, bool resume = false) + private async Task SwitchToAcpAsync(string agentName, bool resume = false, string? sessionId = null) { if (Pane is null) return "Agent panes are not available here."; if (HasActiveWork) return BusyMessage; + if (_acpStart?.IsCompleted == false) return BusyMessage; + var requestedResume = resume; + if (resume) + { + var selection = await SelectAcpSessionAsync(agentName, sessionId); + if (!selection.Proceed) return selection.Error ?? "Session selection cancelled."; + sessionId = selection.SessionId; + resume = sessionId is not null; + if (_paneStopped || _disposed || HasActiveWork) return BusyMessage; + } if (IsAcpPane) { - if (string.Equals(Pane.AcpAgentName, agentName, StringComparison.OrdinalIgnoreCase) + if (!requestedResume && string.Equals(Pane.AcpAgentName, agentName, StringComparison.OrdinalIgnoreCase) && _acp is { Status: AcpRuntimeStatus.Ready or AcpRuntimeStatus.Starting }) return $"This pane already runs '{agentName}'. Use /agent-acp restart to start it again."; } - var handoff = resume ? (Proceed: true, Snapshot: (ContextSnapshot?)null, Error: (string?)null) : await PrepareAgentHandoffAsync(); + var handoff = requestedResume ? (Proceed: true, Snapshot: (ContextSnapshot?)null, Error: (string?)null) : await PrepareAgentHandoffAsync(); if (!handoff.Proceed) return handoff.Error ?? "Agent switch cancelled."; if (IsAcpPane) await TearDownAcpAsync(); AcpPaneMode.Enter(Pane, agentName, resume); + Pane.AcpResumeSessionId = sessionId; if (handoff.Snapshot is { } recap) Snapshots.Queue(recap); _acpFolderChange = null; _pendingAcpProjectNotice = null; @@ -369,7 +381,6 @@ private async Task ProcessAcpRequestAsync(string input, CancellationToken cancel { _lastRequestError = null; _lastCompletedReply = null; - _acpMessages.Add(new ChatMsg { Role = "user", Text = input }); (Pane?.Session ?? TuiConsole.Current)?.BeginToolTurn(); TuiConsole.WriteLine(); @@ -398,6 +409,7 @@ private async Task ProcessAcpRequestAsync(string input, CancellationToken cancel return; } + _acpMessages.Add(new ChatMsg { Role = "user", Text = input }); Spinner.Start("Thinking..."); var driver = new AcpTurnDriver(new PaneSink(this), AcpEntry, _acpTranscript); var bridge = Pane?.Services.GetRequiredService().Bridge; @@ -521,22 +533,39 @@ public void Reply(string markdown) /// What /agent-acp <name> and /agent-acp restart do in this pane. private sealed class PaneHost(App app) : IAcpPaneHost { - public async Task OpenPaneAsync(string agentName, bool resume = false) + public async Task OpenPaneAsync(string agentName, bool resume = false, string? sessionId = null) { if (app.Pane is null) return "Agent panes are not available here."; + var choosing = resume && sessionId is null; + if (choosing && (app.HasActiveWork || app._acpStart?.IsCompleted == false)) + return "Wait for this agent to finish before choosing a session, or specify a session id with --new-panel."; + if (app.Pane.Workspace.Panes.Count >= 4) return "Four agent panes are already open. Close one first."; + if (resume) + { + var selection = await app.SelectAcpSessionAsync(agentName, sessionId); + if (!selection.Proceed) return selection.Error ?? "Session selection cancelled."; + sessionId = selection.SessionId; + resume = sessionId is not null; + if (app._paneStopped || app._disposed || (choosing && app.HasActiveWork)) return BusyMessage; + } string? result = null; await app.InvokeAsync(() => { var workspace = app.Pane.Workspace; var before = workspace.Panes.Count; var pane = workspace.Add(acpAgent: agentName, acpResume: resume); + if (workspace.Panes.Count > before) + { + pane.AcpResumeSessionId = sessionId; + pane.AcpResumeFolder = sessionId is null ? null : app.ProjectRoot.ProjectRoot; + } if (workspace.Panes.Count == before || pane.AcpAgentName != agentName) result = "Four agent panes are already open. Close one first."; }); return result; } - public Task SwitchAsync(string agentName, bool resume = false) => app.SwitchToAcpAsync(agentName, resume); + public Task SwitchAsync(string agentName, bool resume = false, string? sessionId = null) => app.SwitchToAcpAsync(agentName, resume, sessionId); public Task SessionsAsync() => app.ListAcpSessionsAsync(); diff --git a/src/MandoCode/Components/Shell/App.AcpCommands.cs b/src/MandoCode/Components/Shell/App.AcpCommands.cs index b60e328..9d3434f 100644 --- a/src/MandoCode/Components/Shell/App.AcpCommands.cs +++ b/src/MandoCode/Components/Shell/App.AcpCommands.cs @@ -214,6 +214,40 @@ private async Task RunShellLineAsync(string command) // ───────────── sessions ───────────── + private async Task SelectAcpSessionAsync(string name, string? explicitId) + { + if (explicitId is not null) + return AcpSessionPicker.ValidId(explicitId) ? new(true, explicitId) : new(false, Error: "Invalid ACP session id."); + if (!Config.AcpAgents.TryGetValue(name, out var entry)) return new(false, Error: "ACP agent is no longer configured."); + var folder = ProjectRoot.ProjectRoot; + var remembered = Config.AllowPersistence ? AcpSessions.Get(name, folder)?.SessionId : null; + using var selection = CancellationTokenSource.CreateLinkedTokenSource(Lifetime.ApplicationStopping); + _acpSessionSelectionCts = selection; + using var cancelMenu = selection.Token.Register(() => ApprovalMenu.Cancel()); + try + { + IReadOnlyList? sessions; + Spinner.Start("Finding ACP sessions..."); + try + { + if (Pane?.AcpAgentName == name && _acp is { Status: AcpRuntimeStatus.Ready } running) + sessions = running.Support.CanList ? await running.ListSessionsAsync(selection.Token) : null; + else + sessions = await AcpSessionPicker.DiscoverAsync(name, entry, folder, new AcpAgentLauncher(new FileTrustStore()), + async plan => { Spinner.Stop(); return await ConfirmAcpLaunchAsync(plan); }, selection.Token); + } + finally { Spinner.Stop(); } + selection.Token.ThrowIfCancellationRequested(); + var result = await AcpSessionPicker.ChooseAsync(sessions, folder, remembered, + new AcpSessionChoicePrompt(PromptGate, ApprovalMenu, () => KeyCoordinator.Suppress(), name, folder), text => Say(text, Color.Grey)); + selection.Token.ThrowIfCancellationRequested(); + return result; + } + catch (OperationCanceledException) { return new(false); } + catch (Exception ex) { return new(false, Error: "Could not find ACP sessions: " + ex.Message + " The current agent was kept."); } + finally { _acpSessionSelectionCts = null; } + } + /// The session to continue for --resume, from what MandoCode remembers for this agent and folder. private AcpResumeRequest? TakeResumeRequest() { @@ -221,6 +255,13 @@ private async Task RunShellLineAsync(string command) return null; pane.AcpResume = false; + if (pane.AcpResumeSessionId is { } selected) + { + pane.AcpResumeSessionId = null; + if (pane.AcpResumeFolder is { } selectedFolder) ProjectRoot.ProjectRoot = selectedFolder; + pane.AcpResumeFolder = null; + return new AcpResumeRequest(selected); + } if (!Config.AllowPersistence) { Say("Persistence is turned off in the settings, so no earlier session is remembered. Starting a new one."); @@ -255,10 +296,26 @@ private void AnnounceSession(IAcpAgentRuntime runtime) var messages = _acpHistory?.Messages() ?? []; _acpMessages.AddRange(messages.Select(m => new ChatMsg { Role = m.Role, Text = m.Text })); Say($"── Continued the agent's earlier session: {messages.Count} earlier message(s) restored ──", Color.Grey); - foreach (var message in messages) + if (_acpHistory?.Truncated == true) + Say($"Showing recent history only (up to {AcpHistoryCollector.TurnLimit} turns; long entries are shortened).", Color.Grey); + foreach (var item in _acpHistory?.Items() ?? []) { + if (item.Tool is { } tool) + { + _acpTools?.Apply(tool); + continue; + } + if (item.Plan is { } plan) + { + _acpTranscript?.SetPlan(plan); + if (_acpTranscript?.TakePlan() is { } block) Print(block); + continue; + } + var message = new ChatMsg { Role = item.Role!, Text = item.Text }; if (message.Role == "user") { + _acpTools?.BeginTurn(); + _acpTranscript?.BeginTurn(); Print(new Text("> " + message.Text, new Style(Color.Grey))); } else diff --git a/src/MandoCode/Components/Shell/App.Lifecycle.cs b/src/MandoCode/Components/Shell/App.Lifecycle.cs index 25a33a6..ef5ff13 100644 --- a/src/MandoCode/Components/Shell/App.Lifecycle.cs +++ b/src/MandoCode/Components/Shell/App.Lifecycle.cs @@ -14,6 +14,7 @@ private void StopPane() _paneStopped = true; _requestCts?.Cancel(); _acpStartCts?.Cancel(); + _acpSessionSelectionCts?.Cancel(); _snapshotCompletion?.TrySetResult(); _setupCompletion?.TrySetResult(new(false, true, null)); _historyTcs?.TrySetResult(); diff --git a/src/MandoCode/Components/Shell/App.razor b/src/MandoCode/Components/Shell/App.razor index 515ab41..2d701cc 100644 --- a/src/MandoCode/Components/Shell/App.razor +++ b/src/MandoCode/Components/Shell/App.razor @@ -53,10 +53,18 @@ GitChangesOpen="@_gitChangesOpen" OnGitChangesClose="CloseGitChanges" OnGitDiscarded="GitDiscarded" + SessionPickerOpen="@(ApprovalMenu.SessionPicker is not null)" HistoryOpen="@_historyActive" OnHistoryClose="CloseHistory" OnHistoryRestore="RestoreArchivedAgent" OnChangeDirectory="@(() => HandleVdomSubmit("/change-directory"))"> + +@if (ApprovalMenu.SessionPicker is { } sessionPicker) +{ + +} +
@@ -130,7 +138,7 @@ SelectionPrompt so the keyboard pump is the only console reader and arrow keys can't be stolen mid-prompt, which previously hung a plan step. Bridged via ApprovalSelectCoordinator (TCS). *@ -@if (ApprovalMenu.IsActive) +@if (ApprovalMenu.IsActive && ApprovalMenu.SessionPicker is null) { @* A decision on something too long to print (a long diff) shows it here, scrolled with PgUp/PgDn from the menu, which keeps focus. *@ @@ -1725,11 +1733,18 @@ Pane.RestoreFrom = null; } + private bool _sessionPickerWasOpen; private void OnApprovalMenuStateChanged() { _approvalMenuOptions = ApprovalMenu.Options .Select(o => new ApprovalSelect.Option(o.Text, o.Color)) .ToList(); + var sessionPickerOpen = ApprovalMenu.SessionPicker is not null; + if (sessionPickerOpen != _sessionPickerWasOpen) + { + _sessionPickerWasOpen = sessionPickerOpen; + Pane?.Workspace.Refresh(); + } _approvalPreviewOffset = 0; // every request starts at the top of its preview InvokeAsync(StateHasChanged); } diff --git a/src/MandoCode/Components/Shell/ChatShell.razor b/src/MandoCode/Components/Shell/ChatShell.razor index da4d6aa..ce1c2ef 100644 --- a/src/MandoCode/Components/Shell/ChatShell.razor +++ b/src/MandoCode/Components/Shell/ChatShell.razor @@ -6,6 +6,12 @@ @implements IDisposable +@if (SessionPickerOpen) +{ + @SessionPicker +} +else +{ @if (!NarrowPanel) @@ -121,6 +127,7 @@ @Bottom } +} @code { [CascadingParameter] public AgentPane? Pane { get; set; } @@ -167,6 +174,8 @@ if (Pane is not null) { Pane.ExplorerFocus = _explorerFocus; Pane.IsGitDiffOpen = () => GitChangesOpen && _gitDiffOpen; } } private TuiSession Session { get; set; } = default!; + [Parameter] public bool SessionPickerOpen { get; set; } + [Parameter] public RenderFragment? SessionPicker { get; set; } [Parameter] public RenderFragment? Header { get; set; } [Parameter] public RenderFragment? Footer { get; set; } [Parameter] public string ProjectDirectory { get; set; } = ""; diff --git a/src/MandoCode/Components/Workspaces/AgentPaneContent.razor b/src/MandoCode/Components/Workspaces/AgentPaneContent.razor index 003ba16..c10512c 100644 --- a/src/MandoCode/Components/Workspaces/AgentPaneContent.razor +++ b/src/MandoCode/Components/Workspaces/AgentPaneContent.razor @@ -5,6 +5,8 @@ @implements IDisposable + @if (Pane.Services.GetRequiredService().SessionPicker is null) + { @if (Pane.Visible && Pane.Workspace.Registry?.IsWorkspacePickerOpen != true) { @@ -43,6 +45,7 @@ } + } @if (AgentBody is not null) { @AgentBody(Pane) } else { } diff --git a/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor b/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor index 669dce7..825a658 100644 --- a/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor +++ b/src/MandoCode/Components/Workspaces/AgentWorkspaceView.razor @@ -1,6 +1,7 @@ @namespace MandoCode.Components @using RazorConsole.Core.Renderables @using Spectre.Console +@using Microsoft.Extensions.DependencyInjection @inject AgentWorkspace DefaultWorkspace @inject RazorConsole.Core.Rendering.ITerminalViewport Viewport @inject RazorConsole.Core.Focus.FocusManager Focus @@ -41,6 +42,7 @@ pane.Width = Math.Max(1, PaneWidth - (Workspace.Panes.Count > 1 ? 2 : 0)); pane.Height = Math.Max(1, Workspace.Panes.Count == 3 && Workspace.Panes.Count(p => AgentWorkspace.Column(p.Slot) == AgentWorkspace.Column(pane.Slot)) == 1 ? AvailableHeight - 3 : PaneHeight - (Workspace.Panes.Count > 1 ? 3 : 1)); + if (pane.Services.GetRequiredService().SessionPicker is not null) pane.Height++; } } protected override void OnParametersSet() => UpdateSizes(); diff --git a/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor b/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor index afec45f..59d9f30 100644 --- a/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor +++ b/src/MandoCode/Components/Workspaces/TerminalWorkspaceView.razor @@ -8,6 +8,8 @@ @implements IDisposable + @if (!SessionPickerOpen) + { @if (LabelWidth > 0) @@ -50,13 +52,14 @@ } + } @foreach (var workspace in Registry.Entries) { - + } - @if (TipHeight > 0) + @if (!SessionPickerOpen && TipHeight > 0) { @@ -75,6 +78,7 @@ @code { [Parameter] public RenderFragment? AgentBody { get; set; } + private bool SessionPickerOpen => Registry.Active.SelectedPane?.Services.GetRequiredService().SessionPicker is not null; private long _revision; private static readonly Color BarBackground = new(22, 26, 30); private readonly WorkspaceTabWindow _tabs = new(); diff --git a/src/MandoCode/Services/Acp/AcpAgentCommands.cs b/src/MandoCode/Services/Acp/AcpAgentCommands.cs index eb99000..a301ec4 100644 --- a/src/MandoCode/Services/Acp/AcpAgentCommands.cs +++ b/src/MandoCode/Services/Acp/AcpAgentCommands.cs @@ -20,13 +20,13 @@ public interface IAcpAgentCatalog public interface IAcpPaneHost { /// Opens a new pane running the agent. Null on success, otherwise what to tell the user. - Task OpenPaneAsync(string agentName, bool resume = false); + Task OpenPaneAsync(string agentName, bool resume = false, string? sessionId = null); /// /// Switches the current pane to the agent (closing the ACP agent it already runs, if any). The native session stays /// alive underneath. Null on success, otherwise what to tell the user (for example when the pane is busy). /// - Task SwitchAsync(string agentName, bool resume = false); + Task SwitchAsync(string agentName, bool resume = false, string? sessionId = null); /// Prints the agent's sessions for this pane's folder. Null on success, otherwise what to tell the user. Task SessionsAsync(); @@ -45,7 +45,7 @@ public interface IAcpPaneHost public sealed class AcpAgentCommands { public const string Usage = - "Usage: /agent-acp [list] | [--new-panel] [--resume] | restart | stop | sessions | status [name] | add [args...] | test | remove | enable | disable "; + "Usage: /agent-acp [list] | [--new-panel] [--resume [session-id]] | restart | stop | sessions | status [name] | add [args...] | test | remove | enable | disable "; private static readonly HashSet Reserved = new(StringComparer.OrdinalIgnoreCase) { @@ -161,13 +161,19 @@ private async Task OpenAsync(List tokens, TextWriter error, TextWriter o } } - if (names.Count != 1) + if (names.Count != 1 && !(resume && names.Count == 2)) { error.WriteLine(Usage); return; } var name = names[0]; + var sessionId = names.Count == 2 ? names[1] : null; + if (sessionId is not null && !AcpSessionPicker.ValidId(sessionId)) + { + error.WriteLine("Session ids must be nonempty, at most 1024 characters, and contain no control characters."); + return; + } if (!_catalog.Agents.TryGetValue(name, out var agent)) { error.WriteLine($"Unknown /agent-acp command '{name}'."); @@ -181,12 +187,12 @@ private async Task OpenAsync(List tokens, TextWriter error, TextWriter o error.WriteLine("Opening an agent pane is not available here."); else if (newPanel) { - if (await _host.OpenPaneAsync(name, resume) is { } openError) + if (await _host.OpenPaneAsync(name, resume, sessionId) is { } openError) error.WriteLine(openError); else output.WriteLine($"Opened ACP agent '{name}' in a new pane."); } - else if (await _host.SwitchAsync(name, resume) is { } switchError) + else if (await _host.SwitchAsync(name, resume, sessionId) is { } switchError) error.WriteLine(switchError); } 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