Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ All notable changes to MandoCode will be documented in this file.

### Added

- 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.

- `/agent-acp-mode` opens a picker for the connected agent's permission and behavior modes, including the current selection and agent-provided descriptions. Select a mode directly with `/agent-acp-mode <name>`. Changes preserve the current conversation, apply only to the ACP session, and are refused during active work. Agents without advertised modes receive an explanation.
- Codex ACP setup guidance through `/agent-acp add codex`, using the pinned `@agentclientprotocol/codex-acp` 2.6.0 adapter and the existing ACP pane implementation. Document installation, external authentication, command boundaries, and the verified connection and streamed reply on Windows. Setup guidance does not install software or change configuration automatically.
- External agents over the Agent Client Protocol (ACP v1, stdio), phases 1–2 of the ACP client. `/agent-acp <name>` switches the current pane to an agent (for example Claude Code through an ACP adapter; `--new-panel` opens a new pane, `stop` returns to the native agent, and the native session stays alive underneath without sharing context); `/agent-acp list|status|restart|add|test|remove|enable|disable` manage the `acpAgents` entries of `~/.mandocode/config.json`, and `mandocode --acp-probe <name>` checks a connection. The protocol layer is the new `MandoCode.Acp` library (own thin implementation, no third-party ACP package).
Expand Down
12 changes: 10 additions & 2 deletions docs/acp.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,23 @@ A new ACP conversation in the same pane, agent process and folder: if the agent
session is closed, then `session/new` runs in the same process. The pane's ACP messages and their transcript are
cleared, the agent's start mode applies again, and the permissions the agent kept for the old session are gone with
it. The message says it is the ACP conversation that was cleared; **the native conversation and its history are not
touched**. While a request is running `/clear` is refused (press Escape first). The agent's own commands are not forwarded.
touched**. While a request is running `/clear` is refused (press Escape first). MandoCode's `/clear` takes precedence over an agent command with the same name.

### `/model` and `/compact`

- `/model` reads the agent's `configOptions` (category `model`) from `session/new` and lets you pick a value, or
`/model <value or name>` sets it directly (`session/set_config_option`). An agent that offers no model option gets a
plain message. Nothing is adapter specific.
- `/compact` sends `/compact` to the agent as a prompt when it announced a `compact` command
(`available_commands_update`), otherwise it says the agent does not support it. No other agent command is forwarded.
(`available_commands_update`), otherwise it says the agent does not support it.

### Agent-provided commands

Other advertised agent commands appear in `/` suggestions with the connected agent’s display name (for example `[Codex]`, falling back to `[acp-agent]` if no name is available) and are sent as ordinary prompts, including their arguments. Suggestions follow the current session and update when the agent changes its command list. MandoCode commands take precedence on name collisions (except `/compact`, which belongs to the ACP agent in an ACP pane); blocked native commands remain blocked. Unadvertised commands still receive the unknown-command message. The agent decides what each forwarded command does.

For example, if an agent advertises `review`, `/review` appears with its description and an agent-name label such as `[Codex]`.
Selecting it and entering `/review focus on error handling` sends that text to the connected agent.
The available names depend on the agent.

### Changing the folder

Expand Down
10 changes: 9 additions & 1 deletion src/MandoCode/Components/Shell/App.Acp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,15 @@ public void Dispose()
}
}

private void OnAcpChanged() => UpdateAcpHeader();
private void OnAcpChanged()
{
UpdateAcpHeader();
_ = InvokeAsync(() =>
{
StateMachine.RefreshCommandSuggestions();
StateHasChanged();
});
}

private void UpdateAcpHeader()
{
Expand Down
2 changes: 1 addition & 1 deletion src/MandoCode/Components/Shell/App.AcpCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private async Task RunAcpCompactAsync()
return;
}

// The agent's own command, sent as an ordinary prompt; no other agent command is forwarded.
// The agent's own command, sent as an ordinary prompt.
await ProcessAcpRequestAsync("/" + AcpPaneCommands.CompactCommand);
}

Expand Down
7 changes: 7 additions & 0 deletions src/MandoCode/Components/Shell/App.Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ private async Task<CliCommandResult> ExecuteSlashCommandAsync(string input)
return CliCommandResult.Continue;
}

if (IsAcpPane && MandoCode.Services.Acp.AcpAgentCommandCatalog.CanForward(_acp, input))
{
if (HasActiveWork) TuiConsole.WriteLine(BusyMessage);
else await ProcessAcpRequestAsync(input);
return CliCommandResult.Continue;
}

