diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5ac7293..48f3066 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 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 `. 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 ` 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 ` checks a connection. The protocol layer is the new `MandoCode.Acp` library (own thin implementation, no third-party ACP package). diff --git a/docs/acp.md b/docs/acp.md index c21ef1c..9392771 100644 --- a/docs/acp.md +++ b/docs/acp.md @@ -184,7 +184,7 @@ 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` @@ -192,7 +192,15 @@ touched**. While a request is running `/clear` is refused (press Escape first). `/model ` 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 diff --git a/src/MandoCode/Components/Shell/App.Acp.cs b/src/MandoCode/Components/Shell/App.Acp.cs index e4da967..4fd745a 100644 --- a/src/MandoCode/Components/Shell/App.Acp.cs +++ b/src/MandoCode/Components/Shell/App.Acp.cs @@ -173,7 +173,15 @@ public void Dispose() } } - private void OnAcpChanged() => UpdateAcpHeader(); + private void OnAcpChanged() + { + UpdateAcpHeader(); + _ = InvokeAsync(() => + { + StateMachine.RefreshCommandSuggestions(); + StateHasChanged(); + }); + } private void UpdateAcpHeader() { diff --git a/src/MandoCode/Components/Shell/App.AcpCommands.cs b/src/MandoCode/Components/Shell/App.AcpCommands.cs index 5490949..6d74ad3 100644 --- a/src/MandoCode/Components/Shell/App.AcpCommands.cs +++ b/src/MandoCode/Components/Shell/App.AcpCommands.cs @@ -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); } diff --git a/src/MandoCode/Components/Shell/App.Commands.cs b/src/MandoCode/Components/Shell/App.Commands.cs index 053e3ab..cde4838 100644 --- a/src/MandoCode/Components/Shell/App.Commands.cs +++ b/src/MandoCode/Components/Shell/App.Commands.cs @@ -21,6 +21,13 @@ private async Task 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)) { diff --git a/src/MandoCode/Program.cs b/src/MandoCode/Program.cs index 2a0fa94..f1d37e5 100644 --- a/src/MandoCode/Program.cs +++ b/src/MandoCode/Program.cs @@ -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. diff --git a/src/MandoCode/Services/Acp/AcpAgentCommandCatalog.cs b/src/MandoCode/Services/Acp/AcpAgentCommandCatalog.cs new file mode 100644 index 0000000..805bf26 --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpAgentCommandCatalog.cs @@ -0,0 +1,39 @@ +using MandoCode.Acp.Protocol; +using MandoCode.Models; + +namespace MandoCode.Services.Acp; + +/// Agent commands are session-scoped suggestions and prompts, never shell invocations. +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 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 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; + } +} diff --git a/src/MandoCode/Services/Input/CommandAutocomplete.cs b/src/MandoCode/Services/Input/CommandAutocomplete.cs index adaff50..92070b7 100644 --- a/src/MandoCode/Services/Input/CommandAutocomplete.cs +++ b/src/MandoCode/Services/Input/CommandAutocomplete.cs @@ -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); diff --git a/src/MandoCode/Services/Input/InputStateMachine.cs b/src/MandoCode/Services/Input/InputStateMachine.cs index 8219af0..997b3cb 100644 --- a/src/MandoCode/Services/Input/InputStateMachine.cs +++ b/src/MandoCode/Services/Input/InputStateMachine.cs @@ -13,6 +13,7 @@ public class InputStateMachine { private readonly Dictionary _commands; private readonly Func? _commandAvailable; + private readonly Func>? _commandSource; private readonly FileAutocompleteProvider? _fileProvider; // Input state @@ -43,9 +44,11 @@ public void UseCommandDescriptions(IReadOnlyDictionary descripti public InputStateMachine( Dictionary commands, FileAutocompleteProvider? fileProvider, - Func? commandAvailable = null) + Func? commandAvailable = null, + Func>? commandSource = null) { _commands = commands; + _commandSource = commandSource; _commandAvailable = commandAvailable; _fileProvider = fileProvider; State.CommandDescriptions = commands; @@ -172,7 +175,19 @@ public static string GetCommandName(string input) return input.TrimStart().Substring(1).Trim().ToLowerInvariant(); } - public IEnumerable GetAllCommands() => _commands.Keys.Where(cmd => _commandAvailable?.Invoke(cmd) != false); + public IEnumerable GetAllCommands() + { + var commands = _commandSource?.Invoke(); + if (commands is not null) State.CommandDescriptions = commands; + return (commands?.Keys ?? _commands.Keys).Where(cmd => _commandAvailable?.Invoke(cmd) != false); + } + + /// Refresh a visible command popup after its session catalog changes. + public void RefreshCommandSuggestions() + { + UpdateAutocompleteAfterEdit(); + SyncState(); + } // ─── VDOM Text-Level API ────────────────────────────────── diff --git a/tests/MandoCode.Tests/Acp/AcpAgentCommandCatalogTests.cs b/tests/MandoCode.Tests/Acp/AcpAgentCommandCatalogTests.cs new file mode 100644 index 0000000..ceca9b9 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpAgentCommandCatalogTests.cs @@ -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(); + 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().Runtime = runtime; + var input = pane.Services.GetRequiredService(); + 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().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")); + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs b/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs index e514f79..8f98b97 100644 --- a/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs @@ -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(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")] diff --git a/tests/MandoCode.Tests/Acp/AcpPaneTests.cs b/tests/MandoCode.Tests/Acp/AcpPaneTests.cs index f35f03d..eee8e09 100644 --- a/tests/MandoCode.Tests/Acp/AcpPaneTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpPaneTests.cs @@ -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 ModeChanges { get; } = []; diff --git a/tests/MandoCode.Tests/WorkspaceRegistryTests.cs b/tests/MandoCode.Tests/WorkspaceRegistryTests.cs index 2d59547..89db488 100644 --- a/tests/MandoCode.Tests/WorkspaceRegistryTests.cs +++ b/tests/MandoCode.Tests/WorkspaceRegistryTests.cs @@ -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 { + ["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 Flatten(VNode node) => new[] { node }.Concat(node.Children.SelectMany(Flatten)); private static string Paint(IServiceProvider services, VNode node) {