From 04bd18b35bff4f3bc0fa8a6d63822fe90e4e9917 Mon Sep 17 00:00:00 2001 From: DevMando Date: Tue, 1 Dec 2026 22:06:23 -0800 Subject: [PATCH 1/2] Feature: keep ACP conversation context when switching project folders --- docs/CHANGELOG.md | 2 + docs/acp-codex.md | 2 +- docs/acp.md | 33 ++++- src/MandoCode/Components/Shell/App.Acp.cs | 53 ++++++-- .../Components/Shell/App.AcpCommands.cs | 57 +++++--- .../Services/Acp/AcpContextUpdateSink.cs | 19 +++ .../Services/Acp/AcpFolderChangeContext.cs | 66 +++++++++ tests/MandoCode.Acp.MockAgent/Program.cs | 17 ++- .../Acp/AcpContextUpdateSinkTests.cs | 28 ++++ .../Acp/AcpFolderChangeContextTests.cs | 45 +++++++ tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs | 125 ++++++++++++++++-- tests/MandoCode.Tests/Acp/AcpSessionTests.cs | 19 +++ 12 files changed, 416 insertions(+), 50 deletions(-) create mode 100644 src/MandoCode/Services/Acp/AcpContextUpdateSink.cs create mode 100644 src/MandoCode/Services/Acp/AcpFolderChangeContext.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpContextUpdateSinkTests.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpFolderChangeContextTests.cs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a038db0..cf4d321 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -18,6 +18,8 @@ All notable changes to MandoCode will be documented in this file. ### Added +- ACP folder changes retain the selected pane's transcript and attempt to continue its session in the new folder. If the adapter starts fresh, offer a bounded recent-text handoff or a fresh context. Send a project-change note before the next request so the agent rechecks old paths and files. Other ACP panes remain unchanged; `/clear` discards pending handoff context. Use the same concise folder-change wording as native conversations, without repeating the connection card or internal acknowledgment. + - Paste clipboard images into ACP prompts with Alt+V when the connected agent advertises image support. Send in-memory PNG image blocks with text, retain per-pane attachment references and size limits, and explain unsupported agents or expired images without sending an incomplete prompt. - ACP agent-provided commands appear in slash-command suggestions with the connected agent’s display name (for example `[Codex]`), descriptions, and input hints. Advertised commands and arguments are forwarded to the current agent as prompts; session updates replace the list, and MandoCode commands retain precedence on name collisions. diff --git a/docs/acp-codex.md b/docs/acp-codex.md index a49d8e9..997fe3d 100644 --- a/docs/acp-codex.md +++ b/docs/acp-codex.md @@ -48,7 +48,7 @@ entry path with `node`. The live validation below was performed on Windows only. - `/clear` starts another ACP conversation and preserves the native MandoCode conversation. - `/copy` and `/copy-code` read the ACP conversation's last reply. - `/agent-acp stop` returns to the native conversation. -- Folder changes follow the normal ACP restart and confirmation flow. +- Folder changes restart only that ACP pane, retain its transcript, and try to continue its session. If cross-folder continuation is unavailable, choose whether to carry recent text context into a fresh session. A project-change note precedes the next request. Capability handling remains shared with other ACP agents. This setup does not add native agent mentions, context handoff, or the proposed MandoCode MCP bridge. diff --git a/docs/acp.md b/docs/acp.md index 57f353c..7e5d252 100644 --- a/docs/acp.md +++ b/docs/acp.md @@ -216,11 +216,34 @@ The available names depend on the agent. ### Changing the folder -The folder belongs to the pane (each pane has its own `ProjectRootAccessor`), not to the application. The agent was -started in the old folder, so `/change-directory`, Alt+D, the Change Directory button and `!cd` / `! cd` ask first: -"the ACP agent restarts there and the ACP conversation is lost", then restart the agent (new process, new session, -file access rooted in the new folder). The trust hash does not contain the folder, so there is no new trust question. -`chdir`, `pushd`, `Set-Location` and `sl` only run in a child process and never changed the folder. +The folder belongs to the pane (each pane has its own `ProjectRootAccessor`), not to the application. +`/change-directory`, Alt+D, the Change Directory button, and `!cd` / `! cd` switch folders directly and restart **only that pane's ACP agent**, without an extra confirmation. +Other panes keep their folders, sessions, and conversations. Dismissing the folder picker leaves the selected pane unchanged. + +The visible transcript is retained. Folder changes use the same wording as native conversations: +“Changed directory to …” and “Switching to the new project — this conversation is kept.” +Folder restarts use transient progress instead of repeating the connection card. The old process ends before the pane's folder and +filesystem access root change. MandoCode then attempts to continue the current session using the adapter's supported +`session/resume` or `session/load` with the new folder. Cross-folder continuation depends on the adapter; an accepted +continuation keeps agent memory, and history replay is not duplicated in the retained transcript. + +If the adapter starts a fresh session, the pane says so and offers **Carry recent context** or **Start fresh**. The first +option transfers a bounded text excerpt (up to eight recent user/assistant messages and 12,000 characters), not a full +session restoration or a model-generated summary. Attachments are not transferred. Start fresh or Escape declines the +handoff; the earlier transcript remains available for reference either way. + +Before the next user request, MandoCode sends a separate project-context update naming the old and new folders and +asking the agent to re-read files, avoid old path assumptions, and wait for the user's next instruction. A chosen +handoff is included in that update. The internal acknowledgment is hidden; errors, warnings, and actual tool activity remain visible. The original user prompt follows unchanged, including slash commands and images. +If the update fails or is cancelled, the user request is not sent and the update remains pending for retry. The update +is guidance to the agent, not a filesystem-access restriction. + +A failed startup retains the transcript and continuation attempt for `/agent-acp restart`. `/clear` discards any pending +handoff or project note as well as clearing the ACP conversation. Returning to the native agent or switching ACP agents +also discards the pending context. Normal explicit `--resume` behavior is unchanged. + +The trust hash does not contain the folder, so an unchanged launch command needs no new trust question. `chdir`, `pushd`, +`Set-Location`, and `sl` run only in a child shell process and do not change the pane's project folder. ### Sessions diff --git a/src/MandoCode/Components/Shell/App.Acp.cs b/src/MandoCode/Components/Shell/App.Acp.cs index 83cc21c..144cbb1 100644 --- a/src/MandoCode/Components/Shell/App.Acp.cs +++ b/src/MandoCode/Components/Shell/App.Acp.cs @@ -20,6 +20,8 @@ public partial class App private AcpTranscriptAdapter? _acpTranscript; private AcpToolActivityStore? _acpTools; private CancellationTokenSource? _acpStartCts; + private AcpFolderChangeContext? _acpFolderChange; + private string? _pendingAcpProjectNotice; private bool IsAcpPane => Pane?.Runtime == AgentRuntime.Acp; @@ -46,19 +48,22 @@ private async Task InitializeAcpAsync() await InvokeAsync(StateHasChanged); } - private sealed class StartupSink(App app, string name) : IAcpStartupSink + private sealed class StartupSink(App app, string name, bool compact = false) : IAcpStartupSink { public void Connecting(string agentName) { app.Spinner.Start($"Connecting to {name}..."); - Print(new Text($"Connecting to {name}… You can type while the agent starts.", new Style(Color.Grey))); + if (!compact) Print(new Text($"Connecting to {name}… You can type while the agent starts.", new Style(Color.Grey))); } public void Connected(string description, IReadOnlyList warnings) { app.Spinner.Stop(); - if (app._acp is { } runtime) Print(AcpConnectionCard.Build(runtime)); - else TuiConsole.WriteLine($"Connected to {description}."); + if (!compact) + { + if (app._acp is { } runtime) Print(AcpConnectionCard.Build(runtime)); + else TuiConsole.WriteLine($"Connected to {description}."); + } foreach (var warning in warnings) Print(new Text("Warning: " + warning, new Style(Color.Yellow))); } @@ -80,8 +85,10 @@ private async Task StartAcpRuntimeAsync() return false; } - var resume = TakeResumeRequest(); - _acpHistory = resume is null ? null : new AcpHistoryCollector(); + var folderChange = _acpFolderChange; + var resume = folderChange is null ? TakeResumeRequest() : folderChange.Resume; + // The visible transcript already contains these messages during a folder change; don't replay them twice. + _acpHistory = resume is null || folderChange is not null ? null : new AcpHistoryCollector(); var runtime = new AcpAgentRuntime( name, entry, ProjectRoot.ProjectRoot, new AcpAgentLauncher(new FileTrustStore()), @@ -111,9 +118,12 @@ private async Task StartAcpRuntimeAsync() UpdateAcpHeader(); try { - var started = await AcpPaneStartup.RunAsync(runtime, new StartupSink(this, name), _acpStartCts.Token); - if (started) - AnnounceSession(runtime); + var started = await AcpPaneStartup.RunAsync(runtime, new StartupSink(this, name, compact: folderChange is not null), _acpStartCts.Token); + if (started && ReferenceEquals(_acp, runtime)) + { + if (folderChange is not null) await CompleteAcpFolderChangeAsync(runtime, folderChange); + else AnnounceSession(runtime); + } return started; } finally @@ -238,6 +248,8 @@ private async Task TearDownAcpAsync() } AcpPaneMode.Enter(Pane, agentName, resume); + _acpFolderChange = null; + _pendingAcpProjectNotice = null; _acpMessages.Clear(); Print(new Text(AcpPaneMode.EnterMessage(agentName, resume), new Style(Color.Grey))); @@ -260,6 +272,8 @@ private async Task TearDownAcpAsync() await TearDownAcpAsync(); await AcpPaneMode.LeaveAsync(Pane); + _acpFolderChange = null; + _pendingAcpProjectNotice = null; _acpMessages.Clear(); Print(new Text("── Back to the native agent (the ACP conversation is not shared with it). ──", new Style(Color.Grey))); @@ -274,7 +288,7 @@ private async Task TearDownAcpAsync() return null; } - private async Task RestartAcpAsync() + private async Task RestartAcpAsync(string? projectDirectory = null) { try { _acpStartCts?.Cancel(); } catch (ObjectDisposedException) { } var old = _acp; @@ -286,6 +300,7 @@ private async Task RestartAcpAsync() await old.DisposeAsync(); } + if (projectDirectory is not null) Shell.ChangeDirectory(projectDirectory); var start = StartAcpRuntimeAsync(); _acpStart = start; await start; @@ -327,8 +342,22 @@ private async Task ProcessAcpRequestAsync(string input) Spinner.Start("Thinking..."); var driver = new AcpTurnDriver(new PaneSink(this), AcpEntry, _acpTranscript); - var outcome = await driver.RunAsync(_acp, AcpPromptBuilder.Build(input, ProjectRoot.ProjectRoot, - Pane?.Services.GetService(), _acp.PromptCapabilities.Image), token); + var prompt = AcpPromptBuilder.Build(input, ProjectRoot.ProjectRoot, + Pane?.Services.GetService(), _acp.PromptCapabilities.Image); + if (_pendingAcpProjectNotice is { } notice) + { + Spinner.Start("Updating project context..."); + var contextDriver = new AcpTurnDriver(new AcpContextUpdateSink(new PaneSink(this)), AcpEntry, _acpTranscript); + var update = await contextDriver.RunAsync(_acp, [new MandoCode.Acp.Protocol.TextContent(notice)], token); + if (update.Error is not null || update.Cancelled || token.IsCancellationRequested) + { + _lastRequestError = update.Error ?? "Project-context update was cancelled."; + Say("Project update failed. Your request was not sent; send it again to retry."); + return; + } + _pendingAcpProjectNotice = null; + } + var outcome = await driver.RunAsync(_acp, prompt, token); _lastRequestError = outcome.Error; if (outcome.ReplyText.Length > 0) diff --git a/src/MandoCode/Components/Shell/App.AcpCommands.cs b/src/MandoCode/Components/Shell/App.AcpCommands.cs index 6d74ad3..f5e9f51 100644 --- a/src/MandoCode/Components/Shell/App.AcpCommands.cs +++ b/src/MandoCode/Components/Shell/App.AcpCommands.cs @@ -9,8 +9,6 @@ namespace MandoCode.Components; // The decisions (what the agent offers, how a choice is matched) live in Services/Acp. public partial class App { - private const string ChangeFolderLabel = "Change folder and restart the agent"; - private const string KeepFolderLabel = "Cancel"; private AcpSessionStore? _acpSessionStore; private AcpHistoryCollector? _acpHistory; @@ -112,6 +110,8 @@ private async Task ClearAcpConversationAsync() return; } + _acpFolderChange = null; + _pendingAcpProjectNotice = null; _acpMessages.Clear(); _lastCompletedReply = null; _lastRequestError = null; @@ -123,13 +123,13 @@ private async Task ClearAcpConversationAsync() /// /// /change-directory and !cd in an ACP pane. The folder belongs to this pane only, but the agent - /// was started in the old one, so the change restarts it (a new process and session) after the user agrees. + /// was started in the old one, so the change restarts it and tries to continue its session when the user selects a folder. /// private async Task ChangeAcpFolderAsync(string arguments) { - if (HasActiveWork) + if (HasActiveWork || _acpStart?.IsCompleted == false) { - Say(BusyMessage); + Say("Wait for this ACP agent to finish its request or startup before changing folders."); return; } @@ -158,22 +158,45 @@ private async Task ChangeAcpFolderAsync(string arguments) return; } - var answer = await AcpChoices.ChooseAsync( - $"Change this pane's folder to {directory}? The ACP agent restarts there and the ACP conversation is lost; the native conversation is not affected.", - [new AcpChoice(ChangeFolderLabel, Color.Green), new AcpChoice(KeepFolderLabel, new Color(255, 200, 80))]); - if (answer != ChangeFolderLabel) + if (HasActiveWork || _acpStart?.IsCompleted == false) { - Say("Folder not changed.", Color.Grey); + Say("Wait for this ACP agent to finish before changing folders."); return; } - - Shell.ChangeDirectory(directory); - _acpMessages.Clear(); - _lastCompletedReply = null; + var previousFolder = ProjectRoot.ProjectRoot; + _acpFolderChange = new AcpFolderChangeContext(previousFolder, directory, + _acp is { Support.CanContinue: true, SessionId: not null } runtime ? runtime.SessionId : _acpFolderChange?.Resume?.SessionId, + _acpMessages, _pendingAcpProjectNotice); + if (Pane is not null) Pane.AcpResume = false; _lastRequestError = null; - Say($"── Folder changed to {directory}. The ACP agent restarts there with a new conversation. ──", Color.Grey); - await RestartAcpAsync(); - } + try { await RestartAcpAsync(directory); } + catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException or NotSupportedException) + { + if (!AcpPaths.SameFolder(ProjectRoot.ProjectRoot, directory)) _acpFolderChange = null; + Say($"Could not change the ACP project folder: {ex.Message} {AcpErrorMessages.RestartHint}", Color.Red); + } + } + + private async Task CompleteAcpFolderChangeAsync(IAcpAgentRuntime runtime, AcpFolderChangeContext change) + { + if (!ReferenceEquals(_acpFolderChange, change) || !ReferenceEquals(_acp, runtime)) return; + var continued = runtime.SessionOrigin is AcpSessionOrigin.Resumed or AcpSessionOrigin.Loaded; + var carry = false; + if (!continued && change.HasRecentContext) + { + Spinner.Stop(); + var answer = await AcpChoices.ChooseAsync( + "The agent started a fresh session in the new folder. Keep recent conversation context? The transcript remains visible either way; attachments are not transferred.", + [new AcpChoice("Carry recent context", Color.Green), new AcpChoice("Start fresh", new Color(255, 200, 80))]); + carry = answer == "Carry recent context"; + } + if (!ReferenceEquals(_acpFolderChange, change) || !ReferenceEquals(_acp, runtime)) return; + _pendingAcpProjectNotice = change.BuildNotice(continued, carry); + _acpFolderChange = null; + _acpHistory = null; + TuiConsole.WriteLine($"Changed directory to {change.NewFolder}"); + TuiConsole.WriteLine("Switching to the new project — this conversation is kept."); + } /// A shell line typed in the prompt (!cmd, /command cmd): a folder change in an ACP pane goes through the folder flow. private async Task RunShellLineAsync(string command) diff --git a/src/MandoCode/Services/Acp/AcpContextUpdateSink.cs b/src/MandoCode/Services/Acp/AcpContextUpdateSink.cs new file mode 100644 index 0000000..8810606 --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpContextUpdateSink.cs @@ -0,0 +1,19 @@ +using MandoCode.Acp.Protocol; +using Spectre.Console.Rendering; + +namespace MandoCode.Services.Acp; + +/// Internal context acknowledgments stay out of the transcript; errors and actual tool activity stay visible. +public sealed class AcpContextUpdateSink(IAcpTurnSink inner) : IAcpTurnSink +{ + public void Preview(string? tail) { if (tail is null) inner.Preview(null); } + public void Reply(string markdown) { } + public void Activity(string label) => inner.Activity(label); + public void Block(IRenderable block) => inner.Block(block); + public void Notice(string text) => inner.Notice(text); + public void Error(string text) => inner.Error(text); + public void BeginToolActivities() => inner.BeginToolActivities(); + public bool ToolCall(ToolCallBase call) => inner.ToolCall(call); + public void ToolDetail(string id, IRenderable detail) => inner.ToolDetail(id, detail); + public void EndToolActivities(string status) => inner.EndToolActivities(status); +} diff --git a/src/MandoCode/Services/Acp/AcpFolderChangeContext.cs b/src/MandoCode/Services/Acp/AcpFolderChangeContext.cs new file mode 100644 index 0000000..dee4ea9 --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpFolderChangeContext.cs @@ -0,0 +1,66 @@ +using System.Text; +using MandoCode.Models; + +namespace MandoCode.Services.Acp; + +/// In-memory context for one pane's folder transition; never persists conversation text. +public sealed class AcpFolderChangeContext +{ + public const int MaxHandoffChars = 12000; + private const int MaxMessages = 8; + public string OldFolder { get; } + public string NewFolder { get; } + public AcpResumeRequest? Resume { get; } + public string RecentContext { get; } + private readonly string? _previousNotice; + public bool HasRecentContext => RecentContext.Length > 0; + public AcpFolderChangeContext(string oldFolder, string newFolder, string? sessionId, + IReadOnlyList messages, string? previousNotice = null) + { + OldFolder = oldFolder; + NewFolder = newFolder; + Resume = string.IsNullOrWhiteSpace(sessionId) ? null : new AcpResumeRequest(sessionId); + _previousNotice = previousNotice; + var parts = new List(); + var remaining = MaxHandoffChars; + foreach (var message in messages.Where(m => m.Role is "user" or "assistant" && !string.IsNullOrWhiteSpace(m.Text)) + .TakeLast(MaxMessages).Reverse()) + { + var heading = message.Role + ": "; + var available = remaining - heading.Length - 2; + if (available <= 0) break; + const string omitted = "[earlier text omitted] "; + var text = message.Text.Length <= available ? message.Text + : available <= omitted.Length ? Tail(message.Text, available) + : omitted + Tail(message.Text, available - omitted.Length); + parts.Add(heading + text); + remaining -= heading.Length + text.Length + 2; + } + parts.Reverse(); + RecentContext = string.Join("\n\n", parts); + } + + private static string Tail(string text, int limit) + { + var start = Math.Max(0, text.Length - limit); + if (start > 0 && start < text.Length && char.IsLowSurrogate(text[start]) && char.IsHighSurrogate(text[start - 1])) start++; + return text[start..]; + } + + public string BuildNotice(bool sessionContinued, bool carryRecentContext) + { + var note = new StringBuilder(); + if (sessionContinued && !string.IsNullOrWhiteSpace(_previousNotice)) + note.AppendLine(Tail(_previousNotice, MaxHandoffChars)).AppendLine(); + if (!sessionContinued && carryRecentContext && HasRecentContext) + { + note.AppendLine("Earlier conversation excerpt from before the folder change (reference context only; attachments are not included):") + .AppendLine(RecentContext).AppendLine("End of earlier conversation excerpt.").AppendLine(); + } + note.AppendLine($"Project folder changed from {OldFolder} to {NewFolder}.") + .AppendLine($"Use {NewFolder} for new work. Earlier messages may refer to a different project.") + .AppendLine("Re-read files before relying on earlier paths or contents. Do not continue old tasks unless the current user asks.") + .Append("Acknowledge this project-context update briefly without using tools, then wait for the next user request."); + return note.ToString(); + } +} diff --git a/tests/MandoCode.Acp.MockAgent/Program.cs b/tests/MandoCode.Acp.MockAgent/Program.cs index db689f9..188ee9d 100644 --- a/tests/MandoCode.Acp.MockAgent/Program.cs +++ b/tests/MandoCode.Acp.MockAgent/Program.cs @@ -48,8 +48,9 @@ internal sealed class MockAgent private string _mode = "default"; // config-options / sessions / load-only - private bool Config => _scenario is "config-options" or "sessions" or "load-only"; - private bool Sessions => _scenario is "sessions" or "load-only"; + private bool CanResumeSessions => _scenario is "sessions" or "sessions-cross-folder"; + private bool Config => CanResumeSessions || _scenario is "config-options" or "load-only"; + private bool Sessions => CanResumeSessions || _scenario == "load-only"; private readonly Dictionary _values = new() { ["mode"] = "default", ["model"] = "model-a", ["effort"] = "medium" }; private readonly List _closed = []; private readonly object _storeGate = new(); @@ -227,7 +228,7 @@ private void Dispatch(JsonObject message) { ["loadSession"] = Sessions, ["promptCapabilities"] = new JsonObject { ["image"] = false, ["audio"] = false, ["embeddedContext"] = true }, - ["sessionCapabilities"] = _scenario == "sessions" + ["sessionCapabilities"] = CanResumeSessions ? new JsonObject { ["list"] = new JsonObject(), ["resume"] = new JsonObject(), ["close"] = new JsonObject() } : null, }, @@ -306,7 +307,7 @@ private void Dispatch(JsonObject message) break; } - case "session/list" when _scenario == "sessions": + case "session/list" when CanResumeSessions: { var cwd = message["params"]?["cwd"]?.GetValue(); var sessions = new JsonArray(); @@ -316,18 +317,20 @@ private void Dispatch(JsonObject message) break; } - case "session/resume" when _scenario == "sessions": + case "session/resume" when CanResumeSessions: case "session/load" when Sessions: { var wanted = message["params"]?["sessionId"]?.GetValue() ?? ""; var cwd = message["params"]?["cwd"]?.GetValue() ?? ""; var store = LoadStore(); - if (!store.TryGetValue(wanted, out var known) || known.Cwd != cwd) + if (!store.TryGetValue(wanted, out var known) || (known.Cwd != cwd && _scenario != "sessions-cross-folder")) { Error(id, -32002, "Session not found: " + wanted); break; } + known.Cwd = cwd; + SaveStore(store); _sessionId = wanted; if (method == "session/load") { @@ -343,7 +346,7 @@ private void Dispatch(JsonObject message) break; } - case "session/close" when _scenario == "sessions": + case "session/close" when CanResumeSessions: _closed.Add(message["params"]?["sessionId"]?.GetValue() ?? ""); Reply(id, new JsonObject()); break; diff --git a/tests/MandoCode.Tests/Acp/AcpContextUpdateSinkTests.cs b/tests/MandoCode.Tests/Acp/AcpContextUpdateSinkTests.cs new file mode 100644 index 0000000..4aca92b --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpContextUpdateSinkTests.cs @@ -0,0 +1,28 @@ +using MandoCode.Acp.Protocol; +using MandoCode.Services.Acp; +using Spectre.Console; +using Xunit; +namespace MandoCode.Tests.Acp; +public class AcpContextUpdateSinkTests +{ + [Fact] + public async Task InternalAcknowledgmentStaysQuietButFailuresAndToolsRemainVisible() + { + var inner = new RecordingSink(); + var sink = new AcpContextUpdateSink(inner); + var runtime = new FakeRuntime(); + runtime.Send(FakeRuntime.Text("Noted: new folder")); + runtime.Succeed(StopReasons.EndTurn); + var result = await new AcpTurnDriver(sink).RunAsync(runtime, [new TextContent("update")], CancellationToken.None); + Assert.Null(result.Error); + Assert.Empty(inner.Replies); + Assert.DoesNotContain(inner.Of("preview"), preview => preview.Contains("Noted")); + sink.Error("Usage limit"); + sink.Notice("Cancelled"); + var output = new Text("Actual tool output"); + sink.Block(output); + Assert.Contains("Usage limit", inner.Of("error")); + Assert.Contains("Cancelled", inner.Of("notice")); + Assert.Same(output, Assert.Single(inner.Blocks)); + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpFolderChangeContextTests.cs b/tests/MandoCode.Tests/Acp/AcpFolderChangeContextTests.cs new file mode 100644 index 0000000..4f32609 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpFolderChangeContextTests.cs @@ -0,0 +1,45 @@ +using MandoCode.Models; +using MandoCode.Services.Acp; +using Xunit; + +namespace MandoCode.Tests.Acp; + +public class AcpFolderChangeContextTests +{ + [Fact] + public void NoticeNamesBothFoldersAndDoesNotCarryHistoryWithoutConsent() + { + var context = new AcpFolderChangeContext("old-project", "new-project", "opaque session", [new ChatMsg { Role = "user", Text = "private topic" }]); + var note = context.BuildNotice(false, false); + Assert.Equal("opaque session", context.Resume!.SessionId); + Assert.Contains("old-project", note); + Assert.Contains("Use new-project", note); + Assert.Contains("Re-read files", note); + Assert.Contains("without using tools", note); + Assert.DoesNotContain("private topic", note); + Assert.Contains("private topic", context.BuildNotice(false, true)); + } + + [Fact] + public void HandoffIsBoundedRecentTextAndSnapshotsTheMessages() + { + var messages = Enumerable.Range(0, 10).Select(i => new ChatMsg { Role = "user", Text = "turn " + i }).ToList(); + var context = new AcpFolderChangeContext("old", "new", null, messages); + messages[^1].Text = "changed"; + Assert.DoesNotContain("turn 0", context.RecentContext); + Assert.Contains("turn 9", context.RecentContext); + Assert.DoesNotContain("changed", context.RecentContext); + var large = new AcpFolderChangeContext("old", "new", null, + [new ChatMsg { Role = "assistant", Text = new string('x', 100000) + "latest end" }]); + Assert.True(large.RecentContext.Length <= AcpFolderChangeContext.MaxHandoffChars); + Assert.EndsWith("latest end", large.RecentContext); + } + + [Fact] + public void ContinuingAcrossSeveralFoldersRetainsUnsentContextWithinABound() + { + var context = new AcpFolderChangeContext("B", "C", "id", [], "unsent earlier handoff"); + Assert.Contains("unsent earlier handoff", context.BuildNotice(true, false)); + Assert.DoesNotContain("unsent earlier handoff", context.BuildNotice(false, false)); + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs b/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs index 4029ec4..f703328 100644 --- a/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs @@ -352,33 +352,143 @@ public async Task BlockedCommands_AnswerWithTheSharedExplanation(string input, s // ─────────── folder changes ─────────── [Fact] - public async Task ChangeDirectory_Confirmed_ChangesTheFolder_RestartsTheAgent_AndDropsTheAcpConversation() + public async Task ChangeDirectory_ImmediatelyRestartsOnlyThisAgent_AndRetainsTheTranscript() { await using var h = Harness.Create(); var target = Path.Combine(h.Folder, "next"); Directory.CreateDirectory(target); h.AcpMessages.Add(new ChatMsg { Role = "user", Text = "old acp" }); + h.Runtime.Support = new AcpSessionSupport(false, true, true, false); + var other = h.Pane.Workspace.Add(acpAgent: "other"); + var otherRuntime = new FakeRuntime(); + other.Services.GetRequiredService().Runtime = otherRuntime; var run = h.Run("/change-directory " + target); - await h.AnswerMenuAsync("Change folder and restart the agent"); await run; + Assert.False(h.Menu.IsActive); + Assert.DoesNotContain("Switch this agent", h.Output); Assert.True(AcpPaths.SameFolder(target, h.Root.ProjectRoot)); - Assert.Empty(h.AcpMessages); + Assert.Equal("old acp", Assert.Single(h.AcpMessages).Text); + Assert.False(otherRuntime.Disposed); + Assert.True(AcpPaths.SameFolder(h.Folder, other.Services.GetRequiredService().ProjectRoot)); + Assert.Equal(h.Runtime.SessionId, Field(h.App, "_acpFolderChange").Resume!.SessionId); Assert.True(h.Runtime.Disposed); // the old agent process ended; a new one starts in the new folder - Assert.Contains("restarts there with a new conversation", h.Output); + Assert.Contains("No ACP agent named", h.Output); + } + + private static Task CompleteFolderChange(Harness h, AcpFolderChangeContext change) + { + SetField(h.App, "_acpFolderChange", change); + return (Task)typeof(App).GetMethod("CompleteAcpFolderChangeAsync", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(h.App, [h.Runtime, change])!; + } + + [Theory] + [InlineData(AcpSessionOrigin.Resumed)] + [InlineData(AcpSessionOrigin.Loaded)] + public async Task ContinuedFolderSessionKeepsExistingHistoryWithoutReplayDuplicates(AcpSessionOrigin origin) + { + await using var h = Harness.Create(); + h.AcpMessages.Add(new ChatMsg { Role = "user", Text = "existing history" }); + h.Runtime.SessionOrigin = origin; + await CompleteFolderChange(h, new AcpFolderChangeContext("old-folder", h.Folder, "session-1", h.AcpMessages)); + Assert.Single(h.AcpMessages); + Assert.False(h.Menu.IsActive); + Assert.Contains($"Changed directory to {h.Folder}", h.Output); + Assert.Contains("Switching to the new project — this conversation is kept.", h.Output); + Assert.DoesNotContain("Before your next request", h.Output); + Assert.Contains("old-folder", Field(h.App, "_pendingAcpProjectNotice")); + Assert.Null(Field(h.App, "_acpFolderChange")); + } + + [Theory] + [InlineData("Carry recent context", true)] + [InlineData("Start fresh", false)] + [InlineData(null, false)] + public async Task FreshFolderSessionOffersOptionalContextWithoutClearingVisibleHistory(string? answer, bool carries) + { + await using var h = Harness.Create(); + h.AcpMessages.Add(new ChatMsg { Role = "user", Text = "prior project topic" }); + var run = CompleteFolderChange(h, new AcpFolderChangeContext("old-folder", h.Folder, null, h.AcpMessages)); + await h.AnswerMenuAsync(answer!); + await run; + var note = Field(h.App, "_pendingAcpProjectNotice"); + Assert.Equal(carries, note.Contains("prior project topic")); + Assert.Contains("Re-read files", note); + Assert.Single(h.AcpMessages); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task FolderRestartIsCompactButInitialConnectionKeepsItsCard(bool compact) + { + await using var h = Harness.Create(); + var type = typeof(App).GetNestedType("StartupSink", BindingFlags.NonPublic)!; + var sink = (IAcpStartupSink)Activator.CreateInstance(type, h.App, "claude", compact)!; + sink.Connecting("claude"); + sink.Connected("Claude", ["important warning"]); + Assert.Equal(!compact, h.Output.Contains("Connected")); + Assert.Equal(!compact, h.Output.Contains("Connecting to")); + Assert.Contains("important warning", h.Output); + } + + [Fact] + public async Task ProjectNoticeIsSentOnceBeforeOriginalCommandAndImagePrompt() + { + await using var h = Harness.Create(); + h.Runtime.SessionOrigin = AcpSessionOrigin.Resumed; + h.Runtime.PromptCapabilities.Image = true; + await CompleteFolderChange(h, new AcpFolderChangeContext("old-folder", h.Folder, "id", [])); + h.Runtime.Succeed(StopReasons.EndTurn); + var png = new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 1 }; + var reference = h.Pane.Services.GetRequiredService().Add(png); + var command = "/review KeepCase @" + reference; + await (Task)typeof(App).GetMethod("ProcessAcpRequestAsync", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(h.App, [command])!; + Assert.Equal(2, h.Runtime.Prompts.Count); + Assert.Contains("Project folder changed", Assert.IsType(Assert.Single(h.Runtime.Prompts[0])).Text); + Assert.Equal(command, Assert.IsType(h.Runtime.Prompts[1][0]).Text); + Assert.Equal(png, Convert.FromBase64String(Assert.Single(h.Runtime.Prompts[1].OfType()).Data)); + Assert.Null(Field(h.App, "_pendingAcpProjectNotice")); + await (Task)typeof(App).GetMethod("ProcessAcpRequestAsync", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(h.App, ["next request"])!; + Assert.Equal(3, h.Runtime.Prompts.Count); + } + + [Fact] + public async Task CancelledProjectUpdateKeepsNoticeAndDoesNotSendOriginalRequest() + { + await using var h = Harness.Create(); + SetField(h.App, "_pendingAcpProjectNotice", "project update"); + h.Runtime.Succeed(StopReasons.Cancelled); + await (Task)typeof(App).GetMethod("ProcessAcpRequestAsync", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(h.App, ["do work"])!; + Assert.Single(h.Runtime.Prompts); + Assert.Equal("project update", Field(h.App, "_pendingAcpProjectNotice")); + Assert.Contains("Your request was not sent", h.Output); + } + + [Fact] + public async Task ClearDiscardsAnyPendingFolderNoticeOrHandoff() + { + await using var h = Harness.Create(); + SetField(h.App, "_pendingAcpProjectNotice", "old project context"); + SetField(h.App, "_acpFolderChange", new AcpFolderChangeContext("old", h.Folder, "id", [])); + await h.Run("/clear"); + Assert.Null(Field(h.App, "_pendingAcpProjectNotice")); + Assert.Null(Field(h.App, "_acpFolderChange")); } [Fact] - public async Task ChangeDirectory_Declined_KeepsTheFolderAndTheAgent() + public async Task ChangeDirectory_InvalidTarget_KeepsTheFolderAndTheAgent() { await using var h = Harness.Create(); var target = Path.Combine(h.Folder, "next"); - Directory.CreateDirectory(target); h.AcpMessages.Add(new ChatMsg { Role = "user", Text = "old acp" }); var run = h.Run("/change-directory " + target); - await h.AnswerMenuAsync("Cancel"); await run; Assert.True(AcpPaths.SameFolder(h.Folder, h.Root.ProjectRoot)); @@ -407,7 +517,6 @@ public async Task ShellCd_InAnAcpPane_GoesThroughTheSameFolderFlow(string line) Directory.CreateDirectory(target); var run = h.Shell(line); - await h.AnswerMenuAsync("Change folder and restart the agent"); await run; Assert.True(AcpPaths.SameFolder(target, h.Root.ProjectRoot)); diff --git a/tests/MandoCode.Tests/Acp/AcpSessionTests.cs b/tests/MandoCode.Tests/Acp/AcpSessionTests.cs index 5c5acd9..757d8a4 100644 --- a/tests/MandoCode.Tests/Acp/AcpSessionTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpSessionTests.cs @@ -205,6 +205,25 @@ public async Task ASessionTheAgentDoesNotKnow_FallsBackToANewOne_WithAWarning() Assert.Contains(runtime.StartupWarnings, w => w.Contains("previous session")); } + [Theory] + [InlineData("sessions-cross-folder", true)] + [InlineData("sessions", false)] + public async Task FolderRestartContinuesOnlyWhenTheAdapterAcceptsTheNewFolder(string scenario, bool accepts) + { + var first = await ConnectedAsync(Runtime(scenario)); + var id = first.SessionId!; + await ReplyAsync(first, "earlier conversation").Within(20); + await first.DisposeAsync(); + var target = Path.Combine(_work, "new-project"); + Directory.CreateDirectory(target); + var restarted = await ConnectedAsync(Runtime(scenario, new AcpResumeRequest(id), folder: target)); + Assert.Equal(accepts ? AcpSessionOrigin.Resumed : AcpSessionOrigin.New, restarted.SessionOrigin); + Assert.Equal(accepts, restarted.SessionId == id); + var listed = await restarted.ListSessionsAsync(CancellationToken.None).Within(20); + Assert.Contains(listed, session => session.SessionId == restarted.SessionId && AcpPaths.SameFolder(session.Cwd, target)); + Assert.Equal("echo: new work", await ReplyAsync(restarted, "new work").Within(20)); + } + [Fact] public async Task ASessionOfAnotherFolder_IsNotResumed() { From 1bcac179779c3b00fa1e2f16530054a7739c8e06 Mon Sep 17 00:00:00 2001 From: DevMando Date: Tue, 1 Dec 2026 22:10:38 -0800 Subject: [PATCH 2/2] Chore: consolidate ACP guidance in the README --- README.md | 24 +- docs/acp-codex.md | 85 ---- docs/acp.md | 437 ------------------ .../Services/Acp/AcpAgentCommands.cs | 2 +- src/MandoCode/Services/Acp/AcpAgentRuntime.cs | 4 +- .../Services/Acp/AcpConnectionProbe.cs | 2 +- 6 files changed, 24 insertions(+), 530 deletions(-) delete mode 100644 docs/acp-codex.md delete mode 100644 docs/acp.md diff --git a/README.md b/README.md index 30d76b6..4b6cee5 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ With **`/skills` (Alt+K)**, install skills from Git, ZIP files, or local folders | **Workspace** | Independent agents | Up to four agents per workspace, with separate models, conversations, settings, and approvals | | **Workspace** | Named workspaces | Organize projects and switch workspaces while background agents keep working | | **AI** | Agent collaboration | Tag agents with `@` to ask questions, request reviews, and hand off independent tasks | -| **Agents** | External ACP agents | Run an Agent Client Protocol agent (for example Claude Code through an ACP adapter) in its own pane, with tool calls, diffs and permission prompts in the transcript. Opt-in; see [docs/acp.md](docs/acp.md) | +| **Agents** | External ACP agents | Run an Agent Client Protocol agent (for example Claude Code through an ACP adapter) in its own pane, with tool calls, diffs and permission prompts in the transcript. Opt-in; see [ACP setup](#external-agents-acp) | | **Memory** | Context snapshots | Save a conversation summary and import it into another agent | | **Memory** | Agent history | Search, preview, and restore closed agents with their conversation context | | **Tools** | File Explorer and Git review | Browse files, attach references, change directories, and inspect project diffs | @@ -254,7 +254,7 @@ Type `/` to see the autocomplete dropdown, or `!` to run a shell command. | `/agent-new` | Open an independent agent pane (Alt+N) | | `/agent-focus` | Switch agents; optional left/right (Alt+Left/Right) | | `/agent-close` | Close the current idle agent | -| `/agent-acp ` | Switch this pane to an external ACP agent (such as Claude Code through an adapter); `--new-panel` opens it in a new pane. Also `stop`, `list`, `status`, `restart`, `add`, `test`, `remove`, `enable`, `disable` ([details](docs/acp.md)) | +| `/agent-acp ` | Switch this pane to an external ACP agent (such as Claude Code through an adapter); `--new-panel` opens it in a new pane. Also `stop`, `list`, `status`, `restart`, `add`, `test`, `remove`, `enable`, `disable` ([details](#external-agents-acp)) | | `/agent-rename ` | Rename this agent | | `/agent-settings` | Edit this agent's model, behavior, and integrations (Alt+S) | | `/agent-file-explorer` | Browse this agent's files and folders (Alt+E) | @@ -506,10 +506,26 @@ An optional `acpAgents` section in `~/.mandocode/config.json` (read only from th The agent runs without a shell, from a real executable (`.exe`/ELF, never `.cmd`, `npx` or a shell), and MandoCode asks you to confirm the full command before the first start and again whenever it changes. Install the adapter yourself, at a pinned version; MandoCode never downloads anything. The agent signs in with its own tooling, and -`ANTHROPIC_API_KEY` is not passed to it unless you opt in. See [docs/acp.md](docs/acp.md) for setup, trust, permissions, -file access, the debug trace and what is not supported yet. MandoCode does not sandbox the agent: permission +`ANTHROPIC_API_KEY` is not passed to it unless you opt in. MandoCode does not sandbox the agent: permission questions are relayed, and the agent applies the answers itself. +Use `/agent-acp add codex` for Codex adapter installation and registration guidance. After registering an agent: + +```text +/agent-acp test codex +/agent-acp codex --new-panel +``` + +Replace `codex` with your configured agent name. Use `/agent-acp-mode` to choose its advertised permission mode, +`/model` to select an available model, and `/agent-acp stop` to return to the native conversation. Agent-provided +slash commands appear with the connected agent's name. Alt+V attaches an image when the agent supports image prompts. + +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. + ### Config File Located at `~/.mandocode/config.json` diff --git a/docs/acp-codex.md b/docs/acp-codex.md deleted file mode 100644 index 997fe3d..0000000 --- a/docs/acp-codex.md +++ /dev/null @@ -1,85 +0,0 @@ -# Codex in an ACP pane - -MandoCode can use the maintained [Codex ACP adapter](https://github.com/agentclientprotocol/codex-acp) -through the existing ACP client. Codex owns model execution, its tools, and authentication. -MandoCode displays the conversation and relays permissions through the same pane integration used for other ACP agents. - -## Setup on Windows - -Install Node.js and sign in to Codex separately with `codex login`. MandoCode does not perform -the adapter's authentication flow or collect credentials. An existing compatible Codex login -can be reused; if authentication is required, finish it with Codex before reconnecting. - -Install a pinned adapter into a folder you control. For example, in PowerShell: - -```powershell -$adapterFolder = Join-Path $env:USERPROFILE '.mandocode\acp\codex' -npm install --prefix "$adapterFolder" --save-exact @agentclientprotocol/codex-acp@2.6.0 -Join-Path $adapterFolder 'node_modules\@agentclientprotocol\codex-acp\dist\index.js' -``` - -Copy the absolute path printed by the last command. In MandoCode, register it with: - -```text -/agent-acp add codex node "C:\Users\YOUR_NAME\.mandocode\acp\codex\node_modules\@agentclientprotocol\codex-acp\dist\index.js" -/agent-acp test codex -/agent-acp codex --new-panel -``` - -Replace `YOUR_NAME` with your Windows user folder. If Node is not on PATH, use the absolute -path to `node.exe`. The adapter's package includes a compatible Codex dependency; a separately -installed Codex executable can be selected using `CODEX_PATH` in the entry's environment. -Keep the installation's lock file to preserve the resolved dependency versions. - -`/agent-acp add codex` prints this setup guidance. It does not install an adapter or save a -configuration automatically. The normal launch confirmation still applies. MandoCode runs -Node directly, without `npx`, an npm shim, or a shell at launch time. - -Other operating systems can use the same npm package and register its absolute JavaScript -entry path with `node`. The live validation below was performed on Windows only. - -## Commands and boundaries - -- `/agent-acp-mode` opens the agent's mode picker, with its descriptions and current selection. For example, Codex can offer Read-only, Workspace access, Auto review, and Full access. These are agent-defined permission and behavior modes, not MandoCode's native approval settings. -- `/agent-acp-mode read-only` selects an advertised mode directly. Changes keep the conversation and are refused while the pane has active work. The selection applies to this session; it does not rewrite global Codex configuration. -- `/model` uses the adapter's advertised model configuration. Available models depend on the account and adapter. -- `/compact` and other agent-provided commands appear when the adapter advertises them. -- Alt+V attaches a clipboard image when the connected adapter advertises image prompt support. -- `/clear` starts another ACP conversation and preserves the native MandoCode conversation. -- `/copy` and `/copy-code` read the ACP conversation's last reply. -- `/agent-acp stop` returns to the native conversation. -- Folder changes restart only that ACP pane, retain its transcript, and try to continue its session. If cross-folder continuation is unavailable, choose whether to carry recent text context into a fresh session. A project-change note precedes the next request. - -Capability handling remains shared with other ACP agents. This setup does not add native -agent mentions, context handoff, or the proposed MandoCode MCP bridge. -The generic ACP restrictions still apply even if Codex itself advertises additional features. - -The adapter also supports API-key authentication. Existing `OPENAI_API_KEY` and `CODEX_API_KEY` -environment variables are not filtered by MandoCode. Check your Codex authentication setup -if you specifically intend to use an existing ChatGPT login instead of API billing. - -## Validation - -Validated on Windows with `@agentclientprotocol/codex-acp` 2.6.0: - -- ACP v1 initialization and session creation using existing login state, with API-key variables removed from the test process. -- MandoCode's actual `AcpClient` and process transport connected to the adapter and parsed its configuration options. -- Selected read-only mode, received a short streamed text reply, and closed the session and client successfully. -- The adapter accepted a `session/set_config_option` change for its `mode` option to `read-only`, then closed the session. The mode picker and its routing have automated coverage; its full interactive flow still needs a manual terminal check. -- Command tests cover setup guidance without saving an entry and explicit executable registration. - -This verifies the core connection and text path. Interactive permission menus, cancellation, -model changes, compaction, session restoration, and folder restarts need manual validation -with Codex before claiming those flows have been tested against this adapter. - -### Automated test results - -- Final full-suite validation: 1,919 passed, one skipped, and zero failed on each of net8.0 and net10.0. The skip is the existing symlink-creation test on this Windows machine; the junction guard has separate coverage. -- All 95 targeted activity, permission, transcript, and export checks pass on both frameworks, including expansion across live updates and tool-call identity across turns and panes. -- All 64 agent-command tests pass on both net8.0 and net10.0, including the two new Codex tests. -- The first full run had 1,893 passes, one skip, and one failure on each target: a Windows - file-access error in the concurrent config-save test on net8.0, and a command-notification - timeout on net10.0. These are not Codex-specific tests; their cause remains unresolved. -- The notification test passed in isolation. Unchanged main passed its config-save tests and - its complete net10.0 suite (1,892 passes, one skip). The final branch run above is clean; - the earlier failures are retained here as validation history rather than attributed to a known fix. diff --git a/docs/acp.md b/docs/acp.md deleted file mode 100644 index 7e5d252..0000000 --- a/docs/acp.md +++ /dev/null @@ -1,437 +0,0 @@ -# ACP agents (Agent Client Protocol) - -MandoCode can run an external coding agent as a child process and talk to it over the -[Agent Client Protocol](https://agentclientprotocol.com) (ACP v1, JSON-RPC 2.0 over stdio, NDJSON). -Authentication is the agent's own business; MandoCode never handles agent tokens. - -The protocol layer lives in `src/MandoCode.Acp` (no UI dependencies, no third-party ACP libraries). -Schema: pinned to the release tag `v1.16.0` of `agentclientprotocol/agent-client-protocol` (checked to exist), vendored in -`tests/MandoCode.Tests/Acp/schema/schema.v1.json`. The tag is the schema release; the protocol version is still 1 -(`protocolVersion: 1` in `initialize`). - -## Quick start - -For Codex, see [Codex adapter setup and validation](acp-codex.md), or run `/agent-acp add codex` for setup guidance. - -1. Install an ACP adapter yourself, at a pinned version, for example for Claude Code the adapter validated below. No `npx`. -2. Add it (your own paths): `/agent-acp add claude node "C:\path\to\adapter\dist\index.js"`, or edit `acpAgents` in - `~/.mandocode/config.json`. -3. Check it: `/agent-acp test claude` (or `mandocode --acp-probe claude`). You are asked to confirm the command first. -4. Use it: `/agent-acp claude` switches the current pane to the agent (`--new-panel` opens it in a new pane instead). - Sign in to the agent with its own tooling beforehand (`claude auth login`). `/agent-acp stop` returns the pane to - MandoCode's own agent. - -Status of this first version: phases 1–2, plus switching a pane in place (originally planned for a later phase, and -without passing context: see "Deviations"). Not included: `terminal/*`, images, resuming sessions, handing a -conversation between the native agent and an ACP agent, asking an ACP agent with `@`, a settings tab for agents. -Open questions are marked **pending** below. - -**Security model in one paragraph.** MandoCode does not sandbox the agent. It decides what program runs (no shell, -real executables only, confirmed by hash, configured only in the user's own config) and what environment it gets -(no `ANTHROPIC_API_KEY` by default), and it relays the agent's permission questions; the agent applies the answers -itself. Treat an ACP agent as a program with your user's rights. - -## Launch rules - -An agent command is code that runs with your permissions, so launching is deliberately strict: - -- No shell: `ProcessStartInfo` with `UseShellExecute = false` and `ArgumentList`. - `cmd.exe`, `powershell`, `sh -c` and friends are refused. -- The command must resolve (through `PATH`, or as an absolute path) to a real executable: - `.exe` on Windows, ELF/Mach-O on Unix. `.cmd`, `.bat`, `.ps1` and `#!` scripts are refused: - *specify the path to an .exe or run the adapter as `node