From 53f3ffc2dcd89a7399b8c958306ba49169efb1fb Mon Sep 17 00:00:00 2001 From: DevMando Date: Wed, 11 Nov 2026 00:25:16 -0800 Subject: [PATCH 1/2] feat: paste and attach multiple images to Desktop prompts --- CHANGELOG.md | 1 + README.md | 2 + .../MandoCode.Desktop.Tests.csproj | 1 + .../PromptImageAttachmentTests.cs | 115 ++++++++ .../Controls/Chat/ChatTabView.Explorer.cs | 14 +- .../Controls/Chat/ChatTabView.Images.cs | 245 ++++++++++++++++++ .../Controls/Chat/ChatTabView.Input.cs | 58 ++++- .../Controls/Chat/ChatTabView.xaml | 34 ++- .../Controls/Chat/ChatTabView.xaml.cs | 4 + .../Services/Input/PromptImageAttachment.cs | 53 ++++ .../ViewModels/ChatController.cs | 32 ++- 11 files changed, 533 insertions(+), 26 deletions(-) create mode 100644 src/MandoCode.Desktop.Tests/PromptImageAttachmentTests.cs create mode 100644 src/MandoCode.Desktop/Controls/Chat/ChatTabView.Images.cs create mode 100644 src/MandoCode.Desktop/Services/Input/PromptImageAttachment.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a28157..7d8ed00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ submodule. ## [Unreleased] ### Added +- **Attach images to Desktop prompts.** Paste a screenshot or copied image file, use Attach image, or drop image files into the chat. Select multiple files, preview the batch, and remove images individually before sending. Supports up to four PNG, JPEG, GIF, or WebP images per message, each limited to 4 MiB and 16 million pixels. Check vision support again at send time, retain refused drafts, and queue image bytes only after this agent claims the user turn. Image-only messages receive an explicit description prompt. - **Organize agents into workspaces.** A new upper tab row groups agents into named workspaces. Each workspace remembers its selected agent and split layout; switching workspaces keeps background agents running. Existing tabs move into **Main**, and all workspaces reopen on the next launch. Working and approval badges help you find agents that need attention, including in other workspaces. - **Close workspaces directly from their tabs.** The **×** appears on the selected workspace and when another workspace is hovered or focused, without shifting tab labels. Right-click still offers Rename and Close. Both closing actions keep at least one workspace open, block closure while agents or commands are running or approvals are waiting, and save conversations to History before closing. - **More ways for agents to collaborate.** Agents can ask for an immediate answer or a background reply, send information, request a read-only review, hand off work, and update or cancel individual jobs. Messages and results appear in expandable transcript entries that identify the agents involved. Background jobs use readable IDs such as `job1`, support bounded waits, and cancel when an associated agent closes. The existing `ask_agent` tool remains available alongside `ask_agent_and_wait`. diff --git a/README.md b/README.md index a45114a..d6c72ef 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,8 @@ Two problems, one app: ## Features +- **Image attachments for vision models** — paste a screenshot or copied image file, click **Attach image**, or drop image files into chat. Select multiple files or paste screenshots one at a time. Preview and remove individual images before sending. Supports up to four PNG, JPEG, GIF, or WebP images per message, each up to 4 MiB and 16 million pixels. The selected model must have confirmed vision support. Images are supplied for the submitted turn; attach again when another turn needs the original pixels. + - **Workspace tabs** — group agents into named workspaces in the upper tab row. Each workspace remembers its selected agent and split layout; switching keeps background agents running. Use **+ Workspace** to create one. Close with the **×** on the selected tab, or hover/focus another workspace to reveal its close button. Right-click also offers Rename and Close. **Split** and **New agent** apply to the selected workspace. Workspaces restore on launch, and existing installations migrate their tabs into **Main**. Alt+Shift+N creates a workspace, Alt+Shift+Left/Right switches, and Alt+Shift+W closes an idle workspace. - **Agent tabs, and Split view for up to four at once** — each tab is its own independent diff --git a/src/MandoCode.Desktop.Tests/MandoCode.Desktop.Tests.csproj b/src/MandoCode.Desktop.Tests/MandoCode.Desktop.Tests.csproj index e379531..68616d1 100644 --- a/src/MandoCode.Desktop.Tests/MandoCode.Desktop.Tests.csproj +++ b/src/MandoCode.Desktop.Tests/MandoCode.Desktop.Tests.csproj @@ -31,6 +31,7 @@ Windows App SDK into the test host). If these files ever grow UI dependencies, that's a design regression this project exists to catch. --> + diff --git a/src/MandoCode.Desktop.Tests/PromptImageAttachmentTests.cs b/src/MandoCode.Desktop.Tests/PromptImageAttachmentTests.cs new file mode 100644 index 0000000..d4b953e --- /dev/null +++ b/src/MandoCode.Desktop.Tests/PromptImageAttachmentTests.cs @@ -0,0 +1,115 @@ +using MandoCode.Desktop.Services; +using MandoCode.Models; +using Xunit; + +namespace MandoCode.Desktop.Tests; + +public class PromptImageAttachmentTests +{ + [Theory] + [InlineData("89504E470D0A1A0A", "image/png")] + [InlineData("FFD8FF", "image/jpeg")] + [InlineData("474946383961", "image/gif")] + [InlineData("474946383761", "image/gif")] + [InlineData("524946460000000057454250", "image/webp")] + public void UsesFileSignatureRatherThanExtension(string hex, string expected) + { + var image = PromptImageAttachment.Create("misleading.txt", Convert.FromHexString(hex)); + Assert.Equal(expected, image.MediaType); + } + + [Fact] + public void CopiesDraftBytesSoClipboardBuffersCannotChangeQueuedEvidence() + { + var bytes = Convert.FromHexString("89504E470D0A1A0A"); + var image = PromptImageAttachment.Create("screen.png", bytes); + bytes[0] = 0; + Assert.Equal(137, image.Bytes.Span[0]); + } + + [Theory] + [InlineData("")] + [InlineData("3C7376673E")] + [InlineData("424D00000000")] + public void RejectsEmptyAndUnsupportedBinary(string hex) => + Assert.Throws(() => PromptImageAttachment.Create("image.png", Convert.FromHexString(hex))); + + [Fact] + public void EnforcesEngineByteLimit() + { + Assert.Throws(() => PromptImageAttachment.Create("large.png", new byte[PromptImageAttachment.MaxBytes + 1])); + } + + [Theory] + [InlineData(ModelVisionSupport.Unknown)] + [InlineData(ModelVisionSupport.Unsupported)] + public void RechecksVisionWhenSubmittingAfterAModelSwitch(ModelVisionSupport vision) + { + Assert.NotNull(PromptImageAttachment.SubmissionError("Explain this", vision, true, false)); + Assert.Null(PromptImageAttachment.SubmissionError("Explain this", ModelVisionSupport.Supported, true, false)); + } + + [Theory] + [InlineData(" /model")] + [InlineData("/clear")] + [InlineData(" !echo hello")] + public void ImagesCannotBeQueuedByCommands(string prompt) => + Assert.NotNull(PromptImageAttachment.SubmissionError(prompt, ModelVisionSupport.Supported, true, false)); + + [Theory] + [InlineData(false, false)] + [InlineData(true, true)] + public void RefusesUnavailableConnectionOrModel(bool connected, bool error) => + Assert.NotNull(PromptImageAttachment.SubmissionError("Look", ModelVisionSupport.Supported, connected, error)); + + [Fact] + public void ImageOnlySubmissionHasAnExplicitPrompt() + { + Assert.Equal("Describe the attached image.", PromptImageAttachment.MessageText(" ")); + Assert.Equal("Compare the colors", PromptImageAttachment.MessageText("Compare the colors")); + } + [Theory] + [InlineData(1)] + [InlineData(4)] + public void AcceptsSupportedBatchSizes(int count) => + Assert.Null(PromptImageAttachment.SubmissionError("Compare these", ModelVisionSupport.Supported, true, false, count)); + + [Theory] + [InlineData(0)] + [InlineData(5)] + public void RefusesInvalidBatchBeforeQueueing(int count) => + Assert.NotNull(PromptImageAttachment.SubmissionError("Compare these", ModelVisionSupport.Supported, true, false, count)); + + [Fact] + public void MultipleImageOnlyMessageDescribesTheWholeBatch() => + Assert.Equal("Describe the attached images.", PromptImageAttachment.MessageText("", 4)); + + [Fact] + public async Task FourCaptionedImagesFitTheSharedEngineQueue() + { + var config = new MandoCodeConfig(); + var root = new MandoCode.Services.ProjectRootAccessor(Path.GetTempPath()); + var ai = new MandoCode.Services.AIService(root, config, + new MandoCode.Services.TokenTrackingService(), new MandoCode.Services.PlanHandoff(), + new MandoCode.Services.SkillLoader(config, root), new MandoCode.Services.McpClientManager(config), + new MandoCode.Services.McpApprovalGate(config), new MandoCode.Services.SpinnerService()); + using var http = new HttpClient(new VisionHandler()); + // Use the engine's existing HTTP test seam without a live Ollama daemon. + var validate = typeof(MandoCode.Services.AIService).GetMethod("ValidateModelAsync", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, + binder: null, types: new[] { typeof(HttpClient) }, modifiers: null)!; + await (Task)validate.Invoke(ai, new object[] { http })!; + var image = PromptImageAttachment.Create("image.png", Convert.FromHexString("89504E470D0A1A0A")); + for (var index = 0; index < PromptImageAttachment.MaxImages; index++) + Assert.True(ai.TryAttachImage(image.Bytes, image.MediaType, $"Image {index + 1}", out var error), error); + Assert.False(ai.TryAttachImage(image.Bytes, image.MediaType, "Extra", out _)); + } + + private sealed class VisionHandler : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { Content = new StringContent("{\"capabilities\":[\"vision\"]}") }); + } + +} diff --git a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Explorer.cs b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Explorer.cs index 7ba7d83..02a30b2 100644 --- a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Explorer.cs +++ b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Explorer.cs @@ -1278,7 +1278,11 @@ private async Task HandleDropAsync(DragEventArgs e) { // Shell drop (Windows Explorer): real files/folders with paths. var items = await e.DataView.GetStorageItemsAsync(); - InsertFileTokens(items.Select(i => i.Path).Where(p => !string.IsNullOrEmpty(p))); + var files = items.OfType().ToArray(); + if (files.Length > 0 && files.Length == items.Count && files.All(file => MandoCode.Services.ImageFileReference.IsImage(file.Name))) + await AttachImageFilesAsync(files); + else + InsertFileTokens(items.Select(i => i.Path).Where(p => !string.IsNullOrEmpty(p))); } else if (e.DataView.Contains(StandardDataFormats.Text)) { @@ -1286,7 +1290,13 @@ private async Task HandleDropAsync(DragEventArgs e) // line is an existing path, tokenize; otherwise it's ordinary dragged text. var text = await e.DataView.GetTextAsync(); var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - if (lines.Length > 0 && lines.All(l => File.Exists(l) || Directory.Exists(l))) + if (lines.Length > 0 && lines.All(path => File.Exists(path) && MandoCode.Services.ImageFileReference.IsImage(path))) + { + var images = new List(); + foreach (var path in lines) images.Add(await Windows.Storage.StorageFile.GetFileFromPathAsync(path)); + await AttachImageFilesAsync(images); + } + else if (lines.Length > 0 && lines.All(l => File.Exists(l) || Directory.Exists(l))) InsertFileTokens(lines); else InsertAtCaret(text); diff --git a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Images.cs b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Images.cs new file mode 100644 index 0000000..a6e9a9c --- /dev/null +++ b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Images.cs @@ -0,0 +1,245 @@ +using MandoCode.Desktop.Services; +using MandoCode.Models; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media.Imaging; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics.Imaging; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; + +namespace MandoCode.Desktop; + +public sealed partial class ChatTabView +{ + private readonly List _draftImages = new(); + private readonly Dictionary _imagePreviews = new(); + private bool _readingImageFiles; + private bool _imageLoading, _submittingInput; + private int _imageReadVersion; + + private void ImageNotice(string message) + { + if (_shutDown) return; + ImageAttachmentArea.Visibility = !string.IsNullOrEmpty(message) || _draftImages.Count > 0 ? Visibility.Visible : Visibility.Collapsed; + PromptImageNotice.Text = message; + PromptImageNotice.Visibility = string.IsNullOrEmpty(message) ? Visibility.Collapsed : Visibility.Visible; + } + + private void RefreshImageAttachment() + { + ImageAttachmentArea.Visibility = _draftImages.Count > 0 || !string.IsNullOrEmpty(PromptImageNotice.Text) ? Visibility.Visible : Visibility.Collapsed; + PromptImagesScroll.Visibility = PromptImageSummary.Visibility = _draftImages.Count > 0 ? Visibility.Visible : Visibility.Collapsed; + AttachImageButton.IsEnabled = !_imageLoading && !_readingImageFiles && !_submittingInput && !_shutDown && _draftImages.Count < PromptImageAttachment.MaxImages; + PromptImageSummary.Text = $"{_draftImages.Count} / {PromptImageAttachment.MaxImages} images · {_draftImages.Sum(i => i.Bytes.Length) / 1048576d:F1} MiB · sends with your next message"; + PromptImageCards.Children.Clear(); + for (var index = 0; index < _draftImages.Count; index++) + { + var image = _draftImages[index]; + var grid = new Grid { ColumnSpacing = 8 }; + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + var preview = new Image { Width = 56, Height = 48, Stretch = Microsoft.UI.Xaml.Media.Stretch.Uniform, Source = _imagePreviews[image] }; + Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(preview, $"Attached image {index + 1}: {image.Name}"); + grid.Children.Add(preview); + var details = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center }; + details.Children.Add(new TextBlock { Text = $"{index + 1}. {image.Name}", TextTrimming = TextTrimming.CharacterEllipsis, FontSize = 12 }); + details.Children.Add(new TextBlock { Text = $"{image.Bytes.Length / 1024d:F0} KiB", FontSize = 11, Opacity = .7 }); + ToolTipService.SetToolTip(details, image.Name); + Grid.SetColumn(details, 1); + grid.Children.Add(details); + var remove = new Button + { + Content = new FontIcon { Glyph = "", FontSize = 10 }, + Padding = new Thickness(4), MinWidth = 24, VerticalAlignment = VerticalAlignment.Center, + IsEnabled = !_submittingInput, + Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(Microsoft.UI.Colors.Transparent), BorderThickness = new Thickness(0) + }; + ToolTipService.SetToolTip(remove, $"Remove {image.Name}"); + Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(remove, $"Remove image {index + 1}: {image.Name}"); + remove.Click += (_, _) => RemoveImage(image); + Grid.SetColumn(remove, 2); + grid.Children.Add(remove); + PromptImageCards.Children.Add(new Border + { + Width = 240, Padding = new Thickness(8), CornerRadius = new CornerRadius(8), BorderThickness = new Thickness(1), + Background = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["MandoPanelBrush"], + BorderBrush = (Microsoft.UI.Xaml.Media.Brush)Application.Current.Resources["MandoBorderBrush"], Child = grid + }); + } + } + + private bool CanReadImage(bool fromBatch = false) + { + if (_shutDown || _imageLoading || _submittingInput || (_readingImageFiles && !fromBatch)) return false; + if (_draftImages.Count >= PromptImageAttachment.MaxImages) + { + ImageNotice("Up to four images per message. Remove an image before attaching another."); + return false; + } + if (_controller.VisionSupport != ModelVisionSupport.Supported) + { + ImageNotice("Choose a confirmed vision model before attaching an image."); + return false; + } + return true; + } + + private async void AttachImage_Click(object sender, RoutedEventArgs e) + { + if (!CanReadImage()) return; + try + { + var picker = new FileOpenPicker { SettingsIdentifier = "PromptImage" }; + foreach (var extension in new[] { ".png", ".jpg", ".jpeg", ".gif", ".webp" }) + picker.FileTypeFilter.Add(extension); + WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(_owner)); + var files = await picker.PickMultipleFilesAsync(); + if (files.Count > 0 && !_shutDown) await AttachImageFilesAsync(files); + } + catch (Exception ex) { ImageNotice($"Could not open the image: {ex.Message}"); } + } + + private async void InputBox_Paste(object sender, TextControlPasteEventArgs e) + { + try + { + var data = Clipboard.GetContent(); + if (!data.Contains(StandardDataFormats.Bitmap) && !data.Contains(StandardDataFormats.StorageItems)) + return; // Leave native text paste, including multiline prompts, alone. + e.Handled = true; + if (!CanReadImage()) return; + if (data.Contains(StandardDataFormats.Bitmap)) + { + await LoadImageAsync(async () => + { + var reference = await data.GetBitmapAsync(); + using var source = await reference.OpenReadAsync(); + if (source.Size > 64 * 1024 * 1024) throw new InvalidDataException("The clipboard image is too large."); + var decoder = await BitmapDecoder.CreateAsync(source); + CheckImageDimensions(decoder); + using var bitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); + using var encoded = new InMemoryRandomAccessStream(); + var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded); + encoder.SetSoftwareBitmap(bitmap); + await encoder.FlushAsync(); + return PromptImageAttachment.Create("Pasted image.png", await ReadImageBytesAsync(encoded)); + }); + } + else + { + var files = (await data.GetStorageItemsAsync()).OfType().ToArray(); + if (files.Length == 0 || files.Any(file => !MandoCode.Services.ImageFileReference.IsImage(file.Name))) + ImageNotice("Paste PNG, JPEG, GIF, or WebP image files, or use Attach image."); + else await AttachImageFilesAsync(files); + } + } + catch (Exception ex) { ImageNotice($"Could not paste the image: {ex.Message}"); } + } + + private Task AttachImageFileAsync(StorageFile file, bool fromBatch = false) => LoadImageAsync(async () => + { + using var source = await file.OpenReadAsync(); + return PromptImageAttachment.Create(file.Name, await ReadImageBytesAsync(source)); + }, fromBatch); + + private async Task AttachImageFilesAsync(IEnumerable selected) + { + if (!CanReadImage()) return; + var files = selected.ToArray(); + if (files.Length + _draftImages.Count > PromptImageAttachment.MaxImages) + { + ImageNotice($"You can add {PromptImageAttachment.MaxImages - _draftImages.Count} more image(s). Select fewer files."); + return; + } + _readingImageFiles = true; + RefreshImageAttachment(); + var errors = new List(); + try + { + foreach (var file in files) + { + if (_shutDown) break; + var before = _draftImages.Count; + await AttachImageFileAsync(file, fromBatch: true); + if (_draftImages.Count == before && !_shutDown) errors.Add($"{file.Name}: {PromptImageNotice.Text}"); + } + } + finally + { + _readingImageFiles = false; + if (!_shutDown) { ImageNotice(string.Join("\n", errors)); RefreshImageAttachment(); } + } + } + + private static async Task ReadImageBytesAsync(IRandomAccessStream stream) + { + if (stream.Size == 0 || stream.Size > PromptImageAttachment.MaxBytes) + throw new InvalidDataException("Use an image no larger than 4 MiB."); + using var reader = new DataReader(stream.GetInputStreamAt(0)); + var size = checked((uint)stream.Size); + if (await reader.LoadAsync(size) != size) throw new IOException("The image could not be read completely."); + var bytes = new byte[size]; + reader.ReadBytes(bytes); + return bytes; + } + + private static void CheckImageDimensions(BitmapDecoder decoder) + { + if (decoder.PixelWidth == 0 || decoder.PixelHeight == 0 + || (ulong)decoder.PixelWidth * decoder.PixelHeight > PromptImageAttachment.MaxPixels) + throw new InvalidDataException("Use an image with at most 16 million pixels."); + } + + private async Task LoadImageAsync(Func> read, bool fromBatch = false) + { + if (!CanReadImage(fromBatch)) return; + _imageLoading = true; + var version = ++_imageReadVersion; + RefreshImageAttachment(); + ImageNotice("Reading image…"); + try + { + var image = await read(); + using var stream = new InMemoryRandomAccessStream(); + using (var writer = new DataWriter(stream)) + { + writer.WriteBytes(image.Bytes.ToArray()); + await writer.StoreAsync(); + writer.DetachStream(); + } + stream.Seek(0); + var decoder = await BitmapDecoder.CreateAsync(stream); + CheckImageDimensions(decoder); + stream.Seek(0); + var preview = new BitmapImage { DecodePixelWidth = 96 }; + await preview.SetSourceAsync(stream); + if (_shutDown || version != _imageReadVersion) return; + if (_controller.VisionSupport != ModelVisionSupport.Supported) + throw new InvalidOperationException("The selected model changed. Choose a vision model and attach the image again."); + _draftImages.Add(image); + _imagePreviews[image] = preview; + ImageNotice(""); + } + catch (Exception ex) { if (version == _imageReadVersion) ImageNotice($"Image not attached: {ex.Message}"); } + finally + { + if (!_shutDown && version == _imageReadVersion) + { + _imageLoading = false; + RefreshImageAttachment(); + } + } + } + + private void RemoveImage(PromptImageAttachment image) + { + if (_submittingInput) return; + _draftImages.Remove(image); + _imagePreviews.Remove(image); + ImageNotice(""); + RefreshImageAttachment(); + } +} diff --git a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Input.cs b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Input.cs index 35b499c..ebd8436 100644 --- a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Input.cs +++ b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.Input.cs @@ -30,28 +30,58 @@ private void SendButton_Click(object sender, RoutedEventArgs e) SubmitCurrentInput(); } - private void SubmitCurrentInput() + private async void SubmitCurrentInput() { + if (_shutDown || _submittingInput || _imageLoading || _readingImageFiles || _controller.IsProcessing) return; var text = InputBox.Text; - if (string.IsNullOrWhiteSpace(text) || _controller.IsProcessing) return; - - EmitWorkspaceDelta(); // queue outside-the-conversation changes before this send - InputBox.Text = ""; - HideSuggestions(); - UpdateHeader(); + var images = _draftImages.ToArray(); + if (string.IsNullOrWhiteSpace(text) && images.Length == 0) return; + if (images.Length > 0) + { + var error = PromptImageAttachment.SubmissionError(text, _controller.VisionSupport, _controller.IsConnected, _controller.ModelError, images.Length); + if (error != null) { ImageNotice(error); return; } + } + EmitWorkspaceDelta(); var browserContext = CaptureBrowserRequestContext(); - _ = Task.Run(async () => + _submittingInput = true; + InputBox.IsReadOnly = true; + RefreshImageAttachment(); + var accepted = false; + try { - try + await Task.Run(() => _shutDown ? Task.CompletedTask : _controller.SubmitAsync(text, browserContext, images, () => { - await _controller.SubmitAsync(text, browserContext); - } - catch (Exception ex) + accepted = true; + OnUi(() => + { + if (_shutDown) return; + InputBox.Text = ""; + foreach (var image in images) { _draftImages.Remove(image); _imagePreviews.Remove(image); } + InputBox.IsReadOnly = false; + _submittingInput = false; + HideSuggestions(); + ImageNotice(""); + RefreshImageAttachment(); + UpdateHeader(); + }); + })); + if (!accepted && !_shutDown) + ImageNotice("The message was not sent. Your draft is still here; wait until the agent is ready and try again."); + } + catch (Exception ex) + { + if (!_shutDown) ImageNotice($"Could not send: {ex.Message}"); + } + finally + { + if (!_shutDown) { - _transcript.Append(_html.Error($"Unexpected error: {ex.Message}")); + _submittingInput = false; + InputBox.IsReadOnly = false; + RefreshImageAttachment(); } - }); + } } // PreviewKeyDown, NOT KeyDown: the TextBox's own class handler runs before instance diff --git a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.xaml b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.xaml index e037e47..8d67061 100644 --- a/src/MandoCode.Desktop/Controls/Chat/ChatTabView.xaml +++ b/src/MandoCode.Desktop/Controls/Chat/ChatTabView.xaml @@ -651,9 +651,9 @@ - - @@ -690,14 +690,16 @@ + + - @@ -724,13 +726,31 @@ - + + + + + + + + + + Paste="InputBox_Paste" PreviewKeyDown="InputBox_PreviewKeyDown" PreviewKeyUp="InputBox_PreviewKeyUp" TextChanged="InputBox_TextChanged" SelectionChanged="InputBox_SelectionChanged"/> - -