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

- Paste clipboard images into ACP prompts with Alt+V when the connected agent advertises image support. Send in-memory PNG image blocks with text, retain per-pane attachment references and size limits, and explain unsupported agents or expired images without sending an incomplete prompt.

- ACP agent-provided commands appear in slash-command suggestions with the connected agent’s display name (for example `[Codex]`), descriptions, and input hints. Advertised commands and arguments are forwarded to the current agent as prompts; session updates replace the list, and MandoCode commands retain precedence on name collisions.

- `/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.
Expand Down
5 changes: 3 additions & 2 deletions docs/acp-codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@ entry path with `node`. The live validation below was performed on Windows only.
- `/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.
- `/compact` and other agent-provided commands appear when the adapter advertises them.
- Alt+V attaches a clipboard image when the connected adapter advertises image prompt support.
- `/clear` starts another ACP conversation and preserves the native MandoCode conversation.
- `/copy` and `/copy-code` read the ACP conversation's last reply.
- `/agent-acp stop` returns to the native conversation.
- Folder changes 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.
agent mentions, context handoff, or the proposed MandoCode MCP bridge.
The generic ACP restrictions still apply even if Codex itself advertises additional features.

The adapter also supports API-key authentication. Existing `OPENAI_API_KEY` and `CODEX_API_KEY`
Expand Down
16 changes: 14 additions & 2 deletions docs/acp.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ One set in the code (`AcpPaneRestrictions`) feeds autocomplete, the command disp
| `/setup`, `/retry`, `/config`, `/agent-settings` (Alt+S), `/force-skill`, `/plan`, `/plan-resume`, `/plan-discard`, `/context-snap-create`, `/context-snap-import` (Alt+C), `/ollama-*` | The external agent runs the conversation; MandoCode's own model loop, plans and context snapshots do not apply. |
| `/skills` (Alt+K), `/mcp` (Alt+M), `/mcp tools`, `/mcp-reload` | The agent does not use MandoCode's skills or MCP servers (`mcpServers` is empty). |
| `/history` (Alt+H) | Saved history restores native agents, and ACP panes are not saved to it. |
| Alt+V (paste image) | Images are not sent to ACP agents yet. |
| Alt+V (paste image) | Attach a clipboard image when the connected agent advertises image prompt support. |
| Agents group of the `@` picker | See above. |

