diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5b2af77..8f79438 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,16 +4,21 @@ All notable changes to MandoCode will be documented in this file. ## [Unreleased] -**Updated terminal rendering with RazorConsole 0.7.0.** The CLI now includes RazorConsole's upstream fix for focus events raised while the interface is being drawn. MandoCode keeps the deferred focus safeguard introduced in v0.16.2, which prevents the repeated prompt borders seen on some launches. +**External agents with clearer session controls and tool activity.** Run coding agents through ACP, including Codex through its tested adapter. See the connected agent, model, and mode at startup, change the session mode with `/agent-acp-mode`, and expand individual tool calls to inspect their details. The CLI also includes RazorConsole 0.7.0's upstream focus fix and retains MandoCode's startup rendering safeguard. **Highlights** +- Run Codex through the existing ACP client, with documented setup and authentication handled by Codex. +- Choose the external agent's permission and behavior mode without starting another conversation. +- Follow ACP tool calls through compact, expandable rows that update in place. - Upgrade the terminal UI framework while preserving the startup rendering fix. - Keep transcript formatting, hyperlinks, and emoji shortcuts compatible with the updated rendering dependencies. - Clear the clipboard attachment message reliably after sending a prompt. ### Added +- `/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). - Agents are started without a shell from a real executable (`.exe`/ELF; `.cmd`, `npx` and shells are refused), after confirming the full command; the confirmation is remembered per command hash and asked again when the entry changes. `acpAgents` is read only from the user config, and `ANTHROPIC_API_KEY` is not passed to the agent by default. - The ACP pane streams the reply, shows tool calls, plans and diffs, and relays the agent's permission questions as a menu (Escape cancels). It serves `fs/read_text_file` and `fs/write_text_file` inside the project folder, refusing symlinks and junctions that lead outside it, with atomic writes. Escape cancels a turn; an agent that ignores the cancel is shut down with its whole process tree. @@ -24,6 +29,9 @@ All notable changes to MandoCode will be documented in this file. ### Changed +- Show ACP tool calls as persistent, expandable activity rows with status updates in place, concise summaries, and bounded command/output details. Attach completed diffs to their call and show terminal-output limitations only inside the details. Preserve permission denial and mark unfinished calls honestly when a turn ends or is interrupted. Native tool groups retain their existing behavior. +- Present successful ACP connections in a compact card with the agent's display name, selected model, current mode and its advertised description, session origin, and commands to change mode or return to the native conversation. +- Simplify ACP pane headers to the agent's human-readable title, selected model when advertised, and an ACP indicator. Keep adapter versions in diagnostics, and leave the project folder and approval mode out of the header to match native pane presentation. - Upgrade RazorConsole.Core from 0.6.0 to 0.7.0. Retain `DeferredFocus` for startup and panels so focus requests made from `OnAfterRenderAsync` continue to wait until their render batch completes. - Adapt transcript rendering, saved-agent history, HTML exports, and emoji expansion to the updated Spectre.Console APIs. Hyperlinks now use the separate link API, and styles use the new value type. - Update Markdig to 1.5.1 and Microsoft.Extensions.FileSystemGlobbing to 10.0.14 to satisfy the new dependency requirements on both supported .NET targets. @@ -36,7 +44,9 @@ All notable changes to MandoCode will be documented in this file. - Explicitly enable hyperlink support in Markdown rendering tests so their clickable-link assertions run consistently in local terminals and CI. - Add a component check that focusing and redrawing the prompt repeatedly leaves one prompt in the render tree and keeps keyboard focus on it. -- All 1,248 tests pass on net10.0 and net8.0. Verify startup, typing, and resizing in a real pseudo-terminal on both builds, with no reported rendering errors. Confirm the CLI tool package builds successfully. +- The RazorConsole upgrade passed its then-current suite of 1,248 tests on net10.0 and net8.0, plus startup, typing, resizing, and CLI packaging checks. +- Add coverage for ACP mode selection, sparse and interleaved tool updates, permission decisions, cancellation and interruption, reused call ids, bounded output, attached diffs, and expansion that stays open during updates. The 95 targeted activity, permission, transcript, and export checks pass on both supported frameworks. +- Final full-suite validation passes on net10.0 and net8.0: 1,919 tests passed and one existing symlink-creation test skipped on each framework. Verify Codex adapter initialization, session creation, a streamed reply, and a session-scoped mode change on Windows. ## [0.16.2] - 2026-11-11 diff --git a/docs/acp-codex.md b/docs/acp-codex.md new file mode 100644 index 0000000..7c4ab37 --- /dev/null +++ b/docs/acp-codex.md @@ -0,0 +1,84 @@ +# 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` appears when the adapter advertises that command. +- `/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. + +Capability handling remains shared with other ACP agents. This setup does not add native +agent mentions, image paste, 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 index bb03bdf..c21ef1c 100644 --- a/docs/acp.md +++ b/docs/acp.md @@ -11,6 +11,8 @@ Schema: pinned to the release tag `v1.16.0` of `agentclientprotocol/agent-client ## 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`. @@ -107,6 +109,8 @@ failure it prints the exit code and the stderr tail. Exit codes: `0` ok, `1` fai ## The ACP pane +Use `/agent-acp-mode` to pick from the connected agent's advertised permission and behavior modes, or `/agent-acp-mode ` to select one directly. The menu marks the current mode and shows descriptions when supplied. It prefers the agent's mode configuration option and falls back to `session/set_mode` for agents exposing session modes only. Changing modes keeps the conversation and is refused during active work. Unsupported agents receive an explanation; MandoCode does not invent modes or enforce the external agent's permissions. + `/agent-acp ` switches the current pane to the agent; `/agent-acp --new-panel` opens it in a new pane instead (the other panes are unchanged; at most four panes exist, and a fifth is refused with a message). A pane that runs an ACP agent does not touch Ollama, models or MCP: it runs the trust question, starts the agent, runs `initialize` @@ -212,9 +216,12 @@ When the agent advertises the capabilities, MandoCode remembers the last session ### Tool calls, plans and diffs -- `tool_call` / `tool_call_update`: one line per call (` · <path>:<line>`) and one line for the - final status (`completed`, or `failed` with the first line of the agent's message). State is kept by `toolCallId`, so - an update that carries only a status works. `terminal` content is shown as "terminal output not supported". +- `tool_call` / `tool_call_update`: one expandable row per call, identified by `toolCallId` within the pane and turn. + Its current status updates in place. Click the row, or focus it and press Enter/Space, to inspect the full title, + bounded input and available text output, and completed diffs. Expansion remains open as the same call updates. + Long row summaries are clipped to fit the pane. Reused ids in later turns create separate rows. +- Terminal references cannot be resolved to terminal output yet. When present, expanded details say + "Terminal output unavailable in this client." This does not override the agent-reported completion status. - `plan`: the whole checklist is replaced on every update; the current one is printed when the turn ends, and the activity line shows `Plan done/total` meanwhile. - Diffs (`diff` content of a tool call, and files written through `fs/write_text_file`) go through the same renderer as @@ -224,10 +231,11 @@ When the agent advertises the capabilities, MandoCode remembers the last session ### Writes that are not decided yet -A call that changes things (edit, delete, move, execute) shows `Awaiting permission…` while it is `pending` and -`Writing…` / `Running…` while it is `in_progress`. The proposed diff is shown only when the call completes; a call that -fails, or that you refuse, never shows a write. A refusal is shown at once as `permission denied`. The detail after -`failed:` is the first real line of the agent's message (code fences around it are dropped); with none, only `failed`. +Calls show Pending or Running from the agent's updates. Awaiting approval is shown only when a real permission +question opens. A refusal is shown immediately as Permission denied and cannot be overwritten by a late completion. +Proposed diffs are shown in expanded details only after the call completes; failed or refused calls do not show +their proposals as completed writes. Failed calls retain the available agent output in their details. +When a turn ends, still-active rows become Cancelled, Interrupted, or Unfinished rather than claiming success. ### Permissions diff --git a/docs/images/codex-acp-connection-card.png b/docs/images/codex-acp-connection-card.png new file mode 100644 index 0000000..fc37c58 Binary files /dev/null and b/docs/images/codex-acp-connection-card.png differ diff --git a/src/MandoCode.Acp/Protocol/Messages.cs b/src/MandoCode.Acp/Protocol/Messages.cs index d85c01c..2aa0f44 100644 --- a/src/MandoCode.Acp/Protocol/Messages.cs +++ b/src/MandoCode.Acp/Protocol/Messages.cs @@ -25,6 +25,7 @@ public abstract record AcpObject public sealed record Implementation : AcpObject { [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("title")] public string? Title { get; set; } [JsonPropertyName("version")] public string Version { get; set; } = ""; } diff --git a/src/MandoCode/Components/Conversation/AcpToolActivityView.razor b/src/MandoCode/Components/Conversation/AcpToolActivityView.razor new file mode 100644 index 0000000..149bea3 --- /dev/null +++ b/src/MandoCode/Components/Conversation/AcpToolActivityView.razor @@ -0,0 +1,73 @@ +@namespace MandoCode.Components +@using MandoCode.Services.Acp +@using RazorConsole.Core.Input +@using Spectre.Console +@inject RazorConsole.Core.Rendering.ITerminalViewport Viewport + +<WorkspaceButton Parts="@Parts" OnClick="Toggle" /> +@if (_expanded) +{ + <ConversationEntry Entry="Entry" /> +} + +@code { + [Parameter, EditorRequired] public AcpToolActivity Activity { get; set; } = default!; + [Parameter, EditorRequired] public TuiEntry Entry { get; set; } = default!; + [CascadingParameter] public AgentPane? Pane { get; set; } + private bool _expanded; + + private IReadOnlyList<ButtonTextPart> Parts + { + get + { + var snapshot = Activity.Snapshot; + var action = snapshot.Kind switch + { + "execute" => "Run command", "read" => "Read file", "edit" => "Edit file", + "search" => "Search", "delete" => "Delete file", "move" => "Move file", + "fetch" => "Fetch", _ => "Tool call" + }; + var statusColor = snapshot.Status switch + { + "Completed" => Color.Green, + "Failed" => Color.Red, + "Awaiting approval" or "Permission denied" or "Cancelled" or "Interrupted" or "Unfinished" => Color.Gold1, + _ => Color.Grey + }; + var title = snapshot.Title.Replace('\r', ' ').Replace('\n', ' ').Trim(); + var summary = action + (title == "Tool call" || title == action ? "" : " · " + title); + var width = Math.Max(12, (Pane?.Width ?? Viewport.Width) - 4); + var status = width < 40 ? snapshot.Status switch + { + "Awaiting approval" => "Approval", + "Permission denied" => "Denied", + _ => snapshot.Status + } : snapshot.Status; + var budget = Math.Max(1, width - TextSelectionState.CellWidth(status) - 8); + return [new((_expanded ? "▾ " : "▸ ") + AcpTranscriptAdapter.IconFor(snapshot.Kind) + " ", Color.Grey), + new(Clip(summary, budget), Color.Grey85), new(" · " + status, statusColor)]; + } + } + + private static string Clip(string text, int width) + { + if (TextSelectionState.CellWidth(text) <= width) return text; + var result = new System.Text.StringBuilder(); + var elements = System.Globalization.StringInfo.GetTextElementEnumerator(text); + var cells = 0; + while (elements.MoveNext()) + { + var element = elements.GetTextElement(); + cells += TextSelectionState.CellWidth(element); + if (cells > width - 1) break; + result.Append(element); + } + return result.Append('…').ToString(); + } + + private void Toggle() + { + if (Pane is not null && !Pane.Active) Pane.Workspace.Focus(Pane); + _expanded = !_expanded; + } +} diff --git a/src/MandoCode/Components/Conversation/ConversationTranscript.razor b/src/MandoCode/Components/Conversation/ConversationTranscript.razor index 0ea44d6..f5c894a 100644 --- a/src/MandoCode/Components/Conversation/ConversationTranscript.razor +++ b/src/MandoCode/Components/Conversation/ConversationTranscript.razor @@ -2,7 +2,11 @@ @foreach (var entry in Entries) { <Rows @key="entry.Id"> - @if (entry.AgentActivity is { } exchange) + @if (entry.AcpTool is { } acpTool) + { + <AcpToolActivityView @key="entry.Id" Activity="acpTool" Entry="entry" /> + } + else if (entry.AgentActivity is { } exchange) { <WorkspaceButton @key="entry.Id" Parts="@ExchangeParts(exchange)" OnClick="@(() => OnAgentToggle.InvokeAsync(exchange))" /> @if (exchange.Expanded && Details.TryGetValue(exchange, out var details)) diff --git a/src/MandoCode/Components/Shell/App.Acp.cs b/src/MandoCode/Components/Shell/App.Acp.cs index 39e62d3..e4da967 100644 --- a/src/MandoCode/Components/Shell/App.Acp.cs +++ b/src/MandoCode/Components/Shell/App.Acp.cs @@ -18,6 +18,7 @@ public partial class App private readonly List<ChatMsg> _acpMessages = []; private bool _nativeInitialized; private AcpTranscriptAdapter? _acpTranscript; + private AcpToolActivityStore? _acpTools; private CancellationTokenSource? _acpStartCts; private bool IsAcpPane => Pane?.Runtime == AgentRuntime.Acp; @@ -50,13 +51,14 @@ private sealed class StartupSink(App app, string name) : IAcpStartupSink public void Connecting(string agentName) { app.Spinner.Start($"Connecting to {name}..."); - TuiConsole.WriteLine($"Connecting to {name}... (you can type already; the prompt is sent once the agent is ready)"); + Print(new Text($"Connecting to {name}… You can type while the agent starts.", new Style(Color.Grey))); } public void Connected(string description, IReadOnlyList<string> warnings) { app.Spinner.Stop(); - TuiConsole.WriteLine($"Connected to {description}."); + 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))); } @@ -132,6 +134,7 @@ private AcpClientHandler CreateAcpClientHandler() var root = ProjectRoot.ProjectRoot; var renderer = (Pane.Services).GetRequiredService<OperationDisplayRenderer>(); var transcript = _acpTranscript = new AcpTranscriptAdapter(renderer.BuildRenderable, root); + var tools = _acpTools = new AcpToolActivityStore(session.UpdateAcpTool); var files = new AcpFileSystemHandler(root, change => { @@ -152,9 +155,10 @@ private AcpClientHandler CreateAcpClientHandler() decided: (toolCallId, allowed) => { using var output = TuiConsole.Enter(session); - if (transcript.NotePermission(toolCallId, allowed) is { } note) - Print(note); - }); + transcript.NotePermission(toolCallId, allowed); + tools.Permission(toolCallId, allowed); + }, + requested: call => { tools.Apply(call); tools.Permission(call.ToolCallId, null); }); return new AcpClientHandler(prompter, files); } @@ -175,12 +179,11 @@ private void UpdateAcpHeader() { if (Pane is null || !IsAcpPane) return; - var parts = new List<string> { "ACP" }; - if (Pane.Workspace.Panes.Count == 1) parts.Add(Pane.Name); - parts.Add(_acp?.AgentTitle ?? (_acp?.Status == AcpRuntimeStatus.Starting ? "connecting…" : "(not connected)")); - if (_acp?.CurrentMode is { } mode) parts.Add("mode: " + mode); - var folder = Path.GetFileName(ProjectRoot.ProjectRoot.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - parts.Add(string.IsNullOrEmpty(folder) ? ProjectRoot.ProjectRoot : folder); + var parts = new List<string>(); + parts.Add(_acp?.AgentDisplayName ?? (_acp?.Status == AcpRuntimeStatus.Starting ? "Connecting…" : "Not connected")); + if (_acp is { } runtime && AcpPaneCommands.ModelOption(runtime) is { CurrentSelection: { } modelValue } modelOption) + parts.Add(modelOption.Choices().FirstOrDefault(choice => choice.Value == modelValue)?.Name ?? modelValue); + parts.Add("ACP"); if (_acp is { Status: AcpRuntimeStatus.Failed or AcpRuntimeStatus.Closed } || _acp is null) parts.Add("stopped"); Pane.AcpHeader = string.Join(" · ", parts); @@ -345,6 +348,15 @@ private async Task ProcessAcpRequestAsync(string input) private sealed class PaneSink(App app) : IAcpTurnSink { + public void BeginToolActivities() => app._acpTools?.BeginTurn(); + public bool ToolCall(MandoCode.Acp.Protocol.ToolCallBase call) + { + if (app._acpTools is not { } tools) return false; + tools.Apply(call); + return true; + } + public void ToolDetail(string id, IRenderable detail) => app._acpTools?.Detail(id, detail); + public void EndToolActivities(string status) => app._acpTools?.EndTurn(status); public void Preview(string? tail) => app.Spinner.UpdatePreview(tail); public void Activity(string label) => (app.Pane?.Session ?? TuiConsole.Current)?.SetActivity(label); diff --git a/src/MandoCode/Components/Shell/App.AcpCommands.cs b/src/MandoCode/Components/Shell/App.AcpCommands.cs index 7c51250..5490949 100644 --- a/src/MandoCode/Components/Shell/App.AcpCommands.cs +++ b/src/MandoCode/Components/Shell/App.AcpCommands.cs @@ -61,6 +61,18 @@ private async Task RunAcpModelAsync(string arguments) UpdateAcpHeader(); } + private async Task RunAcpModeAsync(string arguments) + { + if (HasActiveWork) + { + Say("Wait for the current request to finish before changing the agent mode."); + return; + } + if (ReadyAcpRuntime() is not { } runtime) return; + await AcpPaneCommands.ModeAsync(runtime, arguments, AcpChoices, text => Say(text, Color.Grey), CancellationToken.None); + UpdateAcpHeader(); + } + private async Task RunAcpCompactAsync() { if (ReadyAcpRuntime() is not { } runtime) diff --git a/src/MandoCode/Components/Shell/App.Commands.cs b/src/MandoCode/Components/Shell/App.Commands.cs index ceae4e9..053e3ab 100644 --- a/src/MandoCode/Components/Shell/App.Commands.cs +++ b/src/MandoCode/Components/Shell/App.Commands.cs @@ -14,6 +14,13 @@ private async Task<CliCommandResult> ExecuteSlashCommandAsync(string input) var parsed = CliCommand.Parse(input); var command = parsed.DispatchText; + if (parsed.Name == "agent-acp-mode") + { + if (IsAcpPane) await RunAcpModeAsync(parsed.Arguments); + else TuiConsole.WriteLine("/agent-acp-mode works inside an ACP agent pane. Open one with /agent-acp <name>."); + 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/Models/SlashCommands.cs b/src/MandoCode/Models/SlashCommands.cs index e8de69e..8567fd5 100644 --- a/src/MandoCode/Models/SlashCommands.cs +++ b/src/MandoCode/Models/SlashCommands.cs @@ -75,6 +75,7 @@ public static class SlashCommands { "/mcp", $"Manage shared MCP servers: add, edit, test, and enable or disable ({Keybindings.McpServers})" }, { "/mcp tools", "List tools exposed by connected MCP servers (usage: /mcp tools <server>)" }, { "/agent-acp", "External ACP agents: /agent-acp <name> switches this pane to one (--new-panel opens a new pane, --resume continues the last session); also stop, sessions, list, status, restart, add, test, remove, enable, disable" }, + { "/agent-acp-mode", "Choose the ACP agent's permissions and behavior mode" }, { "/mcp-reload", "Restart all MCP servers and re-register their tools" }, { "/exit", "Exit MandoCode" } }; diff --git a/src/MandoCode/Services/Acp/AcpAgentCommands.cs b/src/MandoCode/Services/Acp/AcpAgentCommands.cs index 816be79..a2eb88f 100644 --- a/src/MandoCode/Services/Acp/AcpAgentCommands.cs +++ b/src/MandoCode/Services/Acp/AcpAgentCommands.cs @@ -198,6 +198,7 @@ private void List(TextWriter output) output.WriteLine("Add one: /agent-acp add <name> <command> [args...]"); output.WriteLine(@" Node adapter: /agent-acp add myagent node ""C:\path\to\adapter\dist\index.js"""); output.WriteLine(" Claude Code: /agent-acp add claude (shows how to set it up)"); + output.WriteLine(" Codex: /agent-acp add codex (shows how to set it up)"); return; } @@ -269,6 +270,18 @@ private static string Describe(string path) => private void Add(List<string> tokens, TextWriter output, TextWriter error) { + if (tokens.Count == 1 && tokens[0].Equals("codex", StringComparison.OrdinalIgnoreCase)) + { + output.WriteLine("Set up Codex through the Codex ACP adapter:"); + output.WriteLine(" npm install --prefix <adapter-folder> --save-exact @agentclientprotocol/codex-acp@2.6.0"); + output.WriteLine("Then register the installed adapter (use absolute paths):"); + output.WriteLine(@" /agent-acp add codex node ""<adapter-folder>\node_modules\@agentclientprotocol\codex-acp\dist\index.js"""); + output.WriteLine("Check the installed package's bin entry if its layout differs."); + output.WriteLine("Sign in separately with `codex login`; MandoCode never handles your credentials."); + output.WriteLine("The adapter includes a compatible Codex dependency; CODEX_PATH can select another executable."); + output.WriteLine("After adding it: /agent-acp test codex, then /agent-acp codex."); + return; + } if (tokens.Count == 1 && tokens[0].Equals("claude", StringComparison.OrdinalIgnoreCase)) { // No preset: the adapter package, its pinned version and the way it finds the Claude Code binary diff --git a/src/MandoCode/Services/Acp/AcpAgentRuntime.cs b/src/MandoCode/Services/Acp/AcpAgentRuntime.cs index 1b630b3..723e1e8 100644 --- a/src/MandoCode/Services/Acp/AcpAgentRuntime.cs +++ b/src/MandoCode/Services/Acp/AcpAgentRuntime.cs @@ -38,7 +38,11 @@ public interface IAcpAgentRuntime : IAsyncDisposable /// <summary>The agent's own name and version from <c>initialize</c> (for the adapter this is the adapter's version).</summary> string? AgentTitle { get; } + /// <summary>Human-readable agent identity for the pane header, without adapter version details.</summary> + string? AgentDisplayName => AgentTitle; + string? CurrentMode { get; } + SessionModeState? Modes => null; /// <summary>Non-fatal things that happened while starting (for example a refused <c>session/set_mode</c>).</summary> IReadOnlyList<string> StartupWarnings { get; } @@ -76,6 +80,8 @@ public interface IAcpAgentRuntime : IAsyncDisposable /// <summary>Sets a select option; throws <see cref="JsonRpcException"/> when the agent refuses it.</summary> Task SetConfigOptionAsync(string configId, string value, CancellationToken cancellationToken); + Task SetModeAsync(string modeId, CancellationToken cancellationToken) => + Task.FromException(new NotSupportedException("This agent does not expose session modes.")); /// <summary>The agent's sessions for this pane's folder (needs <see cref="AcpSessionSupport.CanList"/>).</summary> Task<IReadOnlyList<SessionInfo>> ListSessionsAsync(CancellationToken cancellationToken); @@ -137,7 +143,11 @@ public AcpAgentRuntime( public string AgentName { get; } public string? AgentTitle => Volatile.Read(ref _title); + public string? AgentDisplayName => _client?.Initialized?.AgentInfo is { } info + ? (string.IsNullOrWhiteSpace(info.Title) ? info.Name : info.Title) + : null; public string? CurrentMode => _session?.CurrentModeId; + public SessionModeState? Modes => _session?.Modes; public IReadOnlyList<string> StartupWarnings { get { lock (_gate) return _warnings.ToArray(); } } public PromptCapabilities PromptCapabilities => _session?.AgentCapabilities.PromptCapabilities ?? new PromptCapabilities(); public string? SessionId => _session?.SessionId; @@ -338,6 +348,15 @@ public async Task SetConfigOptionAsync(string configId, string value, Cancellati await session.SetConfigOptionAsync(configId, value, cancellationToken).ConfigureAwait(false); } + public async Task SetModeAsync(string modeId, CancellationToken cancellationToken) + { + if (Status != AcpRuntimeStatus.Ready || _session is not { } session) + throw new InvalidOperationException("The agent is not running."); + if (session.IsBusy) + throw new InvalidOperationException("Wait for the current request to finish before changing the agent mode."); + await session.SetModeAsync(modeId, cancellationToken).ConfigureAwait(false); + } + public async Task<IReadOnlyList<SessionInfo>> ListSessionsAsync(CancellationToken cancellationToken) { var client = _client; diff --git a/src/MandoCode/Services/Acp/AcpConnectionCard.cs b/src/MandoCode/Services/Acp/AcpConnectionCard.cs new file mode 100644 index 0000000..a7a321d --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpConnectionCard.cs @@ -0,0 +1,46 @@ +using MandoCode.Acp.Protocol; +using Spectre.Console; + +namespace MandoCode.Services.Acp; + +/// <summary>The connected agent's session details, using its own labels and permission description.</summary> +public static class AcpConnectionCard +{ + public static Panel Build(IAcpAgentRuntime runtime) + { + var dim = new Style(Color.Grey); + var body = new Paragraph(); + var model = AcpPaneCommands.ModelOption(runtime); + if (model?.CurrentSelection is { } modelValue) + { + var label = model.Choices().FirstOrDefault(choice => choice.Value == modelValue)?.Name ?? modelValue; + body.Append("Model ", dim).Append(label).Append("\n"); + } + + var modeOption = runtime.ConfigOptions.FirstOrDefault(option => option.IsSelect && option.Category == ConfigOptionCategories.Mode); + var modeId = modeOption?.CurrentSelection ?? runtime.CurrentMode; + var mode = modeOption?.Choices().FirstOrDefault(choice => choice.Value == modeId); + var modeLabel = mode?.Name ?? runtime.Modes?.AvailableModes.FirstOrDefault(choice => choice.Id == modeId)?.Name ?? modeId; + body.Append("Mode ", dim).Append(modeLabel ?? "Not reported", new Style(Color.Gold1)).Append("\n"); + if (!string.IsNullOrWhiteSpace(mode?.Description)) + body.Append(mode.Description, dim).Append("\n"); + + body.Append("Session ", dim).Append(runtime.SessionOrigin switch + { + AcpSessionOrigin.Resumed => "Resumed", + AcpSessionOrigin.Loaded => "Restored", + _ => "New conversation" + }); + body.Append("\n\nNative conversation preserved; its context is not shared.", dim); + body.Append("\n/agent-acp-mode", new Style(Color.Cyan1)).Append(" Change mode", dim); + body.Append("\n/agent-acp stop", new Style(Color.Cyan1)).Append(" Return to the native agent", dim); + return new Panel(body) + { + Header = new PanelHeader($"[green]Connected[/] · {Markup.Escape(runtime.AgentDisplayName ?? runtime.AgentName)} · ACP"), + Border = BoxBorder.Rounded, + BorderStyle = new Style(Color.Purple), + Padding = new Padding(1, 0), + Expand = false + }; + } +} diff --git a/src/MandoCode/Services/Acp/AcpPaneCommands.cs b/src/MandoCode/Services/Acp/AcpPaneCommands.cs index 7ca7ab7..8002156 100644 --- a/src/MandoCode/Services/Acp/AcpPaneCommands.cs +++ b/src/MandoCode/Services/Acp/AcpPaneCommands.cs @@ -48,6 +48,65 @@ public static class AcpPaneCommands public static bool AgentOffersCompact(IAcpAgentRuntime runtime) => runtime.AvailableCommands.Any(c => string.Equals(c.Name, CompactCommand, StringComparison.OrdinalIgnoreCase)); + /// <summary>Change the agent's advertised mode within its current session.</summary> + public static async Task ModeAsync( + IAcpAgentRuntime runtime, string arguments, IAcpChoicePrompt prompt, Action<string> write, CancellationToken cancellationToken) + { + var option = runtime.ConfigOptions.FirstOrDefault(o => o.IsSelect && o.Category == ConfigOptionCategories.Mode); + var choices = option?.Choices() ?? []; + if (choices.Count == 0) + { + option = null; + choices = runtime.Modes?.AvailableModes.Select(mode => new ConfigChoice(mode.Id, mode.Name, null, null)).ToArray() ?? []; + } + if (choices.Count == 0) + { + write("This agent does not expose modes. Change its permissions in the agent's own configuration."); + return; + } + + var current = option?.CurrentSelection ?? runtime.CurrentMode; + string ModeLabel(ConfigChoice choice) => Label(choice, current) + + (string.IsNullOrWhiteSpace(choice.Description) ? "" : " · " + choice.Description); + ConfigChoice? picked; + if (!string.IsNullOrWhiteSpace(arguments)) + { + picked = Match(choices, arguments.Trim()); + if (picked is null) + { + write($"'{arguments.Trim()}' is not one of this agent's modes. Available: {string.Join(", ", choices.Select(c => c.Value))}."); + return; + } + } + else + { + var entries = choices.Select(choice => new AcpChoice(ModeLabel(choice), choice.Value == current ? Color.Green : Color.White)) + .Append(new AcpChoice(CancelLabel, new Color(255, 200, 80))).ToList(); + var initial = Math.Max(0, choices.ToList().FindIndex(choice => choice.Value == current)); + var answer = await prompt.ChooseAsync("Agent mode: the external agent enforces these permissions.", entries, initial).ConfigureAwait(false); + if (answer is null || answer == CancelLabel) return; + picked = choices.FirstOrDefault(choice => ModeLabel(choice) == answer); + if (picked is null) return; + } + if (picked.Value == current) + { + write($"The agent already uses {picked.Name}."); + return; + } + try + { + if (option is not null) + await runtime.SetConfigOptionAsync(option.Id, picked.Value, cancellationToken).ConfigureAwait(false); + else + await runtime.SetModeAsync(picked.Value, cancellationToken).ConfigureAwait(false); + write($"Agent mode set to {picked.Name}. The conversation is unchanged; the agent enforces its permissions."); + } + catch (Exception ex) when (ex is JsonRpcException or InvalidOperationException or NotSupportedException) + { + write($"The agent did not accept that mode: {ex.Message}"); + } + } + public const string NoCompactMessage = "This agent does not announce a /compact command, so there is nothing to compact. Use /clear to start a new ACP conversation."; diff --git a/src/MandoCode/Services/Acp/AcpPaneMode.cs b/src/MandoCode/Services/Acp/AcpPaneMode.cs index 6859088..9bc515e 100644 --- a/src/MandoCode/Services/Acp/AcpPaneMode.cs +++ b/src/MandoCode/Services/Acp/AcpPaneMode.cs @@ -26,8 +26,8 @@ public static void Enter(AgentPane pane, string agentName, bool resume = false) /// agent's earlier session could be continued is reported once the agent is ready. /// </summary> public static string EnterMessage(string agentName, bool resume) => resume - ? $"── This pane now runs the ACP agent '{agentName}' (the native conversation is kept but not shared; continuing the agent's last session if it can). /agent-acp stop returns to it. ──" - : $"── This pane now runs the ACP agent '{agentName}' (fresh start: the native conversation is kept but not shared). /agent-acp stop returns to it. ──"; + ? $"Starting {agentName} via ACP · Requesting the previous session" + : $"Starting {agentName} via ACP · fresh start"; /// <summary>Ends the pane's ACP session (the agent's process tree is killed) and hands the pane back to the native agent.</summary> public static async Task LeaveAsync(AgentPane pane) diff --git a/src/MandoCode/Services/Acp/AcpPaneRestrictions.cs b/src/MandoCode/Services/Acp/AcpPaneRestrictions.cs index 4e873d9..2c50122 100644 --- a/src/MandoCode/Services/Acp/AcpPaneRestrictions.cs +++ b/src/MandoCode/Services/Acp/AcpPaneRestrictions.cs @@ -77,6 +77,7 @@ public static IReadOnlyDictionary<string, string> DescribeCommands(IReadOnlyDict described["/clear"] = "Start a new ACP conversation in this agent (the native conversation is untouched)"; described["/model"] = "Pick the agent's model"; described["/compact"] = "Ask the agent to compact its conversation"; + described["/agent-acp-mode"] = "Choose the agent's permissions and behavior mode"; return described; } diff --git a/src/MandoCode/Services/Acp/AcpPermissionPrompter.cs b/src/MandoCode/Services/Acp/AcpPermissionPrompter.cs index 4f5553b..716fb9b 100644 --- a/src/MandoCode/Services/Acp/AcpPermissionPrompter.cs +++ b/src/MandoCode/Services/Acp/AcpPermissionPrompter.cs @@ -19,6 +19,7 @@ public sealed class AcpPermissionPrompter private readonly Func<string?> _currentMode; private readonly Func<IDisposable>? _pauseActivity; private readonly Action<string, bool>? _decided; + private readonly Action<ToolCallUpdate>? _requested; /// <param name="writeLine">Prints one plain-text line (never parsed as markup).</param> /// <param name="pauseActivity">Stops the spinner while the question is open; disposing resumes it.</param> @@ -29,9 +30,11 @@ public AcpPermissionPrompter( Action<string> writeLine, Func<string?> currentMode, Func<IDisposable>? pauseActivity = null, - Action<string, bool>? decided = null) + Action<string, bool>? decided = null, + Action<ToolCallUpdate>? requested = null) { _decided = decided; + _requested = requested; _gate = gate; _menu = menu; _suppressKeys = suppressKeys; @@ -62,6 +65,8 @@ public async ValueTask<RequestPermissionResponse> RequestAsync(RequestPermission if (cancellationToken.IsCancellationRequested) return cancelled; + _requested?.Invoke(request.ToolCall); + var labels = UniqueLabels(request.Options); foreach (var line in Describe(request, _currentMode())) _writeLine(line); diff --git a/src/MandoCode/Services/Acp/AcpToolActivity.cs b/src/MandoCode/Services/Acp/AcpToolActivity.cs new file mode 100644 index 0000000..0784770 --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpToolActivity.cs @@ -0,0 +1,42 @@ +using Spectre.Console; +using Spectre.Console.Rendering; + +namespace MandoCode.Services.Acp; + +/// <summary>One stable transcript item with an immutable snapshot for concurrent render/update threads.</summary> +public sealed class AcpToolActivity(string id) : IRenderable +{ + private AcpToolSnapshot _snapshot = new(id, "Tool call", "other", "Pending", null, [], [], false); + public AcpToolSnapshot Snapshot => Volatile.Read(ref _snapshot); + internal void Update(AcpToolSnapshot snapshot) => Volatile.Write(ref _snapshot, snapshot); + + private IRenderable Details() + { + var snapshot = Snapshot; + var rows = new List<IRenderable> + { + new Text("Status: " + snapshot.Status, new Style(Color.Grey)), + new Text(snapshot.Title) + }; + if (!string.IsNullOrWhiteSpace(snapshot.Input)) + { + rows.Add(new Text("Input", new Style(Color.Grey))); + rows.Add(AnsiTranscriptText.Parse(snapshot.Input)); + } + if (snapshot.Output.Count > 0) + { + rows.Add(new Text("Output", new Style(Color.Grey))); + rows.AddRange(snapshot.Output.Select(AnsiTranscriptText.Parse)); + } + rows.AddRange(snapshot.Details); + if (snapshot.OutputUnavailable) + rows.Add(new Text("Terminal output unavailable in this client.", new Style(Color.Grey))); + return new Rows(rows); + } + + public Measurement Measure(RenderOptions options, int maxWidth) => Details().Measure(options, maxWidth); + public IEnumerable<Segment> Render(RenderOptions options, int maxWidth) => Details().Render(options, maxWidth); +} + +public sealed record AcpToolSnapshot(string Id, string Title, string Kind, string Status, string? Input, + IReadOnlyList<string> Output, IReadOnlyList<IRenderable> Details, bool OutputUnavailable); diff --git a/src/MandoCode/Services/Acp/AcpToolActivityStore.cs b/src/MandoCode/Services/Acp/AcpToolActivityStore.cs new file mode 100644 index 0000000..acf2ace --- /dev/null +++ b/src/MandoCode/Services/Acp/AcpToolActivityStore.cs @@ -0,0 +1,106 @@ +using MandoCode.Acp.Protocol; +using Spectre.Console.Rendering; + +namespace MandoCode.Services.Acp; + +/// <summary>Per-pane, per-turn mapping from ACP ids to persistent transcript rows.</summary> +public sealed class AcpToolActivityStore(Action<AcpToolActivity, bool> publish) +{ + private readonly object _gate = new(); + private readonly Dictionary<string, AcpToolActivity> _calls = new(StringComparer.Ordinal); + private bool _ended; + private const int TextLimit = 32_000; + + public void BeginTurn() + { + lock (_gate) { _calls.Clear(); _ended = false; } + } + + private AcpToolActivity Get(string id, out bool added) + { + added = !_calls.TryGetValue(id, out var activity); + if (added) _calls[id] = activity = new AcpToolActivity(id); + return activity!; + } + + public void Apply(ToolCallBase update) + { + lock (_gate) + { + if (_ended) return; + var activity = Get(update.ToolCallId, out var added); + var old = activity.Snapshot; + var status = IsFinal(old.Status) ? old.Status : update.Status switch + { + ToolCallStatuses.Completed => "Completed", + ToolCallStatuses.Failed => "Failed", + ToolCallStatuses.InProgress => "Running", + ToolCallStatuses.Pending => "Pending", + _ => old.Status + }; + if (old.Status == "Awaiting approval" && status is "Pending" or "Running") status = old.Status; + var output = old.Output.ToList(); + void AddOutput(string text) + { + if (output.Contains(text, StringComparer.Ordinal)) return; + var remaining = TextLimit - output.Sum(value => value.Length); + if (remaining > 0 && output.Count < 32) output.Add(Clip(text, remaining)); + } + foreach (var content in update.Content ?? []) + if (content is ContentToolCallContent { Content: TextContent text }) AddOutput(text.Text); + if (update.RawOutput is { } raw) AddOutput(raw.ToString()); + activity.Update(old with + { + Title = string.IsNullOrWhiteSpace(update.Title) ? old.Title : Clip(update.Title, TextLimit), + Kind = update.Kind ?? old.Kind, + Status = status, + Input = update.RawInput is { } input ? Clip(input.ToString(), TextLimit) : old.Input, + Output = output.ToArray(), + OutputUnavailable = old.OutputUnavailable || (update.Content ?? []).Any(content => content is TerminalToolCallContent) + }); + publish(activity, added); + } + } + + public void Detail(string id, IRenderable detail) + { + lock (_gate) + { + if (_ended || !_calls.TryGetValue(id, out var activity)) return; + var old = activity.Snapshot; + if (old.Details.Count >= 32) return; + activity.Update(old with { Details = old.Details.Append(detail).ToArray() }); + publish(activity, false); + } + } + + public void Permission(string id, bool? allowed) + { + lock (_gate) + { + if (_ended) return; + var activity = Get(id, out var added); + var old = activity.Snapshot; + if (IsFinal(old.Status)) return; + activity.Update(old with { Status = allowed is null ? "Awaiting approval" : allowed.Value ? "Pending" : "Permission denied" }); + publish(activity, added); + } + } + + public void EndTurn(string status) + { + lock (_gate) + { + _ended = true; + foreach (var activity in _calls.Values) + { + if (IsFinal(activity.Snapshot.Status)) continue; + activity.Update(activity.Snapshot with { Status = status }); + publish(activity, false); + } + } + } + + private static bool IsFinal(string status) => status is "Completed" or "Failed" or "Permission denied" or "Cancelled" or "Interrupted" or "Unfinished"; + private static string Clip(string value, int limit) => value.Length <= limit ? value : value[..Math.Max(0, limit - 1)] + "…"; +} diff --git a/src/MandoCode/Services/Acp/AcpTranscriptAdapter.cs b/src/MandoCode/Services/Acp/AcpTranscriptAdapter.cs index 918155a..0bc3a3e 100644 --- a/src/MandoCode/Services/Acp/AcpTranscriptAdapter.cs +++ b/src/MandoCode/Services/Acp/AcpTranscriptAdapter.cs @@ -82,7 +82,7 @@ public void BeginTurn() }; /// <summary>Applies a <c>tool_call</c> / <c>tool_call_update</c> and returns what to add to the transcript.</summary> - public IReadOnlyList<IRenderable> Apply(ToolCallBase update) + public IReadOnlyList<IRenderable> Apply(ToolCallBase update, bool includeToolText = true) { var blocks = new List<IRenderable>(); lock (_gate) @@ -99,7 +99,7 @@ public IReadOnlyList<IRenderable> Apply(ToolCallBase update) if (!state.Announced) { state.Announced = true; - blocks.Add(new Text(Headline(state), new Style(Color.Grey))); + if (includeToolText) blocks.Add(new Text(Headline(state), new Style(Color.Grey))); } // A diff is what the agent proposes, not what happened: it is shown once the call has completed @@ -114,7 +114,7 @@ public IReadOnlyList<IRenderable> Apply(ToolCallBase update) && PhaseText(state) is { } phase && phase != state.Phase) { state.Phase = phase; - blocks.Add(new Text(" ⎿ " + phase, new Style(Color.Grey))); + if (includeToolText) blocks.Add(new Text(" ⎿ " + phase, new Style(Color.Grey))); } foreach (var content in update.Content ?? []) @@ -123,7 +123,7 @@ public IReadOnlyList<IRenderable> Apply(ToolCallBase update) { case TerminalToolCallContent when !state.TerminalNoted: state.TerminalNoted = true; - blocks.Add(new Text(" ⎿ " + TerminalNotSupported, new Style(Color.Grey))); + if (includeToolText) blocks.Add(new Text(" ⎿ " + TerminalNotSupported, new Style(Color.Grey))); break; // Text, images, unknown variants: the call's title and status are what the transcript shows. @@ -135,14 +135,14 @@ public IReadOnlyList<IRenderable> Apply(ToolCallBase update) state.FinalShown = true; if (state.Status == ToolCallStatuses.Failed) { - blocks.Add(new Text(" ⎿ failed" + FailureDetail(update), new Style(Color.Red))); + if (includeToolText) blocks.Add(new Text(" ⎿ failed" + FailureDetail(update), new Style(Color.Red))); } else { foreach (var diff in state.PendingDiffs) if (ShowDiff(diff.Path, diff.OldText, diff.NewText) is { } rendered) blocks.Add(rendered); - blocks.Add(new Text(" ⎿ completed", new Style(Color.Grey))); + if (includeToolText) blocks.Add(new Text(" ⎿ completed", new Style(Color.Grey))); } state.PendingDiffs.Clear(); diff --git a/src/MandoCode/Services/Acp/AcpTurnDriver.cs b/src/MandoCode/Services/Acp/AcpTurnDriver.cs index f8c803e..a03e0c9 100644 --- a/src/MandoCode/Services/Acp/AcpTurnDriver.cs +++ b/src/MandoCode/Services/Acp/AcpTurnDriver.cs @@ -27,6 +27,10 @@ public interface IAcpTurnSink void Notice(string text); void Error(string text); + void BeginToolActivities() { } + bool ToolCall(ToolCallBase call) => false; + void ToolDetail(string id, IRenderable detail) => Block(detail); + void EndToolActivities(string status) { } } /// <param name="StopReason">The agent's stop reason; null when the turn failed.</param> @@ -60,6 +64,23 @@ public AcpTurnDriver(IAcpTurnSink sink, AcpAgentConfig? config = null, AcpTransc } public async Task<AcpTurnOutcome> RunAsync(IAcpAgentRuntime runtime, IReadOnlyList<ContentBlock> prompt, CancellationToken cancellation) + { + _sink.BeginToolActivities(); + var finalStatus = "Interrupted"; + try + { + var outcome = await RunCoreAsync(runtime, prompt, cancellation).ConfigureAwait(false); + finalStatus = cancellation.IsCancellationRequested || outcome.Cancelled ? "Cancelled" + : outcome.Error is not null ? "Interrupted" : "Unfinished"; + return outcome; + } + finally + { + _sink.EndToolActivities(cancellation.IsCancellationRequested ? "Cancelled" : finalStatus); + } + } + + private async Task<AcpTurnOutcome> RunCoreAsync(IAcpAgentRuntime runtime, IReadOnlyList<ContentBlock> prompt, CancellationToken cancellation) { if (runtime.Status != AcpRuntimeStatus.Ready) { @@ -69,6 +90,7 @@ public async Task<AcpTurnOutcome> RunAsync(IAcpAgentRuntime runtime, IReadOnlyLi } IAcpTurn turn; + _transcript?.BeginTurn(); try { turn = runtime.Prompt(prompt); @@ -79,7 +101,6 @@ public async Task<AcpTurnOutcome> RunAsync(IAcpAgentRuntime runtime, IReadOnlyLi return new AcpTurnOutcome(null, ex.Message, "", RuntimeClosed: false); } - _transcript?.BeginTurn(); var reply = new StringBuilder(); var pending = new StringBuilder(); string? activity = null; @@ -135,13 +156,15 @@ async Task ConsumeAsync() SetActivity(string.IsNullOrWhiteSpace(call.Title) ? "Working…" : call.Title!); } + var structured = _sink.ToolCall(call); if (_transcript is not null) { - var blocks = _transcript.Apply(call); + var blocks = _transcript.Apply(call, includeToolText: !structured); if (blocks.Count > 0 && call is not ToolCall) Settle(); foreach (var block in blocks) - _sink.Block(block); + if (structured) _sink.ToolDetail(call.ToolCallId, block); + else _sink.Block(block); } break; diff --git a/src/MandoCode/Services/Rendering/TuiSession.cs b/src/MandoCode/Services/Rendering/TuiSession.cs index 5c593a7..8d17834 100644 --- a/src/MandoCode/Services/Rendering/TuiSession.cs +++ b/src/MandoCode/Services/Rendering/TuiSession.cs @@ -58,6 +58,15 @@ public void AppendAgentDetail(string id, string title, IRenderable content, stri } } public void BeginToolTurn() { lock (_sync) _toolActivity = null; } + public void UpdateAcpTool(MandoCode.Services.Acp.AcpToolActivity activity, bool added) + { + lock (_sync) + { + if (added) + AddEntry(new(Interlocked.Increment(ref _nextId), activity) { AcpTool = activity, AgentOutput = _capturedExchange.Value }); + Interlocked.Increment(ref _revision); + } + } public IDisposable CaptureToolOutput(bool invoked, bool success = true) { lock (_sync) @@ -211,6 +220,7 @@ public void SetPreview(string? preview) } public sealed record TuiEntry(long Id, IRenderable Content) { + public MandoCode.Services.Acp.AcpToolActivity? AcpTool { get; init; } public AgentExchange? AgentActivity { get; init; } public AgentExchange? AgentOutput { get; init; } public ToolActivity? ToolActivity { get; init; } diff --git a/tests/MandoCode.Tests/Acp/AcpAgentCommandsTests.cs b/tests/MandoCode.Tests/Acp/AcpAgentCommandsTests.cs index 99def04..6934724 100644 --- a/tests/MandoCode.Tests/Acp/AcpAgentCommandsTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpAgentCommandsTests.cs @@ -146,6 +146,28 @@ public async Task Add_DoesNotOverwrite_AnExistingName() Assert.Equal(0, _catalog.Saves); } + [Fact] + public async Task Add_Codex_WithoutACommand_ShowsPinnedAdapterGuidanceWithoutSaving() + { + await Run("add codex"); + + Assert.Empty(_catalog.Stored); + Assert.Equal(0, _catalog.Saves); + Assert.Contains("@agentclientprotocol/codex-acp@2.6.0", _out.ToString()); + Assert.Contains("/agent-acp add codex node", _out.ToString()); + Assert.Contains("codex login", _out.ToString()); + Assert.DoesNotContain("npx", _out.ToString()); + Assert.Equal("", _err.ToString()); + } + + [Fact] + public async Task Add_Codex_WithACommand_PreservesTheConfiguredExecutable() + { + await Run($"add codex {Quoted(_host)}"); + + Assert.Equal(_host, _catalog.Stored["codex"].Command); + } + [Fact] public async Task Add_Claude_WithoutACommand_ShowsGuidanceAndInventsNothing() { diff --git a/tests/MandoCode.Tests/Acp/AcpModeCommandTests.cs b/tests/MandoCode.Tests/Acp/AcpModeCommandTests.cs new file mode 100644 index 0000000..c59ae6a --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpModeCommandTests.cs @@ -0,0 +1,118 @@ +using System.Text.Json; +using MandoCode.Acp; +using MandoCode.Acp.Protocol; +using MandoCode.Services.Acp; +using Xunit; + +namespace MandoCode.Tests.Acp; + +public class AcpModeCommandTests +{ + [Fact] + public void ConnectionCardShowsCurrentModeAndHowToChangeIt() + { + var rendered = Plain.Of(AcpConnectionCard.Build(Configured())); + Assert.Contains("Auto review", rendered); + Assert.Contains("Review actions automatically", rendered); + Assert.Contains("/agent-acp-mode", rendered); + Assert.Contains("/agent-acp stop", rendered); + Assert.Contains("context is not shared", rendered); + } + + [Fact] + public void ConnectionCardDoesNotInventAnUnreportedMode() + { + var runtime = new FakeRuntime { Modes = new SessionModeState + { + AvailableModes = [new SessionMode { Id = "default", Name = "Standard permissions" }] + }}; + var rendered = Plain.Of(AcpConnectionCard.Build(runtime)); + Assert.Contains("Standard permissions", rendered); + Assert.DoesNotContain("Auto review", rendered); + } + private static FakeRuntime Configured() => new() + { + ConfigOptions = [JsonSerializer.Deserialize(""" + {"id":"permissions","name":"Mode","category":"mode","type":"select","currentValue":"agent", + "options":[{"value":"read-only","name":"Read-only","description":"Ask before edits"}, + {"value":"agent","name":"Auto review","description":"Review actions automatically"}]} + """, AcpJsonContext.Default.SessionConfigOption)!] + }; + + private sealed class Picker : IAcpChoicePrompt + { + public int Initial = -1; + public IReadOnlyList<AcpChoice> Choices = []; + public int? Pick { get; init; } + public Task<string?> ChooseAsync(string heading, IReadOnlyList<AcpChoice> choices, int initialIndex = 0) + { + Initial = initialIndex; + Choices = choices; + return Task.FromResult(Pick is { } index ? choices[index].Label : null); + } + } + + [Fact] + public async Task PickerStartsOnCurrentModeAndSendsTheAdvertisedConfigId() + { + var runtime = Configured(); + var picker = new Picker { Pick = 0 }; + await AcpPaneCommands.ModeAsync(runtime, "", picker, _ => { }, default); + Assert.Equal(1, picker.Initial); + Assert.Contains("Ask before edits", picker.Choices[0].Label); + Assert.Equal(("permissions", "read-only"), Assert.Single(runtime.ConfigChanges)); + Assert.Empty(runtime.ModeChanges); + Assert.Equal(0, runtime.NewConversations); + } + + [Fact] + public async Task FallbackUsesSessionModesWhenNoConfigOptionExists() + { + var runtime = new FakeRuntime { Modes = new SessionModeState + { + AvailableModes = [new SessionMode { Id = "plan", Name = "Plan" }] + }}; + await AcpPaneCommands.ModeAsync(runtime, "Plan", new Picker(), _ => { }, default); + Assert.Equal("plan", Assert.Single(runtime.ModeChanges)); + Assert.Empty(runtime.ConfigChanges); + } + + [Theory] + [InlineData(null)] + [InlineData(2)] + public async Task DismissOrCancelDoesNotChangePermissions(int? selection) + { + var runtime = Configured(); + await AcpPaneCommands.ModeAsync(runtime, "", new Picker { Pick = selection }, _ => { }, default); + Assert.Empty(runtime.ConfigChanges); + } + + [Theory] + [InlineData("agent")] + [InlineData("does-not-exist")] + public async Task CurrentOrUnknownModeDoesNotSendAChange(string value) + { + var runtime = Configured(); + await AcpPaneCommands.ModeAsync(runtime, value, new Picker(), _ => { }, default); + Assert.Empty(runtime.ConfigChanges); + } + + [Fact] + public async Task UnsupportedAgentGetsAnExplanation() + { + var messages = new List<string>(); + await AcpPaneCommands.ModeAsync(new FakeRuntime(), "", new Picker(), messages.Add, default); + Assert.Contains("does not expose modes", Assert.Single(messages)); + } + + [Fact] + public async Task AgentRefusalDoesNotReportSuccess() + { + var runtime = Configured(); + runtime.ConfigChangeFails = new InvalidOperationException("refused"); + var messages = new List<string>(); + await AcpPaneCommands.ModeAsync(runtime, "read-only", new Picker(), messages.Add, default); + Assert.Contains("did not accept", Assert.Single(messages)); + Assert.Empty(runtime.ConfigChanges); + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs b/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs index 9b5835e..e514f79 100644 --- a/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpPaneAppTests.cs @@ -85,6 +85,30 @@ private static SessionConfigOption ModelOption(string current = "model-a") => // ─────────── /transcript-save ─────────── + [Fact] + public async Task AgentModeCommandChangesTheAdvertisedSettingInTheSameSession() + { + await using var h = Harness.Create(); + h.Runtime.ConfigOptions = [JsonSerializer.Deserialize(""" + {"id":"mode","name":"Mode","category":"mode","type":"select","currentValue":"agent", + "options":[{"value":"read-only","name":"Read-only"},{"value":"agent","name":"Auto review"}]} + """, AcpJsonContext.Default.SessionConfigOption)!]; + await h.Run("/agent-acp-mode read-only"); + Assert.Equal(("mode", "read-only"), Assert.Single(h.Runtime.ConfigChanges)); + Assert.Equal(0, h.Runtime.NewConversations); + Assert.Contains("Agent mode set", h.Output); + } + + [Fact] + public async Task AgentModeCommandIsRefusedDuringActiveWork() + { + await using var h = Harness.Create(); + SetField(h.App, "_requestCts", new CancellationTokenSource()); + await h.Run("/agent-acp-mode read-only"); + Assert.Empty(h.Runtime.ConfigChanges); + Assert.Contains("current request to finish", h.Output); + } + [Fact] public async Task TranscriptSave_NamesTheAcpAgent_NotTheOllamaModel() { diff --git a/tests/MandoCode.Tests/Acp/AcpPaneTests.cs b/tests/MandoCode.Tests/Acp/AcpPaneTests.cs index d316ad3..f35f03d 100644 --- a/tests/MandoCode.Tests/Acp/AcpPaneTests.cs +++ b/tests/MandoCode.Tests/Acp/AcpPaneTests.cs @@ -25,6 +25,14 @@ public sealed class FakeRuntime : IAcpAgentRuntime public AcpRuntimeStatus Status { get; set; } = AcpRuntimeStatus.Ready; public string? AgentTitle => "fake-adapter 1.2.3"; public string? CurrentMode => "default"; + public SessionModeState? Modes { get; set; } + public List<string> ModeChanges { get; } = []; + public Task SetModeAsync(string modeId, CancellationToken cancellationToken) + { + if (ConfigChangeFails is { } failure) throw failure; + ModeChanges.Add(modeId); + return Task.CompletedTask; + } public IReadOnlyList<string> StartupWarnings { get; } = []; public PromptCapabilities PromptCapabilities { get; } = new(); public event Action? Changed { add { } remove { } } diff --git a/tests/MandoCode.Tests/Acp/AcpToolActivityTests.cs b/tests/MandoCode.Tests/Acp/AcpToolActivityTests.cs new file mode 100644 index 0000000..0831dfc --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpToolActivityTests.cs @@ -0,0 +1,187 @@ +using System.Text.Json; +using MandoCode.Acp; +using MandoCode.Acp.Protocol; +using MandoCode.Services; +using MandoCode.Services.Acp; +using Spectre.Console; +using Spectre.Console.Rendering; +using Xunit; + +namespace MandoCode.Tests.Acp; + +public class AcpToolActivityTests +{ + [Fact] + public void SparseUpdatesReplaceStatusWithoutDuplicatingTheRowOrLosingInput() + { + var session = new TuiSession(); + var store = new AcpToolActivityStore(session.UpdateAcpTool); + store.BeginTurn(); + store.Apply(new ToolCall { ToolCallId = "1", Title = "Inspect library", Kind = "execute", + RawInput = JsonSerializer.SerializeToElement(new { command = "Get-Item library.dll" }) }); + var first = Assert.Single(session.Snapshot().Entries); + var revision = session.Revision; + store.Apply(new ToolCallUpdate { ToolCallId = "1", Status = "in_progress" }); + Assert.Equal("Running", first.AcpTool!.Snapshot.Status); + store.Apply(new ToolCallUpdate { ToolCallId = "1", Status = "completed" }); + var last = Assert.Single(session.Snapshot().Entries); + Assert.Equal(first.Id, last.Id); + Assert.Same(first.AcpTool, last.AcpTool); + Assert.Equal("Inspect library", last.AcpTool!.Snapshot.Title); + Assert.Contains("Get-Item library.dll", last.AcpTool.Snapshot.Input); + Assert.Equal("Completed", last.AcpTool.Snapshot.Status); + Assert.True(session.Revision > revision); + } + + [Fact] + public void InterleavedCallsAndEarlyUpdatesKeepTheirOwnIdentities() + { + var session = new TuiSession(); + var store = new AcpToolActivityStore(session.UpdateAcpTool); + store.Apply(new ToolCallUpdate { ToolCallId = "a", Status = "in_progress" }); + store.Apply(new ToolCall { ToolCallId = "b", Title = "Second call" }); + store.Apply(new ToolCall { ToolCallId = "a", Title = "First call", Kind = "read" }); + store.Apply(new ToolCallUpdate { ToolCallId = "b", Status = "failed" }); + var entries = session.Snapshot().Entries; + Assert.Equal(2, entries.Count); + Assert.Equal("First call", entries[0].AcpTool!.Snapshot.Title); + Assert.Equal("Running", entries[0].AcpTool!.Snapshot.Status); + Assert.Equal("Failed", entries[1].AcpTool!.Snapshot.Status); + } + + [Fact] + public void PermissionDenialCannotBeOverwrittenByALateCompletion() + { + var session = new TuiSession(); + var store = new AcpToolActivityStore(session.UpdateAcpTool); + store.Apply(new ToolCall { ToolCallId = "x", Title = "Write a file" }); + Assert.Equal("Pending", Assert.Single(session.Snapshot().Entries).AcpTool!.Snapshot.Status); + store.Permission("x", null); + store.Apply(new ToolCallUpdate { ToolCallId = "x", Status = "in_progress" }); + Assert.Equal("Awaiting approval", Assert.Single(session.Snapshot().Entries).AcpTool!.Snapshot.Status); + store.Permission("x", false); + store.Apply(new ToolCallUpdate { ToolCallId = "x", Status = "completed" }); + Assert.Equal("Permission denied", Assert.Single(session.Snapshot().Entries).AcpTool!.Snapshot.Status); + } + + [Theory] + [InlineData("Cancelled")] + [InlineData("Interrupted")] + [InlineData("Unfinished")] + public void EndTurnSettlesOnlyUnfinishedCallsAndIgnoresLateUpdates(string status) + { + var session = new TuiSession(); + var store = new AcpToolActivityStore(session.UpdateAcpTool); + store.Apply(new ToolCall { ToolCallId = "done", Status = "completed" }); + store.Apply(new ToolCall { ToolCallId = "pending" }); + store.EndTurn(status); + store.Apply(new ToolCallUpdate { ToolCallId = "pending", Status = "completed" }); + store.Apply(new ToolCall { ToolCallId = "late" }); + var entries = session.Snapshot().Entries; + Assert.Equal(2, entries.Count); + Assert.Equal("Completed", entries[0].AcpTool!.Snapshot.Status); + Assert.Equal(status, entries[1].AcpTool!.Snapshot.Status); + } + + [Fact] + public void ReusedIdsInAnotherTurnOrPaneDoNotChangeEarlierRows() + { + var first = new TuiSession(); + var store = new AcpToolActivityStore(first.UpdateAcpTool); + store.Apply(new ToolCall { ToolCallId = "1", Title = "Earlier", Status = "completed" }); + store.EndTurn("Unfinished"); + store.BeginTurn(); + store.Apply(new ToolCall { ToolCallId = "1", Title = "Later" }); + var second = new TuiSession(); + new AcpToolActivityStore(second.UpdateAcpTool).Apply(new ToolCall { ToolCallId = "1", Title = "Other pane" }); + Assert.Equal(2, first.Snapshot().Entries.Count); + Assert.Equal("Earlier", first.Snapshot().Entries[0].AcpTool!.Snapshot.Title); + Assert.Equal("Completed", first.Snapshot().Entries[0].AcpTool!.Snapshot.Status); + Assert.Equal("Other pane", Assert.Single(second.Snapshot().Entries).AcpTool!.Snapshot.Title); + } + + [Fact] + public void OutputIsBoundedDeduplicatedAndTerminalAvailabilityIsOnlyADetail() + { + var session = new TuiSession(); + var store = new AcpToolActivityStore(session.UpdateAcpTool); + store.Apply(new ToolCall { ToolCallId = "1", Content = + [new ContentToolCallContent { Content = new TextContent("hello") }, new TerminalToolCallContent { TerminalId = "terminal" }] }); + store.Apply(new ToolCallUpdate { ToolCallId = "1", Content = [new ContentToolCallContent { Content = new TextContent("hello") }] }); + Assert.Equal("hello", Assert.Single(Assert.Single(session.Snapshot().Entries).AcpTool!.Snapshot.Output)); + store.Apply(new ToolCallUpdate { ToolCallId = "1", RawOutput = JsonSerializer.SerializeToElement(new string('x', 100_000)) }); + var activity = Assert.Single(session.Snapshot().Entries).AcpTool!; + Assert.True(activity.Snapshot.Output.Sum(text => text.Length) <= 32_000); + Assert.True(activity.Snapshot.OutputUnavailable); + Assert.Contains("Terminal output unavailable", Plain.Of(activity)); + } + + private sealed class Sink : IAcpTurnSink + { + public TuiSession Session { get; } = new(); + private AcpToolActivityStore? _store; + public List<IRenderable> Blocks { get; } = []; + public void BeginToolActivities() { _store = new(Session.UpdateAcpTool); _store.BeginTurn(); } + public bool ToolCall(ToolCallBase call) { _store!.Apply(call); return true; } + public void ToolDetail(string id, IRenderable detail) => _store!.Detail(id, detail); + public void EndToolActivities(string status) => _store!.EndTurn(status); + public void Preview(string? tail) { } + public void Activity(string label) { } + public void Reply(string markdown) => Session.Append(new Text(markdown)); + public void Block(IRenderable block) => Blocks.Add(block); + public void Notice(string text) { } + public void Error(string text) { } + } + + [Theory] + [InlineData("end_turn", "Unfinished")] + [InlineData("cancelled", "Cancelled")] + public async Task DriverSettlesIncompleteActivitiesWithoutAppendingLegacyLines(string stop, string expected) + { + var sink = new Sink(); + var runtime = new FakeRuntime(); + var driver = new AcpTurnDriver(sink, transcript: new AcpTranscriptAdapter(_ => new Text("diff"), Path.GetTempPath())); + var run = driver.RunAsync(runtime, [new TextContent("test")], default); + runtime.Send(FakeRuntime.Text("Before")); + runtime.Send(new ToolCall { ToolCallId = "1", Title = "Run command", Kind = "execute", Status = "in_progress" }); + runtime.Send(FakeRuntime.Text("After")); + runtime.Succeed(stop); + await run.Within(); + var entries = sink.Session.Snapshot().Entries; + Assert.Equal(3, entries.Count); + Assert.Equal("Before", Plain.Of(entries[0].Content)); + Assert.Equal(expected, entries[1].AcpTool!.Snapshot.Status); + Assert.Equal("After", Plain.Of(entries[2].Content)); + Assert.Empty(sink.Blocks); + } + + [Fact] + public async Task CompletedDiffRemainsAttachedToItsActivity() + { + var sink = new Sink(); + var runtime = new FakeRuntime(); + var driver = new AcpTurnDriver(sink, transcript: new AcpTranscriptAdapter(_ => new Text("file diff"), Path.GetTempPath())); + var run = driver.RunAsync(runtime, [new TextContent("test")], default); + runtime.Send(new ToolCall { ToolCallId = "edit", Title = "Edit file", Kind = "edit", Content = + [new DiffToolCallContent { Path = Path.Combine(Path.GetTempPath(), "activity.txt"), OldText = "old", NewText = "new" }] }); + runtime.Send(new ToolCallUpdate { ToolCallId = "edit", Status = "completed" }); + runtime.Succeed(StopReasons.EndTurn); + await run.Within(); + var activity = Assert.Single(sink.Session.Snapshot().Entries).AcpTool!; + Assert.Equal("Completed", activity.Snapshot.Status); + Assert.Equal("file diff", Plain.Of(Assert.Single(activity.Snapshot.Details))); + Assert.Empty(sink.Blocks); + } + + [Fact] + public async Task DriverMarksInterruptedCallsWhenTheRuntimeFails() + { + var sink = new Sink(); + var runtime = new FakeRuntime(); + var run = new AcpTurnDriver(sink).RunAsync(runtime, [new TextContent("test")], default); + runtime.Send(new ToolCall { ToolCallId = "1", Status = "in_progress" }); + runtime.Fail(new IOException("connection failed")); + Assert.NotNull((await run.Within()).Error); + Assert.Equal("Interrupted", Assert.Single(sink.Session.Snapshot().Entries).AcpTool!.Snapshot.Status); + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpToolActivityViewTests.cs b/tests/MandoCode.Tests/Acp/AcpToolActivityViewTests.cs new file mode 100644 index 0000000..ecf6a97 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpToolActivityViewTests.cs @@ -0,0 +1,71 @@ +using System.Reflection; +using MandoCode.Acp.Protocol; +using MandoCode.Components; +using MandoCode.Services; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Rendering; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace MandoCode.Tests.Acp; + +[Trait("Category", "Component")] +public class AcpToolActivityViewTests +{ + [Fact] + public async Task DetailsExpandAndStayOpenAsTheSameCallFinishes() + { + await using var services = AcpTestHost.Services(); + await using var renderer = new HtmlRenderer(services, services.GetRequiredService<ILoggerFactory>()); + var session = new TuiSession(); + var store = new MandoCode.Services.Acp.AcpToolActivityStore(session.UpdateAcpTool); + store.Apply(new ToolCall { ToolCallId = "1", Title = "Inspect metadata", Kind = "execute", Status = "in_progress" }); + var entry = Assert.Single(session.Snapshot().Entries); + await renderer.Dispatcher.InvokeAsync(async () => + { + Host host = null!; + var rendered = await renderer.RenderComponentAsync<Host>(ParameterView.FromDictionary(new Dictionary<string, object?> + { + [nameof(Host.Entry)] = entry, + [nameof(Host.Capture)] = (Action<Host>)(value => host = value) + })); + Assert.Contains("Running", rendered.ToHtmlString()); + Assert.DoesNotContain("data-canvas", rendered.ToHtmlString()); + host.Toggle(); + Assert.Contains("data-canvas", rendered.ToHtmlString()); + store.Apply(new ToolCallUpdate { ToolCallId = "1", Status = "completed" }); + host.Refresh(); + var html = rendered.ToHtmlString(); + Assert.Contains("Completed", html); + Assert.DoesNotContain("Running", html); + Assert.Contains("data-canvas", html); + Assert.Single(session.Snapshot().Entries); + host.Toggle(); + Assert.DoesNotContain("data-canvas", rendered.ToHtmlString()); + }); + } + + public sealed class Host : ComponentBase + { + [Parameter] public TuiEntry Entry { get; set; } = default!; + [Parameter] public Action<Host> Capture { get; set; } = default!; + private AcpToolActivityView _view = default!; + protected override void OnInitialized() => Capture(this); + public void Refresh() => StateHasChanged(); + public void Toggle() + { + typeof(AcpToolActivityView).GetMethod("Toggle", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(_view, null); + Refresh(); + } + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + builder.OpenComponent<AcpToolActivityView>(0); + builder.AddAttribute(1, "Entry", Entry); + builder.AddAttribute(2, "Activity", Entry.AcpTool); + builder.AddComponentReferenceCapture(3, value => _view = (AcpToolActivityView)value); + builder.CloseComponent(); + } + } +}