// What an ACP agent pane does not offer is decided in one place (AcpPaneRestrictions).
if (IsAcpPane && MandoCode.Services.Acp.AcpPaneRestrictions.IsCommandBlocked(command))
{
Expand Down
5 changes: 4 additions & 1 deletion src/MandoCode/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,10 @@ internal static void RegisterAgentServices(IServiceCollection services, MandoCod
return new InputStateMachine(commands, fileProvider,
command => SlashCommands.IsAvailable(command, config)
&& !(acp.IsAcpPane && (MandoCode.Services.Acp.AcpPaneRestrictions.IsCommandBlocked(command)
|| !MandoCode.Services.Acp.AcpPaneRestrictions.IsListed(command, acp.Runtime))));
|| !MandoCode.Services.Acp.AcpPaneRestrictions.IsListed(command, acp.Runtime))),
commandSource: () => acp.IsAcpPane
? Services.Acp.AcpAgentCommandCatalog.Describe(acp.Runtime)
: SlashCommands.All);
});

// Retain rich markdown/tool renderables inside the widget conversation.
Expand Down
39 changes: 39 additions & 0 deletions src/MandoCode/Services/Acp/AcpAgentCommandCatalog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using MandoCode.Acp.Protocol;
using MandoCode.Models;

namespace MandoCode.Services.Acp;

/// <summary>Agent commands are session-scoped suggestions and prompts, never shell invocations.</summary>
public static class AcpAgentCommandCatalog
{
private static bool ValidName(string name) => name.Length > 0 &&
name.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or ':' or '.');

private static bool Reserved(string name) => SlashCommands.All.Keys.Any(key =>
string.Equals(key.TrimStart('/').Split(' ', 2)[0], name, StringComparison.OrdinalIgnoreCase)) ||
AcpPaneRestrictions.IsCommandBlocked(name);

public static IReadOnlyList<AvailableCommand> Forwardable(IAcpAgentRuntime? runtime) =>
runtime is not { Status: AcpRuntimeStatus.Ready } ? [] : runtime.AvailableCommands
.Where(c => ValidName(c.Name) && (!Reserved(c.Name) || c.Name.Equals("compact", StringComparison.OrdinalIgnoreCase)))
.DistinctBy(c => c.Name, StringComparer.OrdinalIgnoreCase).ToArray();