Typing a blocked command, or pressing its shortcut, prints `/<command> is not available in an ACP agent pane: <why>`.
Expand Down Expand Up @@ -194,6 +194,18 @@ touched**. While a request is running `/clear` is refused (press Escape first).
- `/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.

### Clipboard image prompts

When a connected agent advertises `promptCapabilities.image`, Alt+V attaches a clipboard image to the prompt.
Add a message and press Enter to send both together; deleting the image's `@reference` removes the attachment.
The image is sent as an ACP image block with base64 PNG data and an `image/png` MIME type. It stays in memory
in that pane and is not written into the project. Existing `@file` references continue to use resource links.

Each image is limited to 4 MiB, with a 16 MiB total image limit per prompt. Duplicate references attach an image
once. An unavailable or expired clipboard reference produces an error asking you to paste it again. Image support
is checked at send time as well as paste time. Unsupported agents receive an explanation; Ctrl+V text paste
continues to work. On Windows, Ctrl+V also attaches clipboard images when the terminal forwards the key.

### 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.
Expand Down Expand Up @@ -395,7 +407,7 @@ Deviations from the plan

Known limitations
- Markdown links in an agent's reply are shown as raw text (the transcript renderer does not turn them into links).
- Images are not sent; `terminal/*` is not offered.
- Clipboard images require the agent to advertise `promptCapabilities.image`; `terminal/*` is not offered.
- Agents that cannot resume or load sessions always start fresh, and `/model` needs the agent to expose a model option.
- Switching the folder (or `--resume`) affects one pane; restarting all ACP panes at once is a separate change.
- MandoCode's agents are not reachable from an ACP agent, and no context is handed over between the two (a later phase).
Expand Down
22 changes: 15 additions & 7 deletions src/MandoCode/Components/Input/PromptInput.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
@inject IServiceProvider Services
@using MandoCode.Models
@using MandoCode.Services
@using MandoCode.Services.Acp
@using Spectre.Console
@using RazorConsole.Core.Renderables
@implements IDisposable
Expand Down Expand Up @@ -86,9 +87,14 @@
[Parameter] public Color LabelColor { get; set; } = Color.Green;
[Parameter] public string Placeholder { get; set; } = "type / for commands, @ for files and agents, : for emojis · Alt+V paste image";
[Parameter] public bool ChatFeaturesEnabled { get; set; } = true;
// An ACP pane offers files only in the @ picker and no image paste (AcpPaneRestrictions).
// An ACP pane offers files in the @ picker; clipboard images depend on the agent capabilities.
private bool IsAcpPane => Pane?.Runtime == AgentRuntime.Acp;
private string EffectivePlaceholder => IsAcpPane && ChatFeaturesEnabled ? "type / for commands, @ for files, : for emojis" : Placeholder;
private IAcpAgentRuntime? AcpRuntime =>
((Pane?.Services ?? Services).GetService(typeof(AcpRuntimeHolder)) as AcpRuntimeHolder)?.Runtime;
private string? ImageBlockReason => IsAcpPane ? AcpPaneRestrictions.ImagePasteReason(AcpRuntime) : null;
private string EffectivePlaceholder => IsAcpPane && ChatFeaturesEnabled
? "type / for commands, @ for files, : for emojis" + (ImageBlockReason is null ? " · Alt+V paste image" : "")
: Placeholder;
[Parameter] public bool AllowEmpty { get; set; }
[Parameter] public string? PersistenceKey { get; set; }
[Inject] private RazorConsole.Core.Focus.FocusManager Focus { get; set; } = default!;
Expand All @@ -114,6 +120,12 @@
{
if (Disabled || !ChatFeaturesEnabled || ModelPicker is not null || Pane is { Active: false }) return true;
var services = Pane?.Services ?? Services;
bool BlockImage()
{
if (ImageBlockReason is not { } reason) return false;
_clipboardStatus = reason; _clipboardError = true; StateHasChanged(); return true;
}
if (explicitRequest && BlockImage()) return true;
var reader = services.GetService(typeof(IClipboardImageReader)) as IClipboardImageReader ?? new WindowsClipboardImageReader();
// Linux terminal paste remains native; an injected reader can provide clipboard support on any OS.
if (!explicitRequest && !OperatingSystem.IsWindows() && reader is WindowsClipboardImageReader) return false;
Expand All @@ -130,6 +142,7 @@
if (text is not null) { _composer.Buffer.Insert(PromptPaste.Normalize(text)); _composer.Refresh(); _emojiOpen = false; _clipboardStatus = ""; return true; }
_clipboardStatus = explicitRequest ? "No Image in the clipboard. Copy an image, then press Alt+V" : ""; return explicitRequest;
}
if (BlockImage()) return true;
var images = services.GetService(typeof(ClipboardImageStore)) as ClipboardImageStore ?? _fallbackClipboard;
_composer.InsertFileReference(images.Add(png));
_clipboardStatus = "Clipboard image attached · Add a message, then Enter to send · Delete its @reference to remove";
Expand Down Expand Up @@ -277,11 +290,6 @@
if (key.Key is not ("ArrowUp" or "UpArrow" or "ArrowDown" or "DownArrow")) _cursorNavigation.Reset();
if (key.Key.Equals("v", StringComparison.OrdinalIgnoreCase) && (key.CtrlKey || key.AltKey) && ChatFeaturesEnabled && ModelPicker is null)
{
if (IsAcpPane)
{
_clipboardStatus = $"Image paste is unavailable in an ACP pane: {MandoCode.Services.Acp.AcpPaneRestrictions.ImagePasteReason}.";
_clipboardError = true; StateHasChanged(); return true;
}
return await PasteClipboardImage(key.AltKey);
}
if (AgentKeyboardRouter.TryHandleGlobal(Pane, key)) return true;
Expand Down
3 changes: 2 additions & 1 deletion src/MandoCode/Components/Shell/App.Acp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,8 @@ private async Task ProcessAcpRequestAsync(string input)

Spinner.Start("Thinking...");
var driver = new AcpTurnDriver(new PaneSink(this), AcpEntry, _acpTranscript);
var outcome = await driver.RunAsync(_acp, AcpPromptBuilder.Build(input, ProjectRoot.ProjectRoot), token);
var outcome = await driver.RunAsync(_acp, AcpPromptBuilder.Build(input, ProjectRoot.ProjectRoot,
Pane?.Services.GetService<ClipboardImageStore>(), _acp.PromptCapabilities.Image), token);

_lastRequestError = outcome.Error;
if (outcome.ReplyText.Length > 0)
Expand Down
11 changes: 7 additions & 4 deletions src/MandoCode/Services/Acp/AcpPaneRestrictions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,13 @@ public static class AcpPaneRestrictions
["h"] = "/history",
};

/// <summary>The Alt+V image paste: an ACP prompt carries text and file links only for now.</summary>
public const string ImagePasteReason = "images are not sent to ACP agents yet";
/// <summary>Image paste follows the connected agent's advertised prompt capabilities.</summary>
public static string? ImagePasteReason(IAcpAgentRuntime? runtime) =>
runtime is not { Status: AcpRuntimeStatus.Ready }
? "Wait for the ACP agent to connect before attaching an image."
: !runtime.PromptCapabilities.Image
? "This ACP agent does not support image prompts."
: null;

/// <summary>The <c>@</c> picker lists files only; MandoCode's agents are not reachable from an external agent.</summary>
public static bool PickerShowsAgents => false;
Expand Down Expand Up @@ -88,8 +93,6 @@ public static string Message(string command) =>
/// <summary>The command an Alt+<paramref name="key"/> shortcut stands for, when that shortcut is blocked here.</summary>
public static string? BlockedShortcutCommand(string key) => Shortcuts.TryGetValue(key, out var command) ? command : null;

public static bool IsImagePasteBlocked(string key) => key.Equals("v", StringComparison.OrdinalIgnoreCase);

private static string NameOf(string command) =>
command.TrimStart('/').Split(' ', 2)[0].ToLowerInvariant();
}
24 changes: 22 additions & 2 deletions src/MandoCode/Services/Acp/AcpTurnDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,23 +241,43 @@ async Task ConsumeAsync()
}

/// <summary>
/// Builds the prompt blocks for a user message: the text itself plus a <c>resource_link</c> for every <c>@file</c> inside
/// Builds prompt blocks: text, in-memory clipboard images when supported, and a <c>resource_link</c> for every <c>@file</c> inside
/// the project. Mentions are read with the same parser as the native pane (<see cref="FileReferenceToken"/>, so
/// <c>@"src/My Component.cs"</c> works) and judged by the same guard as the agent's own file requests: relative paths
/// only inside the project folder, no <c>..</c> escapes, no link or junction that leads out.
/// </summary>
public static class AcpPromptBuilder
{
public static IReadOnlyList<ContentBlock> Build(string input, string projectRoot)
// Base64 expands image payloads by about one third. Keep them below the transport's 32 MiB line budget.
public const int MaxTotalImageBytes = 16 * 1024 * 1024;

public static IReadOnlyList<ContentBlock> Build(string input, string projectRoot,
ClipboardImageStore? clipboard = null, bool supportsImages = false)
{
var blocks = new List<ContentBlock> { new TextContent(input) };
var seen = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
var guard = new AcpFileSystemHandler(projectRoot);
var imageBytes = 0;

foreach (var mention in FileReferenceToken.Paths(input))
{
foreach (var candidate in Candidates(mention))
{
if (ClipboardImageStore.IsReference(candidate))
{
if (!seen.Add(candidate)) break;
if (!supportsImages) throw new IOException("This ACP agent does not support image prompts. Remove the image reference to send text only.");
if (clipboard is null || !clipboard.TryGet(candidate, out var png))
throw new IOException("This clipboard image is no longer available in this pane. Copy it again and press Alt+V.");
if (png.Length > AIService.MaxImageInputBytes)
throw new IOException("The clipboard image exceeds the 4 MiB attachment limit.");
imageBytes += png.Length;
if (imageBytes > MaxTotalImageBytes)
throw new IOException("Images exceed the 16 MiB total per prompt. Remove some image references and send them separately.");
blocks.Add(new ImageContent { Data = Convert.ToBase64String(png), MimeType = "image/png" });
break;
}

if (TryResolve(guard, projectRoot, candidate) is not { } link || !seen.Add(link.Canonical))
continue;

Expand Down
4 changes: 4 additions & 0 deletions src/MandoCode/Services/Input/ClipboardImage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,8 @@ public string Add(byte[] png)
return reference;
}
public bool TryGet(string reference, out byte[] png) => _images.TryGetValue(reference, out png!);

internal static bool IsReference(string reference) => reference.Length == 46 &&
reference.StartsWith("clipboard-", StringComparison.Ordinal) && reference.EndsWith(".png", StringComparison.Ordinal) &&
Guid.TryParseExact(reference.AsSpan(10, 32), "N", out _);
}
Loading