public static bool CanForward(IAcpAgentRuntime? runtime, string input)
{
var name = input.TrimStart().TrimStart('/').Split(' ', 2)[0];
return Forwardable(runtime).Any(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
}

public static IReadOnlyDictionary<string, string> Describe(IAcpAgentRuntime? runtime)
{
var descriptions = AcpPaneRestrictions.DescribeCommands(SlashCommands.All).ToDictionary(kv => kv.Key, kv => kv.Value);
var label = string.IsNullOrWhiteSpace(runtime?.AgentDisplayName) ? "acp-agent" : runtime.AgentDisplayName.Trim();
foreach (var command in Forwardable(runtime))
{
var key = command.Name.Equals("compact", StringComparison.OrdinalIgnoreCase) ? "/compact" : "/" + command.Name;
var hint = string.IsNullOrWhiteSpace(command.Input?.Hint) ? "" : $" ({command.Input.Hint})";
descriptions[key] = $"[{label}] {command.Description}{hint}";
}
return descriptions;
}
}
3 changes: 2 additions & 1 deletion src/MandoCode/Services/Input/CommandAutocomplete.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,8 @@ private static void DisplayAutocomplete(int cursorLeft, ref int cursorTop, int c
for (int i = start; i < start + visible; i++)
{
var cmd = commands[i];
var rawDescription = Commands.ContainsKey(cmd) ? Commands[cmd] : "";
var descriptions = _stateMachine?.State.CommandDescriptions ?? Commands;
var rawDescription = descriptions.TryGetValue(cmd, out var description) ? description : "";

var cmdField = FitVisible(cmd, cmdCol);
var descField = FitVisible(rawDescription, descCol);
Expand Down
19 changes: 17 additions & 2 deletions src/MandoCode/Services/Input/InputStateMachine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public class InputStateMachine
{
private readonly Dictionary<string, string> _commands;
private readonly Func<string, bool>? _commandAvailable;
private readonly Func<IReadOnlyDictionary<string, string>>? _commandSource;
private readonly FileAutocompleteProvider? _fileProvider;

// Input state
Expand Down Expand Up @@ -43,9 +44,11 @@ public void UseCommandDescriptions(IReadOnlyDictionary<string, string> descripti
public InputStateMachine(
Dictionary<string, string> commands,
FileAutocompleteProvider? fileProvider,
Func<string, bool>? commandAvailable = null)
Func<string, bool>? commandAvailable = null,
Func<IReadOnlyDictionary<string, string>>? commandSource = null)
{
_commands = commands;
_commandSource = commandSource;
_commandAvailable = commandAvailable;
_fileProvider = fileProvider;
State.CommandDescriptions = commands;
Expand Down Expand Up @@ -172,7 +175,19 @@ public static string GetCommandName(string input)
return input.TrimStart().Substring(1).Trim().ToLowerInvariant();
}

public IEnumerable<string> GetAllCommands() => _commands.Keys.Where(cmd => _commandAvailable?.Invoke(cmd) != false);
public IEnumerable<string> GetAllCommands()
{
var commands = _commandSource?.Invoke();
if (commands is not null) State.CommandDescriptions = commands;
return (commands?.Keys ?? _commands.Keys).Where(cmd => _commandAvailable?.Invoke(cmd) != false);
}

/// <summary>Refresh a visible command popup after its session catalog changes.</summary>
public void RefreshCommandSuggestions()
{
UpdateAutocompleteAfterEdit();
SyncState();
}

// ─── VDOM Text-Level API ──────────────────────────────────

Expand Down
65 changes: 65 additions & 0 deletions tests/MandoCode.Tests/Acp/AcpAgentCommandCatalogTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using MandoCode.Acp.Protocol;
using MandoCode.Models;
using MandoCode.Services;
using MandoCode.Services.Acp;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace MandoCode.Tests.Acp;

public class AcpAgentCommandCatalogTests
{
[Fact]
public async Task SuggestionsFollowAgentUpdatesAndLeavingAcpWithoutLeakingAcrossPanes()
{
await using var services = AcpTestHost.Services();
var workspace = services.GetRequiredService<AgentWorkspace>();
var pane = workspace.Add(acpAgent: "test");
var other = workspace.Add();
AcpPaneMode.Enter(pane, "test");
var runtime = new FakeRuntime { AgentDisplayName = "Codex", AvailableCommands = [new AvailableCommand {
Name = "review", Description = "Review changes", Input = new() { Hint = "focus" } }] };
pane.Services.GetRequiredService<AcpRuntimeHolder>().Runtime = runtime;
var input = pane.Services.GetRequiredService<InputStateMachine>();
input.UpdateText("/rev");
Assert.Contains("/review", input.State.DropdownItems);
Assert.Equal("[Codex] Review changes (focus)", input.State.CommandDescriptions["/review"]);
Assert.DoesNotContain("/review", other.Services.GetRequiredService<InputStateMachine>().GetAllCommands());

runtime.AvailableCommands = [new AvailableCommand { Name = "inspect" }];
input.RefreshCommandSuggestions();
Assert.DoesNotContain("/review", input.State.DropdownItems);
input.UpdateText("/ins");
Assert.Contains("/inspect", input.State.DropdownItems);
runtime.Status = AcpRuntimeStatus.Closed;
Assert.DoesNotContain("/inspect", input.GetAllCommands());
runtime.Status = AcpRuntimeStatus.Ready;
await AcpPaneMode.LeaveAsync(pane);
Assert.DoesNotContain("/inspect", input.GetAllCommands());
Assert.Equal(SlashCommands.All["/clear"], input.State.CommandDescriptions["/clear"]);
}

[Theory]
[InlineData("Codex", "Codex")]
[InlineData("Claude", "Claude")]
[InlineData(null, "acp-agent")]
[InlineData(" ", "acp-agent")]
public void CommandLabelUsesTheConnectedAgentsDisplayName(string? name, string expected)
{
var runtime = new FakeRuntime { AgentDisplayName = name,
AvailableCommands = [new AvailableCommand { Name = "review", Description = "Review changes" }] };
Assert.Equal($"[{expected}] Review changes", AcpAgentCommandCatalog.Describe(runtime)["/review"]);
}

[Fact]
public void CatalogRejectsInvalidNamesAndCollisionsAndDeduplicates()
{
var runtime = new FakeRuntime { AvailableCommands = new[] {
"review", "REVIEW", "clear", "plan", "model", "exit", "ollama-custom", "", "/bad", "two words", "bad\nname", "compact"
}.Select(name => new AvailableCommand { Name = name }).ToArray() };
Assert.Equal(new[] { "review", "compact" }, AcpAgentCommandCatalog.Forwardable(runtime).Select(c => c.Name));
Assert.True(AcpAgentCommandCatalog.CanForward(runtime, "/REVIEW Keep Case"));
Assert.False(AcpAgentCommandCatalog.CanForward(runtime, "/unannounced"));
Assert.False(AcpAgentCommandCatalog.CanForward(runtime, "/clear"));
}
}
29 changes: 27 additions & 2 deletions tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,17 +275,42 @@ public async Task Compact_WhenTheAgentHasNoCompactCommand_ExplainsAndSendsNothin
}

[Fact]
public async Task OtherAgentCommands_AreNotForwarded()
public async Task UnadvertisedAgentCommands_AreNotForwarded()
{
await using var h = Harness.Create();
h.Runtime.AvailableCommands = [new AvailableCommand { Name = "review", Description = "x" }];

await h.Run("/review");
await h.Run("/unadvertised");

Assert.Empty(h.Runtime.Prompts);
Assert.Contains("Unknown command", h.Output);
}

[Fact]
public async Task AdvertisedCommand_ForwardsOriginalArgumentsAsPrompt()
{
await using var h = Harness.Create();
h.Runtime.AvailableCommands = [new AvailableCommand { Name = "review", Description = "Review changes" }];
h.Runtime.Succeed(StopReasons.EndTurn);

await h.Run("/review Focus on ErrorHandling.cs --detail");

Assert.Equal("/review Focus on ErrorHandling.cs --detail",
Assert.IsType<TextContent>(Assert.Single(Assert.Single(h.Runtime.Prompts))).Text);
}

[Fact]
public async Task AgentCommand_CannotOverrideNativeClearOrBlockedPlan()
{
await using var h = Harness.Create();
h.Runtime.AvailableCommands = [new AvailableCommand { Name = "clear" }, new AvailableCommand { Name = "plan" }];
await h.Run("/clear");
await h.Run("/plan fix it");
Assert.Equal(1, h.Runtime.NewConversations);
Assert.Empty(h.Runtime.Prompts);
Assert.Contains("not available", h.Output);
}

[Theory]
[InlineData("/mcp", "/mcp is not available in an ACP agent pane")]
[InlineData("/skills", "/skills is not available in an ACP agent pane")]
Expand Down
1 change: 1 addition & 0 deletions tests/MandoCode.Tests/Acp/AcpPaneTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public sealed class FakeRuntime : IAcpAgentRuntime
public string AgentName => "fake";
public AcpRuntimeStatus Status { get; set; } = AcpRuntimeStatus.Ready;
public string? AgentTitle => "fake-adapter 1.2.3";
public string? AgentDisplayName { get; set; } = "Fake Agent";
public string? CurrentMode => "default";
public SessionModeState? Modes { get; set; }
public List<string> ModeChanges { get; } = [];
Expand Down
21 changes: 21 additions & 0 deletions tests/MandoCode.Tests/WorkspaceRegistryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,27 @@ await renderer.Dispatcher.InvokeAsync(async () =>
Assert.Contains("Alt+Shift+N", System.Net.WebUtility.HtmlDecode(root.ToHtmlString()));
});
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task AgentCommandDescriptions_RenderBracketedTextLiterally(bool selected)
{
await using var services = Services();
var rendererType = typeof(RazorConsole.Core.Focus.FocusManager).Assembly.GetType("RazorConsole.Core.Rendering.ConsoleRenderer")!;
var instance = ActivatorUtilities.CreateInstance(services, rendererType,
new ConsoleAppOptions { RenderingPipeline = RazorConsoleRenderingPipeline.WidgetLayout });
await using var renderer = (IAsyncDisposable)instance;
var mount = rendererType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Single(m => m.Name == "MountComponentAsync" && m.IsGenericMethodDefinition);
await (Task)mount.MakeGenericMethod(typeof(CommandSuggestionRow)).Invoke(instance,
new object[] { ParameterView.FromDictionary(new Dictionary<string, object?> {
["Command"] = "/review", ["Description"] = "[acp-agent] Review [bold]changes[/]", ["Selected"] = selected
}), CancellationToken.None })!;
var snapshot = rendererType.GetMethod("RefreshSnapshot", BindingFlags.NonPublic | BindingFlags.Instance)!.Invoke(instance, null)!;
var root = (VNode)snapshot.GetType().GetProperty("Root")!.GetValue(snapshot)!;
Assert.Contains("[acp-agent] Review [bold]changes[/]", Paint(services, root));
}

private static IEnumerable<VNode> Flatten(VNode node) => new[] { node }.Concat(node.Children.SelectMany(Flatten));
private static string Paint(IServiceProvider services, VNode node)
{
Expand Down